1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the snarkVM library.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![forbid(unsafe_code)]
#![allow(clippy::too_many_arguments)]
#![warn(clippy::cast_possible_truncation)]
pub type Program<N> = crate::ProgramCore<N, Instruction<N>, Command<N>>;
pub type Function<N> = crate::FunctionCore<N, Instruction<N>, Command<N>>;
pub type Finalize<N> = crate::FinalizeCore<N, Command<N>>;
pub type Closure<N> = crate::ClosureCore<N, Instruction<N>>;
mod closure;
pub use closure::*;
pub mod finalize;
pub use finalize::*;
mod function;
pub use function::*;
mod import;
pub use import::*;
pub mod logic;
pub use logic::*;
mod mapping;
pub use mapping::*;
pub mod traits;
pub use traits::*;
mod bytes;
mod parse;
mod serialize;
use console::{
network::prelude::{
alt,
anyhow,
bail,
de,
ensure,
error,
fmt,
many0,
many1,
map,
map_res,
tag,
take,
Debug,
Deserialize,
Deserializer,
Display,
Error,
Formatter,
FromBytes,
FromBytesDeserializer,
FromStr,
IoResult,
Network,
Parser,
ParserResult,
Read,
Result,
Sanitizer,
Serialize,
Serializer,
ToBytes,
ToBytesSerializer,
TypeName,
Write,
},
program::{Identifier, PlaintextType, ProgramID, RecordType, StructType},
};
use indexmap::IndexMap;
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
enum ProgramDefinition {
/// A program mapping.
Mapping,
/// A program struct.
Struct,
/// A program record.
Record,
/// A program closure.
Closure,
/// A program function.
Function,
}
#[derive(Clone, PartialEq, Eq)]
pub struct ProgramCore<N: Network, Instruction: InstructionTrait<N>, Command: CommandTrait<N>> {
/// The ID of the program.
id: ProgramID<N>,
/// A map of the declared imports for the program.
imports: IndexMap<ProgramID<N>, Import<N>>,
/// A map of identifiers to their program declaration.
identifiers: IndexMap<Identifier<N>, ProgramDefinition>,
/// A map of the declared mappings for the program.
mappings: IndexMap<Identifier<N>, Mapping<N>>,
/// A map of the declared structs for the program.
structs: IndexMap<Identifier<N>, StructType<N>>,
/// A map of the declared record types for the program.
records: IndexMap<Identifier<N>, RecordType<N>>,
/// A map of the declared closures for the program.
closures: IndexMap<Identifier<N>, ClosureCore<N, Instruction>>,
/// A map of the declared functions for the program.
functions: IndexMap<Identifier<N>, FunctionCore<N, Instruction, Command>>,
}
impl<N: Network, Instruction: InstructionTrait<N>, Command: CommandTrait<N>> ProgramCore<N, Instruction, Command> {
/// Initializes an empty program.
#[inline]
pub fn new(id: ProgramID<N>) -> Result<Self> {
// Ensure the program name is valid.
ensure!(!Self::is_reserved_keyword(id.name()), "Program name is invalid: {}", id.name());
Ok(Self {
id,
imports: IndexMap::new(),
identifiers: IndexMap::new(),
mappings: IndexMap::new(),
structs: IndexMap::new(),
records: IndexMap::new(),
closures: IndexMap::new(),
functions: IndexMap::new(),
})
}
/// Initializes the credits program.
#[inline]
pub fn credits() -> Result<Self> {
Self::from_str(include_str!("./resources/credits.aleo"))
}
/// Returns the ID of the program.
pub const fn id(&self) -> &ProgramID<N> {
&self.id
}
/// Returns the imports in the program.
pub const fn imports(&self) -> &IndexMap<ProgramID<N>, Import<N>> {
&self.imports
}
/// Returns the mappings in the program.
pub const fn mappings(&self) -> &IndexMap<Identifier<N>, Mapping<N>> {
&self.mappings
}
/// Returns the structs in the program.
pub const fn structs(&self) -> &IndexMap<Identifier<N>, StructType<N>> {
&self.structs
}
/// Returns the records in the program.
pub const fn records(&self) -> &IndexMap<Identifier<N>, RecordType<N>> {
&self.records
}
/// Returns the closures in the program.
pub const fn closures(&self) -> &IndexMap<Identifier<N>, ClosureCore<N, Instruction>> {
&self.closures
}
/// Returns the functions in the program.
pub const fn functions(&self) -> &IndexMap<Identifier<N>, FunctionCore<N, Instruction, Command>> {
&self.functions
}
/// Returns `true` if the program contains an import with the given program ID.
pub fn contains_import(&self, id: &ProgramID<N>) -> bool {
self.imports.contains_key(id)
}
/// Returns `true` if the program contains a mapping with the given name.
pub fn contains_mapping(&self, name: &Identifier<N>) -> bool {
self.mappings.contains_key(name)
}
/// Returns `true` if the program contains a struct with the given name.
pub fn contains_struct(&self, name: &Identifier<N>) -> bool {
self.structs.contains_key(name)
}
/// Returns `true` if the program contains a record with the given name.
pub fn contains_record(&self, name: &Identifier<N>) -> bool {
self.records.contains_key(name)
}
/// Returns `true` if the program contains a closure with the given name.
pub fn contains_closure(&self, name: &Identifier<N>) -> bool {
self.closures.contains_key(name)
}
/// Returns `true` if the program contains a function with the given name.
pub fn contains_function(&self, name: &Identifier<N>) -> bool {
self.functions.contains_key(name)
}
/// Returns the mapping with the given name.
pub fn get_mapping(&self, name: &Identifier<N>) -> Result<Mapping<N>> {
// Attempt to retrieve the mapping.
let mapping = self.mappings.get(name).cloned().ok_or_else(|| anyhow!("Mapping '{name}' is not defined."))?;
// Ensure the mapping name matches.
ensure!(mapping.name() == name, "Expected mapping '{name}', but found mapping '{}'", mapping.name());
// Return the mapping.
Ok(mapping)
}
/// Returns the struct with the given name.
pub fn get_struct(&self, name: &Identifier<N>) -> Result<&StructType<N>> {
// Attempt to retrieve the struct.
let struct_ = self.structs.get(name).ok_or_else(|| anyhow!("Struct '{name}' is not defined."))?;
// Ensure the struct name matches.
ensure!(struct_.name() == name, "Expected struct '{name}', but found struct '{}'", struct_.name());
// Ensure the struct contains members.
ensure!(!struct_.members().is_empty(), "Struct '{name}' is missing members.");
// Return the struct.
Ok(struct_)
}
/// Returns the record with the given name.
pub fn get_record(&self, name: &Identifier<N>) -> Result<&RecordType<N>> {
// Attempt to retrieve the record.
let record = self.records.get(name).ok_or_else(|| anyhow!("Record '{name}' is not defined."))?;
// Ensure the record name matches.
ensure!(record.name() == name, "Expected record '{name}', but found record '{}'", record.name());
// Return the record.
Ok(record)
}
/// Returns the closure with the given name.
pub fn get_closure(&self, name: &Identifier<N>) -> Result<ClosureCore<N, Instruction>> {
// Attempt to retrieve the closure.
let closure = self.closures.get(name).cloned().ok_or_else(|| anyhow!("Closure '{name}' is not defined."))?;
// Ensure the closure name matches.
ensure!(closure.name() == name, "Expected closure '{name}', but found closure '{}'", closure.name());
// Ensure there are input statements in the closure.
ensure!(!closure.inputs().is_empty(), "Cannot evaluate a closure without input statements");
// Ensure the number of inputs is within the allowed range.
ensure!(closure.inputs().len() <= N::MAX_INPUTS, "Closure exceeds maximum number of inputs");
// Ensure there are instructions in the closure.
ensure!(!closure.instructions().is_empty(), "Cannot evaluate a closure without instructions");
// Ensure the number of outputs is within the allowed range.
ensure!(closure.outputs().len() <= N::MAX_OUTPUTS, "Closure exceeds maximum number of outputs");
// Return the closure.
Ok(closure)
}
/// Returns the function with the given name.
pub fn get_function(&self, name: &Identifier<N>) -> Result<FunctionCore<N, Instruction, Command>> {
self.get_function_ref(name).map(|function| function.clone())
}
/// Returns a reference to the function with the given name.
pub fn get_function_ref(&self, name: &Identifier<N>) -> Result<&FunctionCore<N, Instruction, Command>> {
// Attempt to retrieve the function.
let function = self.functions.get(name).ok_or_else(|| anyhow!("Function '{name}' is not defined."))?;
// Ensure the function name matches.
ensure!(function.name() == name, "Expected function '{name}', but found function '{}'", function.name());
// Ensure the number of inputs is within the allowed range.
ensure!(function.inputs().len() <= N::MAX_INPUTS, "Function exceeds maximum number of inputs");
// Ensure the number of instructions is within the allowed range.
ensure!(function.instructions().len() <= N::MAX_INSTRUCTIONS, "Function exceeds maximum instructions");
// Ensure the number of outputs is within the allowed range.
ensure!(function.outputs().len() <= N::MAX_OUTPUTS, "Function exceeds maximum number of outputs");
// Return the function.
Ok(function)
}
}
impl<N: Network, Instruction: InstructionTrait<N>, Command: CommandTrait<N>> ProgramCore<N, Instruction, Command> {
/// Adds a new import statement to the program.
///
/// # Errors
/// This method will halt if the imported program was previously added.
#[inline]
fn add_import(&mut self, import: Import<N>) -> Result<()> {
// Retrieve the imported program name.
let import_name = *import.name();
// Ensure the import name is new.
ensure!(self.is_unique_name(&import_name), "'{import_name}' is already in use.");
// Ensure the import name is not a reserved opcode.
ensure!(!Self::is_reserved_opcode(&import_name.to_string()), "'{import_name}' is a reserved opcode.");
// Ensure the import name is not a reserved keyword.
ensure!(!Self::is_reserved_keyword(&import_name), "'{import_name}' is a reserved keyword.");
// Ensure the import is new.
ensure!(
!self.imports.contains_key(import.program_id()),
"Import '{}' is already defined.",
import.program_id()
);
// Add the import statement to the program.
if self.imports.insert(*import.program_id(), import.clone()).is_some() {
bail!("'{}' already exists in the program.", import.program_id())
}
Ok(())
}
/// Adds a new mapping to the program.
///
/// # Errors
/// This method will halt if the mapping name is already in use.
/// This method will halt if the mapping name is a reserved opcode or keyword.
#[inline]
fn add_mapping(&mut self, mapping: Mapping<N>) -> Result<()> {
// Retrieve the mapping name.
let mapping_name = *mapping.name();
// Ensure the program has not exceeded the maximum number of mappings.
ensure!(self.mappings.len() < N::MAX_MAPPINGS, "Program exceeds the maximum number of mappings");
// Ensure the mapping name is new.
ensure!(self.is_unique_name(&mapping_name), "'{mapping_name}' is already in use.");
// Ensure the mapping name is not a reserved keyword.
ensure!(!Self::is_reserved_keyword(&mapping_name), "'{mapping_name}' is a reserved keyword.");
// Ensure the mapping name is not a reserved opcode.
ensure!(!Self::is_reserved_opcode(&mapping_name.to_string()), "'{mapping_name}' is a reserved opcode.");
// Add the mapping name to the identifiers.
if self.identifiers.insert(mapping_name, ProgramDefinition::Mapping).is_some() {
bail!("'{mapping_name}' already exists in the program.")
}
// Add the mapping to the program.
if self.mappings.insert(mapping_name, mapping).is_some() {
bail!("'{mapping_name}' already exists in the program.")
}
Ok(())
}
/// Adds a new struct to the program.
///
/// # Errors
/// This method will halt if the struct was previously added.
/// This method will halt if the struct name is already in use in the program.
/// This method will halt if the struct name is a reserved opcode or keyword.
/// This method will halt if any structs in the struct's members are not already defined.
#[inline]
fn add_struct(&mut self, struct_: StructType<N>) -> Result<()> {
// Retrieve the struct name.
let struct_name = *struct_.name();
// Ensure the struct name is new.
ensure!(self.is_unique_name(&struct_name), "'{struct_name}' is already in use.");
// Ensure the struct name is not a reserved opcode.
ensure!(!Self::is_reserved_opcode(&struct_name.to_string()), "'{struct_name}' is a reserved opcode.");
// Ensure the struct name is not a reserved keyword.
ensure!(!Self::is_reserved_keyword(&struct_name), "'{struct_name}' is a reserved keyword.");
// Ensure the struct contains members.
ensure!(!struct_.members().is_empty(), "Struct '{struct_name}' is missing members.");
// Ensure all struct members are well-formed.
// Note: This design ensures cyclic references are not possible.
for (identifier, plaintext_type) in struct_.members() {
// Ensure the member name is not a reserved keyword.
ensure!(!Self::is_reserved_keyword(identifier), "'{identifier}' is a reserved keyword.");
// Ensure the member type is already defined in the program.
match plaintext_type {
PlaintextType::Literal(_) => continue,
PlaintextType::Struct(member_identifier) => {
// Ensure the member struct name exists in the program.
if !self.structs.contains_key(member_identifier) {
bail!("'{member_identifier}' in struct '{}' is not defined.", struct_name)
}
}
PlaintextType::Array(array_type) => {
if let PlaintextType::Struct(struct_name) = array_type.base_element_type() {
// Ensure the member struct name exists in the program.
if !self.structs.contains_key(struct_name) {
bail!("'{struct_name}' in array '{array_type}' is not defined.")
}
}
}
}
}
// Add the struct name to the identifiers.
if self.identifiers.insert(struct_name, ProgramDefinition::Struct).is_some() {
bail!("'{}' already exists in the program.", struct_name)
}
// Add the struct to the program.
if self.structs.insert(struct_name, struct_).is_some() {
bail!("'{}' already exists in the program.", struct_name)
}
Ok(())
}
/// Adds a new record to the program.
///
/// # Errors
/// This method will halt if the record was previously added.
/// This method will halt if the record name is already in use in the program.
/// This method will halt if the record name is a reserved opcode or keyword.
/// This method will halt if any records in the record's members are not already defined.
#[inline]
fn add_record(&mut self, record: RecordType<N>) -> Result<()> {
// Retrieve the record name.
let record_name = *record.name();
// Ensure the record name is new.
ensure!(self.is_unique_name(&record_name), "'{record_name}' is already in use.");
// Ensure the record name is not a reserved opcode.
ensure!(!Self::is_reserved_opcode(&record_name.to_string()), "'{record_name}' is a reserved opcode.");
// Ensure the record name is not a reserved keyword.
ensure!(!Self::is_reserved_keyword(&record_name), "'{record_name}' is a reserved keyword.");
// Ensure all record entries are well-formed.
// Note: This design ensures cyclic references are not possible.
for (identifier, entry_type) in record.entries() {
// Ensure the member name is not a reserved keyword.
ensure!(!Self::is_reserved_keyword(identifier), "'{identifier}' is a reserved keyword.");
// Ensure the member type is already defined in the program.
match entry_type.plaintext_type() {
PlaintextType::Literal(_) => continue,
PlaintextType::Struct(identifier) => {
if !self.structs.contains_key(identifier) {
bail!("Struct '{identifier}' in record '{record_name}' is not defined.")
}
}
PlaintextType::Array(array_type) => {
if let PlaintextType::Struct(struct_name) = array_type.base_element_type() {
// Ensure the member struct name exists in the program.
if !self.structs.contains_key(struct_name) {
bail!("'{struct_name}' in array '{array_type}' is not defined.")
}
}
}
}
}
// Add the record name to the identifiers.
if self.identifiers.insert(record_name, ProgramDefinition::Record).is_some() {
bail!("'{record_name}' already exists in the program.")
}
// Add the record to the program.
if self.records.insert(record_name, record).is_some() {
bail!("'{record_name}' already exists in the program.")
}
Ok(())
}
/// Adds a new closure to the program.
///
/// # Errors
/// This method will halt if the closure was previously added.
/// This method will halt if the closure name is already in use in the program.
/// This method will halt if the closure name is a reserved opcode or keyword.
/// This method will halt if any registers are assigned more than once.
/// This method will halt if the registers are not incrementing monotonically.
/// This method will halt if an input type references a non-existent definition.
/// This method will halt if an operand register does not already exist in memory.
/// This method will halt if a destination register already exists in memory.
/// This method will halt if an output register does not already exist.
/// This method will halt if an output type references a non-existent definition.
#[inline]
fn add_closure(&mut self, closure: ClosureCore<N, Instruction>) -> Result<()> {
// Retrieve the closure name.
let closure_name = *closure.name();
// Ensure the closure name is new.
ensure!(self.is_unique_name(&closure_name), "'{closure_name}' is already in use.");
// Ensure the closure name is not a reserved opcode.
ensure!(!Self::is_reserved_opcode(&closure_name.to_string()), "'{closure_name}' is a reserved opcode.");
// Ensure the closure name is not a reserved keyword.
ensure!(!Self::is_reserved_keyword(&closure_name), "'{closure_name}' is a reserved keyword.");
// Ensure there are input statements in the closure.
ensure!(!closure.inputs().is_empty(), "Cannot evaluate a closure without input statements");
// Ensure the number of inputs is within the allowed range.
ensure!(closure.inputs().len() <= N::MAX_INPUTS, "Closure exceeds maximum number of inputs");
// Ensure there are instructions in the closure.
ensure!(!closure.instructions().is_empty(), "Cannot evaluate a closure without instructions");
// Ensure the number of outputs is within the allowed range.
ensure!(closure.outputs().len() <= N::MAX_OUTPUTS, "Closure exceeds maximum number of outputs");
// Add the function name to the identifiers.
if self.identifiers.insert(closure_name, ProgramDefinition::Closure).is_some() {
bail!("'{closure_name}' already exists in the program.")
}
// Add the closure to the program.
if self.closures.insert(closure_name, closure).is_some() {
bail!("'{closure_name}' already exists in the program.")
}
Ok(())
}
/// Adds a new function to the program.
///
/// # Errors
/// This method will halt if the function was previously added.
/// This method will halt if the function name is already in use in the program.
/// This method will halt if the function name is a reserved opcode or keyword.
/// This method will halt if any registers are assigned more than once.
/// This method will halt if the registers are not incrementing monotonically.
/// This method will halt if an input type references a non-existent definition.
/// This method will halt if an operand register does not already exist in memory.
/// This method will halt if a destination register already exists in memory.
/// This method will halt if an output register does not already exist.
/// This method will halt if an output type references a non-existent definition.
#[inline]
fn add_function(&mut self, function: FunctionCore<N, Instruction, Command>) -> Result<()> {
// Retrieve the function name.
let function_name = *function.name();
// Ensure the program has not exceeded the maximum number of functions.
ensure!(self.functions.len() < N::MAX_FUNCTIONS, "Program exceeds the maximum number of functions");
// Ensure the function name is new.
ensure!(self.is_unique_name(&function_name), "'{function_name}' is already in use.");
// Ensure the function name is not a reserved opcode.
ensure!(!Self::is_reserved_opcode(&function_name.to_string()), "'{function_name}' is a reserved opcode.");
// Ensure the function name is not a reserved keyword.
ensure!(!Self::is_reserved_keyword(&function_name), "'{function_name}' is a reserved keyword.");
// Ensure the number of inputs is within the allowed range.
ensure!(function.inputs().len() <= N::MAX_INPUTS, "Function exceeds maximum number of inputs");
// Ensure the number of instructions is within the allowed range.
ensure!(function.instructions().len() <= N::MAX_INSTRUCTIONS, "Function exceeds maximum instructions");
// Ensure the number of outputs is within the allowed range.
ensure!(function.outputs().len() <= N::MAX_OUTPUTS, "Function exceeds maximum number of outputs");
// Add the function name to the identifiers.
if self.identifiers.insert(function_name, ProgramDefinition::Function).is_some() {
bail!("'{function_name}' already exists in the program.")
}
// Add the function to the program.
if self.functions.insert(function_name, function).is_some() {
bail!("'{function_name}' already exists in the program.")
}
Ok(())
}
}
impl<N: Network, Instruction: InstructionTrait<N>, Command: CommandTrait<N>> ProgramCore<N, Instruction, Command> {
#[rustfmt::skip]
const KEYWORDS: &'static [&'static str] = &[
// Mode
"const",
"constant",
"public",
"private",
// Literals
"address",
"boolean",
"field",
"group",
"i8",
"i16",
"i32",
"i64",
"i128",
"u8",
"u16",
"u32",
"u64",
"u128",
"scalar",
"string",
// Boolean
"true",
"false",
// Statements
"input",
"output",
"as",
"into",
// Record
"record",
"owner",
// Program
"transition",
"import",
"function",
"struct",
"closure",
"program",
"aleo",
"self",
"storage",
"mapping",
"key",
"value",
"async",
"finalize",
// Reserved (catch all)
"global",
"block",
"return",
"break",
"assert",
"continue",
"let",
"if",
"else",
"while",
"for",
"switch",
"case",
"default",
"match",
"enum",
"struct",
"union",
"trait",
"impl",
"type",
"future",
];
/// Returns `true` if the given name does not already exist in the program.
fn is_unique_name(&self, name: &Identifier<N>) -> bool {
!self.identifiers.contains_key(name)
}
/// Returns `true` if the given name is a reserved opcode.
pub fn is_reserved_opcode(name: &str) -> bool {
Instruction::is_reserved_opcode(name)
}
/// Returns `true` if the given name uses a reserved keyword.
pub fn is_reserved_keyword(name: &Identifier<N>) -> bool {
// Convert the given name to a string.
let name = name.to_string();
// Check if the name is a keyword.
Self::KEYWORDS.iter().any(|keyword| *keyword == name)
}
}
impl<N: Network, Instruction: InstructionTrait<N>, Command: CommandTrait<N>> TypeName
for ProgramCore<N, Instruction, Command>
{
/// Returns the type name as a string.
#[inline]
fn type_name() -> &'static str {
"program"
}
}
#[cfg(test)]
mod tests {
use super::*;
use console::{
network::Testnet3,
program::{Locator, ValueType},
};
type CurrentNetwork = Testnet3;
#[test]
fn test_program_mapping() -> Result<()> {
// Create a new mapping.
let mapping = Mapping::<CurrentNetwork>::from_str(
r"
mapping message:
key as field.public;
value as field.public;",
)?;
// Initialize a new program.
let program = Program::<CurrentNetwork>::from_str(&format!("program unknown.aleo; {mapping}"))?;
// Ensure the mapping was added.
assert!(program.contains_mapping(&Identifier::from_str("message")?));
// Ensure the retrieved mapping matches.
assert_eq!(mapping.to_string(), program.get_mapping(&Identifier::from_str("message")?)?.to_string());
Ok(())
}
#[test]
fn test_program_struct() -> Result<()> {
// Create a new struct.
let struct_ = StructType::<CurrentNetwork>::from_str(
r"
struct message:
first as field;
second as field;",
)?;
// Initialize a new program.
let program = Program::<CurrentNetwork>::from_str(&format!("program unknown.aleo; {struct_}"))?;
// Ensure the struct was added.
assert!(program.contains_struct(&Identifier::from_str("message")?));
// Ensure the retrieved struct matches.
assert_eq!(&struct_, program.get_struct(&Identifier::from_str("message")?)?);
Ok(())
}
#[test]
fn test_program_record() -> Result<()> {
// Create a new record.
let record = RecordType::<CurrentNetwork>::from_str(
r"
record foo:
owner as address.private;
first as field.private;
second as field.public;",
)?;
// Initialize a new program.
let program = Program::<CurrentNetwork>::from_str(&format!("program unknown.aleo; {record}"))?;
// Ensure the record was added.
assert!(program.contains_record(&Identifier::from_str("foo")?));
// Ensure the retrieved record matches.
assert_eq!(&record, program.get_record(&Identifier::from_str("foo")?)?);
Ok(())
}
#[test]
fn test_program_function() -> Result<()> {
// Create a new function.
let function = Function::<CurrentNetwork>::from_str(
r"
function compute:
input r0 as field.public;
input r1 as field.private;
add r0 r1 into r2;
output r2 as field.private;",
)?;
// Initialize a new program.
let program = Program::<CurrentNetwork>::from_str(&format!("program unknown.aleo; {function}"))?;
// Ensure the function was added.
assert!(program.contains_function(&Identifier::from_str("compute")?));
// Ensure the retrieved function matches.
assert_eq!(function, program.get_function(&Identifier::from_str("compute")?)?);
Ok(())
}
#[test]
fn test_program_import() -> Result<()> {
// Initialize a new program.
let program = Program::<CurrentNetwork>::from_str(
r"
import eth.aleo;
import usdc.aleo;
program swap.aleo;
// The `swap` function transfers ownership of the record
// for token A to the record owner of token B, and vice-versa.
function swap:
// Input the record for token A.
input r0 as eth.aleo/eth.record;
// Input the record for token B.
input r1 as usdc.aleo/usdc.record;
// Send the record for token A to the owner of token B.
call eth.aleo/transfer r0 r1.owner r0.amount into r2 r3;
// Send the record for token B to the owner of token A.
call usdc.aleo/transfer r1 r0.owner r1.amount into r4 r5;
// Output the new record for token A.
output r2 as eth.aleo/eth.record;
// Output the new record for token B.
output r4 as usdc.aleo/usdc.record;
",
)
.unwrap();
// Ensure the program imports exist.
assert!(program.contains_import(&ProgramID::from_str("eth.aleo")?));
assert!(program.contains_import(&ProgramID::from_str("usdc.aleo")?));
// Retrieve the 'swap' function.
let function = program.get_function(&Identifier::from_str("swap")?)?;
// Ensure there are two inputs.
assert_eq!(function.inputs().len(), 2);
assert_eq!(function.input_types().len(), 2);
// Ensure the inputs are external records.
assert_eq!(function.input_types()[0], ValueType::ExternalRecord(Locator::from_str("eth.aleo/eth")?));
assert_eq!(function.input_types()[1], ValueType::ExternalRecord(Locator::from_str("usdc.aleo/usdc")?));
// Ensure there are two instructions.
assert_eq!(function.instructions().len(), 2);
// Ensure the instructions are calls.
assert_eq!(function.instructions()[0].opcode(), Opcode::Call);
assert_eq!(function.instructions()[1].opcode(), Opcode::Call);
// Ensure there are two outputs.
assert_eq!(function.outputs().len(), 2);
assert_eq!(function.output_types().len(), 2);
// Ensure the outputs are external records.
assert_eq!(function.output_types()[0], ValueType::ExternalRecord(Locator::from_str("eth.aleo/eth")?));
assert_eq!(function.output_types()[1], ValueType::ExternalRecord(Locator::from_str("usdc.aleo/usdc")?));
Ok(())
}
}