diff --git a/Cargo.lock b/Cargo.lock index 547c9d6ac9..0becff807e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1187,11 +1187,9 @@ dependencies = [ "from-pest", "indexmap", "lazy_static", - "leo-ast", "leo-compiler", "leo-errors", "leo-package", - "leo-parser", "notify", "rand 0.8.4", "rand_core 0.6.3", diff --git a/Cargo.toml b/Cargo.toml index 4872368e58..0892fb13f2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,81 +27,24 @@ path = "leo/main.rs" [workspace] members = [ -# "asg", -# "asg-passes", - "ast", - "ast-passes", - "compiler", - "errors", - "grammar", -# "imports", -# "input", -# "linter", - "package", - "parser", - "span", -# "state", -# "stdlib", -# "synthesizer", -# "test-framework", -# "wasm" + "compiler/compiler", + "docs/grammar", + "leo/errors", + "leo/package", ] -[dependencies.leo-ast] -path = "./ast" -version = "1.5.3" - [dependencies.leo-compiler] -path = "./compiler" +path = "./compiler/compiler" version = "1.5.3" [dependencies.leo-errors] -path = "./errors" +path = "./leo/errors" version = "1.5.3" -#[dependencies.leo-imports] -#path = "./imports" -#version = "1.5.3" -# -#[dependencies.leo-input] -#path = "./input" -#version = "1.5.3" - [dependencies.leo-package] -path = "./package" +path = "./leo/package" version = "1.5.3" -[dependencies.leo-parser] -path = "./parser" -version = "1.5.3" - -#[dependencies.leo-state] -#path = "./state" -#version = "1.5.3" - -#[dependencies.leo-stdlib] -#path = "./stdlib" -#version = "1.5.3" - -#[dependencies.snarkvm-algorithms] -#git = "https://github.com/AleoHQ/snarkVM.git" -#rev = "51633e2" -# -#[dependencies.snarkvm-curves] -#git = "https://github.com/AleoHQ/snarkVM.git" -#rev = "51633e2" -#default-features = false -# -#[dependencies.snarkvm-gadgets] -#git = "https://github.com/AleoHQ/snarkVM.git" -#rev = "51633e2" -#default-features = false -# -#[dependencies.snarkvm-r1cs] -#git = "https://github.com/AleoHQ/snarkVM.git" -#rev = "51633e2" -#default-features = false -# [dependencies.snarkvm-utilities] git = "https://github.com/AleoHQ/snarkVM.git" rev = "51633e2" diff --git a/asg-passes/Cargo.toml b/asg-passes/Cargo.toml deleted file mode 100644 index 5f38b79c87..0000000000 --- a/asg-passes/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -[package] -name = "leo-asg-passes" -version = "1.5.3" -authors = [ "The Aleo Team " ] -description = "The Leo programming language" -homepage = "https://aleo.org" -repository = "https://github.com/AleoHQ/leo" -keywords = [ - "aleo", - "cryptography", - "leo", - "programming-language", - "zero-knowledge" -] -categories = [ "cryptography::cryptocurrencies", "web-programming" ] -include = [ "Cargo.toml", "src", "README.md", "LICENSE.md" ] -license = "GPL-3.0" -edition = "2021" -rust-version = "1.56.1" - -[lib] -path = "src/lib.rs" - -[dependencies.leo-asg] -path = "../asg" -version = "1.5.3" - -[dependencies.leo-errors] -path = "../errors" -version = "1.5.3" diff --git a/asg-passes/src/constant_folding/mod.rs b/asg-passes/src/constant_folding/mod.rs deleted file mode 100644 index 658a455f84..0000000000 --- a/asg-passes/src/constant_folding/mod.rs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use std::cell::Cell; - -use leo_asg::*; -use leo_errors::Result; - -pub struct ConstantFolding<'a, 'b> { - program: &'b Program<'a>, -} - -impl<'a, 'b> ExpressionVisitor<'a> for ConstantFolding<'a, 'b> { - fn visit_expression(&mut self, input: &Cell<&'a Expression<'a>>) -> VisitResult { - let expr = input.get(); - if let Some(const_value) = expr.const_value() { - let folded_expr = Expression::Constant(Constant { - parent: Cell::new(expr.get_parent()), - span: expr.span().cloned(), - value: const_value, - }); - let folded_expr = self.program.context.alloc_expression(folded_expr); - input.set(folded_expr); - VisitResult::SkipChildren - } else { - VisitResult::VisitChildren - } - } -} - -impl<'a, 'b> StatementVisitor<'a> for ConstantFolding<'a, 'b> {} - -impl<'a, 'b> ProgramVisitor<'a> for ConstantFolding<'a, 'b> {} - -impl<'a, 'b> AsgPass<'a> for ConstantFolding<'a, 'b> { - fn do_pass(asg: Program<'a>) -> Result> { - let pass = ConstantFolding { program: &asg }; - let mut director = VisitorDirector::new(pass); - director.visit_program(&asg).ok(); - Ok(asg) - } -} diff --git a/asg-passes/src/dead_code_elimination/mod.rs b/asg-passes/src/dead_code_elimination/mod.rs deleted file mode 100644 index fa1cebf623..0000000000 --- a/asg-passes/src/dead_code_elimination/mod.rs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use std::cell::Cell; - -use leo_asg::*; -use leo_errors::Result; - -pub struct DeadCodeElimination {} - -impl<'a> ReconstructingReducerExpression<'a> for DeadCodeElimination {} - -impl<'a> ReconstructingReducerProgram<'a> for DeadCodeElimination {} - -impl<'a> ReconstructingReducerStatement<'a> for DeadCodeElimination { - /// - /// Removes dead code inside a false conditional statement block. - /// - fn reduce_statement_alloc( - &mut self, - context: AsgContext<'a>, - _input: &'a Statement<'a>, - value: Statement<'a>, - ) -> &'a Statement<'a> { - match &value { - Statement::Conditional(conditional) => match conditional.condition.get().const_value() { - Some(ConstValue::Boolean(true)) => conditional.result.get(), - Some(ConstValue::Boolean(false)) => { - if let Some(if_false) = conditional.next.get() { - if_false - } else { - context.alloc_statement(Statement::Empty(conditional.span.clone())) - } - } - _ => context.alloc_statement(value), - }, - _ => context.alloc_statement(value), - } - } - - fn reduce_block(&mut self, input: BlockStatement<'a>, mut statements: Vec<&'a Statement<'a>>) -> Statement<'a> { - let first_return = statements.iter().position(|x| matches!(x, Statement::Return(_))); - if let Some(first_return) = first_return { - statements.truncate(first_return + 1); - } - Statement::Block(BlockStatement { - parent: input.parent, - span: input.span, - statements: statements.into_iter().map(Cell::new).collect(), - scope: input.scope, - }) - } -} - -impl<'a> AsgPass<'a> for DeadCodeElimination { - fn do_pass(asg: Program<'a>) -> Result> { - let pass = DeadCodeElimination {}; - let mut director = ReconstructingDirector::new(asg.context, pass); - Ok(director.reduce_program(asg)) - } -} diff --git a/asg-passes/src/lib.rs b/asg-passes/src/lib.rs deleted file mode 100644 index 1904bf782d..0000000000 --- a/asg-passes/src/lib.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -#![doc = include_str!("../README.md")] - -pub mod constant_folding; -pub use constant_folding::*; - -pub mod dead_code_elimination; -pub use dead_code_elimination::*; diff --git a/asg/Cargo.toml b/asg/Cargo.toml deleted file mode 100644 index e9c868978b..0000000000 --- a/asg/Cargo.toml +++ /dev/null @@ -1,56 +0,0 @@ -[package] -name = "leo-asg" -version = "1.5.3" -authors = [ "The Aleo Team " ] -description = "ASG of the Leo programming language" -homepage = "https://aleo.org" -repository = "https://github.com/AleoHQ/leo" -keywords = [ - "aleo", - "cryptography", - "leo", - "programming-language", - "zero-knowledge" -] -categories = [ "cryptography::cryptocurrencies", "web-programming" ] -include = [ "Cargo.toml", "src", "README.md", "LICENSE.md" ] -license = "GPL-3.0" -edition = "2021" -rust-version = "1.56.1" - -[dependencies.leo-ast] -version = "1.5.3" -path = "../ast" - -[dependencies.leo-ast-passes] -path = "../ast-passes" -version = "1.5.3" - -[dependencies.leo-errors] -path = "../errors" -version = "1.5.3" - -[dependencies.leo-parser] -version = "1.5.3" -path = "../parser" - -[dependencies.indexmap] -version = "1.7" - -[dependencies.num-bigint] -version = "0.4" - -[dependencies.serde] -version = "1.0" - -[dependencies.serde_json] -version = "1.0" - -[dependencies.tendril] -version = "0.4" - -[dependencies.typed-arena] -version = "2.0" - -[dev-dependencies.criterion] -version = "0.3" diff --git a/asg/README.md b/asg/README.md deleted file mode 100644 index c82025d76e..0000000000 --- a/asg/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# leo-asg - -[![Crates.io](https://img.shields.io/crates/v/leo-asg.svg?color=neon)](https://crates.io/crates/leo-asg) -[![Authors](https://img.shields.io/badge/authors-Aleo-orange.svg)](../AUTHORS) -[![License](https://img.shields.io/badge/License-GPLv3-blue.svg)](./LICENSE.md) diff --git a/asg/src/checks/mod.rs b/asg/src/checks/mod.rs deleted file mode 100644 index f3843860d2..0000000000 --- a/asg/src/checks/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Helper methods to determine the correct return value path in an asg. - -mod return_path; -pub use return_path::*; diff --git a/asg/src/checks/return_path.rs b/asg/src/checks/return_path.rs deleted file mode 100644 index 3761c2e928..0000000000 --- a/asg/src/checks/return_path.rs +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{statement::*, BoolAnd, Expression, Monoid, MonoidalReducerExpression, MonoidalReducerStatement, Node}; - -use leo_errors::Span; - -pub struct ReturnPathReducer { - pub errors: Vec<(Span, String)>, -} - -impl ReturnPathReducer { - fn record_error(&mut self, span: Option<&Span>, error: String) { - self.errors.push((span.cloned().unwrap_or_default(), error)); - } - - pub fn new() -> ReturnPathReducer { - ReturnPathReducer { errors: vec![] } - } -} - -impl Default for ReturnPathReducer { - fn default() -> Self { - Self::new() - } -} - -#[allow(unused_variables)] -impl<'a> MonoidalReducerExpression<'a, BoolAnd> for ReturnPathReducer { - fn reduce_expression(&mut self, input: &'a Expression<'a>, value: BoolAnd) -> BoolAnd { - BoolAnd(false) - } -} - -#[allow(unused_variables)] -impl<'a> MonoidalReducerStatement<'a, BoolAnd> for ReturnPathReducer { - fn reduce_assign_access(&mut self, input: &AssignAccess, left: Option, right: Option) -> BoolAnd { - BoolAnd(false) - } - - fn reduce_assign(&mut self, input: &AssignStatement, accesses: Vec, value: BoolAnd) -> BoolAnd { - BoolAnd(false) - } - - fn reduce_block(&mut self, input: &BlockStatement, statements: Vec) -> BoolAnd { - if statements.is_empty() { - BoolAnd(false) - } else if let Some(index) = statements[..statements.len() - 1].iter().map(|x| x.0).position(|x| x) { - self.record_error( - input.statements[index].get().span(), - "dead code due to unconditional early return".to_string(), - ); - BoolAnd(true) - } else { - BoolAnd(statements[statements.len() - 1].0) - } - } - - fn reduce_conditional_statement( - &mut self, - input: &ConditionalStatement, - condition: BoolAnd, - if_true: BoolAnd, - if_false: Option, - ) -> BoolAnd { - if if_false.as_ref().map(|x| x.0).unwrap_or(false) != if_true.0 { - self.record_error( - input.span(), - "cannot have asymmetrical return in if statement".to_string(), - ); - } - if_true.append(if_false.unwrap_or(BoolAnd(false))) - } - - fn reduce_formatted_string(&mut self, input: &ConsoleArgs, parameters: Vec) -> BoolAnd { - BoolAnd(false) - } - - fn reduce_console(&mut self, input: &ConsoleStatement, argument: BoolAnd) -> BoolAnd { - BoolAnd(false) - } - - fn reduce_definition(&mut self, input: &DefinitionStatement, value: BoolAnd) -> BoolAnd { - BoolAnd(false) - } - - fn reduce_expression_statement(&mut self, input: &ExpressionStatement, expression: BoolAnd) -> BoolAnd { - BoolAnd(false) - } - - fn reduce_iteration( - &mut self, - input: &IterationStatement, - start: BoolAnd, - stop: BoolAnd, - body: BoolAnd, - ) -> BoolAnd { - // loops are const defined ranges, so we could probably check if they run one and emit here - BoolAnd(false) - } - - fn reduce_return(&mut self, input: &ReturnStatement, value: BoolAnd) -> BoolAnd { - BoolAnd(true) - } -} diff --git a/asg/src/const_value.rs b/asg/src/const_value.rs deleted file mode 100644 index 5ed2f9b40d..0000000000 --- a/asg/src/const_value.rs +++ /dev/null @@ -1,363 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{Circuit, Identifier, IntegerType, Type}; -use leo_errors::{AsgError, Result, Span}; - -use indexmap::IndexMap; -use num_bigint::BigInt; -use std::{convert::TryInto, fmt}; -use tendril::StrTendril; - -/// Constant integer values in a program. -#[derive(Clone, Debug, PartialEq)] -pub enum ConstInt { - I8(i8), - I16(i16), - I32(i32), - I64(i64), - I128(i128), - U8(u8), - U16(u16), - U32(u32), - U64(u64), - U128(u128), -} - -/// Specifies how to calculate a group coordinate in a program. -#[derive(Clone, Debug, PartialEq)] -pub enum GroupCoordinate { - /// Explicit field element number string. - Number(StrTendril), - - /// Attempt to recover with a sign high bit. - SignHigh, - - /// Attempt to recover with a sign low bit. - SignLow, - - /// Try recovering with a sign low - upon failure try sign high. - Inferred, -} - -impl fmt::Display for GroupCoordinate { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - GroupCoordinate::Number(number) => write!(f, "{}", number), - GroupCoordinate::SignHigh => write!(f, "+"), - GroupCoordinate::SignLow => write!(f, "-"), - GroupCoordinate::Inferred => write!(f, "_"), - } - } -} - -impl From<&leo_ast::GroupCoordinate> for GroupCoordinate { - fn from(other: &leo_ast::GroupCoordinate) -> GroupCoordinate { - use leo_ast::GroupCoordinate::*; - match other { - Number(value, _) => GroupCoordinate::Number(value.clone()), - SignHigh => GroupCoordinate::SignHigh, - SignLow => GroupCoordinate::SignLow, - Inferred => GroupCoordinate::Inferred, - } - } -} - -impl Into for &GroupCoordinate { - fn into(self) -> leo_ast::GroupCoordinate { - use GroupCoordinate::*; - match self { - Number(value) => leo_ast::GroupCoordinate::Number(value.clone(), Default::default()), - SignHigh => leo_ast::GroupCoordinate::SignHigh, - SignLow => leo_ast::GroupCoordinate::SignLow, - Inferred => leo_ast::GroupCoordinate::Inferred, - } - } -} - -#[derive(Clone, Debug, PartialEq)] -pub enum GroupValue { - Single(StrTendril), - Tuple(GroupCoordinate, GroupCoordinate), -} - -impl From for GroupValue { - fn from(other: leo_ast::GroupValue) -> Self { - use leo_ast::GroupValue::*; - match other { - Single(value, _) => GroupValue::Single(value), - Tuple(value) => GroupValue::Tuple(GroupCoordinate::from(&value.x), GroupCoordinate::from(&value.y)), - } - } -} - -#[derive(Clone, Debug, PartialEq)] -pub enum CharValue { - Scalar(char), - NonScalar(u32), -} - -impl From<&leo_ast::Char> for CharValue { - fn from(other: &leo_ast::Char) -> Self { - use leo_ast::Char::*; - match other { - Scalar(value) => CharValue::Scalar(*value), - NonScalar(value) => CharValue::NonScalar(*value), - } - } -} - -impl Into for &CharValue { - fn into(self) -> leo_ast::Char { - use leo_ast::Char::*; - match self { - CharValue::Scalar(value) => Scalar(*value), - CharValue::NonScalar(value) => NonScalar(*value), - } - } -} - -impl From for CharValue { - fn from(other: leo_ast::CharValue) -> Self { - Self::from(&other.character) - } -} - -#[derive(Clone, PartialEq)] -pub enum ConstValue<'a> { - Int(ConstInt), - Group(GroupValue), - Field(BigInt), - Address(StrTendril), - Boolean(bool), - Char(CharValue), - - // compounds - Tuple(Vec>), - Array(Vec>), - Circuit(&'a Circuit<'a>, IndexMap)>), -} - -macro_rules! const_int_op { - ($name: ident, $retType: ty, $x: ident, $transform: expr) => { - pub fn $name(&self) -> $retType { - match self { - ConstInt::I8($x) => $transform, - ConstInt::I16($x) => $transform, - ConstInt::I32($x) => $transform, - ConstInt::I64($x) => $transform, - ConstInt::I128($x) => $transform, - ConstInt::U8($x) => $transform, - ConstInt::U16($x) => $transform, - ConstInt::U32($x) => $transform, - ConstInt::U64($x) => $transform, - ConstInt::U128($x) => $transform, - } - } - }; -} - -macro_rules! const_int_biop { - ($name: ident, $retType: ty, $x: ident, $y: ident, $transform: expr) => { - pub fn $name(&self, other: &ConstInt) -> Option<$retType> { - match (self, other) { - (ConstInt::I8($x), ConstInt::I8($y)) => $transform, - (ConstInt::I16($x), ConstInt::I16($y)) => $transform, - (ConstInt::I32($x), ConstInt::I32($y)) => $transform, - (ConstInt::I64($x), ConstInt::I64($y)) => $transform, - (ConstInt::I128($x), ConstInt::I128($y)) => $transform, - (ConstInt::U8($x), ConstInt::U8($y)) => $transform, - (ConstInt::U16($x), ConstInt::U16($y)) => $transform, - (ConstInt::U32($x), ConstInt::U32($y)) => $transform, - (ConstInt::U64($x), ConstInt::U64($y)) => $transform, - (ConstInt::U128($x), ConstInt::U128($y)) => $transform, - _ => None, - } - } - }; -} - -macro_rules! const_int_map { - ($name: ident, $x: ident, $transform: expr) => { - pub fn $name(&self) -> Option { - Some(match self { - ConstInt::I8($x) => ConstInt::I8($transform), - ConstInt::I16($x) => ConstInt::I16($transform), - ConstInt::I32($x) => ConstInt::I32($transform), - ConstInt::I64($x) => ConstInt::I64($transform), - ConstInt::I128($x) => ConstInt::I128($transform), - ConstInt::U8($x) => ConstInt::U8($transform), - ConstInt::U16($x) => ConstInt::U16($transform), - ConstInt::U32($x) => ConstInt::U32($transform), - ConstInt::U64($x) => ConstInt::U64($transform), - ConstInt::U128($x) => ConstInt::U128($transform), - }) - } - }; -} - -macro_rules! const_int_bimap { - ($name: ident, $x: ident, $y: ident, $transform: expr) => { - pub fn $name(&self, other: &ConstInt) -> Option { - Some(match (self, other) { - (ConstInt::I8($x), ConstInt::I8($y)) => ConstInt::I8($transform), - (ConstInt::I16($x), ConstInt::I16($y)) => ConstInt::I16($transform), - (ConstInt::I32($x), ConstInt::I32($y)) => ConstInt::I32($transform), - (ConstInt::I64($x), ConstInt::I64($y)) => ConstInt::I64($transform), - (ConstInt::I128($x), ConstInt::I128($y)) => ConstInt::I128($transform), - (ConstInt::U8($x), ConstInt::U8($y)) => ConstInt::U8($transform), - (ConstInt::U16($x), ConstInt::U16($y)) => ConstInt::U16($transform), - (ConstInt::U32($x), ConstInt::U32($y)) => ConstInt::U32($transform), - (ConstInt::U64($x), ConstInt::U64($y)) => ConstInt::U64($transform), - (ConstInt::U128($x), ConstInt::U128($y)) => ConstInt::U128($transform), - _ => return None, - }) - } - }; -} - -#[allow(clippy::useless_conversion)] -impl ConstInt { - const_int_op!(raw_value, String, x, format!("{}", x)); - - const_int_map!(value_negate, x, x.checked_neg()?); - - const_int_map!(value_bit_negate, x, !x); - - const_int_op!(to_usize, Option, x, (*x).try_into().ok()); - - const_int_op!(to_u128, u128, x, *x as u128); - - const_int_op!(to_u64, u64, x, *x as u64); - - const_int_op!(to_u32, u32, x, *x as u32); - - const_int_op!(to_u16, u16, x, *x as u16); - - const_int_op!(to_u8, u8, x, *x as u8); - - const_int_op!(to_i128, i128, x, *x as i128); - - const_int_op!(to_i64, i64, x, *x as i64); - - const_int_op!(to_i32, i32, x, *x as i32); - - const_int_op!(to_i16, i16, x, *x as i16); - - const_int_op!(to_i8, i8, x, *x as i8); - - const_int_op!(to_string, String, x, (*x).to_string()); - - const_int_bimap!(value_add, x, y, x.checked_add(*y)?); - - const_int_bimap!(value_sub, x, y, x.checked_sub(*y)?); - - const_int_bimap!(value_mul, x, y, x.checked_mul(*y)?); - - const_int_bimap!(value_div, x, y, x.checked_div(*y)?); - - // TODO: limited to 32 bit exponents - const_int_bimap!(value_pow, x, y, x.checked_pow((*y).try_into().ok()?)?); - - const_int_biop!(value_lt, bool, x, y, Some(x < y)); - - const_int_biop!(value_le, bool, x, y, Some(x <= y)); - - const_int_biop!(value_gt, bool, x, y, Some(x > y)); - - const_int_biop!(value_ge, bool, x, y, Some(x >= y)); - - pub fn get_int_type(&self) -> IntegerType { - match self { - ConstInt::I8(_) => IntegerType::I8, - ConstInt::I16(_) => IntegerType::I16, - ConstInt::I32(_) => IntegerType::I32, - ConstInt::I64(_) => IntegerType::I64, - ConstInt::I128(_) => IntegerType::I128, - ConstInt::U8(_) => IntegerType::U8, - ConstInt::U16(_) => IntegerType::U16, - ConstInt::U32(_) => IntegerType::U32, - ConstInt::U64(_) => IntegerType::U64, - ConstInt::U128(_) => IntegerType::U128, - } - } - - pub fn cast_to(&self, target: &IntegerType) -> ConstInt { - match target { - IntegerType::I8 => ConstInt::I8(self.to_i8()), - IntegerType::I16 => ConstInt::I16(self.to_i16()), - IntegerType::I32 => ConstInt::I32(self.to_i32()), - IntegerType::I64 => ConstInt::I64(self.to_i64()), - IntegerType::I128 => ConstInt::I128(self.to_i128()), - IntegerType::U8 => ConstInt::U8(self.to_u8()), - IntegerType::U16 => ConstInt::U16(self.to_u16()), - IntegerType::U32 => ConstInt::U32(self.to_u32()), - IntegerType::U64 => ConstInt::U64(self.to_u64()), - IntegerType::U128 => ConstInt::U128(self.to_u128()), - } - } - - pub fn get_type<'a>(&self) -> Type<'a> { - Type::Integer(self.get_int_type()) - } - - pub fn parse(int_type: &IntegerType, value: &str, span: &Span) -> Result { - Ok(match int_type { - IntegerType::I8 => ConstInt::I8(value.parse().map_err(|_| AsgError::invalid_int(value, span))?), - IntegerType::I16 => ConstInt::I16(value.parse().map_err(|_| AsgError::invalid_int(value, span))?), - IntegerType::I32 => ConstInt::I32(value.parse().map_err(|_| AsgError::invalid_int(value, span))?), - IntegerType::I64 => ConstInt::I64(value.parse().map_err(|_| AsgError::invalid_int(value, span))?), - IntegerType::I128 => ConstInt::I128(value.parse().map_err(|_| AsgError::invalid_int(value, span))?), - IntegerType::U8 => ConstInt::U8(value.parse().map_err(|_| AsgError::invalid_int(value, span))?), - IntegerType::U16 => ConstInt::U16(value.parse().map_err(|_| AsgError::invalid_int(value, span))?), - IntegerType::U32 => ConstInt::U32(value.parse().map_err(|_| AsgError::invalid_int(value, span))?), - IntegerType::U64 => ConstInt::U64(value.parse().map_err(|_| AsgError::invalid_int(value, span))?), - IntegerType::U128 => ConstInt::U128(value.parse().map_err(|_| AsgError::invalid_int(value, span))?), - }) - } -} - -impl<'a> ConstValue<'a> { - pub fn get_type(&'a self) -> Option> { - Some(match self { - ConstValue::Int(i) => i.get_type(), - ConstValue::Group(_) => Type::Group, - ConstValue::Field(_) => Type::Field, - ConstValue::Address(_) => Type::Address, - ConstValue::Boolean(_) => Type::Boolean, - ConstValue::Char(_) => Type::Char, - ConstValue::Tuple(sub_consts) => { - Type::Tuple(sub_consts.iter().map(|x| x.get_type()).collect::>>()?) - } - ConstValue::Array(values) => Type::Array(Box::new(values.get(0)?.get_type()?), values.len()), - ConstValue::Circuit(circuit, _) => Type::Circuit(circuit), - }) - } - - pub fn int(&self) -> Option<&ConstInt> { - match self { - ConstValue::Int(x) => Some(x), - _ => None, - } - } - - pub fn field(&self) -> Option<&BigInt> { - match self { - ConstValue::Field(x) => Some(x), - _ => None, - } - } -} diff --git a/asg/src/context.rs b/asg/src/context.rs deleted file mode 100644 index a154b55368..0000000000 --- a/asg/src/context.rs +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use std::{cell::Cell, unimplemented}; - -use typed_arena::Arena; - -use crate::{Alias, ArenaNode, Circuit, Expression, Function, Scope, Statement, Variable}; - -pub struct AsgContextInner<'a> { - pub arena: &'a Arena>, - pub next_id: Cell, -} - -impl<'a> AsgContextInner<'a> { - pub fn new(arena: &'a Arena>) -> &'a Self { - match arena.alloc(ArenaNode::Inner(AsgContextInner { - arena, - next_id: Cell::new(0), - })) { - ArenaNode::Inner(x) => x, - _ => unimplemented!(), - } - } - - pub fn get_id(&self) -> u32 { - let next_id = self.next_id.get(); - self.next_id.replace(next_id + 1); - next_id - } - - #[allow(clippy::mut_from_ref)] - pub fn alloc_expression(&'a self, expr: Expression<'a>) -> &'a Expression<'a> { - match self.arena.alloc(ArenaNode::Expression(expr)) { - ArenaNode::Expression(e) => e, - _ => unimplemented!(), - } - } - - #[allow(clippy::mut_from_ref)] - pub fn alloc_statement(&'a self, statement: Statement<'a>) -> &'a Statement<'a> { - match self.arena.alloc(ArenaNode::Statement(statement)) { - ArenaNode::Statement(e) => e, - _ => unimplemented!(), - } - } - - #[allow(clippy::mut_from_ref)] - pub fn alloc_variable(&'a self, variable: Variable<'a>) -> &'a Variable<'a> { - match self.arena.alloc(ArenaNode::Variable(variable)) { - ArenaNode::Variable(e) => e, - _ => unimplemented!(), - } - } - - #[allow(clippy::mut_from_ref)] - pub fn alloc_scope(&'a self, scope: Scope<'a>) -> &'a Scope<'a> { - match self.arena.alloc(ArenaNode::Scope(Box::new(scope))) { - ArenaNode::Scope(e) => e, - _ => unimplemented!(), - } - } - - #[allow(clippy::mut_from_ref)] - pub fn alloc_alias(&'a self, expr: Alias<'a>) -> &'a Alias<'a> { - match self.arena.alloc(ArenaNode::Alias(expr)) { - ArenaNode::Alias(e) => e, - _ => unimplemented!(), - } - } - - #[allow(clippy::mut_from_ref)] - pub fn alloc_circuit(&'a self, circuit: Circuit<'a>) -> &'a Circuit<'a> { - match self.arena.alloc(ArenaNode::Circuit(circuit)) { - ArenaNode::Circuit(e) => e, - _ => unimplemented!(), - } - } - - #[allow(clippy::mut_from_ref)] - pub fn alloc_function(&'a self, function: Function<'a>) -> &'a Function<'a> { - match self.arena.alloc(ArenaNode::Function(function)) { - ArenaNode::Function(e) => e, - _ => unimplemented!(), - } - } -} - -pub type AsgContext<'a> = &'a AsgContextInner<'a>; diff --git a/asg/src/expression/array_access.rs b/asg/src/expression/array_access.rs deleted file mode 100644 index d25c1e7bdf..0000000000 --- a/asg/src/expression/array_access.rs +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type}; -use leo_ast::IntegerType; -use leo_errors::{AsgError, Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct ArrayAccessExpression<'a> { - pub parent: Cell>>, - pub span: Option, - pub array: Cell<&'a Expression<'a>>, - pub index: Cell<&'a Expression<'a>>, -} - -impl<'a> Node for ArrayAccessExpression<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> ExpressionNode<'a> for ArrayAccessExpression<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - self.parent.replace(Some(parent)); - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - self.parent.get() - } - - fn enforce_parents(&self, expr: &'a Expression<'a>) { - self.array.get().set_parent(expr); - self.index.get().set_parent(expr); - } - - fn get_type(&self) -> Option> { - match self.array.get().get_type() { - Some(Type::Array(element, _)) => Some(*element), - _ => None, - } - } - - fn is_mut_ref(&self) -> bool { - self.array.get().is_mut_ref() - } - - fn const_value(&self) -> Option> { - let mut array = match self.array.get().const_value()? { - ConstValue::Array(values) => values, - _ => return None, - }; - let const_index = match self.index.get().const_value()? { - ConstValue::Int(x) => x.to_usize()?, - _ => return None, - }; - if const_index >= array.len() { - return None; - } - Some(array.remove(const_index)) - } - - fn is_consty(&self) -> bool { - self.array.get().is_consty() - } -} - -impl<'a> FromAst<'a, leo_ast::ArrayAccessExpression> for ArrayAccessExpression<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::ArrayAccessExpression, - expected_type: Option>, - ) -> Result> { - let array = <&Expression<'a>>::from_ast( - scope, - &*value.array, - Some(PartialType::Array(expected_type.map(Box::new), None)), - )?; - let array_len = match array.get_type() { - Some(Type::Array(_, len)) => Some(len), - Some(Type::ArrayWithoutSize(_)) => None, - type_ => { - return Err(AsgError::unexpected_type( - "array", - type_.map(|x| x.to_string()).unwrap_or_else(|| "unknown".to_string()), - &value.span, - ) - .into()); - } - }; - - let index = <&Expression<'a>>::from_ast( - scope, - &*value.index, - Some(PartialType::Integer(None, Some(IntegerType::U32))), - )?; - - if let Some(index) = index - .const_value() - .map(|x| x.int().map(|x| x.to_usize()).flatten()) - .flatten() - { - // Only check index if array size is known. - // Array out of bounds will be caught later if it really happens. - if let Some(array_len) = array_len { - if index >= array_len { - return Err( - AsgError::array_index_out_of_bounds(index, &array.span().cloned().unwrap_or_default()).into(), - ); - } - } - } - - Ok(ArrayAccessExpression { - parent: Cell::new(None), - span: Some(value.span.clone()), - array: Cell::new(array), - index: Cell::new(index), - }) - } -} - -impl<'a> Into for &ArrayAccessExpression<'a> { - fn into(self) -> leo_ast::ArrayAccessExpression { - leo_ast::ArrayAccessExpression { - array: Box::new(self.array.get().into()), - index: Box::new(self.index.get().into()), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/expression/array_init.rs b/asg/src/expression/array_init.rs deleted file mode 100644 index d493d07290..0000000000 --- a/asg/src/expression/array_init.rs +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type}; -use leo_errors::{AsgError, Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct ArrayInitExpression<'a> { - pub parent: Cell>>, - pub span: Option, - pub element: Cell<&'a Expression<'a>>, - pub len: usize, -} - -impl<'a> Node for ArrayInitExpression<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> ExpressionNode<'a> for ArrayInitExpression<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - self.parent.replace(Some(parent)); - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - self.parent.get() - } - - fn enforce_parents(&self, expr: &'a Expression<'a>) { - self.element.get().set_parent(expr); - } - - fn get_type(&self) -> Option> { - Some(Type::Array(Box::new(self.element.get().get_type()?), self.len)) - } - - fn is_mut_ref(&self) -> bool { - false - } - - fn const_value(&self) -> Option> { - let element = self.element.get().const_value()?; - Some(ConstValue::Array(vec![element; self.len])) - } - - fn is_consty(&self) -> bool { - self.element.get().is_consty() - } -} - -impl<'a> FromAst<'a, leo_ast::ArrayInitExpression> for ArrayInitExpression<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::ArrayInitExpression, - expected_type: Option>, - ) -> Result> { - let (mut expected_item, expected_len) = match expected_type { - Some(PartialType::Array(item, dims)) => (item.map(|x| *x), dims), - None => (None, None), - Some(type_) => { - return Err(AsgError::unexpected_type("array", type_, &value.span).into()); - } - }; - let dimensions = value - .dimensions - .0 - .iter() - .map(|x| { - Ok(x.value - .parse::() - .map_err(|_| AsgError::parse_dimension_error(&value.span))?) - }) - .collect::>>()?; - - let len = *dimensions - .get(0) - .ok_or_else(|| AsgError::parse_dimension_error(&value.span))?; - if let Some(expected_len) = expected_len { - if expected_len != len { - return Err(AsgError::unexpected_type( - format!("array of length {}", expected_len), - format!("array of length {}", len), - &value.span, - ) - .into()); - } - } - - for dimension in (&dimensions[1..]).iter().copied() { - expected_item = match expected_item { - Some(PartialType::Array(item, len)) => { - if let Some(len) = len { - if len != dimension { - return Err(AsgError::unexpected_type( - format!("array of length {}", dimension), - format!("array of length {}", len), - &value.span, - ) - .into()); - } - } - - item.map(|x| *x) - } - None => None, - Some(type_) => { - return Err(AsgError::unexpected_type("array", type_, &value.span).into()); - } - } - } - let mut element = Some(<&'a Expression<'a>>::from_ast(scope, &*value.element, expected_item)?); - let mut output = None; - - for dimension in dimensions.iter().rev().copied() { - output = Some(ArrayInitExpression { - parent: Cell::new(None), - span: Some(value.span.clone()), - element: Cell::new( - output - .map(Expression::ArrayInit) - .map(|expr| &*scope.context.alloc_expression(expr)) - .unwrap_or_else(|| element.take().unwrap()), - ), - len: dimension, - }); - } - Ok(output.unwrap()) - } -} - -impl<'a> Into for &ArrayInitExpression<'a> { - fn into(self) -> leo_ast::ArrayInitExpression { - leo_ast::ArrayInitExpression { - element: Box::new(self.element.get().into()), - dimensions: leo_ast::ArrayDimensions(vec![leo_ast::PositiveNumber { - value: self.len.to_string().into(), - }]), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/expression/array_inline.rs b/asg/src/expression/array_inline.rs deleted file mode 100644 index de9772e419..0000000000 --- a/asg/src/expression/array_inline.rs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type}; -use leo_ast::SpreadOrExpression; -use leo_errors::{AsgError, Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct ArrayInlineExpression<'a> { - pub parent: Cell>>, - pub span: Option, - pub elements: Vec<(Cell<&'a Expression<'a>>, bool)>, // bool = if spread -} - -impl<'a> ArrayInlineExpression<'a> { - pub fn expanded_length(&self) -> usize { - self.elements - .iter() - .map(|(expr, is_spread)| { - if *is_spread { - match expr.get().get_type() { - Some(Type::Array(_item, len)) => len, - _ => 0, - } - } else { - 1 - } - }) - .sum() - } -} - -impl<'a> Node for ArrayInlineExpression<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> ExpressionNode<'a> for ArrayInlineExpression<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - self.parent.replace(Some(parent)); - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - self.parent.get() - } - - fn enforce_parents(&self, expr: &'a Expression<'a>) { - self.elements.iter().for_each(|(element, _)| { - element.get().set_parent(expr); - }) - } - - fn get_type(&self) -> Option> { - let first = self.elements.first()?; - let inner_type = match first.0.get().get_type()? { - Type::Array(inner, _) if first.1 => *inner, - _ => first.0.get().get_type()?, - }; - Some(Type::Array(Box::new(inner_type), self.expanded_length())) - } - - fn is_mut_ref(&self) -> bool { - false - } - - fn const_value(&self) -> Option> { - let mut const_values = vec![]; - for (expr, spread) in self.elements.iter() { - if *spread { - match expr.get().const_value()? { - ConstValue::Array(items) => const_values.extend(items), - _ => return None, - } - } else { - const_values.push(expr.get().const_value()?); - } - } - Some(ConstValue::Array(const_values)) - } - - fn is_consty(&self) -> bool { - self.elements.iter().all(|x| x.0.get().is_consty()) - } -} - -impl<'a> FromAst<'a, leo_ast::ArrayInlineExpression> for ArrayInlineExpression<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::ArrayInlineExpression, - expected_type: Option>, - ) -> Result> { - let (mut expected_item, expected_len) = match expected_type { - Some(PartialType::Array(item, dims)) => (item.map(|x| *x), dims), - Some(PartialType::Type(Type::ArrayWithoutSize(item))) => (Some(item.partial()), None), - None => (None, None), - Some(type_) => { - return Err(AsgError::unexpected_type("array", type_, &value.span).into()); - } - }; - - // If we still don't know the type iterate through processing to get a type. - // Once we encouter the type break the loop so we process as little as possible. - if expected_item.is_none() { - for expr in value.elements.iter() { - expected_item = match expr { - SpreadOrExpression::Expression(e) => { - match <&Expression<'a>>::from_ast(scope, e, expected_item.clone()) { - Ok(expr) => expr.get_type().map(Type::partial), - Err(_) => continue, - } - } - _ => None, - }; - - if expected_item.is_some() { - break; - } - } - } - - let mut len = 0; - - let output = ArrayInlineExpression { - parent: Cell::new(None), - span: Some(value.span.clone()), - elements: value - .elements - .iter() - .map(|e| match e { - SpreadOrExpression::Expression(e) => { - let expr = <&Expression<'a>>::from_ast(scope, e, expected_item.clone())?; - if expected_item.is_none() { - expected_item = expr.get_type().map(Type::partial); - } - len += 1; - Ok((Cell::new(expr), false)) - } - SpreadOrExpression::Spread(e) => { - let expr = <&Expression<'a>>::from_ast( - scope, - e, - Some(PartialType::Array(expected_item.clone().map(Box::new), None)), - )?; - - match expr.get_type() { - Some(Type::Array(item, spread_len)) => { - if expected_item.is_none() { - expected_item = Some((*item).partial()); - } - - len += spread_len; - } - type_ => { - return Err(AsgError::unexpected_type( - expected_item - .as_ref() - .map(|x| x.to_string()) - .as_deref() - .unwrap_or("unknown"), - type_.map(|x| x.to_string()).unwrap_or_else(|| "unknown".to_string()), - &value.span, - ) - .into()); - } - } - Ok((Cell::new(expr), true)) - } - }) - .collect::>>()?, - }; - if let Some(expected_len) = expected_len { - if len != expected_len { - return Err(AsgError::unexpected_type( - format!("array of length {}", expected_len), - format!("array of length {}", len), - &value.span, - ) - .into()); - } - } - Ok(output) - } -} - -impl<'a> Into for &ArrayInlineExpression<'a> { - fn into(self) -> leo_ast::ArrayInlineExpression { - leo_ast::ArrayInlineExpression { - elements: self - .elements - .iter() - .map(|(element, spread)| { - let element = element.get().into(); - if *spread { - SpreadOrExpression::Spread(element) - } else { - SpreadOrExpression::Expression(element) - } - }) - .collect(), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/expression/array_range_access.rs b/asg/src/expression/array_range_access.rs deleted file mode 100644 index af54b1a2b0..0000000000 --- a/asg/src/expression/array_range_access.rs +++ /dev/null @@ -1,227 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type}; -use leo_ast::IntegerType; -use leo_errors::{AsgError, Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct ArrayRangeAccessExpression<'a> { - pub parent: Cell>>, - pub span: Option, - pub array: Cell<&'a Expression<'a>>, - pub left: Cell>>, - pub right: Cell>>, - // this is either const(right) - const(left) OR the length inferred by type checking - // special attention must be made to update this if semantic-altering changes are made to left or right. - pub length: usize, -} - -impl<'a> Node for ArrayRangeAccessExpression<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> ExpressionNode<'a> for ArrayRangeAccessExpression<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - self.parent.replace(Some(parent)); - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - self.parent.get() - } - - fn enforce_parents(&self, expr: &'a Expression<'a>) { - self.array.get().set_parent(expr); - self.array.get().enforce_parents(self.array.get()); - if let Some(left) = self.left.get() { - left.set_parent(expr); - } - if let Some(right) = self.right.get() { - right.set_parent(expr); - } - } - - fn get_type(&self) -> Option> { - let element = match self.array.get().get_type() { - Some(Type::Array(element, _)) => element, - _ => return None, - }; - - Some(Type::Array(element, self.length)) - } - - fn is_mut_ref(&self) -> bool { - self.array.get().is_mut_ref() - } - - fn const_value(&self) -> Option> { - let mut array = match self.array.get().const_value()? { - ConstValue::Array(values) => values, - _ => return None, - }; - let const_left = match self.left.get().map(|x| x.const_value()) { - Some(Some(ConstValue::Int(x))) => x.to_usize()?, - None => 0, - _ => return None, - }; - let const_right = match self.right.get().map(|x| x.const_value()) { - Some(Some(ConstValue::Int(x))) => x.to_usize()?, - None => array.len(), - _ => return None, - }; - if const_left > const_right || const_right as usize > array.len() { - return None; - } - - Some(ConstValue::Array(array.drain(const_left..const_right).collect())) - } - - fn is_consty(&self) -> bool { - self.array.get().is_consty() - } -} - -impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessExpression<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::ArrayRangeAccessExpression, - expected_type: Option>, - ) -> Result> { - let (expected_array, expected_len) = match expected_type.clone() { - Some(PartialType::Array(element, len)) => (Some(PartialType::Array(element, None)), len), - None => (None, None), - Some(x) => { - return Err(AsgError::unexpected_type("array", x, &value.span).into()); - } - }; - let array = <&Expression<'a>>::from_ast(scope, &*value.array, expected_array)?; - let array_type = array.get_type(); - let (parent_element, parent_size) = match array_type { - Some(Type::Array(inner, size)) => (inner, size), - type_ => { - return Err(AsgError::unexpected_type( - "array", - type_.map(|x| x.to_string()).unwrap_or_else(|| "unknown".to_string()), - &value.span, - ) - .into()); - } - }; - - let left = value - .left - .as_deref() - .map(|left| { - <&Expression<'a>>::from_ast(scope, left, Some(PartialType::Integer(None, Some(IntegerType::U32)))) - }) - .transpose()?; - let right = value - .right - .as_deref() - .map(|right| { - <&Expression<'a>>::from_ast(scope, right, Some(PartialType::Integer(None, Some(IntegerType::U32)))) - }) - .transpose()?; - - let const_left = match left.map(|x| x.const_value()) { - Some(Some(ConstValue::Int(x))) => x.to_usize(), - None => Some(0), - _ => None, - }; - let const_right = match right.map(|x| x.const_value()) { - Some(Some(ConstValue::Int(inner_value))) => { - let usize_value = inner_value.to_usize(); - if let Some(inner_value) = usize_value { - if inner_value > parent_size { - let error_span = if let Some(right) = right { - right.span().cloned().unwrap_or_default() - } else { - value.span.clone() - }; - return Err(AsgError::array_index_out_of_bounds(inner_value, &error_span).into()); - } else if let Some(left) = const_left { - if left > inner_value { - let error_span = if let Some(right) = right { - right.span().cloned().unwrap_or_default() - } else { - value.span.clone() - }; - return Err(AsgError::array_index_out_of_bounds(inner_value, &error_span).into()); - } - } - } - usize_value - } - None => Some(parent_size), - _ => None, - }; - - let mut length = if let (Some(left), Some(right)) = (const_left, const_right) { - Some(right - left) - } else { - None - }; - - if let Some(expected_len) = expected_len { - if let Some(length) = length { - if length != expected_len { - let concrete_type = Type::Array(parent_element, length); - return Err( - AsgError::unexpected_type(expected_type.as_ref().unwrap(), concrete_type, &value.span).into(), - ); - } - } - if let Some(left_value) = const_left { - if left_value + expected_len > parent_size { - let error_span = if let Some(left) = left { - left.span().cloned().unwrap_or_default() - } else { - value.span.clone() - }; - return Err(AsgError::array_index_out_of_bounds(left_value, &error_span).into()); - } - } - length = Some(expected_len); - } - if length.is_none() { - return Err(AsgError::unknown_array_size(&value.span).into()); - } - - Ok(ArrayRangeAccessExpression { - parent: Cell::new(None), - span: Some(value.span.clone()), - array: Cell::new(array), - left: Cell::new(left), - right: Cell::new(right), - length: length.unwrap(), - }) - } -} - -impl<'a> Into for &ArrayRangeAccessExpression<'a> { - fn into(self) -> leo_ast::ArrayRangeAccessExpression { - leo_ast::ArrayRangeAccessExpression { - array: Box::new(self.array.get().into()), - left: self.left.get().map(|left| Box::new(left.into())), - right: self.right.get().map(|right| Box::new(right.into())), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/expression/binary.rs b/asg/src/expression/binary.rs deleted file mode 100644 index c5b2d4ab2b..0000000000 --- a/asg/src/expression/binary.rs +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type}; -pub use leo_ast::{BinaryOperation, BinaryOperationClass}; -use leo_errors::{AsgError, Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct BinaryExpression<'a> { - pub parent: Cell>>, - pub span: Option, - pub operation: BinaryOperation, - pub left: Cell<&'a Expression<'a>>, - pub right: Cell<&'a Expression<'a>>, -} - -impl<'a> Node for BinaryExpression<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> ExpressionNode<'a> for BinaryExpression<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - self.parent.replace(Some(parent)); - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - self.parent.get() - } - - fn enforce_parents(&self, expr: &'a Expression<'a>) { - self.left.get().set_parent(expr); - self.right.get().set_parent(expr); - } - - fn get_type(&self) -> Option> { - match self.operation.class() { - BinaryOperationClass::Boolean => Some(Type::Boolean), - BinaryOperationClass::Numeric => self.left.get().get_type(), - } - } - - fn is_mut_ref(&self) -> bool { - false - } - - fn const_value(&self) -> Option { - use BinaryOperation::*; - let left = self.left.get().const_value()?; - let right = self.right.get().const_value()?; - - match (left, right) { - (ConstValue::Int(left), ConstValue::Int(right)) => Some(match self.operation { - Add => ConstValue::Int(left.value_add(&right)?), - Sub => ConstValue::Int(left.value_sub(&right)?), - Mul => ConstValue::Int(left.value_mul(&right)?), - Div => ConstValue::Int(left.value_div(&right)?), - Pow => ConstValue::Int(left.value_pow(&right)?), - Eq => ConstValue::Boolean(left == right), - Ne => ConstValue::Boolean(left != right), - Ge => ConstValue::Boolean(left.value_ge(&right)?), - Gt => ConstValue::Boolean(left.value_gt(&right)?), - Le => ConstValue::Boolean(left.value_le(&right)?), - Lt => ConstValue::Boolean(left.value_lt(&right)?), - _ => return None, - }), - // (ConstValue::Field(left), ConstValue::Field(right)) => { - // Some(match self.operation { - // Add => ConstValue::Field(left.checked_add(&right)?), - // Sub => ConstValue::Field(left.checked_sub(&right)?), - // Mul => ConstValue::Field(left.checked_mul(&right)?), - // Div => ConstValue::Field(left.checked_div(&right)?), - // Eq => ConstValue::Boolean(left == right), - // Ne => ConstValue::Boolean(left != right), - // _ => return None, - // }) - // }, - (ConstValue::Boolean(left), ConstValue::Boolean(right)) => Some(match self.operation { - Eq => ConstValue::Boolean(left == right), - Ne => ConstValue::Boolean(left != right), - And => ConstValue::Boolean(left && right), - Or => ConstValue::Boolean(left || right), - _ => return None, - }), - //todo: group? - (left, right) => Some(match self.operation { - Eq => ConstValue::Boolean(left == right), - Ne => ConstValue::Boolean(left != right), - _ => return None, - }), - } - } - - fn is_consty(&self) -> bool { - self.left.get().is_consty() && self.right.get().is_consty() - } -} - -impl<'a> FromAst<'a, leo_ast::BinaryExpression> for BinaryExpression<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::BinaryExpression, - expected_type: Option>, - ) -> Result> { - let class = value.op.class(); - let expected_type = match class { - BinaryOperationClass::Boolean => match expected_type { - Some(PartialType::Type(Type::Boolean)) | None => None, - Some(x) => { - return Err(AsgError::unexpected_type(Type::Boolean, x, &value.span).into()); - } - }, - BinaryOperationClass::Numeric => match expected_type { - Some(x @ PartialType::Integer(_, _)) => Some(x), - Some(x @ PartialType::Type(Type::Field)) => Some(x), - Some(x @ PartialType::Type(Type::Group)) => Some(x), - Some(x) => { - return Err(AsgError::unexpected_type("integer, field, or group", x, &value.span).into()); - } - None => None, - }, - }; - - // left - let (left, right) = match <&Expression<'a>>::from_ast(scope, &*value.left, expected_type.clone()) { - Ok(left) => { - if let Some(left_type) = left.get_type() { - let right = <&Expression<'a>>::from_ast(scope, &*value.right, Some(left_type.partial()))?; - (left, right) - } else { - let right = <&Expression<'a>>::from_ast(scope, &*value.right, expected_type)?; - if let Some(right_type) = right.get_type() { - ( - <&Expression<'a>>::from_ast(scope, &*value.left, Some(right_type.partial()))?, - right, - ) - } else { - (left, right) - } - } - } - Err(e) => { - let right = <&Expression<'a>>::from_ast(scope, &*value.right, expected_type)?; - if let Some(right_type) = right.get_type() { - ( - <&Expression<'a>>::from_ast(scope, &*value.left, Some(right_type.partial()))?, - right, - ) - } else { - return Err(e); - } - } - }; - - let left_type = left.get_type(); - #[allow(clippy::unused_unit)] - match class { - BinaryOperationClass::Numeric => match left_type { - Some(Type::Integer(_)) => (), - Some(Type::Group) | Some(Type::Field) - if value.op == BinaryOperation::Add || value.op == BinaryOperation::Sub => - { - () - } - Some(Type::Field) if value.op == BinaryOperation::Mul || value.op == BinaryOperation::Div => (), - type_ => { - return Err(AsgError::unexpected_type( - "integer", - type_.map(|x| x.to_string()).unwrap_or_else(|| "unknown".to_string()), - &value.span, - ) - .into()); - } - }, - BinaryOperationClass::Boolean => match &value.op { - BinaryOperation::And | BinaryOperation::Or => match left_type { - Some(Type::Boolean) | None => (), - Some(x) => { - return Err(AsgError::unexpected_type(Type::Boolean, x, &value.span).into()); - } - }, - BinaryOperation::Eq | BinaryOperation::Ne => (), // all types allowed - op => match left_type { - Some(Type::Integer(_)) | None => (), - Some(x) => { - return Err( - AsgError::operator_allowed_only_for_type(op.as_ref(), "integer", x, &value.span).into(), - ); - } - }, - }, - } - - let right_type = right.get_type(); - - match (left_type, right_type) { - (Some(left_type), Some(right_type)) => { - if !left_type.is_assignable_from(&right_type) { - return Err(AsgError::unexpected_type(left_type, right_type, &value.span).into()); - } - } - (None, None) => { - return Err(AsgError::unexpected_type("any type", "unknown type", &value.span).into()); - } - (_, _) => (), - } - Ok(BinaryExpression { - parent: Cell::new(None), - span: Some(value.span.clone()), - operation: value.op.clone(), - left: Cell::new(left), - right: Cell::new(right), - }) - } -} - -impl<'a> Into for &BinaryExpression<'a> { - fn into(self) -> leo_ast::BinaryExpression { - leo_ast::BinaryExpression { - op: self.operation.clone(), - left: Box::new(self.left.get().into()), - right: Box::new(self.right.get().into()), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/expression/call.rs b/asg/src/expression/call.rs deleted file mode 100644 index 1ffee942d7..0000000000 --- a/asg/src/expression/call.rs +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ - CircuitMember, ConstValue, Expression, ExpressionNode, FromAst, Function, FunctionQualifier, Node, PartialType, - Scope, Type, -}; -pub use leo_ast::{BinaryOperation, Node as AstNode}; -use leo_errors::{AsgError, Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct CallExpression<'a> { - pub parent: Cell>>, - pub span: Option, - pub function: Cell<&'a Function<'a>>, - pub target: Cell>>, - pub arguments: Vec>>, -} - -impl<'a> Node for CallExpression<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> ExpressionNode<'a> for CallExpression<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - self.parent.replace(Some(parent)); - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - self.parent.get() - } - - fn enforce_parents(&self, expr: &'a Expression<'a>) { - if let Some(target) = self.target.get() { - target.set_parent(expr); - } - self.arguments.iter().for_each(|element| { - element.get().set_parent(expr); - }) - } - - fn get_type(&self) -> Option> { - Some(self.function.get().output.clone()) - } - - fn is_mut_ref(&self) -> bool { - true - } - - fn const_value(&self) -> Option { - // static function const evaluation - None - } - - fn is_consty(&self) -> bool { - self.target.get().map(|x| x.is_consty()).unwrap_or(true) && self.arguments.iter().all(|x| x.get().is_consty()) - } -} - -impl<'a> FromAst<'a, leo_ast::CallExpression> for CallExpression<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::CallExpression, - expected_type: Option>, - ) -> Result> { - let (target, function) = match &*value.function { - leo_ast::Expression::Identifier(name) => ( - None, - scope - .resolve_function(&name.name) - .ok_or_else(|| AsgError::unresolved_function(&name.name, &name.span))?, - ), - leo_ast::Expression::CircuitMemberAccess(leo_ast::CircuitMemberAccessExpression { - circuit: ast_circuit, - name, - span, - .. - }) => { - let target = <&Expression<'a>>::from_ast(scope, &**ast_circuit, None)?; - let circuit = match target.get_type() { - Some(Type::Circuit(circuit)) => circuit, - type_ => { - return Err(AsgError::unexpected_type( - "circuit", - type_.map(|x| x.to_string()).unwrap_or_else(|| "unknown".to_string()), - span, - ) - .into()); - } - }; - let circuit_name = circuit.name.borrow().name.clone(); - let member = circuit.members.borrow(); - let member = member - .get(name.name.as_ref()) - .ok_or_else(|| AsgError::unresolved_circuit_member(&circuit_name, &name.name, span))?; - match member { - CircuitMember::Function(body) => { - if body.qualifier == FunctionQualifier::Static { - return Err(AsgError::circuit_static_call_invalid(&circuit_name, &name.name, span).into()); - } else if body.qualifier == FunctionQualifier::MutSelfRef && !target.is_mut_ref() { - return Err( - AsgError::circuit_member_mut_call_invalid(circuit_name, &name.name, span).into(), - ); - } - (Some(target), *body) - } - CircuitMember::Variable(_) => { - return Err(AsgError::circuit_variable_call(circuit_name, &name.name, span).into()); - } - } - } - leo_ast::Expression::CircuitStaticFunctionAccess(leo_ast::CircuitStaticFunctionAccessExpression { - circuit: ast_circuit, - name, - span, - }) => { - let circuit = if let leo_ast::Expression::Identifier(circuit_name) = &**ast_circuit { - scope - .resolve_circuit(&circuit_name.name) - .ok_or_else(|| AsgError::unresolved_circuit(&circuit_name.name, &circuit_name.span))? - } else { - return Err(AsgError::unexpected_type("circuit", "unknown", span).into()); - }; - let circuit_name = circuit.name.borrow().name.clone(); - - let member = circuit.members.borrow(); - let member = member - .get(name.name.as_ref()) - .ok_or_else(|| AsgError::unresolved_circuit_member(&circuit_name, &name.name, span))?; - match member { - CircuitMember::Function(body) => { - if body.qualifier != FunctionQualifier::Static { - return Err(AsgError::circuit_member_call_invalid(circuit_name, &name.name, span).into()); - } - (None, *body) - } - CircuitMember::Variable(_) => { - return Err(AsgError::circuit_variable_call(circuit_name, &name.name, span).into()); - } - } - } - _ => { - return Err(AsgError::illegal_ast_structure( - "non Identifier/CircuitMemberAccess/CircuitStaticFunctionAccess as call target", - &value.span, - ) - .into()); - } - }; - if let Some(expected) = expected_type { - let output: Type = function.output.clone(); - if !expected.matches(&output) { - return Err(AsgError::unexpected_type(expected, output, &value.span).into()); - } - } - if value.arguments.len() != function.arguments.len() { - return Err(AsgError::unexpected_call_argument_count( - function.arguments.len(), - value.arguments.len(), - &value.span, - ) - .into()); - } - - let arguments = value - .arguments - .iter() - .zip(function.arguments.iter()) - .map(|(expr, (_, argument))| { - let argument = argument.get().borrow(); - let converted = <&Expression<'a>>::from_ast(scope, expr, Some(argument.type_.clone().partial()))?; - if argument.const_ && !converted.is_consty() { - return Err(AsgError::unexpected_nonconst(expr.span()).into()); - } - Ok(Cell::new(converted)) - }) - .collect::>>()?; - - if function.is_test() { - return Err(AsgError::call_test_function(&value.span).into()); - } - Ok(CallExpression { - parent: Cell::new(None), - span: Some(value.span.clone()), - arguments, - function: Cell::new(function), - target: Cell::new(target), - }) - } -} - -impl<'a> Into for &CallExpression<'a> { - fn into(self) -> leo_ast::CallExpression { - let target_function = if let Some(target) = self.target.get() { - target.into() - } else { - let circuit = self.function.get().circuit.get(); - if let Some(circuit) = circuit { - leo_ast::Expression::CircuitStaticFunctionAccess(leo_ast::CircuitStaticFunctionAccessExpression { - circuit: Box::new(leo_ast::Expression::Identifier(circuit.name.borrow().clone())), - name: self.function.get().name.borrow().clone(), - span: self.span.clone().unwrap_or_default(), - }) - } else { - leo_ast::Expression::Identifier(self.function.get().name.borrow().clone()) - } - }; - leo_ast::CallExpression { - function: Box::new(target_function), - arguments: self.arguments.iter().map(|arg| arg.get().into()).collect(), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/expression/cast.rs b/asg/src/expression/cast.rs deleted file mode 100644 index 3f2765ba5a..0000000000 --- a/asg/src/expression/cast.rs +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type}; -pub use leo_ast::UnaryOperation; -use leo_errors::{AsgError, Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct CastExpression<'a> { - pub parent: Cell>>, - pub span: Option, - pub inner: Cell<&'a Expression<'a>>, - pub target_type: Type<'a>, -} - -impl<'a> Node for CastExpression<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> ExpressionNode<'a> for CastExpression<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - self.parent.replace(Some(parent)); - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - self.parent.get() - } - - fn enforce_parents(&self, expr: &'a Expression<'a>) { - self.inner.get().set_parent(expr); - } - - fn get_type(&self) -> Option> { - Some(self.target_type.clone()) - } - - fn is_mut_ref(&self) -> bool { - false - } - - fn const_value(&self) -> Option { - let value = self.inner.get().const_value()?; - match value { - ConstValue::Int(int) => match &self.target_type { - Type::Integer(target) => Some(ConstValue::Int(int.cast_to(target))), - _ => None, - }, - _ => None, - } - } - - fn is_consty(&self) -> bool { - self.inner.get().is_consty() - } -} - -impl<'a> FromAst<'a, leo_ast::CastExpression> for CastExpression<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::CastExpression, - expected_type: Option>, - ) -> Result> { - let target_type = scope.resolve_ast_type(&value.target_type, &value.span)?; - if let Some(expected_type) = &expected_type { - if !expected_type.matches(&target_type) { - return Err(AsgError::unexpected_type(expected_type, target_type, &value.span).into()); - } - } - - let inner = <&Expression<'a>>::from_ast(scope, &*value.inner, None)?; - - Ok(CastExpression { - parent: Cell::new(None), - span: Some(value.span.clone()), - inner: Cell::new(inner), - target_type, - }) - } -} - -impl<'a> Into for &CastExpression<'a> { - fn into(self) -> leo_ast::CastExpression { - leo_ast::CastExpression { - target_type: (&self.target_type).into(), - inner: Box::new(self.inner.get().into()), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/expression/circuit_access.rs b/asg/src/expression/circuit_access.rs deleted file mode 100644 index 9003a4cca0..0000000000 --- a/asg/src/expression/circuit_access.rs +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ - Circuit, CircuitMember, ConstValue, Expression, ExpressionNode, FromAst, Identifier, Node, PartialType, Scope, Type, -}; - -use leo_errors::{AsgError, Result, Span}; -use std::cell::Cell; - -#[derive(Clone)] -pub struct CircuitAccessExpression<'a> { - pub parent: Cell>>, - pub span: Option, - pub circuit: Cell<&'a Circuit<'a>>, - pub target: Cell>>, - pub member: Identifier, -} - -impl<'a> Node for CircuitAccessExpression<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> ExpressionNode<'a> for CircuitAccessExpression<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - self.parent.replace(Some(parent)); - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - self.parent.get() - } - - fn enforce_parents(&self, expr: &'a Expression<'a>) { - if let Some(target) = self.target.get() { - target.set_parent(expr); - } - } - - fn get_type(&self) -> Option> { - if self.target.get().is_none() { - None // function target only for static - } else { - let members = self.circuit.get().members.borrow(); - let member = members.get(self.member.name.as_ref())?; - match member { - CircuitMember::Variable(type_) => Some(type_.clone()), - CircuitMember::Function(_) => None, - } - } - } - - fn is_mut_ref(&self) -> bool { - if let Some(target) = self.target.get() { - target.is_mut_ref() - } else { - false - } - } - - fn const_value(&self) -> Option> { - match self.target.get()?.const_value()? { - ConstValue::Circuit(_, members) => { - let (_, const_value) = members.get(&self.member.name.to_string())?.clone(); - Some(const_value) - } - _ => None, - } - } - - fn is_consty(&self) -> bool { - self.target.get().map(|x| x.is_consty()).unwrap_or(true) - } -} - -impl<'a> FromAst<'a, leo_ast::CircuitMemberAccessExpression> for CircuitAccessExpression<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::CircuitMemberAccessExpression, - expected_type: Option>, - ) -> Result> { - let target = <&'a Expression<'a>>::from_ast(scope, &*value.circuit, None)?; - let circuit = match target.get_type() { - Some(Type::Circuit(circuit)) => circuit, - x => { - return Err(AsgError::unexpected_type( - "circuit", - x.map(|x| x.to_string()).unwrap_or_else(|| "unknown".to_string()), - &value.span, - ) - .into()); - } - }; - - // scoping refcell reference - let found_member = { - if let Some(member) = circuit.members.borrow().get(value.name.name.as_ref()) { - if let Some(expected_type) = &expected_type { - if let CircuitMember::Variable(type_) = &member { - let type_: Type = type_.clone(); - if !expected_type.matches(&type_) { - return Err(AsgError::unexpected_type(expected_type, type_, &value.span).into()); - } - } // used by call expression - } - true - } else { - false - } - }; - - if found_member { - // skip - } else if circuit.is_input_pseudo_circuit() { - // add new member to implicit input - if let Some(expected_type) = expected_type.map(PartialType::full).flatten() { - circuit.members.borrow_mut().insert( - value.name.name.to_string(), - CircuitMember::Variable(expected_type.clone()), - ); - } else { - return Err( - AsgError::input_ref_needs_type(&circuit.name.borrow().name, &value.name.name, &value.span).into(), - ); - } - } else { - return Err(AsgError::unresolved_circuit_member( - &circuit.name.borrow().name, - &value.name.name, - &value.span, - ) - .into()); - } - - Ok(CircuitAccessExpression { - parent: Cell::new(None), - span: Some(value.span.clone()), - target: Cell::new(Some(target)), - circuit: Cell::new(circuit), - member: value.name.clone(), - }) - } -} - -impl<'a> FromAst<'a, leo_ast::CircuitStaticFunctionAccessExpression> for CircuitAccessExpression<'a> { - fn from_ast( - scope: &Scope<'a>, - value: &leo_ast::CircuitStaticFunctionAccessExpression, - expected_type: Option, - ) -> Result> { - let circuit = match &*value.circuit { - leo_ast::Expression::Identifier(name) => scope - .resolve_circuit(&name.name) - .ok_or_else(|| AsgError::unresolved_circuit(&name.name, &name.span))?, - _ => { - return Err(AsgError::unexpected_type("circuit", "unknown", &value.span).into()); - } - }; - - if let Some(expected_type) = expected_type { - return Err(AsgError::unexpected_type("none", expected_type, &value.span).into()); - } - - if let Some(CircuitMember::Function(_)) = circuit.members.borrow().get(value.name.name.as_ref()) { - // okay - } else { - return Err(AsgError::unresolved_circuit_member( - &circuit.name.borrow().name, - &value.name.name, - &value.span, - ) - .into()); - } - - Ok(CircuitAccessExpression { - parent: Cell::new(None), - span: Some(value.span.clone()), - target: Cell::new(None), - circuit: Cell::new(circuit), - member: value.name.clone(), - }) - } -} - -impl<'a> Into for &CircuitAccessExpression<'a> { - fn into(self) -> leo_ast::Expression { - if let Some(target) = self.target.get() { - leo_ast::Expression::CircuitMemberAccess(leo_ast::CircuitMemberAccessExpression { - circuit: Box::new(target.into()), - name: self.member.clone(), - span: self.span.clone().unwrap_or_default(), - type_: None, - }) - } else { - leo_ast::Expression::CircuitStaticFunctionAccess(leo_ast::CircuitStaticFunctionAccessExpression { - circuit: Box::new(leo_ast::Expression::Identifier( - self.circuit.get().name.borrow().clone(), - )), - name: self.member.clone(), - span: self.span.clone().unwrap_or_default(), - }) - } - } -} diff --git a/asg/src/expression/circuit_init.rs b/asg/src/expression/circuit_init.rs deleted file mode 100644 index 0223047839..0000000000 --- a/asg/src/expression/circuit_init.rs +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ - Circuit, CircuitMember, ConstValue, Expression, ExpressionNode, FromAst, Identifier, Node, PartialType, Scope, Type, -}; - -use leo_errors::{AsgError, Result, Span}; - -use indexmap::{IndexMap, IndexSet}; -use std::cell::Cell; - -#[derive(Clone)] -pub struct CircuitInitExpression<'a> { - pub parent: Cell>>, - pub span: Option, - pub circuit: Cell<&'a Circuit<'a>>, - pub values: Vec<(Identifier, Cell<&'a Expression<'a>>)>, -} - -impl<'a> Node for CircuitInitExpression<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> ExpressionNode<'a> for CircuitInitExpression<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - self.parent.replace(Some(parent)); - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - self.parent.get() - } - - fn enforce_parents(&self, expr: &'a Expression<'a>) { - self.values.iter().for_each(|(_, element)| { - element.get().set_parent(expr); - }) - } - - fn get_type(&self) -> Option> { - Some(Type::Circuit(self.circuit.get())) - } - - fn is_mut_ref(&self) -> bool { - true - } - - fn const_value(&self) -> Option> { - let mut members = IndexMap::new(); - for (identifier, member) in self.values.iter() { - // insert by name because accessmembers identifiers are different. - members.insert( - identifier.name.to_string(), - (identifier.clone(), member.get().const_value()?), - ); - } - // Store circuit as well for get_type. - Some(ConstValue::Circuit(self.circuit.get(), members)) - } - - fn is_consty(&self) -> bool { - self.values.iter().all(|(_, value)| value.get().is_consty()) - } -} - -impl<'a> FromAst<'a, leo_ast::CircuitInitExpression> for CircuitInitExpression<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::CircuitInitExpression, - expected_type: Option>, - ) -> Result> { - let circuit = scope - .resolve_circuit(&value.name.name) - .ok_or_else(|| AsgError::unresolved_circuit(&value.name.name, &value.name.span))?; - match expected_type { - Some(PartialType::Type(Type::Circuit(expected_circuit))) if expected_circuit == circuit => (), - None => (), - Some(x) => { - return Err(AsgError::unexpected_type(x, circuit.name.borrow().name.to_string(), &value.span).into()); - } - } - let members: IndexMap<&str, (&Identifier, Option<&leo_ast::Expression>)> = value - .members - .iter() - .map(|x| (x.identifier.name.as_ref(), (&x.identifier, x.expression.as_ref()))) - .collect(); - - let mut values: Vec<(Identifier, Cell<&'a Expression<'a>>)> = vec![]; - let mut defined_variables = IndexSet::::new(); - - { - let circuit_members = circuit.members.borrow(); - for (name, member) in circuit_members.iter() { - if defined_variables.contains(name) { - return Err( - AsgError::overridden_circuit_member(&circuit.name.borrow().name, name, &value.span).into(), - ); - } - defined_variables.insert(name.clone()); - let type_: Type = if let CircuitMember::Variable(type_) = &member { - type_.clone() - } else { - continue; - }; - if let Some((identifier, receiver)) = members.get(&**name) { - let received = if let Some(receiver) = *receiver { - <&Expression<'a>>::from_ast(scope, receiver, Some(type_.partial()))? - } else { - <&Expression<'a>>::from_ast( - scope, - &leo_ast::Expression::Identifier((*identifier).clone()), - Some(type_.partial()), - )? - }; - values.push(((*identifier).clone(), Cell::new(received))); - } else { - return Err( - AsgError::missing_circuit_member(&circuit.name.borrow().name, name, &value.span).into(), - ); - } - } - - for (name, (identifier, _expression)) in members.iter() { - if circuit_members.get(*name).is_none() { - return Err( - AsgError::extra_circuit_member(&circuit.name.borrow().name, name, &identifier.span).into(), - ); - } - } - } - - Ok(CircuitInitExpression { - parent: Cell::new(None), - span: Some(value.span.clone()), - circuit: Cell::new(circuit), - values, - }) - } -} - -impl<'a> Into for &CircuitInitExpression<'a> { - fn into(self) -> leo_ast::CircuitInitExpression { - leo_ast::CircuitInitExpression { - name: self.circuit.get().name.borrow().clone(), - members: self - .values - .iter() - .map(|(name, value)| leo_ast::CircuitImpliedVariableDefinition { - identifier: name.clone(), - expression: Some(value.get().into()), - }) - .collect(), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/expression/constant.rs b/asg/src/expression/constant.rs deleted file mode 100644 index acdef6c076..0000000000 --- a/asg/src/expression/constant.rs +++ /dev/null @@ -1,241 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ - CharValue, ConstInt, ConstValue, Expression, ExpressionNode, FromAst, GroupValue, Node, PartialType, Scope, Type, -}; - -use leo_errors::{AsgError, Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct Constant<'a> { - pub parent: Cell>>, - pub span: Option, - pub value: ConstValue<'a>, // should not be compound constants -} - -impl<'a> Node for Constant<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> ExpressionNode<'a> for Constant<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - self.parent.replace(Some(parent)); - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - self.parent.get() - } - - fn enforce_parents(&self, _expr: &'a Expression<'a>) {} - - fn get_type(&'a self) -> Option> { - self.value.get_type() - } - - fn is_mut_ref(&self) -> bool { - false - } - - fn const_value(&self) -> Option> { - Some(self.value.clone()) - } - - fn is_consty(&self) -> bool { - true - } -} - -impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> { - fn from_ast( - _scope: &'a Scope<'a>, - value: &leo_ast::ValueExpression, - expected_type: Option>, - ) -> Result> { - use leo_ast::ValueExpression::*; - Ok(match value { - Address(value, span) => { - match expected_type.map(PartialType::full).flatten() { - Some(Type::Address) | None => (), - Some(x) => { - return Err(AsgError::unexpected_type(x, Type::Address, span).into()); - } - } - Constant { - parent: Cell::new(None), - span: Some(span.clone()), - value: ConstValue::Address(value.clone()), - } - } - Boolean(value, span) => { - match expected_type.map(PartialType::full).flatten() { - Some(Type::Boolean) | None => (), - Some(x) => { - return Err(AsgError::unexpected_type(x, Type::Boolean, span).into()); - } - } - Constant { - parent: Cell::new(None), - span: Some(span.clone()), - value: ConstValue::Boolean( - value - .parse::() - .map_err(|_| AsgError::invalid_boolean(value, span))?, - ), - } - } - Char(value) => { - match expected_type.map(PartialType::full).flatten() { - Some(Type::Char) | None => (), - Some(x) => { - return Err(AsgError::unexpected_type(x, Type::Char, value.span()).into()); - } - } - - Constant { - parent: Cell::new(None), - span: Some(value.span().clone()), - value: ConstValue::Char(CharValue::from(value.clone())), - } - } - Field(value, span) => { - match expected_type.map(PartialType::full).flatten() { - Some(Type::Field) | None => (), - Some(x) => { - return Err(AsgError::unexpected_type(x, Type::Field, span).into()); - } - } - Constant { - parent: Cell::new(None), - span: Some(span.clone()), - value: ConstValue::Field(value.parse().map_err(|_| AsgError::invalid_int(value, span))?), - } - } - Group(value) => { - match expected_type.map(PartialType::full).flatten() { - Some(Type::Group) | None => (), - Some(x) => { - return Err(AsgError::unexpected_type(x, Type::Group, value.span()).into()); - } - } - Constant { - parent: Cell::new(None), - span: Some(value.span().clone()), - value: ConstValue::Group(match &**value { - leo_ast::GroupValue::Single(value, _) => GroupValue::Single(value.clone()), - leo_ast::GroupValue::Tuple(leo_ast::GroupTuple { x, y, .. }) => { - GroupValue::Tuple(x.into(), y.into()) - } - }), - } - } - Implicit(value, span) => match expected_type { - None => return Err(AsgError::unresolved_type("unknown", span).into()), - Some(PartialType::Integer(Some(sub_type), _)) | Some(PartialType::Integer(None, Some(sub_type))) => { - Constant { - parent: Cell::new(None), - span: Some(span.clone()), - value: ConstValue::Int(ConstInt::parse(&sub_type, value, span)?), - } - } - Some(PartialType::Type(Type::Field)) => Constant { - parent: Cell::new(None), - span: Some(span.clone()), - value: ConstValue::Field(value.parse().map_err(|_| AsgError::invalid_int(value, span))?), - }, - Some(PartialType::Type(Type::Group)) => Constant { - parent: Cell::new(None), - span: Some(span.clone()), - value: ConstValue::Group(GroupValue::Single(value.clone())), - }, - Some(PartialType::Type(Type::Address)) => Constant { - parent: Cell::new(None), - span: Some(span.clone()), - value: ConstValue::Address(value.clone()), - }, - Some(x) => { - return Err(AsgError::unexpected_type(x, "unknown", span).into()); - } - }, - Integer(int_type, value, span) => { - match expected_type { - Some(PartialType::Integer(Some(sub_type), _)) if &sub_type == int_type => (), - Some(PartialType::Integer(None, Some(_))) => (), - None => (), - Some(x) => { - return Err(AsgError::unexpected_type(x, int_type, span).into()); - } - } - Constant { - parent: Cell::new(None), - span: Some(span.clone()), - value: ConstValue::Int(ConstInt::parse(int_type, value, span)?), - } - } - String(_str_type, _value) => { - unimplemented!("strings do not exist on ASG level") - } - }) - } -} - -impl<'a> Into for &Constant<'a> { - fn into(self) -> leo_ast::ValueExpression { - match &self.value { - ConstValue::Address(value) => { - leo_ast::ValueExpression::Address(value.clone(), self.span.clone().unwrap_or_default()) - } - ConstValue::Boolean(value) => { - leo_ast::ValueExpression::Boolean(value.to_string().into(), self.span.clone().unwrap_or_default()) - } - ConstValue::Char(value) => match value { - CharValue::Scalar(scalar) => leo_ast::ValueExpression::Char(leo_ast::CharValue { - character: leo_ast::Char::Scalar(*scalar), - span: self.span.clone().unwrap_or_default(), - }), - CharValue::NonScalar(non_scalar) => leo_ast::ValueExpression::Char(leo_ast::CharValue { - character: leo_ast::Char::NonScalar(*non_scalar), - span: self.span.clone().unwrap_or_default(), - }), - }, - ConstValue::Field(value) => { - leo_ast::ValueExpression::Field(value.to_string().into(), self.span.clone().unwrap_or_default()) - } - ConstValue::Group(value) => leo_ast::ValueExpression::Group(Box::new(match value { - GroupValue::Single(single) => { - leo_ast::GroupValue::Single(single.clone(), self.span.clone().unwrap_or_default()) - } - GroupValue::Tuple(left, right) => leo_ast::GroupValue::Tuple(leo_ast::GroupTuple { - x: left.into(), - y: right.into(), - span: self.span.clone().unwrap_or_default(), - }), - })), - ConstValue::Int(int) => leo_ast::ValueExpression::Integer( - int.get_int_type(), - int.raw_value().into(), - self.span.clone().unwrap_or_default(), - ), - ConstValue::Tuple(_) => unimplemented!(), - ConstValue::Array(_) => unimplemented!(), - ConstValue::Circuit(_, _) => unimplemented!(), - } - } -} diff --git a/asg/src/expression/lengthof.rs b/asg/src/expression/lengthof.rs deleted file mode 100644 index ee8c883ebb..0000000000 --- a/asg/src/expression/lengthof.rs +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ConstValue, Expression, ExpressionNode, FromAst, IntegerType, Node, PartialType, Scope, Type}; -pub use leo_ast::UnaryOperation; -use leo_errors::{Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct LengthOfExpression<'a> { - pub parent: Cell>>, - pub span: Option, - pub inner: Cell<&'a Expression<'a>>, -} - -impl<'a> Node for LengthOfExpression<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> ExpressionNode<'a> for LengthOfExpression<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - self.parent.replace(Some(parent)); - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - self.parent.get() - } - - fn enforce_parents(&self, expr: &'a Expression<'a>) { - self.inner.get().set_parent(expr); - } - - fn get_type(&self) -> Option> { - Some(Type::Integer(IntegerType::U32)) // For now we stick to U32 value type - } - - fn is_mut_ref(&self) -> bool { - false - } - - fn const_value(&self) -> Option { - None - } - - fn is_consty(&self) -> bool { - true - } -} - -impl<'a> FromAst<'a, leo_ast::LengthOfExpression> for LengthOfExpression<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::LengthOfExpression, - _expected_type: Option>, - ) -> Result> { - let inner = <&Expression<'a>>::from_ast(scope, &*value.inner, None)?; - - Ok(LengthOfExpression { - parent: Cell::new(None), - span: Some(value.span.clone()), - inner: Cell::new(inner), - }) - } -} - -impl<'a> Into for &LengthOfExpression<'a> { - fn into(self) -> leo_ast::LengthOfExpression { - leo_ast::LengthOfExpression { - inner: Box::new(self.inner.get().into()), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/expression/mod.rs b/asg/src/expression/mod.rs deleted file mode 100644 index 734b227344..0000000000 --- a/asg/src/expression/mod.rs +++ /dev/null @@ -1,388 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! This module defines an expression node in an asg. -//! -//! Notable differences after conversion from an ast expression include: -//! 1. Storing variable references instead of variable identifiers - better history tracking and mutability -//! 2. Resolving constant values - optimizes execution of program circuit. - -mod array_access; -pub use array_access::*; - -mod array_inline; -pub use array_inline::*; - -mod array_init; -pub use array_init::*; - -mod array_range_access; -pub use array_range_access::*; - -mod binary; -pub use binary::*; - -mod call; -pub use call::*; - -mod circuit_access; -pub use circuit_access::*; - -mod circuit_init; -pub use circuit_init::*; - -mod constant; -pub use constant::*; - -mod ternary; -pub use ternary::*; - -mod tuple_access; -pub use tuple_access::*; - -mod tuple_init; -pub use tuple_init::*; - -mod unary; -pub use unary::*; - -mod variable_ref; -pub use variable_ref::*; - -mod cast; -pub use cast::*; - -mod lengthof; -pub use lengthof::*; - -use crate::{ConstValue, FromAst, Node, PartialType, Scope, Type}; -use leo_errors::{Result, Span}; - -#[derive(Clone)] -pub enum Expression<'a> { - VariableRef(VariableRef<'a>), - Constant(Constant<'a>), - Binary(BinaryExpression<'a>), - Unary(UnaryExpression<'a>), - Ternary(TernaryExpression<'a>), - Cast(CastExpression<'a>), - LengthOf(LengthOfExpression<'a>), - - ArrayInline(ArrayInlineExpression<'a>), - ArrayInit(ArrayInitExpression<'a>), - ArrayAccess(ArrayAccessExpression<'a>), - ArrayRangeAccess(ArrayRangeAccessExpression<'a>), - - TupleInit(TupleInitExpression<'a>), - TupleAccess(TupleAccessExpression<'a>), - - CircuitInit(CircuitInitExpression<'a>), - CircuitAccess(CircuitAccessExpression<'a>), - - Call(CallExpression<'a>), -} - -impl<'a> Expression<'a> { - pub fn ptr_eq(&self, other: &Expression<'a>) -> bool { - std::ptr::eq(self as *const Expression<'a>, other as *const Expression<'a>) - } -} - -impl<'a> Node for Expression<'a> { - fn span(&self) -> Option<&Span> { - use Expression::*; - match self { - VariableRef(x) => x.span(), - Constant(x) => x.span(), - Binary(x) => x.span(), - Unary(x) => x.span(), - Ternary(x) => x.span(), - Cast(x) => x.span(), - LengthOf(x) => x.span(), - ArrayInline(x) => x.span(), - ArrayInit(x) => x.span(), - ArrayAccess(x) => x.span(), - ArrayRangeAccess(x) => x.span(), - TupleInit(x) => x.span(), - TupleAccess(x) => x.span(), - CircuitInit(x) => x.span(), - CircuitAccess(x) => x.span(), - Call(x) => x.span(), - } - } -} - -pub trait ExpressionNode<'a>: Node { - fn set_parent(&self, parent: &'a Expression<'a>); - fn get_parent(&self) -> Option<&'a Expression<'a>>; - fn enforce_parents(&self, expr: &'a Expression<'a>); - - fn get_type(&'a self) -> Option>; - fn is_mut_ref(&self) -> bool; - fn const_value(&'a self) -> Option; // todo: memoize - fn is_consty(&self) -> bool; -} - -impl<'a> ExpressionNode<'a> for Expression<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - use Expression::*; - match self { - VariableRef(x) => x.set_parent(parent), - Constant(x) => x.set_parent(parent), - Binary(x) => x.set_parent(parent), - Unary(x) => x.set_parent(parent), - Ternary(x) => x.set_parent(parent), - Cast(x) => x.set_parent(parent), - LengthOf(x) => x.set_parent(parent), - ArrayInline(x) => x.set_parent(parent), - ArrayInit(x) => x.set_parent(parent), - ArrayAccess(x) => x.set_parent(parent), - ArrayRangeAccess(x) => x.set_parent(parent), - TupleInit(x) => x.set_parent(parent), - TupleAccess(x) => x.set_parent(parent), - CircuitInit(x) => x.set_parent(parent), - CircuitAccess(x) => x.set_parent(parent), - Call(x) => x.set_parent(parent), - } - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - use Expression::*; - match self { - VariableRef(x) => x.get_parent(), - Constant(x) => x.get_parent(), - Binary(x) => x.get_parent(), - Unary(x) => x.get_parent(), - Ternary(x) => x.get_parent(), - Cast(x) => x.get_parent(), - LengthOf(x) => x.get_parent(), - ArrayInline(x) => x.get_parent(), - ArrayInit(x) => x.get_parent(), - ArrayAccess(x) => x.get_parent(), - ArrayRangeAccess(x) => x.get_parent(), - TupleInit(x) => x.get_parent(), - TupleAccess(x) => x.get_parent(), - CircuitInit(x) => x.get_parent(), - CircuitAccess(x) => x.get_parent(), - Call(x) => x.get_parent(), - } - } - - fn enforce_parents(&self, expr: &'a Expression<'a>) { - use Expression::*; - match self { - VariableRef(x) => x.enforce_parents(expr), - Constant(x) => x.enforce_parents(expr), - Binary(x) => x.enforce_parents(expr), - Unary(x) => x.enforce_parents(expr), - Ternary(x) => x.enforce_parents(expr), - Cast(x) => x.enforce_parents(expr), - LengthOf(x) => x.enforce_parents(expr), - ArrayInline(x) => x.enforce_parents(expr), - ArrayInit(x) => x.enforce_parents(expr), - ArrayAccess(x) => x.enforce_parents(expr), - ArrayRangeAccess(x) => x.enforce_parents(expr), - TupleInit(x) => x.enforce_parents(expr), - TupleAccess(x) => x.enforce_parents(expr), - CircuitInit(x) => x.enforce_parents(expr), - CircuitAccess(x) => x.enforce_parents(expr), - Call(x) => x.enforce_parents(expr), - } - } - - fn get_type(&'a self) -> Option> { - use Expression::*; - match self { - VariableRef(x) => x.get_type(), - Constant(x) => x.get_type(), - Binary(x) => x.get_type(), - Unary(x) => x.get_type(), - Ternary(x) => x.get_type(), - Cast(x) => x.get_type(), - LengthOf(x) => x.get_type(), - ArrayInline(x) => x.get_type(), - ArrayInit(x) => x.get_type(), - ArrayAccess(x) => x.get_type(), - ArrayRangeAccess(x) => x.get_type(), - TupleInit(x) => x.get_type(), - TupleAccess(x) => x.get_type(), - CircuitInit(x) => x.get_type(), - CircuitAccess(x) => x.get_type(), - Call(x) => x.get_type(), - } - } - - fn is_mut_ref(&self) -> bool { - use Expression::*; - match self { - VariableRef(x) => x.is_mut_ref(), - Constant(x) => x.is_mut_ref(), - Binary(x) => x.is_mut_ref(), - Unary(x) => x.is_mut_ref(), - Ternary(x) => x.is_mut_ref(), - Cast(x) => x.is_mut_ref(), - LengthOf(x) => x.is_mut_ref(), - ArrayInline(x) => x.is_mut_ref(), - ArrayInit(x) => x.is_mut_ref(), - ArrayAccess(x) => x.is_mut_ref(), - ArrayRangeAccess(x) => x.is_mut_ref(), - TupleInit(x) => x.is_mut_ref(), - TupleAccess(x) => x.is_mut_ref(), - CircuitInit(x) => x.is_mut_ref(), - CircuitAccess(x) => x.is_mut_ref(), - Call(x) => x.is_mut_ref(), - } - } - - fn const_value(&'a self) -> Option> { - use Expression::*; - match self { - VariableRef(x) => x.const_value(), - Constant(x) => x.const_value(), - Binary(x) => x.const_value(), - Unary(x) => x.const_value(), - Ternary(x) => x.const_value(), - Cast(x) => x.const_value(), - LengthOf(x) => x.const_value(), - ArrayInline(x) => x.const_value(), - ArrayInit(x) => x.const_value(), - ArrayAccess(x) => x.const_value(), - ArrayRangeAccess(x) => x.const_value(), - TupleInit(x) => x.const_value(), - TupleAccess(x) => x.const_value(), - CircuitInit(x) => x.const_value(), - CircuitAccess(x) => x.const_value(), - Call(x) => x.const_value(), - } - } - - fn is_consty(&self) -> bool { - use Expression::*; - match self { - VariableRef(x) => x.is_consty(), - Constant(x) => x.is_consty(), - Binary(x) => x.is_consty(), - Unary(x) => x.is_consty(), - Ternary(x) => x.is_consty(), - Cast(x) => x.is_consty(), - LengthOf(x) => x.is_consty(), - ArrayInline(x) => x.is_consty(), - ArrayInit(x) => x.is_consty(), - ArrayAccess(x) => x.is_consty(), - ArrayRangeAccess(x) => x.is_consty(), - TupleInit(x) => x.is_consty(), - TupleAccess(x) => x.is_consty(), - CircuitInit(x) => x.is_consty(), - CircuitAccess(x) => x.is_consty(), - Call(x) => x.is_consty(), - } - } -} - -impl<'a> FromAst<'a, leo_ast::Expression> for &'a Expression<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::Expression, - expected_type: Option>, - ) -> Result { - use leo_ast::Expression::*; - let expression = match value { - Identifier(identifier) => Self::from_ast(scope, identifier, expected_type)?, - Value(value) => scope - .context - .alloc_expression(Constant::from_ast(scope, value, expected_type).map(Expression::Constant)?), - Binary(binary) => scope - .context - .alloc_expression(BinaryExpression::from_ast(scope, binary, expected_type).map(Expression::Binary)?), - Unary(unary) => scope - .context - .alloc_expression(UnaryExpression::from_ast(scope, unary, expected_type).map(Expression::Unary)?), - Ternary(conditional) => scope.context.alloc_expression( - TernaryExpression::from_ast(scope, conditional, expected_type).map(Expression::Ternary)?, - ), - Cast(cast) => scope - .context - .alloc_expression(CastExpression::from_ast(scope, cast, expected_type).map(Expression::Cast)?), - - LengthOf(lengthof) => scope.context.alloc_expression( - LengthOfExpression::from_ast(scope, lengthof, expected_type).map(Expression::LengthOf)?, - ), - - ArrayInline(array_inline) => scope.context.alloc_expression( - ArrayInlineExpression::from_ast(scope, array_inline, expected_type).map(Expression::ArrayInline)?, - ), - ArrayInit(array_init) => scope.context.alloc_expression( - ArrayInitExpression::from_ast(scope, array_init, expected_type).map(Expression::ArrayInit)?, - ), - ArrayAccess(array_access) => scope.context.alloc_expression( - ArrayAccessExpression::from_ast(scope, array_access, expected_type).map(Expression::ArrayAccess)?, - ), - ArrayRangeAccess(array_range_access) => scope.context.alloc_expression( - ArrayRangeAccessExpression::from_ast(scope, array_range_access, expected_type) - .map(Expression::ArrayRangeAccess)?, - ), - - TupleInit(tuple_init) => scope.context.alloc_expression( - TupleInitExpression::from_ast(scope, tuple_init, expected_type).map(Expression::TupleInit)?, - ), - TupleAccess(tuple_access) => scope.context.alloc_expression( - TupleAccessExpression::from_ast(scope, tuple_access, expected_type).map(Expression::TupleAccess)?, - ), - - CircuitInit(circuit_init) => scope.context.alloc_expression( - CircuitInitExpression::from_ast(scope, circuit_init, expected_type).map(Expression::CircuitInit)?, - ), - CircuitMemberAccess(circuit_member) => scope.context.alloc_expression( - CircuitAccessExpression::from_ast(scope, circuit_member, expected_type) - .map(Expression::CircuitAccess)?, - ), - CircuitStaticFunctionAccess(circuit_member) => scope.context.alloc_expression( - CircuitAccessExpression::from_ast(scope, circuit_member, expected_type) - .map(Expression::CircuitAccess)?, - ), - - Call(call) => scope - .context - .alloc_expression(CallExpression::from_ast(scope, call, expected_type).map(Expression::Call)?), - }; - expression.enforce_parents(expression); - Ok(expression) - } -} - -impl<'a> Into for &Expression<'a> { - fn into(self) -> leo_ast::Expression { - use Expression::*; - match self { - VariableRef(x) => leo_ast::Expression::Identifier(x.into()), - Constant(x) => leo_ast::Expression::Value(x.into()), - Binary(x) => leo_ast::Expression::Binary(x.into()), - Unary(x) => leo_ast::Expression::Unary(x.into()), - Ternary(x) => leo_ast::Expression::Ternary(x.into()), - Cast(x) => leo_ast::Expression::Cast(x.into()), - LengthOf(x) => leo_ast::Expression::LengthOf(x.into()), - ArrayInline(x) => leo_ast::Expression::ArrayInline(x.into()), - ArrayInit(x) => leo_ast::Expression::ArrayInit(x.into()), - ArrayAccess(x) => leo_ast::Expression::ArrayAccess(x.into()), - ArrayRangeAccess(x) => leo_ast::Expression::ArrayRangeAccess(x.into()), - TupleInit(x) => leo_ast::Expression::TupleInit(x.into()), - TupleAccess(x) => leo_ast::Expression::TupleAccess(x.into()), - CircuitInit(x) => leo_ast::Expression::CircuitInit(x.into()), - CircuitAccess(x) => x.into(), - Call(x) => leo_ast::Expression::Call(x.into()), - } - } -} diff --git a/asg/src/expression/ternary.rs b/asg/src/expression/ternary.rs deleted file mode 100644 index 4e26d254aa..0000000000 --- a/asg/src/expression/ternary.rs +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type}; -use leo_errors::{AsgError, Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct TernaryExpression<'a> { - pub parent: Cell>>, - pub span: Option, - pub condition: Cell<&'a Expression<'a>>, - pub if_true: Cell<&'a Expression<'a>>, - pub if_false: Cell<&'a Expression<'a>>, -} - -impl<'a> Node for TernaryExpression<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> ExpressionNode<'a> for TernaryExpression<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - self.parent.replace(Some(parent)); - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - self.parent.get() - } - - fn enforce_parents(&self, expr: &'a Expression<'a>) { - self.condition.get().set_parent(expr); - self.if_true.get().set_parent(expr); - self.if_false.get().set_parent(expr); - } - - fn get_type(&self) -> Option> { - self.if_true.get().get_type() - } - - fn is_mut_ref(&self) -> bool { - self.if_true.get().is_mut_ref() && self.if_false.get().is_mut_ref() - } - - fn const_value(&self) -> Option> { - if let Some(ConstValue::Boolean(switch)) = self.condition.get().const_value() { - if switch { - self.if_true.get().const_value() - } else { - self.if_false.get().const_value() - } - } else { - None - } - } - - fn is_consty(&self) -> bool { - self.condition.get().is_consty() && self.if_true.get().is_consty() && self.if_false.get().is_consty() - } -} - -impl<'a> FromAst<'a, leo_ast::TernaryExpression> for TernaryExpression<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::TernaryExpression, - expected_type: Option>, - ) -> Result> { - let if_true = Cell::new(<&Expression<'a>>::from_ast( - scope, - &*value.if_true, - expected_type.clone(), - )?); - let left: PartialType = if_true.get().get_type().unwrap().into(); - - let if_false = if expected_type.is_none() { - Cell::new(<&Expression<'a>>::from_ast( - scope, - &*value.if_false, - Some(left.clone()), - )?) - } else { - Cell::new(<&Expression<'a>>::from_ast(scope, &*value.if_false, expected_type)?) - }; - let right = if_false.get().get_type().unwrap().into(); - - if left != right { - return Err(AsgError::ternary_different_types(left, right, &value.span).into()); - } - - Ok(TernaryExpression { - parent: Cell::new(None), - span: Some(value.span.clone()), - condition: Cell::new(<&Expression<'a>>::from_ast( - scope, - &*value.condition, - Some(Type::Boolean.partial()), - )?), - if_true, - if_false, - }) - } -} - -impl<'a> Into for &TernaryExpression<'a> { - fn into(self) -> leo_ast::TernaryExpression { - leo_ast::TernaryExpression { - condition: Box::new(self.condition.get().into()), - if_true: Box::new(self.if_true.get().into()), - if_false: Box::new(self.if_false.get().into()), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/expression/tuple_access.rs b/asg/src/expression/tuple_access.rs deleted file mode 100644 index 44f524aec0..0000000000 --- a/asg/src/expression/tuple_access.rs +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type}; -use leo_errors::{AsgError, Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct TupleAccessExpression<'a> { - pub parent: Cell>>, - pub span: Option, - pub tuple_ref: Cell<&'a Expression<'a>>, - pub index: usize, -} - -impl<'a> Node for TupleAccessExpression<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> ExpressionNode<'a> for TupleAccessExpression<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - self.parent.replace(Some(parent)); - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - self.parent.get() - } - - fn enforce_parents(&self, expr: &'a Expression<'a>) { - self.tuple_ref.get().set_parent(expr); - } - - fn get_type(&self) -> Option> { - match self.tuple_ref.get().get_type()? { - Type::Tuple(subtypes) => subtypes.get(self.index).cloned(), - _ => None, - } - } - - fn is_mut_ref(&self) -> bool { - self.tuple_ref.get().is_mut_ref() - } - - fn const_value(&self) -> Option> { - let tuple_const = self.tuple_ref.get().const_value()?; - match tuple_const { - ConstValue::Tuple(sub_consts) => sub_consts.get(self.index).cloned(), - _ => None, - } - } - - fn is_consty(&self) -> bool { - self.tuple_ref.get().is_consty() - } -} - -impl<'a> FromAst<'a, leo_ast::TupleAccessExpression> for TupleAccessExpression<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::TupleAccessExpression, - expected_type: Option>, - ) -> Result> { - let index = value - .index - .value - .parse::() - .map_err(|_| AsgError::parse_index_error(&value.span))?; - - let mut expected_tuple = vec![None; index + 1]; - expected_tuple[index] = expected_type; - - let tuple = <&Expression<'a>>::from_ast(scope, &*value.tuple, Some(PartialType::Tuple(expected_tuple)))?; - let tuple_type = tuple.get_type(); - if let Some(Type::Tuple(_items)) = tuple_type { - } else { - return Err(AsgError::unexpected_type( - "tuple", - tuple_type - .map(|x| x.to_string()) - .unwrap_or_else(|| "unknown".to_string()), - &value.span, - ) - .into()); - } - - Ok(TupleAccessExpression { - parent: Cell::new(None), - span: Some(value.span.clone()), - tuple_ref: Cell::new(tuple), - index, - }) - } -} - -impl<'a> Into for &TupleAccessExpression<'a> { - fn into(self) -> leo_ast::TupleAccessExpression { - leo_ast::TupleAccessExpression { - tuple: Box::new(self.tuple_ref.get().into()), - index: leo_ast::PositiveNumber { - value: self.index.to_string().into(), - }, - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/expression/tuple_init.rs b/asg/src/expression/tuple_init.rs deleted file mode 100644 index 317020f80a..0000000000 --- a/asg/src/expression/tuple_init.rs +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type}; -use leo_errors::{AsgError, Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct TupleInitExpression<'a> { - pub parent: Cell>>, - pub span: Option, - pub elements: Vec>>, -} - -impl<'a> Node for TupleInitExpression<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> ExpressionNode<'a> for TupleInitExpression<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - self.parent.replace(Some(parent)); - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - self.parent.get() - } - - fn enforce_parents(&self, expr: &'a Expression<'a>) { - self.elements.iter().for_each(|element| { - element.get().set_parent(expr); - }) - } - - fn get_type(&self) -> Option> { - let mut output = vec![]; - for element in self.elements.iter() { - output.push(element.get().get_type()?); - } - Some(Type::Tuple(output)) - } - - fn is_mut_ref(&self) -> bool { - false - } - - fn const_value(&self) -> Option> { - let mut consts = vec![]; - for element in self.elements.iter() { - if let Some(const_value) = element.get().const_value() { - consts.push(const_value); - } else { - return None; - } - } - Some(ConstValue::Tuple(consts)) - } - - fn is_consty(&self) -> bool { - self.elements.iter().all(|x| x.get().is_consty()) - } -} - -impl<'a> FromAst<'a, leo_ast::TupleInitExpression> for TupleInitExpression<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::TupleInitExpression, - expected_type: Option>, - ) -> Result> { - let tuple_types = match expected_type { - Some(PartialType::Tuple(sub_types)) => Some(sub_types), - None => None, - x => { - return Err(AsgError::unexpected_type( - "tuple", - x.map(|x| x.to_string()).unwrap_or_else(|| "unknown".to_string()), - &value.span, - ) - .into()); - } - }; - - if let Some(tuple_types) = tuple_types.as_ref() { - // Expected type can be equal or less than actual size of a tuple. - // Size of expected tuple can be based on accessed index. - if tuple_types.len() > value.elements.len() { - return Err(AsgError::unexpected_type( - format!("tuple of length {}", tuple_types.len()), - format!("tuple of length {}", value.elements.len()), - &value.span, - ) - .into()); - } - } - - let elements = value - .elements - .iter() - .enumerate() - .map(|(i, e)| { - <&Expression<'a>>::from_ast( - scope, - e, - tuple_types.as_ref().map(|x| x.get(i)).flatten().cloned().flatten(), - ) - .map(Cell::new) - }) - .collect::>>()?; - - Ok(TupleInitExpression { - parent: Cell::new(None), - span: Some(value.span.clone()), - elements, - }) - } -} - -impl<'a> Into for &TupleInitExpression<'a> { - fn into(self) -> leo_ast::TupleInitExpression { - leo_ast::TupleInitExpression { - elements: self.elements.iter().map(|e| e.get().into()).collect(), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/expression/unary.rs b/asg/src/expression/unary.rs deleted file mode 100644 index d3aad2dea0..0000000000 --- a/asg/src/expression/unary.rs +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type}; -pub use leo_ast::UnaryOperation; -use leo_errors::{AsgError, Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct UnaryExpression<'a> { - pub parent: Cell>>, - pub span: Option, - pub operation: UnaryOperation, - pub inner: Cell<&'a Expression<'a>>, -} - -impl<'a> Node for UnaryExpression<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> ExpressionNode<'a> for UnaryExpression<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - self.parent.replace(Some(parent)); - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - self.parent.get() - } - - fn enforce_parents(&self, expr: &'a Expression<'a>) { - self.inner.get().set_parent(expr); - } - - fn get_type(&self) -> Option> { - self.inner.get().get_type() - } - - fn is_mut_ref(&self) -> bool { - false - } - - fn const_value(&self) -> Option { - if let Some(inner) = self.inner.get().const_value() { - match self.operation { - UnaryOperation::Not => match inner { - ConstValue::Boolean(value) => Some(ConstValue::Boolean(!value)), - _ => None, - }, - UnaryOperation::Negate => { - match inner { - ConstValue::Int(value) => Some(ConstValue::Int(value.value_negate()?)), - // ConstValue::Group(value) => Some(ConstValue::Group(value)), TODO: groups - // ConstValue::Field(value) => Some(ConstValue::Field(-value)), - _ => None, - } - } - UnaryOperation::BitNot => match inner { - ConstValue::Int(value) => Some(ConstValue::Int(value.value_bit_negate()?)), - _ => None, - }, - } - } else { - None - } - } - - fn is_consty(&self) -> bool { - self.inner.get().is_consty() - } -} - -impl<'a> FromAst<'a, leo_ast::UnaryExpression> for UnaryExpression<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::UnaryExpression, - expected_type: Option>, - ) -> Result> { - let expected_type = match value.op { - UnaryOperation::Not => match expected_type.map(|x| x.full()).flatten() { - Some(Type::Boolean) | None => Some(Type::Boolean), - Some(type_) => { - return Err(AsgError::unexpected_type(Type::Boolean, type_, &value.span).into()); - } - }, - UnaryOperation::Negate => match expected_type.map(|x| x.full()).flatten() { - Some(type_ @ Type::Integer(_)) => Some(type_), - Some(Type::Group) => Some(Type::Group), - Some(Type::Field) => Some(Type::Field), - None => None, - Some(type_) => { - return Err(AsgError::unexpected_type("integer, group, field", type_, &value.span).into()); - } - }, - UnaryOperation::BitNot => match expected_type.map(|x| x.full()).flatten() { - Some(type_ @ Type::Integer(_)) => Some(type_), - None => None, - Some(type_) => { - return Err(AsgError::unexpected_type("integer", type_, &value.span).into()); - } - }, - }; - let expr = <&Expression<'a>>::from_ast(scope, &*value.inner, expected_type.map(Into::into))?; - - if matches!(value.op, UnaryOperation::Negate) { - let is_expr_unsigned = expr - .get_type() - .map(|x| match x { - Type::Integer(x) => !x.is_signed(), - _ => false, - }) - .unwrap_or(false); - if is_expr_unsigned { - return Err(AsgError::unsigned_negation(&value.span).into()); - } - } - Ok(UnaryExpression { - parent: Cell::new(None), - span: Some(value.span.clone()), - operation: value.op.clone(), - inner: Cell::new(expr), - }) - } -} - -impl<'a> Into for &UnaryExpression<'a> { - fn into(self) -> leo_ast::UnaryExpression { - leo_ast::UnaryExpression { - op: self.operation.clone(), - inner: Box::new(self.inner.get().into()), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/expression/variable_ref.rs b/asg/src/expression/variable_ref.rs deleted file mode 100644 index bb514fb38d..0000000000 --- a/asg/src/expression/variable_ref.rs +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ - ConstValue, Constant, DefinitionStatement, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, - Statement, Type, Variable, -}; - -use leo_errors::{AsgError, Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct VariableRef<'a> { - pub parent: Cell>>, - pub span: Option, - pub variable: &'a Variable<'a>, -} - -impl<'a> Node for VariableRef<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> ExpressionNode<'a> for VariableRef<'a> { - fn set_parent(&self, parent: &'a Expression<'a>) { - self.parent.replace(Some(parent)); - } - - fn get_parent(&self) -> Option<&'a Expression<'a>> { - self.parent.get() - } - - fn enforce_parents(&self, _expr: &'a Expression<'a>) {} - - fn get_type(&self) -> Option> { - Some(self.variable.borrow().type_.clone()) - } - - fn is_mut_ref(&self) -> bool { - self.variable.borrow().mutable - } - - // todo: we can use use hacky ssa here to catch more cases, or just enforce ssa before asg generation finished - fn const_value(&self) -> Option> { - let variable = self.variable.borrow(); - if variable.mutable || variable.assignments.len() != 1 { - return None; - } - let assignment = variable.assignments.get(0).unwrap(); - match &*assignment { - Statement::Definition(DefinitionStatement { variables, value, .. }) => { - if variables.len() == 1 { - let defined_variable = variables.get(0).unwrap().borrow(); - assert_eq!(variable.id, defined_variable.id); - - value.get().const_value() - } else { - for (i, defined_variable) in variables.iter().enumerate() { - let defined_variable = defined_variable.borrow(); - if defined_variable.id == variable.id { - match value.get().const_value() { - Some(ConstValue::Tuple(values)) => return values.get(i).cloned(), - None => return None, - _ => (), - } - } - } - panic!("no corresponding tuple variable found during const destructuring (corrupt asg?)"); - } - } - _ => None, //todo unroll loops during asg phase - } - } - - fn is_consty(&self) -> bool { - let variable = self.variable.borrow(); - if variable.const_ { - return true; - } - if variable.mutable || variable.assignments.len() != 1 { - return false; - } - let assignment = variable.assignments.get(0).unwrap(); - - match &*assignment { - Statement::Definition(DefinitionStatement { variables, value, .. }) => { - if variables.len() == 1 { - let defined_variable = variables.get(0).unwrap().borrow(); - assert_eq!(variable.id, defined_variable.id); - - value.get().is_consty() - } else { - for defined_variable in variables.iter() { - let defined_variable = defined_variable.borrow(); - if defined_variable.id == variable.id { - return value.get().is_consty(); - } - } - panic!("no corresponding tuple variable found during const destructuring (corrupt asg?)"); - } - } - Statement::Iteration(_) => true, - _ => false, - } - } -} - -impl<'a> FromAst<'a, leo_ast::Identifier> for &'a Expression<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::Identifier, - expected_type: Option>, - ) -> Result<&'a Expression<'a>> { - let variable = if value.name.as_ref() == "input" { - if let Some(input) = scope.resolve_input() { - input.container - } else { - return Err(AsgError::illegal_input_variable_reference(&value.span).into()); - } - } else if let Some(gc) = scope.resolve_global_const(&value.name) { - gc.variables - .iter() - .find(|&&v| v.borrow().name.name == value.name) - .unwrap() - } else { - match scope.resolve_variable(&value.name) { - Some(v) => v, - None => { - if value.name.starts_with("aleo1") { - return Ok(scope.context.alloc_expression(Expression::Constant(Constant { - parent: Cell::new(None), - span: Some(value.span.clone()), - value: ConstValue::Address(value.name.clone()), - }))); - } - return Err(AsgError::unresolved_reference(&value.name, &value.span).into()); - } - } - }; - - let variable_ref = VariableRef { - parent: Cell::new(None), - span: Some(value.span.clone()), - variable, - }; - let expression = scope.context.alloc_expression(Expression::VariableRef(variable_ref)); - - if let Some(expected_type) = expected_type { - let type_ = expression - .get_type() - .ok_or_else(|| AsgError::unresolved_reference(&value.name, &value.span))?; - if !expected_type.matches(&type_) { - return Err(AsgError::unexpected_type(expected_type, type_, &value.span).into()); - } - } - - let mut variable_ref = variable.borrow_mut(); - variable_ref.references.push(expression); - - Ok(expression) - } -} - -impl<'a> Into for &VariableRef<'a> { - fn into(self) -> leo_ast::Identifier { - self.variable.borrow().name.clone() - } -} diff --git a/asg/src/input.rs b/asg/src/input.rs deleted file mode 100644 index 625500ed0f..0000000000 --- a/asg/src/input.rs +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{Circuit, CircuitMember, Identifier, Scope, Type, Variable}; -use leo_errors::Span; - -use indexmap::IndexMap; -use std::cell::RefCell; - -/// Stores program input values as ASG nodes. -#[derive(Clone, Copy)] -pub struct Input<'a> { - pub registers: &'a Circuit<'a>, - pub state: &'a Circuit<'a>, - pub state_leaf: &'a Circuit<'a>, - pub record: &'a Circuit<'a>, - pub container_circuit: &'a Circuit<'a>, - pub container: &'a Variable<'a>, -} - -pub const CONTAINER_PSEUDO_CIRCUIT: &str = "$InputContainer"; -pub const REGISTERS_PSEUDO_CIRCUIT: &str = "$InputRegister"; -pub const RECORD_PSEUDO_CIRCUIT: &str = "$InputRecord"; -pub const STATE_PSEUDO_CIRCUIT: &str = "$InputState"; -pub const STATE_LEAF_PSEUDO_CIRCUIT: &str = "$InputStateLeaf"; - -impl<'a> Input<'a> { - fn make_header(scope: &'a Scope<'a>, name: &str) -> &'a Circuit<'a> { - scope.context.alloc_circuit(Circuit { - id: scope.context.get_id(), - name: RefCell::new(Identifier::new(name.into())), - members: RefCell::new(IndexMap::new()), - core_mapping: RefCell::new(None), - scope, - span: Some(Span::default()), - }) - } - - pub fn new(scope: &'a Scope<'a>) -> Self { - let input_scope = scope.make_subscope(); - let registers = Self::make_header(input_scope, REGISTERS_PSEUDO_CIRCUIT); - let record = Self::make_header(input_scope, RECORD_PSEUDO_CIRCUIT); - let state = Self::make_header(input_scope, STATE_PSEUDO_CIRCUIT); - let state_leaf = Self::make_header(input_scope, STATE_LEAF_PSEUDO_CIRCUIT); - - let mut container_members = IndexMap::new(); - container_members.insert( - "registers".to_string(), - CircuitMember::Variable(Type::Circuit(registers)), - ); - container_members.insert("record".to_string(), CircuitMember::Variable(Type::Circuit(record))); - container_members.insert("state".to_string(), CircuitMember::Variable(Type::Circuit(state))); - container_members.insert( - "state_leaf".to_string(), - CircuitMember::Variable(Type::Circuit(state_leaf)), - ); - - let container_circuit = input_scope.context.alloc_circuit(Circuit { - id: scope.context.get_id(), - name: RefCell::new(Identifier::new(CONTAINER_PSEUDO_CIRCUIT.into())), - members: RefCell::new(container_members), - core_mapping: RefCell::new(None), - scope: input_scope, - span: Some(Span::default()), - }); - - Input { - registers, - record, - state, - state_leaf, - container_circuit, - container: input_scope.context.alloc_variable(RefCell::new(crate::InnerVariable { - id: scope.context.get_id(), - name: Identifier::new("input".into()), - type_: Type::Circuit(container_circuit), - mutable: false, - const_: false, - declaration: crate::VariableDeclaration::Input, - references: vec![], - assignments: vec![], - })), - } - } -} - -impl<'a> Circuit<'a> { - pub fn is_input_pseudo_circuit(&self) -> bool { - matches!( - &*self.name.borrow().name, - REGISTERS_PSEUDO_CIRCUIT | RECORD_PSEUDO_CIRCUIT | STATE_PSEUDO_CIRCUIT | STATE_LEAF_PSEUDO_CIRCUIT - ) - } -} diff --git a/asg/src/lib.rs b/asg/src/lib.rs deleted file mode 100644 index 686672db14..0000000000 --- a/asg/src/lib.rs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! The abstract semantic graph (ASG) for a Leo program. -//! -//! This module contains the [`Asg`] type, an abstract data type that represents a Leo program -//! as a series of graph nodes. The [`Asg`] type is at a greater level of abstraction than an [`Ast`]. -//! -//! A new [`Asg`] type can be created from an [`Ast`]. -//! Converting to an [`Asg`] provides greater type safety by canonicalizing and checking program types. - -#![allow(clippy::from_over_into)] -#![allow(clippy::result_unit_err)] -#![doc = include_str!("../README.md")] - -pub mod checks; -pub use checks::*; - -pub mod const_value; -pub use const_value::*; - -pub mod expression; -pub use expression::*; - -mod input; -pub use input::*; - -pub mod node; -pub use node::*; - -pub mod program; -pub use program::*; - -pub mod reducer; -pub use reducer::*; - -pub mod scope; -pub use scope::*; - -pub mod statement; -pub use statement::*; - -pub mod type_; -pub use type_::*; - -pub mod variable; -use typed_arena::Arena; -pub use variable::*; - -pub mod pass; -pub use pass::*; - -pub mod context; -pub use context::*; - -pub use leo_ast::{Ast, Identifier}; -use leo_errors::Result; - -/// The abstract semantic graph (ASG) for a Leo program. -/// -/// The [`Asg`] type represents a Leo program as a series of recursive data types. -/// These data types form a graph that begins from a [`Program`] type node. -/// -/// A new [`Asg`] can be created from an [`Ast`] generated in the `ast` module. -#[derive(Clone)] -pub struct Asg<'a> { - #[allow(dead_code)] // todo: revisit this during asg refactor - context: AsgContext<'a>, - asg: Program<'a>, -} - -impl<'a> Asg<'a> { - /// Creates a new ASG from a given AST and import resolver. - pub fn new>(context: AsgContext<'a>, ast: Y) -> Result { - Ok(Self { - context, - asg: Program::new(context, ast.as_ref())?, - }) - } - - /// Returns the internal program ASG representation. - pub fn as_repr(&self) -> &Program<'a> { - &self.asg - } - - pub fn into_repr(self) -> Program<'a> { - self.asg - } -} - -pub fn new_alloc_context<'a>() -> Arena> { - Arena::new() -} - -pub fn new_context<'a>(arena: &'a Arena>) -> AsgContext<'a> { - AsgContextInner::new(arena) -} diff --git a/asg/src/node.rs b/asg/src/node.rs deleted file mode 100644 index 41710ba406..0000000000 --- a/asg/src/node.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{Alias, AsgContextInner, Circuit, Expression, Function, PartialType, Scope, Statement, Variable}; - -use leo_errors::{Result, Span}; - -/// A node in the abstract semantic graph. -pub trait Node { - fn span(&self) -> Option<&Span>; -} - -pub(super) trait FromAst<'a, T: leo_ast::Node + 'static>: Sized { - // expected_type contract: if present, output expression must be of type expected_type. - // type of an element may NEVER be None unless it is functionally a non-expression. (static call targets, function ref call targets are not expressions) - fn from_ast(scope: &'a Scope<'a>, value: &T, expected_type: Option>) -> Result; -} - -pub enum ArenaNode<'a> { - Expression(Expression<'a>), - Scope(Box>), - Statement(Statement<'a>), - Variable(Variable<'a>), - Circuit(Circuit<'a>), - Function(Function<'a>), - Inner(AsgContextInner<'a>), - Alias(Alias<'a>), -} diff --git a/asg/src/pass.rs b/asg/src/pass.rs deleted file mode 100644 index 6828362e57..0000000000 --- a/asg/src/pass.rs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::Program; -use leo_errors::Result; - -pub trait AsgPass<'a> { - fn do_pass(asg: Program<'a>) -> Result>; -} diff --git a/asg/src/program/alias.rs b/asg/src/program/alias.rs deleted file mode 100644 index d5e7ebf4aa..0000000000 --- a/asg/src/program/alias.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{Identifier, Node, Scope, Type}; -use leo_errors::{Result, Span}; - -use std::cell::RefCell; - -#[derive(Clone)] -pub struct Alias<'a> { - pub id: u32, - pub name: RefCell, - pub span: Option, - pub represents: Type<'a>, -} - -impl<'a> PartialEq for Alias<'a> { - fn eq(&self, other: &Alias) -> bool { - if self.name != other.name { - return false; - } - self.id == other.id - } -} - -impl<'a> Eq for Alias<'a> {} - -impl<'a> Node for Alias<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> Alias<'a> { - pub(super) fn init(scope: &'a Scope<'a>, value: &leo_ast::Alias) -> Result<&'a Alias<'a>> { - let alias = scope.context.alloc_alias(Alias { - id: scope.context.get_id(), - name: RefCell::new(value.name.clone()), - span: Some(value.span.clone()), - represents: scope.resolve_ast_type(&value.represents, &value.span)?, - }); - - Ok(alias) - } -} diff --git a/asg/src/program/circuit.rs b/asg/src/program/circuit.rs deleted file mode 100644 index f206a63401..0000000000 --- a/asg/src/program/circuit.rs +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{Function, Identifier, Node, Scope, Type}; -use leo_errors::{AsgError, Result, Span}; - -use indexmap::IndexMap; -use std::cell::RefCell; - -#[derive(Clone)] -pub enum CircuitMember<'a> { - Variable(Type<'a>), - Function(&'a Function<'a>), -} - -#[derive(Clone)] -pub struct Circuit<'a> { - pub id: u32, - pub name: RefCell, - pub core_mapping: RefCell>, - pub scope: &'a Scope<'a>, - pub span: Option, - pub members: RefCell>>, -} - -impl<'a> PartialEq for Circuit<'a> { - fn eq(&self, other: &Circuit) -> bool { - if self.name != other.name { - return false; - } - self.id == other.id - } -} - -impl<'a> Eq for Circuit<'a> {} - -impl<'a> Node for Circuit<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> Circuit<'a> { - pub(super) fn init(scope: &'a Scope<'a>, value: &leo_ast::Circuit) -> Result<&'a Circuit<'a>> { - let new_scope = scope.make_subscope(); - - let circuit = scope.context.alloc_circuit(Circuit { - id: scope.context.get_id(), - name: RefCell::new(value.circuit_name.clone()), - members: RefCell::new(IndexMap::new()), - core_mapping: value.core_mapping.clone(), - span: Some(value.circuit_name.span.clone()), - scope: new_scope, - }); - - let mut members = circuit.members.borrow_mut(); - for member in value.members.iter() { - if let leo_ast::CircuitMember::CircuitVariable(name, type_) = member { - if members.contains_key(name.name.as_ref()) { - return Err( - AsgError::redefined_circuit_member(&value.circuit_name.name, &name.name, &name.span).into(), - ); - } - members.insert( - name.name.to_string(), - CircuitMember::Variable(new_scope.resolve_ast_type(type_, &name.span)?), - ); - } - } - - Ok(circuit) - } - - pub(super) fn init_member(scope: &'a Scope<'a>, value: &leo_ast::Circuit) -> Result<&'a Circuit<'a>> { - let new_scope = scope.make_subscope(); - let circuits = scope.circuits.borrow(); - - let circuit = circuits.get(value.circuit_name.name.as_ref()).unwrap(); - - let mut members = circuit.members.borrow_mut(); - for member in value.members.iter() { - if let leo_ast::CircuitMember::CircuitFunction(function) = member { - if members.contains_key(function.identifier.name.as_ref()) { - return Err(AsgError::redefined_circuit_member( - &value.circuit_name.name, - &function.identifier.name, - &function.identifier.span, - ) - .into()); - } - let asg_function = Function::init(new_scope, function)?; - asg_function.circuit.replace(Some(circuit)); - if asg_function.is_test() { - return Err(AsgError::circuit_test_function(&function.identifier.span).into()); - } - members.insert( - function.identifier.name.to_string(), - CircuitMember::Function(asg_function), - ); - } - } - - Ok(circuit) - } - - pub(super) fn fill_from_ast(self: &'a Circuit<'a>, value: &leo_ast::Circuit) -> Result<()> { - for member in value.members.iter() { - match member { - leo_ast::CircuitMember::CircuitVariable(..) => {} - leo_ast::CircuitMember::CircuitFunction(function) => { - let asg_function = match *self - .members - .borrow() - .get(function.identifier.name.as_ref()) - .expect("missing header for defined circuit function") - { - CircuitMember::Function(f) => f, - _ => unimplemented!(), - }; - Function::fill_from_ast(asg_function, function)?; - } - } - } - Ok(()) - } -} - -impl<'a> Into for &Circuit<'a> { - fn into(self) -> leo_ast::Circuit { - let members = self - .members - .borrow() - .iter() - .map(|(name, member)| match &member { - CircuitMember::Variable(type_) => { - leo_ast::CircuitMember::CircuitVariable(Identifier::new((&**name).into()), type_.into()) - } - CircuitMember::Function(func) => leo_ast::CircuitMember::CircuitFunction((*func).into()), - }) - .collect(); - leo_ast::Circuit { - circuit_name: self.name.borrow().clone(), - core_mapping: self.core_mapping.clone(), - members, - } - } -} diff --git a/asg/src/program/function.rs b/asg/src/program/function.rs deleted file mode 100644 index 67bd656a57..0000000000 --- a/asg/src/program/function.rs +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ - BlockStatement, Circuit, FromAst, Identifier, MonoidalDirector, ReturnPathReducer, Scope, Statement, Type, Variable, -}; -use indexmap::IndexMap; -pub use leo_ast::Annotation; -use leo_ast::FunctionInput; -use leo_errors::{AsgError, Result, Span}; - -use std::cell::{Cell, RefCell}; - -#[derive(Clone, Copy, PartialEq)] -pub enum FunctionQualifier { - SelfRef, - ConstSelfRef, - MutSelfRef, - Static, -} - -#[derive(Clone)] -pub struct Function<'a> { - pub id: u32, - pub name: RefCell, - pub output: Type<'a>, - pub arguments: IndexMap>>, - pub circuit: Cell>>, - pub span: Option, - pub body: Cell>>, - pub scope: &'a Scope<'a>, - pub qualifier: FunctionQualifier, - pub annotations: Vec, -} - -impl<'a> PartialEq for Function<'a> { - fn eq(&self, other: &Function<'a>) -> bool { - if self.name.borrow().name != other.name.borrow().name { - return false; - } - self.id == other.id - } -} - -impl<'a> Eq for Function<'a> {} - -impl<'a> Function<'a> { - pub(crate) fn init(scope: &'a Scope<'a>, value: &leo_ast::Function) -> Result<&'a Function<'a>> { - let output: Type<'a> = value - .output - .as_ref() - .map(|t| scope.resolve_ast_type(t, &value.span)) - .transpose()? - .unwrap_or_else(|| Type::Tuple(vec![])); - let mut qualifier = FunctionQualifier::Static; - let new_scope = scope.make_subscope(); - - let mut arguments = IndexMap::new(); - { - for input in value.input.iter() { - match input { - FunctionInput::SelfKeyword(_) => { - qualifier = FunctionQualifier::SelfRef; - } - FunctionInput::ConstSelfKeyword(_) => { - qualifier = FunctionQualifier::ConstSelfRef; - } - FunctionInput::MutSelfKeyword(_) => { - qualifier = FunctionQualifier::MutSelfRef; - } - FunctionInput::Variable(input_variable) => { - if arguments.contains_key(input_variable.identifier.name.as_ref()) { - return Err(AsgError::duplicate_function_input_definition( - input_variable.identifier.name.as_ref(), - &input_variable.identifier.span, - ) - .into()); - } - - let variable = scope.context.alloc_variable(RefCell::new(crate::InnerVariable { - id: scope.context.get_id(), - name: input_variable.identifier.clone(), - type_: scope.resolve_ast_type(&input_variable.type_, &value.span)?, - mutable: input_variable.mutable, - const_: input_variable.const_, - declaration: crate::VariableDeclaration::Parameter, - references: vec![], - assignments: vec![], - })); - arguments.insert(input_variable.identifier.name.to_string(), Cell::new(&*variable)); - } - } - } - } - let function = scope.context.alloc_function(Function { - id: scope.context.get_id(), - name: RefCell::new(value.identifier.clone()), - output, - arguments, - circuit: Cell::new(None), - body: Cell::new(None), - qualifier, - scope: new_scope, - span: Some(value.span.clone()), - annotations: value.annotations.clone(), - }); - function.scope.function.replace(Some(function)); - - Ok(function) - } - - pub(super) fn fill_from_ast(self: &'a Function<'a>, value: &leo_ast::Function) -> Result<()> { - if self.qualifier != FunctionQualifier::Static { - let circuit = self.circuit.get(); - let self_variable = self.scope.context.alloc_variable(RefCell::new(crate::InnerVariable { - id: self.scope.context.get_id(), - name: Identifier::new("self".into()), - type_: Type::Circuit(circuit.as_ref().unwrap()), - mutable: self.qualifier == FunctionQualifier::MutSelfRef, - const_: false, - declaration: crate::VariableDeclaration::Parameter, - references: vec![], - assignments: vec![], - })); - self.scope - .variables - .borrow_mut() - .insert("self".to_string(), self_variable); - } - for (name, argument) in self.arguments.iter() { - if self.scope.resolve_global_const(name).is_some() { - return Err(AsgError::function_input_cannot_shadow_global_const( - name, - &argument.get().borrow().name.span, - ) - .into()); - } - - self.scope.variables.borrow_mut().insert(name.clone(), argument.get()); - } - - let main_block = BlockStatement::from_ast(self.scope, &value.block, None)?; - let mut director = MonoidalDirector::new(ReturnPathReducer::new()); - if !director.reduce_block(&main_block).0 && !self.output.is_unit() { - return Err(AsgError::function_missing_return(&self.name.borrow().name, &value.span).into()); - } - - #[allow(clippy::never_loop)] // TODO @Protryon: How should we return multiple errors? - for (span, error) in director.reducer().errors { - return Err(AsgError::function_return_validation(&self.name.borrow().name, error, &span).into()); - } - - self.body - .replace(Some(self.scope.context.alloc_statement(Statement::Block(main_block)))); - - Ok(()) - } - - pub fn is_test(&self) -> bool { - self.annotations.iter().any(|x| x.name.name.as_ref() == "test") - } -} - -impl<'a> Into for &Function<'a> { - fn into(self) -> leo_ast::Function { - let input = self - .arguments - .iter() - .map(|(_, variable)| { - let variable = variable.get().borrow(); - leo_ast::FunctionInput::Variable(leo_ast::FunctionInputVariable { - identifier: variable.name.clone(), - mutable: variable.mutable, - const_: variable.const_, - type_: (&variable.type_).into(), - span: Span::default(), - }) - }) - .collect(); - let (body, span) = match self.body.get() { - Some(Statement::Block(block)) => (block.into(), block.span.clone().unwrap_or_default()), - Some(_) => unimplemented!(), - None => ( - leo_ast::Block { - statements: vec![], - span: Default::default(), - }, - Default::default(), - ), - }; - let output: Type = self.output.clone(); - leo_ast::Function { - identifier: self.name.borrow().clone(), - input, - block: body, - output: Some((&output).into()), - span, - annotations: self.annotations.clone(), - } - } -} diff --git a/asg/src/program/mod.rs b/asg/src/program/mod.rs deleted file mode 100644 index 7187a1916d..0000000000 --- a/asg/src/program/mod.rs +++ /dev/null @@ -1,404 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! This module defines the program node for an asg. -//! -//! - -mod alias; -pub use alias::*; - -mod circuit; -pub use circuit::*; - -mod function; -pub use function::*; - -use crate::{node::FromAst, ArenaNode, AsgContext, DefinitionStatement, Input, Scope, Statement}; -use leo_ast::{PackageAccess, PackageOrPackages}; -use leo_errors::{AsgError, Result, Span}; - -use indexmap::IndexMap; -use std::cell::{Cell, RefCell}; - -/// Stores the Leo program abstract semantic graph (ASG). -#[derive(Clone)] -pub struct Program<'a> { - pub context: AsgContext<'a>, - - /// The unique id of the program. - pub id: u32, - - /// The program file name. - pub name: String, - - /// The packages imported by this program. - /// these should generally not be accessed directly, but through scoped imports - pub imported_modules: IndexMap>, - - /// Maps alias name => alias definition. - pub aliases: IndexMap>, - - /// Maps function name => function code block. - pub functions: IndexMap>, - - /// Maps global constant name => global const code block. - pub global_consts: IndexMap>, - - /// Maps circuit name => circuit code block. - pub circuits: IndexMap>, - - pub scope: &'a Scope<'a>, -} - -/// Enumerates what names are imported from a package. -#[derive(Clone)] -enum ImportSymbol { - /// Import the symbol by name. - Direct(String), - - /// Import the symbol by name and store it under an alias. - Alias(String, String), // from remote -> to local - - /// Import all symbols from the package. - All, -} - -fn resolve_import_package( - output: &mut Vec<(Vec, ImportSymbol, Span)>, - mut package_segments: Vec, - package_or_packages: &PackageOrPackages, -) { - match package_or_packages { - PackageOrPackages::Package(package) => { - package_segments.push(package.name.name.to_string()); - resolve_import_package_access(output, package_segments, &package.access); - } - PackageOrPackages::Packages(packages) => { - package_segments.push(packages.name.name.to_string()); - for access in packages.accesses.clone() { - resolve_import_package_access(output, package_segments.clone(), &access); - } - } - } -} - -fn resolve_import_package_access( - output: &mut Vec<(Vec, ImportSymbol, Span)>, - mut package_segments: Vec, - package: &PackageAccess, -) { - match package { - PackageAccess::Star { span } => { - output.push((package_segments, ImportSymbol::All, span.clone())); - } - PackageAccess::SubPackage(subpackage) => { - resolve_import_package( - output, - package_segments, - &PackageOrPackages::Package(*(*subpackage).clone()), - ); - } - PackageAccess::Symbol(symbol) => { - let span = symbol.symbol.span.clone(); - let symbol = if let Some(alias) = symbol.alias.as_ref() { - ImportSymbol::Alias(symbol.symbol.name.to_string(), alias.name.to_string()) - } else { - ImportSymbol::Direct(symbol.symbol.name.to_string()) - }; - output.push((package_segments, symbol, span)); - } - PackageAccess::Multiple(packages) => { - package_segments.push(packages.name.name.to_string()); - for subaccess in packages.accesses.iter() { - resolve_import_package_access(output, package_segments.clone(), subaccess); - } - } - } -} - -/// Checks whether a given string is found in any other global namespaces. -/// If it is found it returns an error. -fn check_top_level_namespaces<'a>( - name: &str, - span: &Span, - aliases: &IndexMap>, - functions: &IndexMap>, - circuits: &IndexMap>, - global_consts: &IndexMap>, -) -> Result<()> { - if aliases.contains_key(name) { - Err(AsgError::duplicate_alias_definition(name, span).into()) - } else if global_consts.contains_key(name) { - Err(AsgError::duplicate_global_const_definition(name, span).into()) - } else if functions.contains_key(name) { - Err(AsgError::duplicate_function_definition(name, span).into()) - } else if circuits.contains_key(name) { - Err(AsgError::duplicate_circuit_definition(name, span).into()) - } else { - Ok(()) - } -} - -impl<'a> Program<'a> { - /// Returns a new Leo program ASG from the given Leo program AST and its imports. - /// - /// Stages: - /// 1. resolve imports into super scope - /// 2. finalize declared types - /// 3. finalize declared functions - /// 4. resolve all asg nodes - /// - pub fn new(context: AsgContext<'a>, program: &leo_ast::Program) -> Result> { - let mut imported_aliases: IndexMap> = IndexMap::new(); - let mut imported_functions: IndexMap> = IndexMap::new(); - let mut imported_circuits: IndexMap> = IndexMap::new(); - let mut imported_global_consts: IndexMap> = IndexMap::new(); - - // Convert each sub AST. - // Import all prelude symbols on the way. - let mut imported_modules: IndexMap, Program> = IndexMap::new(); - for (package, program) in program.imports.iter() { - let sub_program = Program::new(context, program)?; - imported_modules.insert(package.clone(), sub_program.clone()); - - let pretty_package = package.join("."); - - if pretty_package.contains("std.prelude") { - imported_aliases.extend(sub_program.aliases.clone().into_iter()); - imported_functions.extend(sub_program.functions.clone().into_iter()); - imported_circuits.extend(sub_program.circuits.clone().into_iter()); - imported_global_consts.extend(sub_program.global_consts.clone().into_iter()); - } - } - - let mut imported_symbols: Vec<(Vec, ImportSymbol, Span)> = vec![]; - for import_statement in program.import_statements.iter() { - resolve_import_package(&mut imported_symbols, vec![], &import_statement.package_or_packages); - } - - let mut deduplicated_imports: IndexMap, Span> = IndexMap::new(); - for (package, _symbol, span) in imported_symbols.iter() { - deduplicated_imports.insert(package.clone(), span.clone()); - } - - for (package, symbol, span) in imported_symbols.into_iter() { - let pretty_package = package.join("."); - - let resolved_package = imported_modules - .get_mut(&package) - .expect("could not find preloaded package"); - - match symbol { - ImportSymbol::All => { - imported_aliases.extend(resolved_package.aliases.clone().into_iter()); - imported_functions.extend(resolved_package.functions.clone().into_iter()); - imported_circuits.extend(resolved_package.circuits.clone().into_iter()); - imported_global_consts.extend(resolved_package.global_consts.clone().into_iter()); - } - ImportSymbol::Direct(name) => { - if let Some(alias) = resolved_package.aliases.get(&name) { - imported_aliases.insert(name.clone(), *alias); - } else if let Some(function) = resolved_package.functions.get(&name) { - imported_functions.insert(name.clone(), *function); - } else if let Some(circuit) = resolved_package.circuits.get(&name) { - imported_circuits.insert(name.clone(), *circuit); - } else if let Some(global_const) = resolved_package.global_consts.get(&name) { - imported_global_consts.insert(name.clone(), *global_const); - } else { - return Err(AsgError::unresolved_import(pretty_package, &span).into()); - } - } - ImportSymbol::Alias(name, alias) => { - if let Some(type_alias) = resolved_package.aliases.get(&name) { - imported_aliases.insert(alias.clone(), *type_alias); - } else if let Some(function) = resolved_package.functions.get(&name) { - imported_functions.insert(alias.clone(), *function); - } else if let Some(circuit) = resolved_package.circuits.get(&name) { - imported_circuits.insert(alias.clone(), *circuit); - } else if let Some(global_const) = resolved_package.global_consts.get(&name) { - imported_global_consts.insert(alias.clone(), *global_const); - } else { - return Err(AsgError::unresolved_import(pretty_package, &span).into()); - } - } - } - } - - let import_scope = match context.arena.alloc(ArenaNode::Scope(Box::new(Scope { - context, - id: context.get_id(), - parent_scope: Cell::new(None), - variables: RefCell::new(IndexMap::new()), - aliases: RefCell::new(imported_aliases), - functions: RefCell::new(imported_functions), - global_consts: RefCell::new(imported_global_consts), - circuits: RefCell::new(imported_circuits), - function: Cell::new(None), - input: Cell::new(None), - }))) { - ArenaNode::Scope(c) => c, - _ => unimplemented!(), - }; - - let scope = import_scope.context.alloc_scope(Scope { - context, - input: Cell::new(Some(Input::new(import_scope))), // we use import_scope to avoid recursive scope ref here - id: context.get_id(), - parent_scope: Cell::new(Some(import_scope)), - variables: RefCell::new(IndexMap::new()), - aliases: RefCell::new(IndexMap::new()), - functions: RefCell::new(IndexMap::new()), - global_consts: RefCell::new(IndexMap::new()), - circuits: RefCell::new(IndexMap::new()), - function: Cell::new(None), - }); - - // Prepare header-like scope entries. - // Have to do aliases first. - for (name, alias) in program.aliases.iter() { - assert_eq!(name.name, alias.name.name); - - let asg_alias = Alias::init(scope, alias)?; - scope.aliases.borrow_mut().insert(name.name.to_string(), asg_alias); - } - - for (name, circuit) in program.circuits.iter() { - assert_eq!(name.name, circuit.circuit_name.name); - let asg_circuit = Circuit::init(scope, circuit)?; - - scope.circuits.borrow_mut().insert(name.name.to_string(), asg_circuit); - } - - // Second pass for circuit members. - for (name, circuit) in program.circuits.iter() { - assert_eq!(name.name, circuit.circuit_name.name); - let asg_circuit = Circuit::init_member(scope, circuit)?; - - scope.circuits.borrow_mut().insert(name.name.to_string(), asg_circuit); - } - - for (name, function) in program.functions.iter() { - assert_eq!(name.name, function.identifier.name); - let function = Function::init(scope, function)?; - - scope.functions.borrow_mut().insert(name.name.to_string(), function); - } - - for (names, global_const) in program.global_consts.iter() { - let gc = <&Statement<'a>>::from_ast(scope, global_const, None)?; - if let Statement::Definition(def) = gc { - let name = names - .iter() - .enumerate() - .map(|(i, name)| { - assert_eq!(name.name, def.variables.get(i).unwrap().borrow().name.name); - name.name.to_string() - }) - .collect::>() - .join(","); - - scope.global_consts.borrow_mut().insert(name, def); - } - } - - // Load concrete definitions. - let mut aliases = IndexMap::new(); - let mut functions = IndexMap::new(); - let mut circuits = IndexMap::new(); - let mut global_consts = IndexMap::new(); - - for (name, alias) in program.aliases.iter() { - assert_eq!(name.name, alias.name.name); - let asg_alias = *scope.aliases.borrow().get(name.name.as_ref()).unwrap(); - - let name = name.name.to_string(); - - check_top_level_namespaces(&name, &alias.span, &aliases, &functions, &circuits, &global_consts)?; - - aliases.insert(name, asg_alias); - } - - for (name, function) in program.functions.iter() { - assert_eq!(name.name, function.identifier.name); - let asg_function = *scope.functions.borrow().get(name.name.as_ref()).unwrap(); - - asg_function.fill_from_ast(function)?; - - let name = name.name.to_string(); - - check_top_level_namespaces(&name, &function.span, &aliases, &functions, &circuits, &global_consts)?; - - functions.insert(name, asg_function); - } - - for (name, circuit) in program.circuits.iter() { - assert_eq!(name.name, circuit.circuit_name.name); - let asg_circuit = *scope.circuits.borrow().get(name.name.as_ref()).unwrap(); - - asg_circuit.fill_from_ast(circuit)?; - - let name = name.name.to_string(); - - check_top_level_namespaces( - &name, - &circuit.circuit_name.span, - &aliases, - &functions, - &circuits, - &global_consts, - )?; - - circuits.insert(name, asg_circuit); - } - - for (names, global_const) in program.global_consts.iter() { - let name = names - .iter() - .map(|name| name.name.to_string()) - .collect::>() - .join(","); - - let asg_global_const = *scope.global_consts.borrow().get(&name).unwrap(); - - check_top_level_namespaces( - &name, - &global_const.span, - &aliases, - &functions, - &circuits, - &global_consts, - )?; - - global_consts.insert(name.clone(), asg_global_const); - } - - Ok(Program { - context, - id: context.get_id(), - name: program.name.clone(), - aliases, - functions, - global_consts, - circuits, - imported_modules: imported_modules - .into_iter() - .map(|(package, program)| (package.join("."), program)) - .collect(), - scope, - }) - } -} diff --git a/asg/src/reducer/mod.rs b/asg/src/reducer/mod.rs deleted file mode 100644 index 7349d1a04e..0000000000 --- a/asg/src/reducer/mod.rs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! This module contains the reducer which iterates through ast nodes - converting them into -//! asg nodes and saving relevant information. - -mod monoid; -pub use monoid::*; - -mod monoidal_director; -pub use monoidal_director::*; - -mod monoidal_reducer; -pub use monoidal_reducer::*; - -mod reconstructing_reducer; -pub use reconstructing_reducer::*; - -mod reconstructing_director; -pub use reconstructing_director::*; - -mod visitor; -pub use visitor::*; - -mod visitor_director; -pub use visitor_director::*; diff --git a/asg/src/reducer/monoid/bool_and.rs b/asg/src/reducer/monoid/bool_and.rs deleted file mode 100644 index a319b92c92..0000000000 --- a/asg/src/reducer/monoid/bool_and.rs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::*; - -#[derive(Default)] -pub struct BoolAnd(pub bool); - -impl Monoid for BoolAnd { - fn append(self, other: Self) -> Self { - BoolAnd(self.0 && other.0) - } - - fn append_all(self, mut others: impl Iterator) -> Self { - BoolAnd(others.all(|i| i.0)) - } -} diff --git a/asg/src/reducer/monoid/mod.rs b/asg/src/reducer/monoid/mod.rs deleted file mode 100644 index cdb7c7b7d7..0000000000 --- a/asg/src/reducer/monoid/mod.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -mod bool_and; -pub use bool_and::*; - -mod set_append; -pub use set_append::*; - -mod vec_append; -pub use vec_append::*; - -pub trait Monoid: Default { - fn append(self, other: Self) -> Self; - - fn append_all(self, others: impl Iterator) -> Self { - let mut current = self; - for item in others { - current = current.append(item); - } - current - } - - fn append_option(self, other: Option) -> Self { - match other { - None => self, - Some(other) => self.append(other), - } - } -} diff --git a/asg/src/reducer/monoid/set_append.rs b/asg/src/reducer/monoid/set_append.rs deleted file mode 100644 index e32f8c75d8..0000000000 --- a/asg/src/reducer/monoid/set_append.rs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::*; - -use indexmap::IndexSet; -use std::hash::Hash; - -pub struct SetAppend(IndexSet); - -impl Default for SetAppend { - fn default() -> Self { - Self(IndexSet::new()) - } -} - -impl Monoid for SetAppend { - fn append(mut self, other: Self) -> Self { - self.0.extend(other.0); - SetAppend(self.0) - } - - fn append_all(mut self, others: impl Iterator) -> Self { - let all: Vec> = others.map(|x| x.0).collect(); - let total_size = all.iter().fold(0, |acc, v| acc + v.len()); - self.0.reserve(total_size); - for item in all.into_iter() { - self.0.extend(item); - } - self - } -} - -impl Into> for SetAppend { - fn into(self) -> IndexSet { - self.0 - } -} diff --git a/asg/src/reducer/monoid/vec_append.rs b/asg/src/reducer/monoid/vec_append.rs deleted file mode 100644 index 11188fa58d..0000000000 --- a/asg/src/reducer/monoid/vec_append.rs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::*; - -pub struct VecAppend(Vec); - -impl Default for VecAppend { - fn default() -> Self { - Self(vec![]) - } -} - -impl Monoid for VecAppend { - fn append(mut self, other: Self) -> Self { - self.0.extend(other.0); - VecAppend(self.0) - } - - fn append_all(mut self, others: impl Iterator) -> Self { - let all: Vec> = others.map(|x| x.0).collect(); - let total_size = all.iter().fold(0, |acc, v| acc + v.len()); - self.0.reserve(total_size); - for item in all.into_iter() { - self.0.extend(item); - } - self - } -} - -impl Into> for VecAppend { - fn into(self) -> Vec { - self.0 - } -} diff --git a/asg/src/reducer/monoidal_director.rs b/asg/src/reducer/monoidal_director.rs deleted file mode 100644 index 8ce0e1e58b..0000000000 --- a/asg/src/reducer/monoidal_director.rs +++ /dev/null @@ -1,320 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::*; -use crate::{expression::*, program::*, statement::*}; - -use std::marker::PhantomData; - -pub struct MonoidalDirector<'a, T: Monoid, R: MonoidalReducerExpression<'a, T>> { - reducer: R, - _monoid: PhantomData<&'a T>, -} - -impl<'a, T: Monoid, R: MonoidalReducerExpression<'a, T>> MonoidalDirector<'a, T, R> { - pub fn new(reducer: R) -> Self { - Self { - reducer, - _monoid: PhantomData, - } - } - - pub fn reducer(self) -> R { - self.reducer - } - - pub fn reduce_expression(&mut self, input: &'a Expression<'a>) -> T { - let value = match input { - Expression::ArrayAccess(e) => self.reduce_array_access(e), - Expression::ArrayInit(e) => self.reduce_array_init(e), - Expression::ArrayInline(e) => self.reduce_array_inline(e), - Expression::ArrayRangeAccess(e) => self.reduce_array_range_access(e), - Expression::Binary(e) => self.reduce_binary(e), - Expression::Call(e) => self.reduce_call(e), - Expression::CircuitAccess(e) => self.reduce_circuit_access(e), - Expression::CircuitInit(e) => self.reduce_circuit_init(e), - Expression::Ternary(e) => self.reduce_ternary_expression(e), - Expression::Cast(e) => self.reduce_cast_expression(e), - Expression::LengthOf(e) => self.reduce_lengthof_expression(e), - Expression::Constant(e) => self.reduce_constant(e), - Expression::TupleAccess(e) => self.reduce_tuple_access(e), - Expression::TupleInit(e) => self.reduce_tuple_init(e), - Expression::Unary(e) => self.reduce_unary(e), - Expression::VariableRef(e) => self.reduce_variable_ref(e), - }; - - self.reducer.reduce_expression(input, value) - } - - pub fn reduce_array_access(&mut self, input: &ArrayAccessExpression<'a>) -> T { - let array = self.reduce_expression(input.array.get()); - let index = self.reduce_expression(input.index.get()); - - self.reducer.reduce_array_access(input, array, index) - } - - pub fn reduce_array_init(&mut self, input: &ArrayInitExpression<'a>) -> T { - let element = self.reduce_expression(input.element.get()); - - self.reducer.reduce_array_init(input, element) - } - - pub fn reduce_array_inline(&mut self, input: &ArrayInlineExpression<'a>) -> T { - let elements = input - .elements - .iter() - .map(|(x, _)| self.reduce_expression(x.get())) - .collect(); - - self.reducer.reduce_array_inline(input, elements) - } - - pub fn reduce_array_range_access(&mut self, input: &ArrayRangeAccessExpression<'a>) -> T { - let array = self.reduce_expression(input.array.get()); - let left = input.left.get().map(|e| self.reduce_expression(e)); - let right = input.right.get().map(|e| self.reduce_expression(e)); - - self.reducer.reduce_array_range_access(input, array, left, right) - } - - pub fn reduce_binary(&mut self, input: &BinaryExpression<'a>) -> T { - let left = self.reduce_expression(input.left.get()); - let right = self.reduce_expression(input.right.get()); - - self.reducer.reduce_binary(input, left, right) - } - - pub fn reduce_call(&mut self, input: &CallExpression<'a>) -> T { - let target = input.target.get().map(|e| self.reduce_expression(e)); - let arguments = input - .arguments - .iter() - .map(|e| self.reduce_expression(e.get())) - .collect(); - - self.reducer.reduce_call(input, target, arguments) - } - - pub fn reduce_circuit_access(&mut self, input: &CircuitAccessExpression<'a>) -> T { - let target = input.target.get().map(|e| self.reduce_expression(e)); - - self.reducer.reduce_circuit_access(input, target) - } - - pub fn reduce_circuit_init(&mut self, input: &CircuitInitExpression<'a>) -> T { - let values = input - .values - .iter() - .map(|(_, e)| self.reduce_expression(e.get())) - .collect(); - - self.reducer.reduce_circuit_init(input, values) - } - - pub fn reduce_ternary_expression(&mut self, input: &TernaryExpression<'a>) -> T { - let condition = self.reduce_expression(input.condition.get()); - let if_true = self.reduce_expression(input.if_true.get()); - let if_false = self.reduce_expression(input.if_false.get()); - - self.reducer - .reduce_ternary_expression(input, condition, if_true, if_false) - } - - pub fn reduce_cast_expression(&mut self, input: &CastExpression<'a>) -> T { - let inner = self.reduce_expression(input.inner.get()); - - self.reducer.reduce_cast_expression(input, inner) - } - - pub fn reduce_lengthof_expression(&mut self, input: &LengthOfExpression<'a>) -> T { - let inner = self.reduce_expression(input.inner.get()); - - self.reducer.reduce_lengthof_expression(input, inner) - } - - pub fn reduce_constant(&mut self, input: &Constant<'a>) -> T { - self.reducer.reduce_constant(input) - } - - pub fn reduce_tuple_access(&mut self, input: &TupleAccessExpression<'a>) -> T { - let tuple_ref = self.reduce_expression(input.tuple_ref.get()); - - self.reducer.reduce_tuple_access(input, tuple_ref) - } - - pub fn reduce_tuple_init(&mut self, input: &TupleInitExpression<'a>) -> T { - let values = input.elements.iter().map(|e| self.reduce_expression(e.get())).collect(); - - self.reducer.reduce_tuple_init(input, values) - } - - pub fn reduce_unary(&mut self, input: &UnaryExpression<'a>) -> T { - let inner = self.reduce_expression(input.inner.get()); - - self.reducer.reduce_unary(input, inner) - } - - pub fn reduce_variable_ref(&mut self, input: &VariableRef<'a>) -> T { - self.reducer.reduce_variable_ref(input) - } -} - -impl<'a, T: Monoid, R: MonoidalReducerStatement<'a, T>> MonoidalDirector<'a, T, R> { - pub fn reduce_statement(&mut self, input: &'a Statement<'a>) -> T { - let value = match input { - Statement::Assign(s) => self.reduce_assign(s), - Statement::Block(s) => self.reduce_block(s), - Statement::Conditional(s) => self.reduce_conditional_statement(s), - Statement::Console(s) => self.reduce_console(s), - Statement::Definition(s) => self.reduce_definition(s), - Statement::Expression(s) => self.reduce_expression_statement(s), - Statement::Iteration(s) => self.reduce_iteration(s), - Statement::Return(s) => self.reduce_return(s), - Statement::Empty(_) => T::default(), - }; - - self.reducer.reduce_statement(input, value) - } - - pub fn reduce_assign_access(&mut self, input: &AssignAccess<'a>) -> T { - let (left, right) = match input { - AssignAccess::ArrayRange(left, right) => ( - left.get().map(|e| self.reduce_expression(e)), - right.get().map(|e| self.reduce_expression(e)), - ), - AssignAccess::ArrayIndex(index) => (Some(self.reduce_expression(index.get())), None), - _ => (None, None), - }; - - self.reducer.reduce_assign_access(input, left, right) - } - - pub fn reduce_assign(&mut self, input: &AssignStatement<'a>) -> T { - let accesses = input - .target_accesses - .iter() - .map(|x| self.reduce_assign_access(x)) - .collect(); - let value = self.reduce_expression(input.value.get()); - - self.reducer.reduce_assign(input, accesses, value) - } - - pub fn reduce_block(&mut self, input: &BlockStatement<'a>) -> T { - let statements = input - .statements - .iter() - .map(|x| self.reduce_statement(x.get())) - .collect(); - - self.reducer.reduce_block(input, statements) - } - - pub fn reduce_conditional_statement(&mut self, input: &ConditionalStatement<'a>) -> T { - let condition = self.reduce_expression(input.condition.get()); - let if_true = self.reduce_statement(input.result.get()); - let if_false = input.next.get().map(|s| self.reduce_statement(s)); - - self.reducer - .reduce_conditional_statement(input, condition, if_true, if_false) - } - - pub fn reduce_formatted_string(&mut self, input: &ConsoleArgs<'a>) -> T { - let parameters = input - .parameters - .iter() - .map(|e| self.reduce_expression(e.get())) - .collect(); - - self.reducer.reduce_formatted_string(input, parameters) - } - - pub fn reduce_console(&mut self, input: &ConsoleStatement<'a>) -> T { - let argument = match &input.function { - ConsoleFunction::Assert(e) => self.reduce_expression(e.get()), - ConsoleFunction::Error(f) | ConsoleFunction::Log(f) => self.reduce_formatted_string(f), - }; - - self.reducer.reduce_console(input, argument) - } - - pub fn reduce_definition(&mut self, input: &DefinitionStatement<'a>) -> T { - let value = self.reduce_expression(input.value.get()); - - self.reducer.reduce_definition(input, value) - } - - pub fn reduce_expression_statement(&mut self, input: &ExpressionStatement<'a>) -> T { - let value = self.reduce_expression(input.expression.get()); - - self.reducer.reduce_expression_statement(input, value) - } - - pub fn reduce_iteration(&mut self, input: &IterationStatement<'a>) -> T { - let start = self.reduce_expression(input.start.get()); - let stop = self.reduce_expression(input.stop.get()); - let body = self.reduce_statement(input.body.get()); - - self.reducer.reduce_iteration(input, start, stop, body) - } - - pub fn reduce_return(&mut self, input: &ReturnStatement<'a>) -> T { - let value = self.reduce_expression(input.expression.get()); - - self.reducer.reduce_return(input, value) - } -} - -impl<'a, T: Monoid, R: MonoidalReducerProgram<'a, T>> MonoidalDirector<'a, T, R> { - pub fn reduce_function(&mut self, input: &'a Function<'a>) -> T { - let body = input.body.get().map(|s| self.reduce_statement(s)).unwrap_or_default(); - - self.reducer.reduce_function(input, body) - } - - pub fn reduce_circuit_member(&mut self, input: &CircuitMember<'a>) -> T { - let function = match input { - CircuitMember::Function(f) => Some(self.reduce_function(f)), - _ => None, - }; - - self.reducer.reduce_circuit_member(input, function) - } - - pub fn reduce_circuit(&mut self, input: &'a Circuit<'a>) -> T { - let members = input - .members - .borrow() - .iter() - .map(|(_, member)| self.reduce_circuit_member(member)) - .collect(); - - self.reducer.reduce_circuit(input, members) - } - - pub fn reduce_program(&mut self, input: &Program<'a>) -> T { - let imported_modules = input - .imported_modules - .iter() - .map(|(_, import)| self.reduce_program(import)) - .collect(); - let functions = input.functions.iter().map(|(_, f)| self.reduce_function(f)).collect(); - let circuits = input.circuits.iter().map(|(_, c)| self.reduce_circuit(c)).collect(); - - self.reducer - .reduce_program(input, imported_modules, functions, circuits) - } -} diff --git a/asg/src/reducer/monoidal_reducer.rs b/asg/src/reducer/monoidal_reducer.rs deleted file mode 100644 index f33b311f26..0000000000 --- a/asg/src/reducer/monoidal_reducer.rs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{expression::*, program::*, statement::*, Monoid}; - -#[allow(unused_variables)] -pub trait MonoidalReducerExpression<'a, T: Monoid> { - fn reduce_expression(&mut self, input: &'a Expression<'a>, value: T) -> T { - value - } - - fn reduce_array_access(&mut self, input: &ArrayAccessExpression<'a>, array: T, index: T) -> T { - array.append(index) - } - - fn reduce_array_init(&mut self, input: &ArrayInitExpression<'a>, element: T) -> T { - element - } - - fn reduce_array_inline(&mut self, input: &ArrayInlineExpression<'a>, elements: Vec) -> T { - T::default().append_all(elements.into_iter()) - } - - fn reduce_array_range_access( - &mut self, - input: &ArrayRangeAccessExpression<'a>, - array: T, - left: Option, - right: Option, - ) -> T { - array.append_option(left).append_option(right) - } - - fn reduce_binary(&mut self, input: &BinaryExpression<'a>, left: T, right: T) -> T { - left.append(right) - } - - fn reduce_call(&mut self, input: &CallExpression<'a>, target: Option, arguments: Vec) -> T { - target.unwrap_or_default().append_all(arguments.into_iter()) - } - - fn reduce_circuit_access(&mut self, input: &CircuitAccessExpression<'a>, target: Option) -> T { - target.unwrap_or_default() - } - - fn reduce_circuit_init(&mut self, input: &CircuitInitExpression<'a>, values: Vec) -> T { - T::default().append_all(values.into_iter()) - } - - fn reduce_ternary_expression(&mut self, input: &TernaryExpression<'a>, condition: T, if_true: T, if_false: T) -> T { - condition.append(if_true).append(if_false) - } - - fn reduce_cast_expression(&mut self, input: &CastExpression<'a>, inner: T) -> T { - inner - } - - fn reduce_lengthof_expression(&mut self, input: &LengthOfExpression<'a>, inner: T) -> T { - inner - } - - fn reduce_constant(&mut self, input: &Constant<'a>) -> T { - T::default() - } - - fn reduce_tuple_access(&mut self, input: &TupleAccessExpression<'a>, tuple_ref: T) -> T { - tuple_ref - } - - fn reduce_tuple_init(&mut self, input: &TupleInitExpression<'a>, values: Vec) -> T { - T::default().append_all(values.into_iter()) - } - - fn reduce_unary(&mut self, input: &UnaryExpression<'a>, inner: T) -> T { - inner - } - - fn reduce_variable_ref(&mut self, input: &VariableRef<'a>) -> T { - T::default() - } -} - -#[allow(unused_variables)] -pub trait MonoidalReducerStatement<'a, T: Monoid>: MonoidalReducerExpression<'a, T> { - fn reduce_statement(&mut self, input: &'a Statement<'a>, value: T) -> T { - value - } - - // left = Some(ArrayIndex.0) always if AssignAccess::ArrayIndex. if member/tuple, always None - fn reduce_assign_access(&mut self, input: &AssignAccess<'a>, left: Option, right: Option) -> T { - left.unwrap_or_default().append_option(right) - } - - fn reduce_assign(&mut self, input: &AssignStatement<'a>, accesses: Vec, value: T) -> T { - T::default().append_all(accesses.into_iter()).append(value) - } - - fn reduce_block(&mut self, input: &BlockStatement<'a>, statements: Vec) -> T { - T::default().append_all(statements.into_iter()) - } - - fn reduce_conditional_statement( - &mut self, - input: &ConditionalStatement<'a>, - condition: T, - if_true: T, - if_false: Option, - ) -> T { - condition.append(if_true).append_option(if_false) - } - - fn reduce_formatted_string(&mut self, input: &ConsoleArgs<'a>, parameters: Vec) -> T { - T::default().append_all(parameters.into_iter()) - } - - fn reduce_console(&mut self, input: &ConsoleStatement<'a>, argument: T) -> T { - argument - } - - fn reduce_definition(&mut self, input: &DefinitionStatement<'a>, value: T) -> T { - value - } - - fn reduce_expression_statement(&mut self, input: &ExpressionStatement<'a>, expression: T) -> T { - expression - } - - fn reduce_iteration(&mut self, input: &IterationStatement<'a>, start: T, stop: T, body: T) -> T { - start.append(stop).append(body) - } - - fn reduce_return(&mut self, input: &ReturnStatement<'a>, value: T) -> T { - value - } -} - -#[allow(unused_variables)] -pub trait MonoidalReducerProgram<'a, T: Monoid>: MonoidalReducerStatement<'a, T> { - fn reduce_function(&mut self, input: &'a Function<'a>, body: T) -> T { - body - } - - fn reduce_circuit_member(&mut self, input: &CircuitMember<'a>, function: Option) -> T { - function.unwrap_or_default() - } - - fn reduce_circuit(&mut self, input: &'a Circuit<'a>, members: Vec) -> T { - T::default().append_all(members.into_iter()) - } - - fn reduce_program(&mut self, input: &Program, imported_modules: Vec, functions: Vec, circuits: Vec) -> T { - T::default() - .append_all(imported_modules.into_iter()) - .append_all(functions.into_iter()) - .append_all(circuits.into_iter()) - } -} diff --git a/asg/src/reducer/reconstructing_director.rs b/asg/src/reducer/reconstructing_director.rs deleted file mode 100644 index 92029b0c43..0000000000 --- a/asg/src/reducer/reconstructing_director.rs +++ /dev/null @@ -1,359 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::*; -use crate::{expression::*, program::*, statement::*, AsgContext}; - -/* -reconstructing director tries to maintain a normalized ASG but may require renormalization under the following circumstances: -* breaking strict reducer model (i.e. live mutations) -* dropping or duplicating branches -*/ -pub struct ReconstructingDirector<'a, R: ReconstructingReducerExpression<'a>> { - context: AsgContext<'a>, - reducer: R, -} - -impl<'a, R: ReconstructingReducerExpression<'a>> ReconstructingDirector<'a, R> { - pub fn new(context: AsgContext<'a>, reducer: R) -> Self { - Self { context, reducer } - } - - pub fn reducer(self) -> R { - self.reducer - } - - pub fn reduce_expression(&mut self, input: &'a Expression<'a>) -> &'a Expression<'a> { - let value = match input.clone() { - Expression::ArrayAccess(e) => self.reduce_array_access(e), - Expression::ArrayInit(e) => self.reduce_array_init(e), - Expression::ArrayInline(e) => self.reduce_array_inline(e), - Expression::ArrayRangeAccess(e) => self.reduce_array_range_access(e), - Expression::Binary(e) => self.reduce_binary(e), - Expression::Call(e) => self.reduce_call(e), - Expression::CircuitAccess(e) => self.reduce_circuit_access(e), - Expression::CircuitInit(e) => self.reduce_circuit_init(e), - Expression::Ternary(e) => self.reduce_ternary_expression(e), - Expression::Cast(e) => self.reduce_cast_expression(e), - Expression::LengthOf(e) => Expression::LengthOf(e), // TODO: implement REDUCER - Expression::Constant(e) => self.reduce_constant(e), - Expression::TupleAccess(e) => self.reduce_tuple_access(e), - Expression::TupleInit(e) => self.reduce_tuple_init(e), - Expression::Unary(e) => self.reduce_unary(e), - Expression::VariableRef(e) => { - { - let mut variable = e.variable.borrow_mut(); - let index = variable.references.iter().position(|x| (*x).ptr_eq(input)); - if let Some(index) = index { - variable.references.remove(index); - } - } - self.reduce_variable_ref(e) - } - }; - - let allocated = self - .context - .alloc_expression(self.reducer.reduce_expression(input, value)); - if let Expression::VariableRef(reference) = allocated { - let mut variable = reference.variable.borrow_mut(); - variable.references.push(allocated); - } - allocated - } - - pub fn reduce_array_access(&mut self, input: ArrayAccessExpression<'a>) -> Expression<'a> { - let array = self.reduce_expression(input.array.get()); - let index = self.reduce_expression(input.index.get()); - - self.reducer.reduce_array_access(input, array, index) - } - - pub fn reduce_array_init(&mut self, input: ArrayInitExpression<'a>) -> Expression<'a> { - let element = self.reduce_expression(input.element.get()); - - self.reducer.reduce_array_init(input, element) - } - - pub fn reduce_array_inline(&mut self, input: ArrayInlineExpression<'a>) -> Expression<'a> { - let elements = input - .elements - .iter() - .map(|(x, spread)| (self.reduce_expression(x.get()), *spread)) - .collect(); - - self.reducer.reduce_array_inline(input, elements) - } - - pub fn reduce_array_range_access(&mut self, input: ArrayRangeAccessExpression<'a>) -> Expression<'a> { - let array = self.reduce_expression(input.array.get()); - let left = input.left.get().map(|e| self.reduce_expression(e)); - let right = input.right.get().map(|e| self.reduce_expression(e)); - - self.reducer.reduce_array_range_access(input, array, left, right) - } - - pub fn reduce_binary(&mut self, input: BinaryExpression<'a>) -> Expression<'a> { - let left = self.reduce_expression(input.left.get()); - let right = self.reduce_expression(input.right.get()); - - self.reducer.reduce_binary(input, left, right) - } - - pub fn reduce_call(&mut self, input: CallExpression<'a>) -> Expression<'a> { - let target = input.target.get().map(|e| self.reduce_expression(e)); - let arguments = input - .arguments - .iter() - .map(|e| self.reduce_expression(e.get())) - .collect(); - - self.reducer.reduce_call(input, target, arguments) - } - - pub fn reduce_circuit_access(&mut self, input: CircuitAccessExpression<'a>) -> Expression<'a> { - let target = input.target.get().map(|e| self.reduce_expression(e)); - - self.reducer.reduce_circuit_access(input, target) - } - - pub fn reduce_circuit_init(&mut self, input: CircuitInitExpression<'a>) -> Expression<'a> { - let values = input - .values - .iter() - .map(|(ident, e)| (ident.clone(), self.reduce_expression(e.get()))) - .collect(); - - self.reducer.reduce_circuit_init(input, values) - } - - pub fn reduce_ternary_expression(&mut self, input: TernaryExpression<'a>) -> Expression<'a> { - let condition = self.reduce_expression(input.condition.get()); - let if_true = self.reduce_expression(input.if_true.get()); - let if_false = self.reduce_expression(input.if_false.get()); - - self.reducer - .reduce_ternary_expression(input, condition, if_true, if_false) - } - - pub fn reduce_cast_expression(&mut self, input: CastExpression<'a>) -> Expression<'a> { - let inner = self.reduce_expression(input.inner.get()); - - self.reducer.reduce_cast_expression(input, inner) - } - - pub fn reduce_constant(&mut self, input: Constant<'a>) -> Expression<'a> { - self.reducer.reduce_constant(input) - } - - pub fn reduce_tuple_access(&mut self, input: TupleAccessExpression<'a>) -> Expression<'a> { - let tuple_ref = self.reduce_expression(input.tuple_ref.get()); - - self.reducer.reduce_tuple_access(input, tuple_ref) - } - - pub fn reduce_tuple_init(&mut self, input: TupleInitExpression<'a>) -> Expression<'a> { - let values = input.elements.iter().map(|e| self.reduce_expression(e.get())).collect(); - - self.reducer.reduce_tuple_init(input, values) - } - - pub fn reduce_unary(&mut self, input: UnaryExpression<'a>) -> Expression<'a> { - let inner = self.reduce_expression(input.inner.get()); - - self.reducer.reduce_unary(input, inner) - } - - pub fn reduce_variable_ref(&mut self, input: VariableRef<'a>) -> Expression<'a> { - self.reducer.reduce_variable_ref(input) - } -} - -impl<'a, R: ReconstructingReducerStatement<'a>> ReconstructingDirector<'a, R> { - pub fn reduce_statement(&mut self, input: &'a Statement<'a>) -> &'a Statement<'a> { - let value = match input.clone() { - Statement::Assign(s) => self.reduce_assign(s), - Statement::Block(s) => self.reduce_block(s), - Statement::Conditional(s) => self.reduce_conditional_statement(s), - Statement::Console(s) => self.reduce_console(s), - Statement::Definition(s) => self.reduce_definition(s), - Statement::Expression(s) => self.reduce_expression_statement(s), - Statement::Iteration(s) => self.reduce_iteration(s), - Statement::Return(s) => self.reduce_return(s), - x @ Statement::Empty(_) => x, - }; - - self.reducer.reduce_statement_alloc(self.context, input, value) - } - - pub fn reduce_assign_access(&mut self, input: AssignAccess<'a>) -> AssignAccess<'a> { - match &input { - AssignAccess::ArrayRange(left, right) => { - let left = left.get().map(|e| self.reduce_expression(e)); - let right = right.get().map(|e| self.reduce_expression(e)); - self.reducer.reduce_assign_access_range(input, left, right) - } - AssignAccess::ArrayIndex(index) => { - let index = self.reduce_expression(index.get()); - self.reducer.reduce_assign_access_index(input, index) - } - _ => self.reducer.reduce_assign_access(input), - } - } - - pub fn reduce_assign(&mut self, input: AssignStatement<'a>) -> Statement<'a> { - let accesses = input - .target_accesses - .iter() - .map(|x| self.reduce_assign_access(x.clone())) - .collect(); - let value = self.reduce_expression(input.value.get()); - - self.reducer.reduce_assign(input, accesses, value) - } - - pub fn reduce_block(&mut self, input: BlockStatement<'a>) -> Statement<'a> { - let statements = input - .statements - .iter() - .map(|x| self.reduce_statement(x.get())) - .collect(); - - self.reducer.reduce_block(input, statements) - } - - pub fn reduce_conditional_statement(&mut self, input: ConditionalStatement<'a>) -> Statement<'a> { - let condition = self.reduce_expression(input.condition.get()); - let if_true = self.reduce_statement(input.result.get()); - let if_false = input.next.get().map(|s| self.reduce_statement(s)); - - self.reducer - .reduce_conditional_statement(input, condition, if_true, if_false) - } - - pub fn reduce_formatted_string(&mut self, input: ConsoleArgs<'a>) -> ConsoleArgs<'a> { - let parameters = input - .parameters - .iter() - .map(|e| self.reduce_expression(e.get())) - .collect(); - - self.reducer.reduce_formatted_string(input, parameters) - } - - pub fn reduce_console(&mut self, input: ConsoleStatement<'a>) -> Statement<'a> { - match &input.function { - ConsoleFunction::Assert(argument) => { - let argument = self.reduce_expression(argument.get()); - self.reducer.reduce_console_assert(input, argument) - } - ConsoleFunction::Error(f) | ConsoleFunction::Log(f) => { - let formatted = self.reduce_formatted_string(f.clone()); - self.reducer.reduce_console_log(input, formatted) - } - } - } - - pub fn reduce_definition(&mut self, input: DefinitionStatement<'a>) -> Statement<'a> { - let value = self.reduce_expression(input.value.get()); - - self.reducer.reduce_definition(input, value) - } - - pub fn reduce_expression_statement(&mut self, input: ExpressionStatement<'a>) -> Statement<'a> { - let value = self.reduce_expression(input.expression.get()); - - self.reducer.reduce_expression_statement(input, value) - } - - pub fn reduce_iteration(&mut self, input: IterationStatement<'a>) -> Statement<'a> { - let start = self.reduce_expression(input.start.get()); - let stop = self.reduce_expression(input.stop.get()); - let body = self.reduce_statement(input.body.get()); - - self.reducer.reduce_iteration(input, start, stop, body) - } - - pub fn reduce_return(&mut self, input: ReturnStatement<'a>) -> Statement<'a> { - let value = self.reduce_expression(input.expression.get()); - - self.reducer.reduce_return(input, value) - } -} - -#[allow(dead_code)] -impl<'a, R: ReconstructingReducerProgram<'a>> ReconstructingDirector<'a, R> { - fn reduce_function(&mut self, input: &'a Function<'a>) -> &'a Function<'a> { - let body = input.body.get().map(|s| self.reduce_statement(s)); - - self.reducer.reduce_function(input, body) - } - - pub fn reduce_circuit_member(&mut self, input: CircuitMember<'a>) -> CircuitMember<'a> { - match input { - CircuitMember::Function(function) => { - let function = self.reduce_function(function); - self.reducer.reduce_circuit_member_function(input, function) - } - CircuitMember::Variable(_) => self.reducer.reduce_circuit_member_variable(input), - } - } - - pub fn reduce_circuit(&mut self, input: &'a Circuit<'a>) -> &'a Circuit<'a> { - let members = input - .members - .borrow() - .iter() - .map(|(_, member)| self.reduce_circuit_member(member.clone())) - .collect(); - - self.reducer.reduce_circuit(input, members) - } - - pub fn reduce_global_const(&mut self, input: &'a DefinitionStatement<'a>) -> &'a DefinitionStatement<'a> { - let value = self.reduce_expression(input.value.get()); - - self.reducer.reduce_global_const(input, value) - } - - pub fn reduce_program(&mut self, input: Program<'a>) -> Program<'a> { - let imported_modules = input - .imported_modules - .iter() - .map(|(module, import)| (module.clone(), self.reduce_program(import.clone()))) - .collect(); - let aliases = input.aliases.iter().map(|(name, a)| (name.clone(), *a)).collect(); - let functions = input - .functions - .iter() - .map(|(name, f)| (name.clone(), self.reduce_function(f))) - .collect(); - let circuits = input - .circuits - .iter() - .map(|(name, c)| (name.clone(), self.reduce_circuit(c))) - .collect(); - - let global_consts = input - .global_consts - .iter() - .map(|(name, gc)| (name.clone(), self.reduce_global_const(gc))) - .collect(); - - self.reducer - .reduce_program(input, imported_modules, aliases, functions, circuits, global_consts) - } -} diff --git a/asg/src/reducer/reconstructing_reducer.rs b/asg/src/reducer/reconstructing_reducer.rs deleted file mode 100644 index f43a77e4f6..0000000000 --- a/asg/src/reducer/reconstructing_reducer.rs +++ /dev/null @@ -1,416 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use std::cell::Cell; - -use leo_ast::Identifier; - -use crate::{expression::*, program::*, statement::*, AsgContext}; - -#[allow(unused_variables)] -pub trait ReconstructingReducerExpression<'a> { - fn reduce_expression(&mut self, input: &'a Expression<'a>, value: Expression<'a>) -> Expression<'a> { - value - } - - fn reduce_array_access( - &mut self, - input: ArrayAccessExpression<'a>, - array: &'a Expression<'a>, - index: &'a Expression<'a>, - ) -> Expression<'a> { - Expression::ArrayAccess(ArrayAccessExpression { - parent: input.parent, - array: Cell::new(array), - index: Cell::new(index), - span: input.span, - }) - } - - fn reduce_array_init(&mut self, input: ArrayInitExpression<'a>, element: &'a Expression<'a>) -> Expression<'a> { - Expression::ArrayInit(ArrayInitExpression { - parent: input.parent, - element: Cell::new(element), - len: input.len, - span: input.span, - }) - } - - fn reduce_array_inline( - &mut self, - input: ArrayInlineExpression<'a>, - elements: Vec<(&'a Expression<'a>, bool)>, - ) -> Expression<'a> { - Expression::ArrayInline(ArrayInlineExpression { - parent: input.parent, - elements: elements.into_iter().map(|x| (Cell::new(x.0), x.1)).collect(), - span: input.span, - }) - } - - fn reduce_array_range_access( - &mut self, - input: ArrayRangeAccessExpression<'a>, - array: &'a Expression<'a>, - left: Option<&'a Expression<'a>>, - right: Option<&'a Expression<'a>>, - ) -> Expression<'a> { - Expression::ArrayRangeAccess(ArrayRangeAccessExpression { - parent: input.parent, - array: Cell::new(array), - left: Cell::new(left), - right: Cell::new(right), - span: input.span, - length: input.length, - }) - } - - fn reduce_binary( - &mut self, - input: BinaryExpression<'a>, - left: &'a Expression<'a>, - right: &'a Expression<'a>, - ) -> Expression<'a> { - Expression::Binary(BinaryExpression { - parent: input.parent, - left: Cell::new(left), - right: Cell::new(right), - span: input.span, - operation: input.operation, - }) - } - - fn reduce_call( - &mut self, - input: CallExpression<'a>, - target: Option<&'a Expression<'a>>, - arguments: Vec<&'a Expression<'a>>, - ) -> Expression<'a> { - Expression::Call(CallExpression { - parent: input.parent, - function: input.function, - target: Cell::new(target), - arguments: arguments.into_iter().map(Cell::new).collect(), - span: input.span, - }) - } - - fn reduce_circuit_access( - &mut self, - input: CircuitAccessExpression<'a>, - target: Option<&'a Expression<'a>>, - ) -> Expression<'a> { - Expression::CircuitAccess(CircuitAccessExpression { - parent: input.parent, - circuit: input.circuit, - target: Cell::new(target), - member: input.member, - span: input.span, - }) - } - - fn reduce_circuit_init( - &mut self, - input: CircuitInitExpression<'a>, - values: Vec<(Identifier, &'a Expression<'a>)>, - ) -> Expression<'a> { - Expression::CircuitInit(CircuitInitExpression { - parent: input.parent, - circuit: input.circuit, - values: values.into_iter().map(|x| (x.0, Cell::new(x.1))).collect(), - span: input.span, - }) - } - - fn reduce_ternary_expression( - &mut self, - input: TernaryExpression<'a>, - condition: &'a Expression<'a>, - if_true: &'a Expression<'a>, - if_false: &'a Expression<'a>, - ) -> Expression<'a> { - Expression::Ternary(TernaryExpression { - parent: input.parent, - condition: Cell::new(condition), - if_true: Cell::new(if_true), - if_false: Cell::new(if_false), - span: input.span, - }) - } - - fn reduce_cast_expression(&mut self, input: CastExpression<'a>, inner: &'a Expression<'a>) -> Expression<'a> { - Expression::Cast(CastExpression { - parent: input.parent, - inner: Cell::new(inner), - target_type: input.target_type, - span: input.span, - }) - } - - fn reduce_constant(&mut self, input: Constant<'a>) -> Expression<'a> { - Expression::Constant(input) - } - - fn reduce_tuple_access( - &mut self, - input: TupleAccessExpression<'a>, - tuple_ref: &'a Expression<'a>, - ) -> Expression<'a> { - Expression::TupleAccess(TupleAccessExpression { - parent: input.parent, - tuple_ref: Cell::new(tuple_ref), - index: input.index, - span: input.span, - }) - } - - fn reduce_tuple_init(&mut self, input: TupleInitExpression<'a>, values: Vec<&'a Expression<'a>>) -> Expression<'a> { - Expression::TupleInit(TupleInitExpression { - parent: input.parent, - elements: values.into_iter().map(Cell::new).collect(), - span: input.span, - }) - } - - fn reduce_unary(&mut self, input: UnaryExpression<'a>, inner: &'a Expression<'a>) -> Expression<'a> { - Expression::Unary(UnaryExpression { - parent: input.parent, - inner: Cell::new(inner), - span: input.span, - operation: input.operation, - }) - } - - fn reduce_variable_ref(&mut self, input: VariableRef<'a>) -> Expression<'a> { - Expression::VariableRef(input) - } -} - -#[allow(unused_variables)] -pub trait ReconstructingReducerStatement<'a>: ReconstructingReducerExpression<'a> { - fn reduce_statement_alloc( - &mut self, - context: AsgContext<'a>, - input: &'a Statement<'a>, - value: Statement<'a>, - ) -> &'a Statement<'a> { - context.alloc_statement(value) - } - - fn reduce_statement(&mut self, input: &'a Statement<'a>, value: Statement<'a>) -> Statement<'a> { - value - } - - fn reduce_assign_access_range( - &mut self, - input: AssignAccess<'a>, - left: Option<&'a Expression<'a>>, - right: Option<&'a Expression<'a>>, - ) -> AssignAccess<'a> { - AssignAccess::ArrayRange(Cell::new(left), Cell::new(right)) - } - - fn reduce_assign_access_index(&mut self, input: AssignAccess<'a>, index: &'a Expression<'a>) -> AssignAccess<'a> { - AssignAccess::ArrayIndex(Cell::new(index)) - } - - fn reduce_assign_access(&mut self, input: AssignAccess<'a>) -> AssignAccess<'a> { - input - } - - fn reduce_assign( - &mut self, - input: AssignStatement<'a>, - accesses: Vec>, - value: &'a Expression<'a>, - ) -> Statement<'a> { - Statement::Assign(AssignStatement { - parent: input.parent, - span: input.span, - operation: input.operation, - target_accesses: accesses, - target_variable: input.target_variable, - value: Cell::new(value), - }) - } - - fn reduce_block(&mut self, input: BlockStatement<'a>, statements: Vec<&'a Statement<'a>>) -> Statement<'a> { - Statement::Block(BlockStatement { - parent: input.parent, - span: input.span, - statements: statements.into_iter().map(Cell::new).collect(), - scope: input.scope, - }) - } - - fn reduce_conditional_statement( - &mut self, - input: ConditionalStatement<'a>, - condition: &'a Expression<'a>, - if_true: &'a Statement<'a>, - if_false: Option<&'a Statement<'a>>, - ) -> Statement<'a> { - Statement::Conditional(ConditionalStatement { - parent: input.parent, - span: input.span, - condition: Cell::new(condition), - result: Cell::new(if_true), - next: Cell::new(if_false), - }) - } - - fn reduce_formatted_string( - &mut self, - input: ConsoleArgs<'a>, - parameters: Vec<&'a Expression<'a>>, - ) -> ConsoleArgs<'a> { - ConsoleArgs { - span: input.span, - string: input.string, - parameters: parameters.into_iter().map(Cell::new).collect(), - } - } - - fn reduce_console_assert(&mut self, input: ConsoleStatement<'a>, argument: &'a Expression<'a>) -> Statement<'a> { - assert!(matches!(input.function, ConsoleFunction::Assert(_))); - Statement::Console(ConsoleStatement { - parent: input.parent, - span: input.span, - function: ConsoleFunction::Assert(Cell::new(argument)), - }) - } - - fn reduce_console_log(&mut self, input: ConsoleStatement<'a>, argument: ConsoleArgs<'a>) -> Statement<'a> { - assert!(!matches!(input.function, ConsoleFunction::Assert(_))); - Statement::Console(ConsoleStatement { - parent: input.parent, - span: input.span, - function: match input.function { - ConsoleFunction::Assert(_) => unimplemented!(), - ConsoleFunction::Error(_) => ConsoleFunction::Error(argument), - ConsoleFunction::Log(_) => ConsoleFunction::Log(argument), - }, - }) - } - - fn reduce_definition(&mut self, input: DefinitionStatement<'a>, value: &'a Expression<'a>) -> Statement<'a> { - Statement::Definition(DefinitionStatement { - parent: input.parent, - span: input.span, - variables: input.variables, - value: Cell::new(value), - }) - } - - fn reduce_expression_statement( - &mut self, - input: ExpressionStatement<'a>, - expression: &'a Expression<'a>, - ) -> Statement<'a> { - Statement::Expression(ExpressionStatement { - parent: input.parent, - span: input.span, - expression: Cell::new(expression), - }) - } - - fn reduce_iteration( - &mut self, - input: IterationStatement<'a>, - start: &'a Expression<'a>, - stop: &'a Expression<'a>, - body: &'a Statement<'a>, - ) -> Statement<'a> { - Statement::Iteration(IterationStatement { - parent: input.parent, - span: input.span, - variable: input.variable, - start: Cell::new(start), - stop: Cell::new(stop), - inclusive: input.inclusive, - body: Cell::new(body), - }) - } - - fn reduce_return(&mut self, input: ReturnStatement<'a>, value: &'a Expression<'a>) -> Statement<'a> { - Statement::Return(ReturnStatement { - parent: input.parent, - span: input.span, - expression: Cell::new(value), - }) - } -} - -#[allow(unused_variables)] -pub trait ReconstructingReducerProgram<'a>: ReconstructingReducerStatement<'a> { - // todo @protryon: this is kind of hacky - fn reduce_function(&mut self, input: &'a Function<'a>, body: Option<&'a Statement<'a>>) -> &'a Function<'a> { - input.body.set(body); - input - } - - fn reduce_circuit_member_variable(&mut self, input: CircuitMember<'a>) -> CircuitMember<'a> { - input - } - - fn reduce_circuit_member_function( - &mut self, - input: CircuitMember<'a>, - function: &'a Function<'a>, - ) -> CircuitMember<'a> { - CircuitMember::Function(function) - } - - // todo @protryon: this is kind of hacky - fn reduce_circuit(&mut self, input: &'a Circuit<'a>, members: Vec>) -> &'a Circuit<'a> { - let mut input_members = input.members.borrow_mut(); - for ((name, input_member), member) in input_members.iter_mut().zip(members) { - *input_member = member; - } - input - } - - fn reduce_global_const( - &mut self, - input: &'a DefinitionStatement<'a>, - value: &'a Expression<'a>, - ) -> &'a DefinitionStatement<'a> { - input.value.set(value); - input - } - - fn reduce_program( - &mut self, - input: Program<'a>, - imported_modules: Vec<(String, Program<'a>)>, - aliases: Vec<(String, &'a Alias<'a>)>, - functions: Vec<(String, &'a Function<'a>)>, - circuits: Vec<(String, &'a Circuit<'a>)>, - global_consts: Vec<(String, &'a DefinitionStatement<'a>)>, - ) -> Program<'a> { - Program { - context: input.context, - id: input.id, - name: input.name, - imported_modules: imported_modules.into_iter().collect(), - aliases: aliases.into_iter().collect(), - functions: functions.into_iter().collect(), - circuits: circuits.into_iter().collect(), - scope: input.scope, - global_consts: global_consts.into_iter().collect(), - } - } -} diff --git a/asg/src/reducer/visitor.rs b/asg/src/reducer/visitor.rs deleted file mode 100644 index 4f3b468ab5..0000000000 --- a/asg/src/reducer/visitor.rs +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use std::cell::Cell; - -use crate::{expression::*, program::*, statement::*}; - -pub enum VisitResult { - VisitChildren, - SkipChildren, - Exit, -} - -impl Default for VisitResult { - fn default() -> Self { - VisitResult::VisitChildren - } -} - -#[allow(unused_variables)] -pub trait ExpressionVisitor<'a> { - fn visit_expression(&mut self, input: &Cell<&'a Expression<'a>>) -> VisitResult { - Default::default() - } - - fn visit_array_access(&mut self, input: &ArrayAccessExpression<'a>) -> VisitResult { - Default::default() - } - - fn visit_array_init(&mut self, input: &ArrayInitExpression<'a>) -> VisitResult { - Default::default() - } - - fn visit_array_inline(&mut self, input: &ArrayInlineExpression<'a>) -> VisitResult { - Default::default() - } - - fn visit_array_range_access(&mut self, input: &ArrayRangeAccessExpression<'a>) -> VisitResult { - Default::default() - } - - fn visit_binary(&mut self, input: &BinaryExpression<'a>) -> VisitResult { - Default::default() - } - - fn visit_call(&mut self, input: &CallExpression<'a>) -> VisitResult { - Default::default() - } - - fn visit_circuit_access(&mut self, input: &CircuitAccessExpression<'a>) -> VisitResult { - Default::default() - } - - fn visit_circuit_init(&mut self, input: &CircuitInitExpression<'a>) -> VisitResult { - Default::default() - } - - fn visit_ternary_expression(&mut self, input: &TernaryExpression<'a>) -> VisitResult { - Default::default() - } - - fn visit_cast_expression(&mut self, input: &CastExpression<'a>) -> VisitResult { - Default::default() - } - - fn visit_lengthof_expression(&mut self, input: &LengthOfExpression<'a>) -> VisitResult { - Default::default() - } - - fn visit_constant(&mut self, input: &Constant<'a>) -> VisitResult { - Default::default() - } - - fn visit_tuple_access(&mut self, input: &TupleAccessExpression<'a>) -> VisitResult { - Default::default() - } - - fn visit_tuple_init(&mut self, input: &TupleInitExpression<'a>) -> VisitResult { - Default::default() - } - - fn visit_unary(&mut self, input: &UnaryExpression<'a>) -> VisitResult { - Default::default() - } - - fn visit_variable_ref(&mut self, input: &VariableRef<'a>) -> VisitResult { - Default::default() - } -} - -#[allow(unused_variables)] -pub trait StatementVisitor<'a>: ExpressionVisitor<'a> { - fn visit_statement(&mut self, input: &Cell<&'a Statement<'a>>) -> VisitResult { - Default::default() - } - - // left = Some(ArrayIndex.0) always if AssignAccess::ArrayIndex. if member/tuple, always None - fn visit_assign_access(&mut self, input: &AssignAccess<'a>) -> VisitResult { - Default::default() - } - - fn visit_assign(&mut self, input: &AssignStatement<'a>) -> VisitResult { - Default::default() - } - - fn visit_block(&mut self, input: &BlockStatement<'a>) -> VisitResult { - Default::default() - } - - fn visit_conditional_statement(&mut self, input: &ConditionalStatement<'a>) -> VisitResult { - Default::default() - } - - fn visit_formatted_string(&mut self, input: &ConsoleArgs<'a>) -> VisitResult { - Default::default() - } - - fn visit_console(&mut self, input: &ConsoleStatement<'a>) -> VisitResult { - Default::default() - } - - fn visit_definition(&mut self, input: &DefinitionStatement<'a>) -> VisitResult { - Default::default() - } - - fn visit_expression_statement(&mut self, input: &ExpressionStatement<'a>) -> VisitResult { - Default::default() - } - - fn visit_iteration(&mut self, input: &IterationStatement<'a>) -> VisitResult { - Default::default() - } - - fn visit_return(&mut self, input: &ReturnStatement<'a>) -> VisitResult { - Default::default() - } -} - -#[allow(unused_variables)] -pub trait ProgramVisitor<'a>: StatementVisitor<'a> { - fn visit_function(&mut self, input: &'a Function<'a>) -> VisitResult { - Default::default() - } - - fn visit_circuit_member(&mut self, input: &CircuitMember<'a>) -> VisitResult { - Default::default() - } - - fn visit_circuit(&mut self, input: &'a Circuit<'a>) -> VisitResult { - Default::default() - } - - fn visit_global_const(&mut self, input: &'a DefinitionStatement<'a>) -> VisitResult { - Default::default() - } - - fn visit_program(&mut self, input: &Program<'a>) -> VisitResult { - Default::default() - } -} diff --git a/asg/src/reducer/visitor_director.rs b/asg/src/reducer/visitor_director.rs deleted file mode 100644 index 5490f4b014..0000000000 --- a/asg/src/reducer/visitor_director.rs +++ /dev/null @@ -1,466 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::*; -use crate::{expression::*, program::*, statement::*}; - -use std::{cell::Cell, marker::PhantomData}; - -pub struct VisitorDirector<'a, R: ExpressionVisitor<'a>> { - visitor: R, - lifetime: PhantomData<&'a ()>, -} - -pub type ConcreteVisitResult = Result<(), ()>; - -impl Into for VisitResult { - fn into(self) -> ConcreteVisitResult { - match self { - VisitResult::VisitChildren => Ok(()), - VisitResult::SkipChildren => Ok(()), - VisitResult::Exit => Err(()), - } - } -} - -impl<'a, R: ExpressionVisitor<'a>> VisitorDirector<'a, R> { - pub fn new(visitor: R) -> Self { - Self { - visitor, - lifetime: PhantomData, - } - } - - pub fn visitor(self) -> R { - self.visitor - } - - pub fn visit_expression(&mut self, input: &Cell<&'a Expression<'a>>) -> ConcreteVisitResult { - match self.visitor.visit_expression(input) { - VisitResult::VisitChildren => match input.get() { - Expression::ArrayAccess(e) => self.visit_array_access(e), - Expression::ArrayInit(e) => self.visit_array_init(e), - Expression::ArrayInline(e) => self.visit_array_inline(e), - Expression::ArrayRangeAccess(e) => self.visit_array_range_access(e), - Expression::Binary(e) => self.visit_binary(e), - Expression::Call(e) => self.visit_call(e), - Expression::CircuitAccess(e) => self.visit_circuit_access(e), - Expression::CircuitInit(e) => self.visit_circuit_init(e), - Expression::Ternary(e) => self.visit_ternary_expression(e), - Expression::Cast(e) => self.visit_cast_expression(e), - Expression::LengthOf(e) => self.visit_lengthof_expression(e), - Expression::Constant(e) => self.visit_constant(e), - Expression::TupleAccess(e) => self.visit_tuple_access(e), - Expression::TupleInit(e) => self.visit_tuple_init(e), - Expression::Unary(e) => self.visit_unary(e), - Expression::VariableRef(e) => self.visit_variable_ref(e), - }, - x => x.into(), - } - } - - fn visit_opt_expression(&mut self, input: &Cell>>) -> ConcreteVisitResult { - let interior = input.get().map(Cell::new); - if let Some(interior) = interior.as_ref() { - let result = self.visit_expression(interior); - input.replace(Some(interior.get())); - result - } else { - Ok(()) - } - } - - pub fn visit_array_access(&mut self, input: &ArrayAccessExpression<'a>) -> ConcreteVisitResult { - match self.visitor.visit_array_access(input) { - VisitResult::VisitChildren => { - self.visit_expression(&input.array)?; - self.visit_expression(&input.index)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_array_init(&mut self, input: &ArrayInitExpression<'a>) -> ConcreteVisitResult { - match self.visitor.visit_array_init(input) { - VisitResult::VisitChildren => { - self.visit_expression(&input.element)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_array_inline(&mut self, input: &ArrayInlineExpression<'a>) -> ConcreteVisitResult { - match self.visitor.visit_array_inline(input) { - VisitResult::VisitChildren => { - for (element, _) in input.elements.iter() { - self.visit_expression(element)?; - } - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_array_range_access(&mut self, input: &ArrayRangeAccessExpression<'a>) -> ConcreteVisitResult { - match self.visitor.visit_array_range_access(input) { - VisitResult::VisitChildren => { - self.visit_expression(&input.array)?; - self.visit_opt_expression(&input.left)?; - self.visit_opt_expression(&input.right)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_binary(&mut self, input: &BinaryExpression<'a>) -> ConcreteVisitResult { - match self.visitor.visit_binary(input) { - VisitResult::VisitChildren => { - self.visit_expression(&input.left)?; - self.visit_expression(&input.right)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_call(&mut self, input: &CallExpression<'a>) -> ConcreteVisitResult { - match self.visitor.visit_call(input) { - VisitResult::VisitChildren => { - self.visit_opt_expression(&input.target)?; - for argument in input.arguments.iter() { - self.visit_expression(argument)?; - } - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_circuit_access(&mut self, input: &CircuitAccessExpression<'a>) -> ConcreteVisitResult { - match self.visitor.visit_circuit_access(input) { - VisitResult::VisitChildren => { - self.visit_opt_expression(&input.target)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_circuit_init(&mut self, input: &CircuitInitExpression<'a>) -> ConcreteVisitResult { - match self.visitor.visit_circuit_init(input) { - VisitResult::VisitChildren => { - for (_, argument) in input.values.iter() { - self.visit_expression(argument)?; - } - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_ternary_expression(&mut self, input: &TernaryExpression<'a>) -> ConcreteVisitResult { - match self.visitor.visit_ternary_expression(input) { - VisitResult::VisitChildren => { - self.visit_expression(&input.condition)?; - self.visit_expression(&input.if_true)?; - self.visit_expression(&input.if_false)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_cast_expression(&mut self, input: &CastExpression<'a>) -> ConcreteVisitResult { - match self.visitor.visit_cast_expression(input) { - VisitResult::VisitChildren => { - self.visit_expression(&input.inner)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_lengthof_expression(&mut self, input: &LengthOfExpression<'a>) -> ConcreteVisitResult { - match self.visitor.visit_lengthof_expression(input) { - VisitResult::VisitChildren => { - self.visit_expression(&input.inner)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_constant(&mut self, input: &Constant<'a>) -> ConcreteVisitResult { - self.visitor.visit_constant(input).into() - } - - pub fn visit_tuple_access(&mut self, input: &TupleAccessExpression<'a>) -> ConcreteVisitResult { - match self.visitor.visit_tuple_access(input) { - VisitResult::VisitChildren => { - self.visit_expression(&input.tuple_ref)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_tuple_init(&mut self, input: &TupleInitExpression<'a>) -> ConcreteVisitResult { - match self.visitor.visit_tuple_init(input) { - VisitResult::VisitChildren => { - for argument in input.elements.iter() { - self.visit_expression(argument)?; - } - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_unary(&mut self, input: &UnaryExpression<'a>) -> ConcreteVisitResult { - match self.visitor.visit_unary(input) { - VisitResult::VisitChildren => { - self.visit_expression(&input.inner)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_variable_ref(&mut self, input: &VariableRef<'a>) -> ConcreteVisitResult { - self.visitor.visit_variable_ref(input).into() - } -} - -impl<'a, R: StatementVisitor<'a>> VisitorDirector<'a, R> { - pub fn visit_statement(&mut self, input: &Cell<&'a Statement<'a>>) -> ConcreteVisitResult { - match self.visitor.visit_statement(input) { - VisitResult::VisitChildren => match input.get() { - Statement::Assign(s) => self.visit_assign(s), - Statement::Block(s) => self.visit_block(s), - Statement::Conditional(s) => self.visit_conditional_statement(s), - Statement::Console(s) => self.visit_console(s), - Statement::Definition(s) => self.visit_definition(s), - Statement::Expression(s) => self.visit_expression_statement(s), - Statement::Iteration(s) => self.visit_iteration(s), - Statement::Return(s) => self.visit_return(s), - Statement::Empty(_) => Ok(()), - }, - x => x.into(), - } - } - - fn visit_opt_statement(&mut self, input: &Cell>>) -> ConcreteVisitResult { - let interior = input.get().map(Cell::new); - if let Some(interior) = interior.as_ref() { - let result = self.visit_statement(interior); - input.replace(Some(interior.get())); - result - } else { - Ok(()) - } - } - - pub fn visit_assign_access(&mut self, input: &AssignAccess<'a>) -> ConcreteVisitResult { - match self.visitor.visit_assign_access(input) { - VisitResult::VisitChildren => { - match input { - AssignAccess::ArrayRange(left, right) => { - self.visit_opt_expression(left)?; - self.visit_opt_expression(right)?; - } - AssignAccess::ArrayIndex(index) => self.visit_expression(index)?, - _ => (), - } - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_assign(&mut self, input: &AssignStatement<'a>) -> ConcreteVisitResult { - match self.visitor.visit_assign(input) { - VisitResult::VisitChildren => { - for access in input.target_accesses.iter() { - self.visit_assign_access(access)?; - } - self.visit_expression(&input.value)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_block(&mut self, input: &BlockStatement<'a>) -> ConcreteVisitResult { - match self.visitor.visit_block(input) { - VisitResult::VisitChildren => { - for statement in input.statements.iter() { - self.visit_statement(statement)?; - } - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_conditional_statement(&mut self, input: &ConditionalStatement<'a>) -> ConcreteVisitResult { - match self.visitor.visit_conditional_statement(input) { - VisitResult::VisitChildren => { - self.visit_expression(&input.condition)?; - self.visit_statement(&input.result)?; - self.visit_opt_statement(&input.next)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_formatted_string(&mut self, input: &ConsoleArgs<'a>) -> ConcreteVisitResult { - match self.visitor.visit_formatted_string(input) { - VisitResult::VisitChildren => { - for parameter in input.parameters.iter() { - self.visit_expression(parameter)?; - } - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_console(&mut self, input: &ConsoleStatement<'a>) -> ConcreteVisitResult { - match self.visitor.visit_console(input) { - VisitResult::VisitChildren => { - match &input.function { - ConsoleFunction::Assert(e) => self.visit_expression(e)?, - ConsoleFunction::Error(f) | ConsoleFunction::Log(f) => self.visit_formatted_string(f)?, - } - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_definition(&mut self, input: &DefinitionStatement<'a>) -> ConcreteVisitResult { - match self.visitor.visit_definition(input) { - VisitResult::VisitChildren => { - self.visit_expression(&input.value)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_expression_statement(&mut self, input: &ExpressionStatement<'a>) -> ConcreteVisitResult { - match self.visitor.visit_expression_statement(input) { - VisitResult::VisitChildren => { - self.visit_expression(&input.expression)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_iteration(&mut self, input: &IterationStatement<'a>) -> ConcreteVisitResult { - match self.visitor.visit_iteration(input) { - VisitResult::VisitChildren => { - self.visit_expression(&input.start)?; - self.visit_expression(&input.stop)?; - self.visit_statement(&input.body)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_return(&mut self, input: &ReturnStatement<'a>) -> ConcreteVisitResult { - match self.visitor.visit_return(input) { - VisitResult::VisitChildren => { - self.visit_expression(&input.expression)?; - Ok(()) - } - x => x.into(), - } - } -} - -impl<'a, R: ProgramVisitor<'a>> VisitorDirector<'a, R> { - pub fn visit_function(&mut self, input: &'a Function<'a>) -> ConcreteVisitResult { - match self.visitor.visit_function(input) { - VisitResult::VisitChildren => { - self.visit_opt_statement(&input.body)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_circuit_member(&mut self, input: &CircuitMember<'a>) -> ConcreteVisitResult { - match self.visitor.visit_circuit_member(input) { - VisitResult::VisitChildren => { - if let CircuitMember::Function(f) = input { - self.visit_function(f)?; - } - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_circuit(&mut self, input: &'a Circuit<'a>) -> ConcreteVisitResult { - match self.visitor.visit_circuit(input) { - VisitResult::VisitChildren => { - for (_, member) in input.members.borrow().iter() { - self.visit_circuit_member(member)?; - } - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_global_const(&mut self, input: &'a DefinitionStatement<'a>) -> ConcreteVisitResult { - match self.visitor.visit_global_const(input) { - VisitResult::VisitChildren => { - self.visit_expression(&input.value)?; - Ok(()) - } - x => x.into(), - } - } - - pub fn visit_program(&mut self, input: &Program<'a>) -> ConcreteVisitResult { - match self.visitor.visit_program(input) { - VisitResult::VisitChildren => { - for (_, import) in input.imported_modules.iter() { - self.visit_program(import)?; - } - for (_, function) in input.functions.iter() { - self.visit_function(function)?; - } - for (_, circuit) in input.circuits.iter() { - self.visit_circuit(circuit)?; - } - for (_, global_const) in input.global_consts.iter() { - self.visit_global_const(global_const)?; - } - Ok(()) - } - x => x.into(), - } - } -} diff --git a/asg/src/scope.rs b/asg/src/scope.rs deleted file mode 100644 index 9b05af5cc3..0000000000 --- a/asg/src/scope.rs +++ /dev/null @@ -1,235 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{Alias, AsgContext, Circuit, DefinitionStatement, Function, Input, Type, Variable}; -use leo_errors::{AsgError, Result, Span}; - -use indexmap::IndexMap; -use std::cell::{Cell, RefCell}; - -/// An abstract data type that track the current bindings for variables, functions, and circuits. -#[derive(Clone)] -pub struct Scope<'a> { - pub context: AsgContext<'a>, - - /// The unique id of the scope. - pub id: u32, - - /// The parent scope that this scope inherits. - pub parent_scope: Cell>>, - - /// The function definition that this scope occurs in. - pub function: Cell>>, - - /// Maps variable name => variable. - pub variables: RefCell>>, - - /// Maps alias name => alias. - pub aliases: RefCell>>, - - /// Maps function name => function. - pub functions: RefCell>>, - - /// Maps global constant name => global const code block. - pub global_consts: RefCell>>, - - /// Maps circuit name => circuit. - pub circuits: RefCell>>, - - /// The main input to the program. - pub input: Cell>>, -} - -#[allow(clippy::mut_from_ref)] -impl<'a> Scope<'a> { - /// - /// Returns a reference to the variable corresponding to the name. - /// - /// If the current scope did not have this name present, then the parent scope is checked. - /// If there is no parent scope, then `None` is returned. - /// - pub fn resolve_variable(&self, name: &str) -> Option<&'a Variable<'a>> { - if let Some(resolved) = self.variables.borrow().get(name) { - Some(*resolved) - } else if let Some(scope) = self.parent_scope.get() { - scope.resolve_variable(name) - } else { - None - } - } - - /// - /// Returns a reference to the current function. - /// - /// If the current scope did not have a function present, then the parent scope is checked. - /// If there is no parent scope, then `None` is returned. - /// - pub fn resolve_current_function(&self) -> Option<&'a Function> { - if let Some(resolved) = self.function.get() { - Some(resolved) - } else if let Some(scope) = self.parent_scope.get() { - scope.resolve_current_function() - } else { - None - } - } - - /// - /// Returns a reference to the current input. - /// - /// If the current scope did not have an input present, then the parent scope is checked. - /// If there is no parent scope, then `None` is returned. - /// - pub fn resolve_input(&self) -> Option> { - if let Some(input) = self.input.get() { - Some(input) - } else if let Some(resolved) = self.parent_scope.get() { - resolved.resolve_input() - } else { - None - } - } - - /// - /// Returns a reference to the alias corresponding to the name. - /// - /// If the current scope did not have this name present, then the parent scope is checked. - /// If there is no parent scope, then `None` is returned. - /// - pub fn resolve_alias(&self, name: &str) -> Option<&'a Alias<'a>> { - if let Some(resolved) = self.aliases.borrow().get(name) { - Some(*resolved) - } else if let Some(resolved) = self.parent_scope.get() { - resolved.resolve_alias(name) - } else { - None - } - } - - /// - /// Returns a reference to the function corresponding to the name. - /// - /// If the current scope did not have this name present, then the parent scope is checked. - /// If there is no parent scope, then `None` is returned. - /// - pub fn resolve_function(&self, name: &str) -> Option<&'a Function<'a>> { - if let Some(resolved) = self.functions.borrow().get(name) { - Some(*resolved) - } else if let Some(resolved) = self.parent_scope.get() { - resolved.resolve_function(name) - } else { - None - } - } - - /// - /// Returns a reference to the circuit corresponding to the name. - /// - /// If the current scope did not have this name present, then the parent scope is checked. - /// If there is no parent scope, then `None` is returned. - /// - pub fn resolve_circuit(&self, name: &str) -> Option<&'a Circuit<'a>> { - if let Some(resolved) = self.circuits.borrow().get(name) { - Some(*resolved) - } else if let Some(resolved) = self.parent_scope.get() { - resolved.resolve_circuit(name) - } else { - None - } - } - - /// - /// Returns a reference to the global const definition statement corresponding to the name. - /// - /// If the current scope did not have this name present, then the parent scope is checked. - /// If there is no parent scope, then `None` is returned. - /// - pub fn resolve_global_const(&self, name: &str) -> Option<&'a DefinitionStatement<'a>> { - if let Some(resolved) = self.global_consts.borrow().get(name) { - Some(*resolved) - } else if let Some(resolved) = self.parent_scope.get() { - resolved.resolve_global_const(name) - } else { - None - } - } - - /// - /// Returns a new scope given a parent scope. - /// - pub fn make_subscope(self: &'a Scope<'a>) -> &'a Scope<'a> { - self.context.alloc_scope(Scope::<'a> { - context: self.context, - id: self.context.get_id(), - parent_scope: Cell::new(Some(self)), - variables: RefCell::new(IndexMap::new()), - aliases: RefCell::new(IndexMap::new()), - functions: RefCell::new(IndexMap::new()), - circuits: RefCell::new(IndexMap::new()), - global_consts: RefCell::new(IndexMap::new()), - function: Cell::new(None), - input: Cell::new(None), - }) - } - - /// - /// Returns the type returned by the current scope. - /// - pub fn resolve_ast_type(&self, type_: &leo_ast::Type, span: &Span) -> Result> { - use leo_ast::Type::*; - Ok(match type_ { - Address => Type::Address, - Boolean => Type::Boolean, - Char => Type::Char, - Field => Type::Field, - Group => Type::Group, - IntegerType(int_type) => Type::Integer(int_type.clone()), - Array(sub_type, dimensions) => { - let mut item = Box::new(self.resolve_ast_type(&*sub_type, span)?); - - if let Some(dimensions) = dimensions { - for dimension in dimensions.0.iter().rev() { - let dimension = dimension - .value - .parse::() - .map_err(|_| AsgError::parse_index_error(span))?; - item = Box::new(Type::Array(item, dimension)); - } - } else { - item = Box::new(Type::ArrayWithoutSize(item)); - } - - *item - } - Tuple(sub_types) => Type::Tuple( - sub_types - .iter() - .map(|x| self.resolve_ast_type(x, span)) - .collect::>>()?, - ), - SelfType => return Err(AsgError::unexpected_big_self(span).into()), - Identifier(name) => { - if let Some(circuit) = self.resolve_circuit(&name.name) { - Type::Circuit(circuit) - } else if let Some(alias) = self.resolve_alias(&name.name) { - alias.represents.clone() - } else { - return Err(AsgError::unresolved_circuit(&name.name, &name.span).into()); - } - } - }) - } -} diff --git a/asg/src/statement/assign.rs b/asg/src/statement/assign.rs deleted file mode 100644 index 59c7b3a528..0000000000 --- a/asg/src/statement/assign.rs +++ /dev/null @@ -1,246 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ - CircuitMember, ConstInt, ConstValue, Expression, ExpressionNode, FromAst, Identifier, IntegerType, Node, - PartialType, Scope, Statement, Type, Variable, -}; -pub use leo_ast::AssignOperation; -use leo_ast::AssigneeAccess as AstAssigneeAccess; -use leo_errors::{AsgError, Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub enum AssignAccess<'a> { - ArrayRange(Cell>>, Cell>>), - ArrayIndex(Cell<&'a Expression<'a>>), - Tuple(usize), - Member(Identifier), -} - -#[derive(Clone)] -pub struct AssignStatement<'a> { - pub parent: Cell>>, - pub span: Option, - pub operation: AssignOperation, - pub target_variable: Cell<&'a Variable<'a>>, - pub target_accesses: Vec>, - pub value: Cell<&'a Expression<'a>>, -} - -impl<'a> Node for AssignStatement<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> { - fn from_ast( - scope: &'a Scope<'a>, - statement: &leo_ast::AssignStatement, - _expected_type: Option>, - ) -> Result { - let (name, span) = ( - &statement.assignee.identifier.name.clone(), - &statement.assignee.identifier.span, - ); - - let variable = if name.as_ref() == "input" { - if let Some(input) = scope.resolve_input() { - input.container - } else { - return Err(AsgError::illegal_input_variable_reference(&statement.span).into()); - } - } else { - scope - .resolve_variable(name) - .ok_or_else(|| AsgError::unresolved_reference(name, span))? - }; - - if !variable.borrow().mutable { - return Err(AsgError::immutable_assignment(name, &statement.span).into()); - } - let mut target_type: Option = Some(variable.borrow().type_.clone().into()); - - let mut target_accesses = vec![]; - for access in statement.assignee.accesses.iter() { - target_accesses.push(match access { - AstAssigneeAccess::ArrayRange(left, right) => { - let index_type = Some(PartialType::Integer(None, Some(IntegerType::U32))); - let left = left - .as_ref() - .map(|left: &leo_ast::Expression| -> Result<&'a Expression<'a>> { - <&Expression<'a>>::from_ast(scope, left, index_type.clone()) - }) - .transpose()?; - let right = right - .as_ref() - .map(|right: &leo_ast::Expression| -> Result<&'a Expression<'a>> { - <&Expression<'a>>::from_ast(scope, right, index_type) - }) - .transpose()?; - - match &target_type { - Some(PartialType::Array(item, len)) => { - if let (Some(left), Some(right)) = ( - left.as_ref() - .map(|x| x.const_value()) - .unwrap_or_else(|| Some(ConstValue::Int(ConstInt::U32(0)))), - right - .as_ref() - .map(|x| x.const_value()) - .unwrap_or_else(|| Some(ConstValue::Int(ConstInt::U32(len.map(|x| x as u32)?)))), - ) { - let left = match left { - ConstValue::Int(x) => x.to_usize().ok_or_else(|| { - AsgError::invalid_assign_index(name, x.to_string(), &statement.span) - })?, - _ => unimplemented!(), - }; - let right = match right { - ConstValue::Int(x) => x.to_usize().ok_or_else(|| { - AsgError::invalid_assign_index(name, x.to_string(), &statement.span) - })?, - _ => unimplemented!(), - }; - if right >= left { - target_type = Some(PartialType::Array(item.clone(), Some((right - left) as usize))) - } else { - return Err(AsgError::invalid_backwards_assignment( - name, - left, - right, - &statement.span, - ) - .into()); - } - } - } - _ => return Err(AsgError::index_into_non_array(name, &statement.span).into()), - } - - AssignAccess::ArrayRange(Cell::new(left), Cell::new(right)) - } - AstAssigneeAccess::ArrayIndex(index) => { - target_type = match target_type.clone() { - Some(PartialType::Array(item, _)) => item.map(|x| *x), - _ => return Err(AsgError::index_into_non_array(name, &statement.span).into()), - }; - AssignAccess::ArrayIndex(Cell::new(<&Expression<'a>>::from_ast( - scope, - index, - Some(PartialType::Integer(None, Some(IntegerType::U32))), - )?)) - } - AstAssigneeAccess::Tuple(index, span) => { - let index = index - .value - .parse::() - .map_err(|_| AsgError::parse_index_error(span))?; - target_type = match target_type { - Some(PartialType::Tuple(types)) => types - .get(index) - .cloned() - .ok_or_else(|| AsgError::tuple_index_out_of_bounds(index, &statement.span))?, - _ => return Err(AsgError::index_into_non_tuple(name, &statement.span).into()), - }; - AssignAccess::Tuple(index) - } - AstAssigneeAccess::Member(name) => { - target_type = match target_type { - Some(PartialType::Type(Type::Circuit(circuit))) => { - let circuit = circuit; - - let members = circuit.members.borrow(); - let member = members.get(name.name.as_ref()).ok_or_else(|| { - AsgError::unresolved_circuit_member( - &circuit.name.borrow().name, - &name.name, - &statement.span, - ) - })?; - - let x = match &member { - CircuitMember::Variable(type_) => type_.clone(), - CircuitMember::Function(_) => { - return Err(AsgError::illegal_function_assign(&name.name, &statement.span).into()); - } - }; - Some(x.partial()) - } - _ => { - return Err(AsgError::index_into_non_tuple( - &statement.assignee.identifier.name, - &statement.span, - ) - .into()); - } - }; - AssignAccess::Member(name.clone()) - } - }); - } - let value = <&Expression<'a>>::from_ast(scope, &statement.value, target_type)?; - - let statement = scope.context.alloc_statement(Statement::Assign(AssignStatement { - parent: Cell::new(None), - span: Some(statement.span.clone()), - operation: statement.operation, - target_variable: Cell::new(variable), - target_accesses, - value: Cell::new(value), - })); - - { - let mut variable = variable.borrow_mut(); - variable.assignments.push(statement); - } - - Ok(statement) - } -} - -impl<'a> Into for &AssignStatement<'a> { - fn into(self) -> leo_ast::AssignStatement { - leo_ast::AssignStatement { - operation: self.operation, - assignee: leo_ast::Assignee { - identifier: self.target_variable.get().borrow().name.clone(), - accesses: self - .target_accesses - .iter() - .map(|access| match access { - AssignAccess::ArrayRange(left, right) => { - AstAssigneeAccess::ArrayRange(left.get().map(|e| e.into()), right.get().map(|e| e.into())) - } - AssignAccess::ArrayIndex(index) => AstAssigneeAccess::ArrayIndex(index.get().into()), - AssignAccess::Tuple(index) => AstAssigneeAccess::Tuple( - leo_ast::PositiveNumber { - value: index.to_string().into(), - }, - self.span.clone().unwrap_or_default(), - ), - AssignAccess::Member(name) => AstAssigneeAccess::Member(name.clone()), - }) - .collect(), - span: self.span.clone().unwrap_or_default(), - }, - value: self.value.get().into(), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/statement/block.rs b/asg/src/statement/block.rs deleted file mode 100644 index f93faa0ad8..0000000000 --- a/asg/src/statement/block.rs +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{FromAst, Node, PartialType, Scope, Statement}; -use leo_errors::{Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct BlockStatement<'a> { - pub parent: Cell>>, - pub span: Option, - pub statements: Vec>>, - pub scope: &'a Scope<'a>, -} - -impl<'a> Node for BlockStatement<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> FromAst<'a, leo_ast::Block> for BlockStatement<'a> { - fn from_ast( - scope: &'a Scope<'a>, - statement: &leo_ast::Block, - _expected_type: Option>, - ) -> Result { - let new_scope = scope.make_subscope(); - - let mut output = vec![]; - for item in statement.statements.iter() { - output.push(Cell::new(<&'a Statement<'a>>::from_ast(new_scope, item, None)?)); - } - Ok(BlockStatement { - parent: Cell::new(None), - span: Some(statement.span.clone()), - statements: output, - scope: new_scope, - }) - } -} - -impl<'a> Into for &BlockStatement<'a> { - fn into(self) -> leo_ast::Block { - leo_ast::Block { - statements: self.statements.iter().map(|statement| statement.get().into()).collect(), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/statement/conditional.rs b/asg/src/statement/conditional.rs deleted file mode 100644 index ad71ba442a..0000000000 --- a/asg/src/statement/conditional.rs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{BlockStatement, Expression, FromAst, Node, PartialType, Scope, Statement, Type}; -use leo_errors::{Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct ConditionalStatement<'a> { - pub parent: Cell>>, - pub span: Option, - pub condition: Cell<&'a Expression<'a>>, - pub result: Cell<&'a Statement<'a>>, - pub next: Cell>>, -} - -impl<'a> Node for ConditionalStatement<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> FromAst<'a, leo_ast::ConditionalStatement> for ConditionalStatement<'a> { - fn from_ast( - scope: &'a Scope<'a>, - statement: &leo_ast::ConditionalStatement, - _expected_type: Option>, - ) -> Result { - let condition = <&Expression<'a>>::from_ast(scope, &statement.condition, Some(Type::Boolean.into()))?; - let result = scope.context.alloc_statement(Statement::Block(BlockStatement::from_ast( - scope, - &statement.block, - None, - )?)); - let next = statement - .next - .as_deref() - .map(|next| -> Result<&'a Statement<'a>> { <&'a Statement<'a>>::from_ast(scope, next, None) }) - .transpose()?; - - Ok(ConditionalStatement { - parent: Cell::new(None), - span: Some(statement.span.clone()), - condition: Cell::new(condition), - result: Cell::new(result), - next: Cell::new(next), - }) - } -} - -impl<'a> Into for &ConditionalStatement<'a> { - fn into(self) -> leo_ast::ConditionalStatement { - leo_ast::ConditionalStatement { - condition: self.condition.get().into(), - block: match self.result.get() { - Statement::Block(block) => block.into(), - _ => unimplemented!(), - }, - next: self.next.get().map(|e| Box::new(e.into())), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/statement/console.rs b/asg/src/statement/console.rs deleted file mode 100644 index 3d34b1296e..0000000000 --- a/asg/src/statement/console.rs +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{CharValue, Expression, FromAst, Node, PartialType, Scope, Statement, Type}; -use leo_ast::ConsoleFunction as AstConsoleFunction; -use leo_errors::{Result, Span}; - -use std::cell::Cell; - -// TODO (protryon): Refactor to not require/depend on span -#[derive(Clone)] -pub struct ConsoleArgs<'a> { - pub string: Vec, - pub parameters: Vec>>, - pub span: Span, -} - -#[derive(Clone)] -pub enum ConsoleFunction<'a> { - Assert(Cell<&'a Expression<'a>>), - Error(ConsoleArgs<'a>), - Log(ConsoleArgs<'a>), -} - -#[derive(Clone)] -pub struct ConsoleStatement<'a> { - pub parent: Cell>>, - pub span: Option, - pub function: ConsoleFunction<'a>, -} - -impl<'a> Node for ConsoleStatement<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> FromAst<'a, leo_ast::ConsoleArgs> for ConsoleArgs<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::ConsoleArgs, - _expected_type: Option>, - ) -> Result { - let mut parameters = vec![]; - for parameter in value.parameters.iter() { - parameters.push(Cell::new(<&Expression<'a>>::from_ast(scope, parameter, None)?)); - } - Ok(ConsoleArgs { - string: value.string.iter().map(CharValue::from).collect::>(), - parameters, - span: value.span.clone(), - }) - } -} - -impl<'a> Into for &ConsoleArgs<'a> { - fn into(self) -> leo_ast::ConsoleArgs { - leo_ast::ConsoleArgs { - string: self.string.iter().map(|c| c.into()).collect::>(), - parameters: self.parameters.iter().map(|e| e.get().into()).collect(), - span: self.span.clone(), - } - } -} - -impl<'a> FromAst<'a, leo_ast::ConsoleStatement> for ConsoleStatement<'a> { - fn from_ast( - scope: &'a Scope<'a>, - statement: &leo_ast::ConsoleStatement, - _expected_type: Option>, - ) -> Result { - Ok(ConsoleStatement { - parent: Cell::new(None), - span: Some(statement.span.clone()), - function: match &statement.function { - AstConsoleFunction::Assert(expression) => ConsoleFunction::Assert(Cell::new( - <&Expression<'a>>::from_ast(scope, expression, Some(Type::Boolean.into()))?, - )), - AstConsoleFunction::Error(args) => ConsoleFunction::Error(ConsoleArgs::from_ast(scope, args, None)?), - AstConsoleFunction::Log(args) => ConsoleFunction::Log(ConsoleArgs::from_ast(scope, args, None)?), - }, - }) - } -} - -impl<'a> Into for &ConsoleStatement<'a> { - fn into(self) -> leo_ast::ConsoleStatement { - use ConsoleFunction::*; - leo_ast::ConsoleStatement { - function: match &self.function { - Assert(e) => AstConsoleFunction::Assert(e.get().into()), - Error(args) => AstConsoleFunction::Error(args.into()), - Log(args) => AstConsoleFunction::Log(args.into()), - }, - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/statement/definition.rs b/asg/src/statement/definition.rs deleted file mode 100644 index a896a9cb3a..0000000000 --- a/asg/src/statement/definition.rs +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{Expression, ExpressionNode, FromAst, InnerVariable, Node, PartialType, Scope, Statement, Type, Variable}; -use leo_errors::{AsgError, Result, Span}; - -use std::cell::{Cell, RefCell}; - -#[derive(Clone)] -pub struct DefinitionStatement<'a> { - pub parent: Cell>>, - pub span: Option, - pub variables: Vec<&'a Variable<'a>>, - pub value: Cell<&'a Expression<'a>>, -} - -impl<'a> DefinitionStatement<'a> { - pub fn split(&self) -> Vec<(String, Self)> { - self.variables - .iter() - .map(|variable| { - ( - variable.borrow().name.name.to_string(), - DefinitionStatement { - parent: self.parent.clone(), - span: self.span.clone(), - variables: vec![variable], - value: self.value.clone(), - }, - ) - }) - .collect() - } -} - -impl<'a> Node for DefinitionStatement<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> FromAst<'a, leo_ast::DefinitionStatement> for &'a Statement<'a> { - fn from_ast( - scope: &'a Scope<'a>, - statement: &leo_ast::DefinitionStatement, - _expected_type: Option>, - ) -> Result { - let type_ = statement - .type_ - .as_ref() - .map(|x| scope.resolve_ast_type(x, &statement.span)) - .transpose()?; - - let value = <&Expression<'a>>::from_ast(scope, &statement.value, type_.clone().map(Into::into))?; - - if matches!(statement.declaration_type, leo_ast::Declare::Const) && !value.is_consty() { - let var_names = statement - .variable_names - .iter() - .map(ToString::to_string) - .collect::>() - .join(" ,"); - - return Err(AsgError::invalid_const_assign(var_names, &statement.span).into()); - } - - let type_ = type_.or_else(|| value.get_type()); - - let mut output_types = vec![]; - - let mut variables = vec![]; - if statement.variable_names.is_empty() { - return Err(AsgError::illegal_ast_structure( - "cannot have 0 variable names in destructuring tuple", - &statement.span, - ) - .into()); - } - if statement.variable_names.len() == 1 { - // any return type is fine - output_types.push(type_); - } else { - // tuple destructure - match type_.as_ref() { - Some(Type::Tuple(sub_types)) if sub_types.len() == statement.variable_names.len() => { - output_types.extend(sub_types.clone().into_iter().map(Some).collect::>()); - } - type_ => { - return Err(AsgError::unexpected_type( - format!("{}-ary tuple", statement.variable_names.len()), - type_.map(|x| x.to_string()).unwrap_or_else(|| "unknown".to_string()), - &statement.span, - ) - .into()); - } - } - } - - for (variable, type_) in statement.variable_names.iter().zip(output_types.into_iter()) { - let name = variable.identifier.name.as_ref(); - if scope.resolve_global_const(name).is_some() { - return Err( - AsgError::function_variable_cannot_shadow_global_const(name, &variable.identifier.span).into(), - ); - } else if scope.resolve_variable(name).is_some() { - return Err(AsgError::function_variable_cannot_shadow_other_function_variable( - name, - &variable.identifier.span, - ) - .into()); - } - - variables.push(&*scope.context.alloc_variable(RefCell::new(InnerVariable { - id: scope.context.get_id(), - name: variable.identifier.clone(), - type_: type_.ok_or_else(|| AsgError::unresolved_type(&variable.identifier.name, &statement.span))?, - mutable: variable.mutable, - const_: false, - declaration: crate::VariableDeclaration::Definition, - references: vec![], - assignments: vec![], - }))); - } - - for variable in variables.iter() { - let mut variables = scope.variables.borrow_mut(); - let var_name = variable.borrow().name.name.to_string(); - if variables.contains_key(&var_name) { - return Err(AsgError::duplicate_variable_definition(var_name, &statement.span).into()); - } - - variables.insert(var_name, *variable); - } - - let statement = scope - .context - .alloc_statement(Statement::Definition(DefinitionStatement { - parent: Cell::new(None), - span: Some(statement.span.clone()), - variables: variables.clone(), - value: Cell::new(value), - })); - - for variable in variables { - variable.borrow_mut().assignments.push(statement); - } - - Ok(statement) - } -} - -impl<'a> Into for &DefinitionStatement<'a> { - fn into(self) -> leo_ast::DefinitionStatement { - assert!(!self.variables.is_empty()); - - let mut variable_names = vec![]; - let mut type_ = None::; - for variable in self.variables.iter() { - let variable = variable.borrow(); - variable_names.push(leo_ast::VariableName { - mutable: variable.mutable, - identifier: variable.name.clone(), - span: variable.name.span.clone(), - }); - if type_.is_none() { - type_ = Some((&variable.type_.clone()).into()); - } - } - - leo_ast::DefinitionStatement { - declaration_type: leo_ast::Declare::Let, - variable_names, - type_, - value: self.value.get().into(), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/statement/expression.rs b/asg/src/statement/expression.rs deleted file mode 100644 index 02dbb0628a..0000000000 --- a/asg/src/statement/expression.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{Expression, FromAst, Node, PartialType, Scope, Statement}; -use leo_errors::{Result, Span}; - -use std::cell::Cell; - -#[derive(Clone)] -pub struct ExpressionStatement<'a> { - pub parent: Cell>>, - pub span: Option, - pub expression: Cell<&'a Expression<'a>>, -} - -impl<'a> Node for ExpressionStatement<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> FromAst<'a, leo_ast::ExpressionStatement> for ExpressionStatement<'a> { - fn from_ast( - scope: &'a Scope<'a>, - statement: &leo_ast::ExpressionStatement, - _expected_type: Option>, - ) -> Result { - let expression = <&Expression<'a>>::from_ast(scope, &statement.expression, None)?; - - Ok(ExpressionStatement { - parent: Cell::new(None), - span: Some(statement.span.clone()), - expression: Cell::new(expression), - }) - } -} - -impl<'a> Into for &ExpressionStatement<'a> { - fn into(self) -> leo_ast::ExpressionStatement { - leo_ast::ExpressionStatement { - expression: self.expression.get().into(), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/statement/iteration.rs b/asg/src/statement/iteration.rs deleted file mode 100644 index 27de5b4deb..0000000000 --- a/asg/src/statement/iteration.rs +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use leo_ast::IntegerType; - -use crate::{Expression, ExpressionNode, FromAst, InnerVariable, Node, PartialType, Scope, Statement, Variable}; -use leo_errors::{AsgError, Result, Span}; - -use std::cell::{Cell, RefCell}; - -#[derive(Clone)] -pub struct IterationStatement<'a> { - pub parent: Cell>>, - pub span: Option, - pub variable: &'a Variable<'a>, - pub start: Cell<&'a Expression<'a>>, - pub stop: Cell<&'a Expression<'a>>, - pub inclusive: bool, - pub body: Cell<&'a Statement<'a>>, -} - -impl<'a> Node for IterationStatement<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> FromAst<'a, leo_ast::IterationStatement> for &'a Statement<'a> { - fn from_ast( - scope: &'a Scope<'a>, - statement: &leo_ast::IterationStatement, - _expected_type: Option>, - ) -> Result { - let expected_index_type = Some(PartialType::Integer(Some(IntegerType::U32), None)); - let start = <&Expression<'a>>::from_ast(scope, &statement.start, expected_index_type.clone())?; - let stop = <&Expression<'a>>::from_ast(scope, &statement.stop, expected_index_type)?; - - // Return an error if start or stop is not constant. - if !start.is_consty() { - return Err(AsgError::unexpected_nonconst(&start.span().cloned().unwrap_or_default()).into()); - } - if !stop.is_consty() { - return Err(AsgError::unexpected_nonconst(&stop.span().cloned().unwrap_or_default()).into()); - } - - let variable = scope.context.alloc_variable(RefCell::new(InnerVariable { - id: scope.context.get_id(), - name: statement.variable.clone(), - type_: start - .get_type() - .ok_or_else(|| AsgError::unresolved_type(&statement.variable.name, &statement.span))?, - mutable: false, - const_: true, - declaration: crate::VariableDeclaration::IterationDefinition, - references: vec![], - assignments: vec![], - })); - scope - .variables - .borrow_mut() - .insert(statement.variable.name.to_string(), variable); - - let statement = scope.context.alloc_statement(Statement::Iteration(IterationStatement { - parent: Cell::new(None), - span: Some(statement.span.clone()), - variable, - stop: Cell::new(stop), - start: Cell::new(start), - inclusive: statement.inclusive, - body: Cell::new( - scope - .context - .alloc_statement(Statement::Block(crate::BlockStatement::from_ast( - scope, - &statement.block, - None, - )?)), - ), - })); - variable.borrow_mut().assignments.push(statement); - Ok(statement) - } -} - -impl<'a> Into for &IterationStatement<'a> { - fn into(self) -> leo_ast::IterationStatement { - leo_ast::IterationStatement { - variable: self.variable.borrow().name.clone(), - start: self.start.get().into(), - stop: self.stop.get().into(), - inclusive: self.inclusive, - block: match self.body.get() { - Statement::Block(block) => block.into(), - _ => unimplemented!(), - }, - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/statement/mod.rs b/asg/src/statement/mod.rs deleted file mode 100644 index 2ababe353c..0000000000 --- a/asg/src/statement/mod.rs +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! This module defines a statement node in an asg. -//! -//! Ast statement nodes can be directly converted into asg nodes with no major differences. - -mod assign; -pub use assign::*; - -mod block; -pub use block::*; - -mod conditional; -pub use conditional::*; - -mod console; -pub use console::*; - -mod definition; -pub use definition::*; - -mod expression; -pub use expression::*; - -mod iteration; -pub use iteration::*; - -mod return_; -pub use return_::*; - -use crate::{FromAst, Node, PartialType, Scope}; -use leo_errors::{Result, Span}; - -#[derive(Clone)] -pub enum Statement<'a> { - Return(ReturnStatement<'a>), - Definition(DefinitionStatement<'a>), - Assign(AssignStatement<'a>), - Conditional(ConditionalStatement<'a>), - Iteration(IterationStatement<'a>), - Console(ConsoleStatement<'a>), - Expression(ExpressionStatement<'a>), - Block(BlockStatement<'a>), - Empty(Option), -} - -impl<'a> Node for Statement<'a> { - fn span(&self) -> Option<&Span> { - use Statement::*; - match self { - Return(s) => s.span(), - Definition(s) => s.span(), - Assign(s) => s.span(), - Conditional(s) => s.span(), - Iteration(s) => s.span(), - Console(s) => s.span(), - Expression(s) => s.span(), - Block(s) => s.span(), - Empty(s) => s.as_ref(), - } - } -} - -impl<'a> FromAst<'a, leo_ast::Statement> for &'a Statement<'a> { - fn from_ast( - scope: &'a Scope<'a>, - value: &leo_ast::Statement, - _expected_type: Option>, - ) -> Result<&'a Statement<'a>> { - use leo_ast::Statement::*; - Ok(match value { - Return(statement) => scope - .context - .alloc_statement(Statement::Return(ReturnStatement::from_ast(scope, statement, None)?)), - Definition(statement) => Self::from_ast(scope, statement, None)?, - Assign(statement) => Self::from_ast(scope, &**statement, None)?, - Conditional(statement) => { - scope - .context - .alloc_statement(Statement::Conditional(ConditionalStatement::from_ast( - scope, statement, None, - )?)) - } - Iteration(ref statement) => Self::from_ast(scope, &**statement, None)?, - Console(statement) => scope - .context - .alloc_statement(Statement::Console(ConsoleStatement::from_ast(scope, statement, None)?)), - Expression(statement) => { - scope - .context - .alloc_statement(Statement::Expression(ExpressionStatement::from_ast( - scope, statement, None, - )?)) - } - Block(statement) => scope - .context - .alloc_statement(Statement::Block(BlockStatement::from_ast(scope, statement, None)?)), - }) - } -} - -impl<'a> Into for &Statement<'a> { - fn into(self) -> leo_ast::Statement { - use Statement::*; - match self { - Return(statement) => leo_ast::Statement::Return(statement.into()), - Definition(statement) => leo_ast::Statement::Definition(statement.into()), - Assign(statement) => leo_ast::Statement::Assign(Box::new(statement.into())), - Conditional(statement) => leo_ast::Statement::Conditional(statement.into()), - Iteration(statement) => leo_ast::Statement::Iteration(Box::new(statement.into())), - Console(statement) => leo_ast::Statement::Console(statement.into()), - Expression(statement) => leo_ast::Statement::Expression(statement.into()), - Block(statement) => leo_ast::Statement::Block(statement.into()), - Empty(_) => unimplemented!(), - } - } -} diff --git a/asg/src/statement/return_.rs b/asg/src/statement/return_.rs deleted file mode 100644 index e4ed97db01..0000000000 --- a/asg/src/statement/return_.rs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{Expression, FromAst, Node, PartialType, Scope, Statement, Type}; -use leo_errors::{Result, Span}; - -use std::cell::Cell; -#[derive(Clone)] -pub struct ReturnStatement<'a> { - pub parent: Cell>>, - pub span: Option, - pub expression: Cell<&'a Expression<'a>>, -} - -impl<'a> Node for ReturnStatement<'a> { - fn span(&self) -> Option<&Span> { - self.span.as_ref() - } -} - -impl<'a> FromAst<'a, leo_ast::ReturnStatement> for ReturnStatement<'a> { - fn from_ast( - scope: &'a Scope<'a>, - statement: &leo_ast::ReturnStatement, - _expected_type: Option>, - ) -> Result { - let return_type: Option = scope - .resolve_current_function() - .map(|x| x.output.clone()) - .map(Into::into); - Ok(ReturnStatement { - parent: Cell::new(None), - span: Some(statement.span.clone()), - expression: Cell::new(<&Expression<'a>>::from_ast( - scope, - &statement.expression, - return_type.map(Into::into), - )?), - }) - } -} - -impl<'a> Into for &ReturnStatement<'a> { - fn into(self) -> leo_ast::ReturnStatement { - leo_ast::ReturnStatement { - expression: self.expression.get().into(), - span: self.span.clone().unwrap_or_default(), - } - } -} diff --git a/asg/src/type_.rs b/asg/src/type_.rs deleted file mode 100644 index 14bcc2d643..0000000000 --- a/asg/src/type_.rs +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::Circuit; -pub use leo_ast::IntegerType; - -use std::fmt; - -/// A type in an asg. -#[derive(Clone, PartialEq)] -pub enum Type<'a> { - // Data types - Address, - Boolean, - Char, - Field, - Group, - Integer(IntegerType), - - // Data type wrappers - Array(Box>, usize), - ArrayWithoutSize(Box>), - Tuple(Vec>), - Circuit(&'a Circuit<'a>), -} - -#[derive(Clone, PartialEq)] -pub enum PartialType<'a> { - Type(Type<'a>), // non-array or tuple - Integer(Option, Option), // specific, context-specific - Array(Option>>, Option), - Tuple(Vec>>), -} - -impl<'a> Into>> for PartialType<'a> { - fn into(self) -> Option> { - match self { - PartialType::Type(t) => Some(t), - PartialType::Integer(sub_type, contextual_type) => Some(Type::Integer(sub_type.or(contextual_type)?)), - PartialType::Array(element, len) => Some(Type::Array(Box::new((*element?).full()?), len?)), - PartialType::Tuple(sub_types) => Some(Type::Tuple( - sub_types - .into_iter() - .map(|x| x.map(|x| x.full()).flatten()) - .collect::>>()?, - )), - } - } -} - -impl<'a> PartialType<'a> { - pub fn full(self) -> Option> { - self.into() - } - - pub fn matches(&self, other: &Type<'a>) -> bool { - match (self, other) { - (PartialType::Type(t), other) => t.is_assignable_from(other), - (PartialType::Integer(self_sub_type, _), Type::Integer(sub_type)) => { - self_sub_type.as_ref().map(|x| x == sub_type).unwrap_or(true) - } - (PartialType::Array(element, _len), Type::ArrayWithoutSize(other_element)) => { - if let Some(element) = element { - if !element.matches(&*other_element) { - return false; - } - } - true - } - (PartialType::Array(element, len), Type::Array(other_element, other_len)) => { - if let Some(element) = element { - if !element.matches(&*other_element) { - return false; - } - } - if let Some(len) = len { - return len == other_len; - } - true - } - (PartialType::Tuple(sub_types), Type::Tuple(other_sub_types)) => { - // we dont enforce exact length for tuples here (relying on prior type checking) to allow for full-context-free tuple indexing - if sub_types.len() > other_sub_types.len() { - return false; - } - for (sub_type, other_sub_type) in sub_types.iter().zip(other_sub_types.iter()) { - if let Some(sub_type) = sub_type { - if !sub_type.matches(other_sub_type) { - return false; - } - } - } - true - } - _ => false, - } - } -} - -impl<'a> Into> for Type<'a> { - fn into(self) -> PartialType<'a> { - match self { - Type::Integer(sub_type) => PartialType::Integer(Some(sub_type), None), - Type::Array(element, len) => PartialType::Array(Some(Box::new((*element).into())), Some(len)), - Type::Tuple(sub_types) => PartialType::Tuple(sub_types.into_iter().map(Into::into).map(Some).collect()), - x => PartialType::Type(x), - } - } -} - -impl<'a> Type<'a> { - pub fn is_assignable_from(&self, from: &Type<'a>) -> bool { - match (self, from) { - (Type::Array(_, _), Type::ArrayWithoutSize(_)) => true, - (Type::ArrayWithoutSize(_), Type::Array(_, _)) => true, - _ => self == from, - } - } - - pub fn partial(self) -> PartialType<'a> { - self.into() - } - - pub fn is_unit(&self) -> bool { - matches!(self, Type::Tuple(t) if t.is_empty()) - } - - pub fn can_cast_to(&self, to: &Type<'a>) -> bool { - matches!(self, Type::Integer(_)) && matches!(to, Type::Integer(_)) - } -} - -impl<'a> fmt::Display for Type<'a> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Type::Address => write!(f, "address"), - Type::Boolean => write!(f, "bool"), - Type::Char => write!(f, "char"), - Type::Field => write!(f, "field"), - Type::Group => write!(f, "group"), - Type::Integer(sub_type) => sub_type.fmt(f), - Type::Array(sub_type, len) => write!(f, "[{}; {}]", sub_type, len), - Type::ArrayWithoutSize(sub_type) => write!(f, "[{}; _]", sub_type), - Type::Tuple(sub_types) => { - write!(f, "(")?; - for (i, sub_type) in sub_types.iter().enumerate() { - write!(f, "{}", sub_type)?; - if i < sub_types.len() - 1 { - write!(f, ", ")?; - } - } - write!(f, ")") - } - Type::Circuit(circuit) => write!(f, "{}", &circuit.name.borrow().name), - } - } -} - -impl<'a> fmt::Display for PartialType<'a> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - PartialType::Type(t) => t.fmt(f), - PartialType::Integer(Some(sub_type), _) => write!(f, "{}", sub_type), - PartialType::Integer(_, Some(sub_type)) => write!(f, "<{}>", sub_type), - PartialType::Integer(_, _) => write!(f, "integer"), - PartialType::Array(sub_type, len) => { - write!(f, "[")?; - if let Some(sub_type) = sub_type { - write!(f, "{}", *sub_type)?; - } else { - write!(f, "?")?; - } - write!(f, "; ")?; - if let Some(len) = len { - write!(f, "{}", len)?; - } else { - write!(f, "?")?; - } - write!(f, "]") - } - PartialType::Tuple(sub_types) => { - write!(f, "(")?; - for (i, sub_type) in sub_types.iter().enumerate() { - if let Some(sub_type) = sub_type { - write!(f, "{}", *sub_type)?; - } else { - write!(f, "?")?; - } - if i < sub_types.len() - 1 { - write!(f, ", ")?; - } - } - write!(f, ")") - } - } - } -} - -impl<'a> Into for &Type<'a> { - fn into(self) -> leo_ast::Type { - use Type::*; - match self { - Address => leo_ast::Type::Address, - Boolean => leo_ast::Type::Boolean, - Char => leo_ast::Type::Char, - Field => leo_ast::Type::Field, - Group => leo_ast::Type::Group, - Integer(int_type) => leo_ast::Type::IntegerType(int_type.clone()), - Array(type_, len) => leo_ast::Type::Array( - Box::new(type_.as_ref().into()), - Some(leo_ast::ArrayDimensions(vec![leo_ast::PositiveNumber { - value: len.to_string().into(), - }])), - ), - ArrayWithoutSize(type_) => leo_ast::Type::Array(Box::new(type_.as_ref().into()), None), - Tuple(subtypes) => leo_ast::Type::Tuple(subtypes.iter().map(Into::into).collect()), - Circuit(circuit) => leo_ast::Type::Identifier(circuit.name.borrow().clone()), - } - } -} diff --git a/asg/src/variable.rs b/asg/src/variable.rs deleted file mode 100644 index 831de1c63f..0000000000 --- a/asg/src/variable.rs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use std::cell::RefCell; - -use crate::{Expression, Statement, Type}; -use leo_ast::Identifier; - -/// Specifies how a program variable was declared. -#[derive(Clone, Copy, PartialEq)] -pub enum VariableDeclaration { - Definition, - IterationDefinition, - Parameter, - Input, -} - -/// Stores information on a program variable. -#[derive(Clone)] -pub struct InnerVariable<'a> { - pub id: u32, - pub name: Identifier, - pub type_: Type<'a>, - pub mutable: bool, - pub const_: bool, // only function arguments, const var definitions NOT included - pub declaration: VariableDeclaration, - pub references: Vec<&'a Expression<'a>>, // all Expression::VariableRef or panic - pub assignments: Vec<&'a Statement<'a>>, // all Statement::Assign or panic -- must be 1 if not mutable, or 0 if declaration == input | parameter -} - -pub type Variable<'a> = RefCell>; diff --git a/asg/tests/fail/address/implicit_invalid.leo b/asg/tests/fail/address/implicit_invalid.leo deleted file mode 100644 index aadc38a6d8..0000000000 --- a/asg/tests/fail/address/implicit_invalid.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const public_key_string: address = zleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8; -} \ No newline at end of file diff --git a/asg/tests/fail/address/mod.rs b/asg/tests/fail/address/mod.rs deleted file mode 100644 index 0ee77207c6..0000000000 --- a/asg/tests/fail/address/mod.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_implicit_invalid() { - let program_string = include_str!("implicit_invalid.leo"); - load_asg(program_string).err().unwrap(); -} diff --git a/asg/tests/fail/array/initializer_fail.leo b/asg/tests/fail/array/initializer_fail.leo deleted file mode 100644 index 3b2e7785cc..0000000000 --- a/asg/tests/fail/array/initializer_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: [u8; 3]) { - console.assert(a == [1u8; -3]); -} \ No newline at end of file diff --git a/asg/tests/fail/array/input_nested_3x2_fail.leo b/asg/tests/fail/array/input_nested_3x2_fail.leo deleted file mode 100644 index 1f5bf7b334..0000000000 --- a/asg/tests/fail/array/input_nested_3x2_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: [u8; (3, 2)]) { - console.assert(a == [[0u8; 2]; 3)]); // This should be written the right way as this test is for the input file. -} diff --git a/asg/tests/fail/array/input_tuple_3x2_fail.leo b/asg/tests/fail/array/input_tuple_3x2_fail.leo deleted file mode 100644 index b84f26a97e..0000000000 --- a/asg/tests/fail/array/input_tuple_3x2_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: [u8; (3, 2)]) { - console.assert(a == [0u8; (2, 3)]); -} diff --git a/asg/tests/fail/array/mod.rs b/asg/tests/fail/array/mod.rs deleted file mode 100644 index 1a9eaf4ae5..0000000000 --- a/asg/tests/fail/array/mod.rs +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -// Expressions - -#[test] -fn test_initializer_fail() { - let program_string = include_str!("initializer_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_input_nested_3x2_fail() { - let program_string = include_str!("input_nested_3x2_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_input_tuple_3x2_fail() { - let program_string = include_str!("input_tuple_3x2_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_multi_fail_initializer() { - let program_string = include_str!("multi_fail_initializer.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_multi_inline_fail() { - let program_string = include_str!("multi_fail_inline.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_multi_initializer_fail() { - let program_string = include_str!("multi_initializer_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_nested_3x2_value_fail() { - let program_string = include_str!("nested_3x2_value_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_tuple_3x2_value_fail() { - let program_string = include_str!("tuple_3x2_value_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -// Array type tests - -#[test] -fn test_type_fail() { - let program_string = include_str!("type_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_type_nested_value_nested_3x2_fail() { - let program_string = include_str!("type_nested_value_nested_3x2_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_type_nested_value_nested_4x3x2_fail() { - let program_string = include_str!("type_nested_value_nested_4x3x2_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_type_nested_value_tuple_3x2_fail() { - let program_string = include_str!("type_nested_value_tuple_3x2_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_type_nested_value_tuple_4x3x2_fail() { - let program_string = include_str!("type_nested_value_tuple_4x3x2_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_type_tuple_value_nested_3x2_fail() { - let program_string = include_str!("type_tuple_value_nested_3x2_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_type_tuple_value_nested_3x2_swap_fail() { - let program_string = include_str!("type_tuple_value_nested_3x2_swap_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_type_tuple_value_nested_4x3x2_fail() { - let program_string = include_str!("type_tuple_value_nested_4x3x2_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_type_tuple_value_tuple_3x2_fail() { - let program_string = include_str!("type_tuple_value_tuple_3x2_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_type_tuple_value_tuple_3x2_swap_fail() { - let program_string = include_str!("type_tuple_value_tuple_3x2_swap_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_type_tuple_value_tuple_4x3x2_fail() { - let program_string = include_str!("type_tuple_value_tuple_4x3x2_fail.leo"); - load_asg(program_string).err().unwrap(); -} diff --git a/asg/tests/fail/array/multi_fail_initializer.leo b/asg/tests/fail/array/multi_fail_initializer.leo deleted file mode 100644 index be1ab315bd..0000000000 --- a/asg/tests/fail/array/multi_fail_initializer.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const arr: [u8; (2, 2)] = [[1u8; 2]; 1]; // incorrect dimensions -} \ No newline at end of file diff --git a/asg/tests/fail/array/multi_fail_inline.leo b/asg/tests/fail/array/multi_fail_inline.leo deleted file mode 100644 index 49c9296798..0000000000 --- a/asg/tests/fail/array/multi_fail_inline.leo +++ /dev/null @@ -1,4 +0,0 @@ -function main() { - const arr: [u8; (2, 2)] = [[1u8, 1u8], - [1u8]]; // incorrect dimensions -} \ No newline at end of file diff --git a/asg/tests/fail/array/multi_initializer_fail.leo b/asg/tests/fail/array/multi_initializer_fail.leo deleted file mode 100644 index e38a8fdaee..0000000000 --- a/asg/tests/fail/array/multi_initializer_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const arr: [u8; (2, 2)] = [1u8; (2, 1)]; // incorrect dimensions -} \ No newline at end of file diff --git a/asg/tests/fail/array/nested_3x2_value_fail.leo b/asg/tests/fail/array/nested_3x2_value_fail.leo deleted file mode 100644 index a187a51991..0000000000 --- a/asg/tests/fail/array/nested_3x2_value_fail.leo +++ /dev/null @@ -1,4 +0,0 @@ -// Multidimensional array syntax in leo -function main() { - const a: [u32; (3, 2)] = [[0; 3]; 2]; // initializer (incorrectly reversed ordering) -} diff --git a/asg/tests/fail/array/tuple_3x2_value_fail.leo b/asg/tests/fail/array/tuple_3x2_value_fail.leo deleted file mode 100644 index 78593ab696..0000000000 --- a/asg/tests/fail/array/tuple_3x2_value_fail.leo +++ /dev/null @@ -1,4 +0,0 @@ -// Multidimensional array syntax in leo -function main() { - const a: [u32; (3, 2)] = [0; (2, 3)]; // initializer (incorrectly reversed ordering) -} diff --git a/asg/tests/fail/array/type_fail.leo b/asg/tests/fail/array/type_fail.leo deleted file mode 100644 index 356bba976a..0000000000 --- a/asg/tests/fail/array/type_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: [u8; -2] = [0u32; 2]; -} \ No newline at end of file diff --git a/asg/tests/fail/array/type_nested_value_nested_3x2_fail.leo b/asg/tests/fail/array/type_nested_value_nested_3x2_fail.leo deleted file mode 100644 index 56c8916fb0..0000000000 --- a/asg/tests/fail/array/type_nested_value_nested_3x2_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const b: [[u8; 2]; 3] = [[0; 3]; 2]; // initializer (incorrectly reversed ordering) -} \ No newline at end of file diff --git a/asg/tests/fail/array/type_nested_value_nested_4x3x2_fail.leo b/asg/tests/fail/array/type_nested_value_nested_4x3x2_fail.leo deleted file mode 100644 index 480327a91d..0000000000 --- a/asg/tests/fail/array/type_nested_value_nested_4x3x2_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const b: [[[u8; 2]; 3]; 4] = [[[0; 4]; 3]; 2]; // initializer (incorrectly reversed ordering) -} \ No newline at end of file diff --git a/asg/tests/fail/array/type_nested_value_tuple_3x2_fail.leo b/asg/tests/fail/array/type_nested_value_tuple_3x2_fail.leo deleted file mode 100644 index 3bfb559615..0000000000 --- a/asg/tests/fail/array/type_nested_value_tuple_3x2_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const b: [[u8; 2]; 3] = [0; (2, 3)]; // initializer (incorrectly reversed ordering) -} \ No newline at end of file diff --git a/asg/tests/fail/array/type_nested_value_tuple_4x3x2_fail.leo b/asg/tests/fail/array/type_nested_value_tuple_4x3x2_fail.leo deleted file mode 100644 index ce1219a37b..0000000000 --- a/asg/tests/fail/array/type_nested_value_tuple_4x3x2_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const b: [[[u8; 2]; 3]; 4] = [0; (2, 3, 4)]; // initializer (incorrectly reversed ordering) -} \ No newline at end of file diff --git a/asg/tests/fail/array/type_tuple_value_nested_3x2_fail.leo b/asg/tests/fail/array/type_tuple_value_nested_3x2_fail.leo deleted file mode 100644 index e84f025a9f..0000000000 --- a/asg/tests/fail/array/type_tuple_value_nested_3x2_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const b: [u8; (2, 3)] = [[0; 2]; 3]; // initializer (incorrectly reversed ordering) -} \ No newline at end of file diff --git a/asg/tests/fail/array/type_tuple_value_nested_3x2_swap_fail.leo b/asg/tests/fail/array/type_tuple_value_nested_3x2_swap_fail.leo deleted file mode 100644 index 0b960c6b44..0000000000 --- a/asg/tests/fail/array/type_tuple_value_nested_3x2_swap_fail.leo +++ /dev/null @@ -1,7 +0,0 @@ -function main() { - const a = [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]]; // inline - - const b: [u8; (2, 3)] = [[0; 3]; 2]; // initializer - - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/fail/array/type_tuple_value_nested_4x3x2_fail.leo b/asg/tests/fail/array/type_tuple_value_nested_4x3x2_fail.leo deleted file mode 100644 index cbb7ccbf76..0000000000 --- a/asg/tests/fail/array/type_tuple_value_nested_4x3x2_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const b: [u8; (4, 3, 2)] = [[[0; 4]; 3]; 2]; // initializer (incorrectly reversed ordering) -} \ No newline at end of file diff --git a/asg/tests/fail/array/type_tuple_value_tuple_3x2_fail.leo b/asg/tests/fail/array/type_tuple_value_tuple_3x2_fail.leo deleted file mode 100644 index 884a75db9d..0000000000 --- a/asg/tests/fail/array/type_tuple_value_tuple_3x2_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const b: [u8; (2, 3)] = [0; (3, 2)]; // initializer (incorrectly reversed ordering) -} \ No newline at end of file diff --git a/asg/tests/fail/array/type_tuple_value_tuple_3x2_swap_fail.leo b/asg/tests/fail/array/type_tuple_value_tuple_3x2_swap_fail.leo deleted file mode 100644 index d742a544a7..0000000000 --- a/asg/tests/fail/array/type_tuple_value_tuple_3x2_swap_fail.leo +++ /dev/null @@ -1,7 +0,0 @@ -function main() { - const a = [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]]; // inline - - const b: [u8; (2, 3)] = [0; (2, 3)]; // initializer - - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/fail/array/type_tuple_value_tuple_4x3x2_fail.leo b/asg/tests/fail/array/type_tuple_value_tuple_4x3x2_fail.leo deleted file mode 100644 index 31e2a5e552..0000000000 --- a/asg/tests/fail/array/type_tuple_value_tuple_4x3x2_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const b: [u8; (4, 3, 2)] = [0; (2, 3, 4)]; // initializer (incorrectly reversed order) -} \ No newline at end of file diff --git a/asg/tests/fail/boolean/mod.rs b/asg/tests/fail/boolean/mod.rs deleted file mode 100644 index 4712d5b89c..0000000000 --- a/asg/tests/fail/boolean/mod.rs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_not_u32() { - let program_string = include_str!("not_u32.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_true_or_u32() { - let program_string = include_str!("true_or_u32.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_true_and_u32() { - let program_string = include_str!("true_and_u32.leo"); - load_asg(program_string).err().unwrap(); -} diff --git a/asg/tests/fail/boolean/not_u32.leo b/asg/tests/fail/boolean/not_u32.leo deleted file mode 100644 index 44491d785b..0000000000 --- a/asg/tests/fail/boolean/not_u32.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() -> bool { - console.assert(!1u32 == 0u32); -} \ No newline at end of file diff --git a/asg/tests/fail/boolean/true_and_u32.leo b/asg/tests/fail/boolean/true_and_u32.leo deleted file mode 100644 index ad3ead9040..0000000000 --- a/asg/tests/fail/boolean/true_and_u32.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a = true && 1u32; -} \ No newline at end of file diff --git a/asg/tests/fail/boolean/true_or_u32.leo b/asg/tests/fail/boolean/true_or_u32.leo deleted file mode 100644 index 38dab727b9..0000000000 --- a/asg/tests/fail/boolean/true_or_u32.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a = true || 1u32; -} \ No newline at end of file diff --git a/asg/tests/fail/circuits/inline_fail.leo b/asg/tests/fail/circuits/inline_fail.leo deleted file mode 100644 index 302c84298a..0000000000 --- a/asg/tests/fail/circuits/inline_fail.leo +++ /dev/null @@ -1,7 +0,0 @@ -circuit Foo { - x: u32; -} - -function main() { - const a = Foo { y: 0u32 }; -} \ No newline at end of file diff --git a/asg/tests/fail/circuits/inline_undefined.leo b/asg/tests/fail/circuits/inline_undefined.leo deleted file mode 100644 index 40c4cf722c..0000000000 --- a/asg/tests/fail/circuits/inline_undefined.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a = Foo { }; -} \ No newline at end of file diff --git a/asg/tests/fail/circuits/member_function_fail.leo b/asg/tests/fail/circuits/member_function_fail.leo deleted file mode 100644 index 57b15383a3..0000000000 --- a/asg/tests/fail/circuits/member_function_fail.leo +++ /dev/null @@ -1,10 +0,0 @@ -circuit Foo { - function echo(x: u32) -> u32 { - return x; - } -} - -function main() { - const a = Foo { }; - const err = a.echoed(1u32); -} \ No newline at end of file diff --git a/asg/tests/fail/circuits/member_function_invalid.leo b/asg/tests/fail/circuits/member_function_invalid.leo deleted file mode 100644 index 7283cf144d..0000000000 --- a/asg/tests/fail/circuits/member_function_invalid.leo +++ /dev/null @@ -1,10 +0,0 @@ -circuit Foo { - function echo(x: u32) -> u32 { - return x; - } -} - -function main() { - const a = Foo { }; - const err = a.echo(1u32); // echo is a static function and must be accessed using `::` -} \ No newline at end of file diff --git a/asg/tests/fail/circuits/member_static_function_invalid.leo b/asg/tests/fail/circuits/member_static_function_invalid.leo deleted file mode 100644 index b886cff8fa..0000000000 --- a/asg/tests/fail/circuits/member_static_function_invalid.leo +++ /dev/null @@ -1,9 +0,0 @@ -circuit Foo { - function echo(x: u32) -> u32 { - return x; - } -} - -function main() { - const err = Foo.echo(1u32); // Invalid, echo is a static function and must be accessed using `::` -} \ No newline at end of file diff --git a/asg/tests/fail/circuits/member_static_function_undefined.leo b/asg/tests/fail/circuits/member_static_function_undefined.leo deleted file mode 100644 index 121c80e34c..0000000000 --- a/asg/tests/fail/circuits/member_static_function_undefined.leo +++ /dev/null @@ -1,9 +0,0 @@ -circuit Foo { - function echo(x: u32) -> u32 { - return x; - } -} - -function main() { - const err = Foo::echoed(1u32); -} \ No newline at end of file diff --git a/asg/tests/fail/circuits/member_variable_fail.leo b/asg/tests/fail/circuits/member_variable_fail.leo deleted file mode 100644 index a0a9823486..0000000000 --- a/asg/tests/fail/circuits/member_variable_fail.leo +++ /dev/null @@ -1,9 +0,0 @@ -circuit Foo { - x: u32; -} - -function main() { - const a = Foo { x: 1u32 }; - - const err = a.y; -} \ No newline at end of file diff --git a/asg/tests/fail/circuits/mod.rs b/asg/tests/fail/circuits/mod.rs deleted file mode 100644 index 4d343b25a0..0000000000 --- a/asg/tests/fail/circuits/mod.rs +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -// Expressions - -#[test] -fn test_inline_fail() { - let program_string = include_str!("inline_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_inline_undefined() { - let program_string = include_str!("inline_undefined.leo"); - load_asg(program_string).err().unwrap(); -} - -// Members - -#[test] -fn test_member_variable_fail() { - let program_string = include_str!("member_variable_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_member_function_fail() { - let program_string = include_str!("member_function_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_member_function_invalid() { - let program_string = include_str!("member_function_invalid.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_mut_member_function_fail() { - let program_string = r#" - circuit Foo { - function echo(mut self, x: u32) -> u32 { - return x; - } - } - - function main() { - const a = Foo { }; - - console.assert(a.echo(1u32) == 1u32); - }"#; - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_member_static_function_invalid() { - let program_string = include_str!("member_static_function_invalid.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_member_static_function_undefined() { - let program_string = include_str!("member_static_function_undefined.leo"); - load_asg(program_string).err().unwrap(); -} - -// Mutability - -#[test] -fn test_mutate_function_fail() { - let program_string = include_str!("mut_function_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_mutate_self_variable_fail() { - let program_string = include_str!("mut_self_variable_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_mutate_self_function_fail() { - let program_string = include_str!("mut_self_function_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_mutate_self_static_function_fail() { - let program_string = include_str!("mut_self_static_function_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_mutate_static_function_fail() { - let program_string = include_str!("mut_static_function_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_mutate_variable_fail() { - let program_string = include_str!("mut_variable_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -// Self - -#[test] -fn test_self_fail() { - let program_string = include_str!("self_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_self_member_invalid() { - let program_string = include_str!("self_member_invalid.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_self_member_undefined() { - let program_string = include_str!("self_member_undefined.leo"); - load_asg(program_string).err().unwrap(); -} diff --git a/asg/tests/fail/circuits/mut_function_fail.leo b/asg/tests/fail/circuits/mut_function_fail.leo deleted file mode 100644 index d66edac76b..0000000000 --- a/asg/tests/fail/circuits/mut_function_fail.leo +++ /dev/null @@ -1,11 +0,0 @@ -circuit Foo { - a: u8; - - function bar() {} -} - -function main() { - let f = Foo { a: 0u8 }; - - f.bar = 1u8; -} \ No newline at end of file diff --git a/asg/tests/fail/circuits/mut_self_function_fail.leo b/asg/tests/fail/circuits/mut_self_function_fail.leo deleted file mode 100644 index dde5133a00..0000000000 --- a/asg/tests/fail/circuits/mut_self_function_fail.leo +++ /dev/null @@ -1,15 +0,0 @@ -circuit Foo { - a: u8; - - function bar() {} - - function set_a(mut self, new: u8) { - self.bar = new; - } -} - -function main() { - let f = Foo { a: 0u8 }; - - f.set_a(1u8); -} \ No newline at end of file diff --git a/asg/tests/fail/circuits/mut_self_static_function_fail.leo b/asg/tests/fail/circuits/mut_self_static_function_fail.leo deleted file mode 100644 index dde5133a00..0000000000 --- a/asg/tests/fail/circuits/mut_self_static_function_fail.leo +++ /dev/null @@ -1,15 +0,0 @@ -circuit Foo { - a: u8; - - function bar() {} - - function set_a(mut self, new: u8) { - self.bar = new; - } -} - -function main() { - let f = Foo { a: 0u8 }; - - f.set_a(1u8); -} \ No newline at end of file diff --git a/asg/tests/fail/circuits/mut_self_variable_fail.leo b/asg/tests/fail/circuits/mut_self_variable_fail.leo deleted file mode 100644 index 50edbc11f1..0000000000 --- a/asg/tests/fail/circuits/mut_self_variable_fail.leo +++ /dev/null @@ -1,13 +0,0 @@ -circuit Foo { - a: u8; - - function set_a(self, new: u8) { - self.a = new; - } -} - -function main() { - let f = Foo { a: 0u8 }; - - f.set_a(1u8); -} \ No newline at end of file diff --git a/asg/tests/fail/circuits/mut_static_function_fail.leo b/asg/tests/fail/circuits/mut_static_function_fail.leo deleted file mode 100644 index fd873bd17b..0000000000 --- a/asg/tests/fail/circuits/mut_static_function_fail.leo +++ /dev/null @@ -1,9 +0,0 @@ -circuit Foo { - function bar() {} -} - -function main() { - let f = Foo { a: 0u8 }; - - f.bar = 1u8; -} \ No newline at end of file diff --git a/asg/tests/fail/circuits/mut_variable_fail.leo b/asg/tests/fail/circuits/mut_variable_fail.leo deleted file mode 100644 index 4b741ed07f..0000000000 --- a/asg/tests/fail/circuits/mut_variable_fail.leo +++ /dev/null @@ -1,9 +0,0 @@ -circuit Foo { - a: u8; -} - -function main() { - const f = Foo { a: 0u8 }; - - f.a = 1u8; -} \ No newline at end of file diff --git a/asg/tests/fail/circuits/self_fail.leo b/asg/tests/fail/circuits/self_fail.leo deleted file mode 100644 index e4e878dc89..0000000000 --- a/asg/tests/fail/circuits/self_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - Self::main(); -} \ No newline at end of file diff --git a/asg/tests/fail/circuits/self_member_invalid.leo b/asg/tests/fail/circuits/self_member_invalid.leo deleted file mode 100644 index 51ba9b53df..0000000000 --- a/asg/tests/fail/circuits/self_member_invalid.leo +++ /dev/null @@ -1,12 +0,0 @@ -circuit Foo { - f: u32; - - function bar() -> u32 { - return f; - } -} - -function main() -> u32 { - const foo = Foo { f: 1u32 }; - const err = foo.bar(); -} \ No newline at end of file diff --git a/asg/tests/fail/circuits/self_member_undefined.leo b/asg/tests/fail/circuits/self_member_undefined.leo deleted file mode 100644 index 8b52d305a3..0000000000 --- a/asg/tests/fail/circuits/self_member_undefined.leo +++ /dev/null @@ -1,10 +0,0 @@ -circuit Foo { - function bar() -> u32 { - return self.f; - } -} - -function main() { - const foo = Foo { }; - const err = foo.bar(); -} \ No newline at end of file diff --git a/asg/tests/fail/console/assert.leo b/asg/tests/fail/console/assert.leo deleted file mode 100644 index ba6be77256..0000000000 --- a/asg/tests/fail/console/assert.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: bool) { - console.assert(a == true); -} \ No newline at end of file diff --git a/asg/tests/fail/console/conditional_assert.leo b/asg/tests/fail/console/conditional_assert.leo deleted file mode 100644 index f2c1591e9c..0000000000 --- a/asg/tests/fail/console/conditional_assert.leo +++ /dev/null @@ -1,7 +0,0 @@ -function main(a: bool) { - if a { - console.assert(a == true); - } else { - console.assert(a == false); - } -} \ No newline at end of file diff --git a/asg/tests/fail/console/debug.leo b/asg/tests/fail/console/debug.leo deleted file mode 100644 index 54e6eb539f..0000000000 --- a/asg/tests/fail/console/debug.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.debug("hello debug"); -} \ No newline at end of file diff --git a/asg/tests/fail/console/error.leo b/asg/tests/fail/console/error.leo deleted file mode 100644 index 86d13f8cee..0000000000 --- a/asg/tests/fail/console/error.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.error("hello error"); -} \ No newline at end of file diff --git a/asg/tests/fail/console/log.leo b/asg/tests/fail/console/log.leo deleted file mode 100644 index a190ca4ba9..0000000000 --- a/asg/tests/fail/console/log.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.log("hello world"); -} \ No newline at end of file diff --git a/asg/tests/fail/console/log_fail.leo b/asg/tests/fail/console/log_fail.leo deleted file mode 100644 index dafa6bea8e..0000000000 --- a/asg/tests/fail/console/log_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.log( hello ); -} \ No newline at end of file diff --git a/asg/tests/fail/console/log_input.leo b/asg/tests/fail/console/log_input.leo deleted file mode 100644 index c4fd0a8b12..0000000000 --- a/asg/tests/fail/console/log_input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: bool) { - console.log("a = {}", a); -} \ No newline at end of file diff --git a/asg/tests/fail/console/log_parameter.leo b/asg/tests/fail/console/log_parameter.leo deleted file mode 100644 index ebcb931a2b..0000000000 --- a/asg/tests/fail/console/log_parameter.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.log("{}", 1u32); -} \ No newline at end of file diff --git a/asg/tests/fail/console/log_parameter_fail_unknown.leo b/asg/tests/fail/console/log_parameter_fail_unknown.leo deleted file mode 100644 index 757f4c27c3..0000000000 --- a/asg/tests/fail/console/log_parameter_fail_unknown.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.log("{}", a); -} \ No newline at end of file diff --git a/asg/tests/fail/console/log_parameter_many.leo b/asg/tests/fail/console/log_parameter_many.leo deleted file mode 100644 index 60455ebbb0..0000000000 --- a/asg/tests/fail/console/log_parameter_many.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.log("{} {}", 1u32, true); -} \ No newline at end of file diff --git a/asg/tests/fail/console/mod.rs b/asg/tests/fail/console/mod.rs deleted file mode 100644 index d825a4db05..0000000000 --- a/asg/tests/fail/console/mod.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_log_fail() { - let program_string = include_str!("log_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_log_parameter_fail_unknown() { - let program_string = include_str!("log_parameter_fail_unknown.leo"); - load_asg(program_string).err().unwrap(); -} diff --git a/asg/tests/fail/core/mod.rs b/asg/tests/fail/core/mod.rs deleted file mode 100644 index ff53f73aae..0000000000 --- a/asg/tests/fail/core/mod.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . diff --git a/asg/tests/fail/definition/mod.rs b/asg/tests/fail/definition/mod.rs deleted file mode 100644 index ff53f73aae..0000000000 --- a/asg/tests/fail/definition/mod.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . diff --git a/asg/tests/fail/field/mod.rs b/asg/tests/fail/field/mod.rs deleted file mode 100644 index ff53f73aae..0000000000 --- a/asg/tests/fail/field/mod.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . diff --git a/asg/tests/fail/function/array_input.leo b/asg/tests/fail/function/array_input.leo deleted file mode 100644 index 899c0e4af6..0000000000 --- a/asg/tests/fail/function/array_input.leo +++ /dev/null @@ -1,6 +0,0 @@ -function foo(a: [u8; 1]) {} - -function main() { - const a: [u16; 1] = [1; 1]; - foo(a); -} \ No newline at end of file diff --git a/asg/tests/fail/function/empty.leo b/asg/tests/fail/function/empty.leo deleted file mode 100644 index f06c976158..0000000000 --- a/asg/tests/fail/function/empty.leo +++ /dev/null @@ -1,5 +0,0 @@ -function empty() { } - -function main() { - empty(); -} \ No newline at end of file diff --git a/asg/tests/fail/function/mod.rs b/asg/tests/fail/function/mod.rs deleted file mode 100644 index 07d80c4a1f..0000000000 --- a/asg/tests/fail/function/mod.rs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_multiple_returns_fail() { - let program_string = include_str!("multiple_returns_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_multiple_returns_input_ambiguous() { - let program_string = include_str!("multiple_returns_input_ambiguous.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_multiple_returns_fail_conditional() { - let program_string = include_str!("multiple_returns_fail_conditional.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_scope_fail() { - let program_string = include_str!("scope_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_undefined() { - let program_string = include_str!("undefined.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_array_input() { - let program_string = include_str!("array_input.leo"); - load_asg(program_string).err().unwrap(); -} - -// Test return multidimensional arrays - -#[test] -fn test_return_array_nested_fail() { - let program_string = include_str!("return_array_nested_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_return_array_tuple_fail() { - let program_string = include_str!("return_array_tuple_fail.leo"); - load_asg(program_string).err().unwrap(); -} diff --git a/asg/tests/fail/function/multiple_returns_fail.leo b/asg/tests/fail/function/multiple_returns_fail.leo deleted file mode 100644 index daa773f2e8..0000000000 --- a/asg/tests/fail/function/multiple_returns_fail.leo +++ /dev/null @@ -1,7 +0,0 @@ -function main () -> i8 { - if true { - return 1i8; //ignored - } - return 2i8; //ignored - return 3i8; //returns -} \ No newline at end of file diff --git a/asg/tests/fail/function/multiple_returns_fail_conditional.leo b/asg/tests/fail/function/multiple_returns_fail_conditional.leo deleted file mode 100644 index ded39534a4..0000000000 --- a/asg/tests/fail/function/multiple_returns_fail_conditional.leo +++ /dev/null @@ -1,9 +0,0 @@ -function main () -> u16 { - if false { - const a = 1u16; - const b = a + 1u16; - return b; - } else if false { - return 0u16; - } -} \ No newline at end of file diff --git a/asg/tests/fail/function/multiple_returns_input_ambiguous.leo b/asg/tests/fail/function/multiple_returns_input_ambiguous.leo deleted file mode 100644 index 363408e61e..0000000000 --- a/asg/tests/fail/function/multiple_returns_input_ambiguous.leo +++ /dev/null @@ -1,7 +0,0 @@ -function main(input) -> u32 { - if input.registers.a == 0 { - return 0u32; - } else { - return 1u32; - } -} \ No newline at end of file diff --git a/asg/tests/fail/function/return_array_nested_fail.leo b/asg/tests/fail/function/return_array_nested_fail.leo deleted file mode 100644 index 8eca684b8a..0000000000 --- a/asg/tests/fail/function/return_array_nested_fail.leo +++ /dev/null @@ -1,7 +0,0 @@ -function array_3x2_tuple() -> [[u8; 2]; 3] { - return [0u8; (2, 3)] // The correct 3x2 array tuple is `[0u8; (3, 2)]` -} - -function main() { - const b = array_3x2_tuple(); -} \ No newline at end of file diff --git a/asg/tests/fail/function/return_array_tuple_fail.leo b/asg/tests/fail/function/return_array_tuple_fail.leo deleted file mode 100644 index c960456ac1..0000000000 --- a/asg/tests/fail/function/return_array_tuple_fail.leo +++ /dev/null @@ -1,7 +0,0 @@ -function array_3x2_nested() -> [u8; (3, 2)] { - return [[0u8; 3]; 2] // The correct 3x2 nested array is `[0u8; 2]; 3]` -} - -function main() { - const a = array_3x2_nested(); -} \ No newline at end of file diff --git a/asg/tests/fail/function/scope_fail.leo b/asg/tests/fail/function/scope_fail.leo deleted file mode 100644 index 693682d297..0000000000 --- a/asg/tests/fail/function/scope_fail.leo +++ /dev/null @@ -1,8 +0,0 @@ -function foo() -> field { - return myGlobal; -} - -function main() { - const myGlobal = 42field; - const err = foo(); -} \ No newline at end of file diff --git a/asg/tests/fail/function/undefined.leo b/asg/tests/fail/function/undefined.leo deleted file mode 100644 index e1db3b9f09..0000000000 --- a/asg/tests/fail/function/undefined.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - my_function(); -} \ No newline at end of file diff --git a/asg/tests/fail/group/both_sign_high.leo b/asg/tests/fail/group/both_sign_high.leo deleted file mode 100644 index 4c93573e1e..0000000000 --- a/asg/tests/fail/group/both_sign_high.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const element = (+, +)group; -} \ No newline at end of file diff --git a/asg/tests/fail/group/both_sign_inferred.leo b/asg/tests/fail/group/both_sign_inferred.leo deleted file mode 100644 index 0bbd360ba0..0000000000 --- a/asg/tests/fail/group/both_sign_inferred.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const element = (_, _)group; -} \ No newline at end of file diff --git a/asg/tests/fail/group/both_sign_low.leo b/asg/tests/fail/group/both_sign_low.leo deleted file mode 100644 index 1cb4f46c55..0000000000 --- a/asg/tests/fail/group/both_sign_low.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const element = (-, -)group; -} \ No newline at end of file diff --git a/asg/tests/fail/group/mod.rs b/asg/tests/fail/group/mod.rs deleted file mode 100644 index 01a3059bde..0000000000 --- a/asg/tests/fail/group/mod.rs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_both_sign_high() { - let program_string = include_str!("both_sign_high.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_both_sign_low() { - let program_string = include_str!("both_sign_low.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_both_sign_inferred() { - let program_string = include_str!("both_sign_inferred.leo"); - load_asg(program_string).err().unwrap(); -} diff --git a/asg/tests/fail/integers/i128/max_fail.leo b/asg/tests/fail/integers/i128/max_fail.leo deleted file mode 100644 index a9a46afd7f..0000000000 --- a/asg/tests/fail/integers/i128/max_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i128 = 170141183460469231731687303715884105728; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/i128/min_fail.leo b/asg/tests/fail/integers/i128/min_fail.leo deleted file mode 100644 index 918f0e439d..0000000000 --- a/asg/tests/fail/integers/i128/min_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i128 = -170141183460469231731687303715884105729; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/i128/mod.rs b/asg/tests/fail/integers/i128/mod.rs deleted file mode 100644 index c6fe80d4f9..0000000000 --- a/asg/tests/fail/integers/i128/mod.rs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_int!(TestI128); - -#[test] -fn test_i128_min_fail() { - TestI128::test_min_fail(); -} - -#[test] -fn test_i128_max_fail() { - TestI128::test_max_fail(); -} - -// #[test] -// fn test_i128_neg_max_fail() { -// TestI128::test_negate_min_fail(); -// } diff --git a/asg/tests/fail/integers/i128/negate_min.leo b/asg/tests/fail/integers/i128/negate_min.leo deleted file mode 100644 index c9de272960..0000000000 --- a/asg/tests/fail/integers/i128/negate_min.leo +++ /dev/null @@ -1,4 +0,0 @@ -function main() { - const a: i128 = -170141183460469231731687303715884105728; - const b = -a; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/i16/max_fail.leo b/asg/tests/fail/integers/i16/max_fail.leo deleted file mode 100644 index 209bcc6518..0000000000 --- a/asg/tests/fail/integers/i16/max_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i16 = 32768; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/i16/min_fail.leo b/asg/tests/fail/integers/i16/min_fail.leo deleted file mode 100644 index 13d7c8b7f2..0000000000 --- a/asg/tests/fail/integers/i16/min_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i16 = -32769; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/i16/mod.rs b/asg/tests/fail/integers/i16/mod.rs deleted file mode 100644 index fd0d2bee1f..0000000000 --- a/asg/tests/fail/integers/i16/mod.rs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_int!(TestI16); - -#[test] -fn test_i16_min_fail() { - TestI16::test_min_fail(); -} - -#[test] -fn test_i16_max_fail() { - TestI16::test_max_fail(); -} - -// #[test] -// fn test_i16_neg_max_fail() { -// TestI16::test_negate_min_fail(); -// } diff --git a/asg/tests/fail/integers/i16/negate_min.leo b/asg/tests/fail/integers/i16/negate_min.leo deleted file mode 100644 index d52a356396..0000000000 --- a/asg/tests/fail/integers/i16/negate_min.leo +++ /dev/null @@ -1,4 +0,0 @@ -function main() { - const a = -32768i16; - const b = -a; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/i32/max_fail.leo b/asg/tests/fail/integers/i32/max_fail.leo deleted file mode 100644 index af2877ff5e..0000000000 --- a/asg/tests/fail/integers/i32/max_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i32 = 2147483648; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/i32/min_fail.leo b/asg/tests/fail/integers/i32/min_fail.leo deleted file mode 100644 index 11a683b087..0000000000 --- a/asg/tests/fail/integers/i32/min_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i32 = -2147483649; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/i32/mod.rs b/asg/tests/fail/integers/i32/mod.rs deleted file mode 100644 index 37b6b714dd..0000000000 --- a/asg/tests/fail/integers/i32/mod.rs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_int!(TestI32); - -#[test] -fn test_i32_min_fail() { - TestI32::test_min_fail(); -} - -#[test] -fn test_i32_max_fail() { - TestI32::test_max_fail(); -} - -// #[test] -// fn test_i32_neg_max_fail() { -// TestI32::test_negate_min_fail(); -// } diff --git a/asg/tests/fail/integers/i32/negate_min.leo b/asg/tests/fail/integers/i32/negate_min.leo deleted file mode 100644 index a96455d57a..0000000000 --- a/asg/tests/fail/integers/i32/negate_min.leo +++ /dev/null @@ -1,4 +0,0 @@ -function main() { - const a = -2147483648i32; - const b = -a; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/i64/max_fail.leo b/asg/tests/fail/integers/i64/max_fail.leo deleted file mode 100644 index 362b794a2c..0000000000 --- a/asg/tests/fail/integers/i64/max_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i64 = 9223372036854775808; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/i64/min_fail.leo b/asg/tests/fail/integers/i64/min_fail.leo deleted file mode 100644 index bb260ecc3f..0000000000 --- a/asg/tests/fail/integers/i64/min_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i64 = -9223372036854775809; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/i64/mod.rs b/asg/tests/fail/integers/i64/mod.rs deleted file mode 100644 index 4ea12a11df..0000000000 --- a/asg/tests/fail/integers/i64/mod.rs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_int!(TestI64); - -#[test] -fn test_i64_min_fail() { - TestI64::test_min_fail(); -} - -#[test] -fn test_i64_max_fail() { - TestI64::test_max_fail(); -} - -// #[test] -// fn test_i64_neg_max_fail() { -// TestI64::test_negate_min_fail(); -// } diff --git a/asg/tests/fail/integers/i64/negate_min.leo b/asg/tests/fail/integers/i64/negate_min.leo deleted file mode 100644 index daf694491b..0000000000 --- a/asg/tests/fail/integers/i64/negate_min.leo +++ /dev/null @@ -1,4 +0,0 @@ -function main() { - const a: i64 = -9223372036854775808; - const b = -a; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/i8/max_fail.leo b/asg/tests/fail/integers/i8/max_fail.leo deleted file mode 100644 index 9e1956024a..0000000000 --- a/asg/tests/fail/integers/i8/max_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i8 = 128; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/i8/min_fail.leo b/asg/tests/fail/integers/i8/min_fail.leo deleted file mode 100644 index 41170e9b93..0000000000 --- a/asg/tests/fail/integers/i8/min_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i8 = -129; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/i8/mod.rs b/asg/tests/fail/integers/i8/mod.rs deleted file mode 100644 index 245d20a169..0000000000 --- a/asg/tests/fail/integers/i8/mod.rs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_int!(TestI8); - -#[test] -fn test_i8_min_fail() { - TestI8::test_min_fail(); -} - -#[test] -fn test_i8_max_fail() { - TestI8::test_max_fail(); -} - -// #[test] -// fn test_i8_neg_max_fail() { -// TestI8::test_negate_min_fail(); -// } diff --git a/asg/tests/fail/integers/i8/negate_min.leo b/asg/tests/fail/integers/i8/negate_min.leo deleted file mode 100644 index 7f664a1b78..0000000000 --- a/asg/tests/fail/integers/i8/negate_min.leo +++ /dev/null @@ -1,4 +0,0 @@ -function main() { - const a = -128i8; - const b = -a; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/int_macro.rs b/asg/tests/fail/integers/int_macro.rs deleted file mode 100644 index cd06cba948..0000000000 --- a/asg/tests/fail/integers/int_macro.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -macro_rules! test_int { - ($name: ident) => { - pub struct $name {} - - // we are not doing constant folding here, so asg doesnt catch this - // impl $name { - // fn test_negate_min_fail() { - // let program_string = include_str!("negate_min.leo"); - // crate::load_asg(program_string).err().unwrap(); - // } - // } - - impl super::IntegerTester for $name { - fn test_min_fail() { - let program_string = include_str!("min_fail.leo"); - crate::load_asg(program_string).err().unwrap(); - } - - fn test_max_fail() { - let program_string = include_str!("max_fail.leo"); - crate::load_asg(program_string).err().unwrap(); - } - } - }; -} diff --git a/asg/tests/fail/integers/integer_tester.rs b/asg/tests/fail/integers/integer_tester.rs deleted file mode 100644 index ca6ead5f72..0000000000 --- a/asg/tests/fail/integers/integer_tester.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub trait IntegerTester { - /// Tests defining the smallest value - 1 - fn test_min_fail(); - - /// Tests defining the largest value + 1 - fn test_max_fail(); -} diff --git a/asg/tests/fail/integers/mod.rs b/asg/tests/fail/integers/mod.rs deleted file mode 100644 index 0cfd4f643c..0000000000 --- a/asg/tests/fail/integers/mod.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -#[macro_use] -pub mod int_macro; - -#[macro_use] -pub mod uint_macro; - -pub mod integer_tester; -pub use self::integer_tester::*; - -// must be below macro definitions! -pub mod u128; -pub mod u16; -pub mod u32; -pub mod u64; -pub mod u8; - -pub mod i128; -pub mod i16; -pub mod i32; -pub mod i64; -pub mod i8; diff --git a/asg/tests/fail/integers/u128/max_fail.leo b/asg/tests/fail/integers/u128/max_fail.leo deleted file mode 100644 index f51c967925..0000000000 --- a/asg/tests/fail/integers/u128/max_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u128 = 340282366920938463463374607431768211456; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/u128/min_fail.leo b/asg/tests/fail/integers/u128/min_fail.leo deleted file mode 100644 index b0d17191ff..0000000000 --- a/asg/tests/fail/integers/u128/min_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u128 = -1; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/u128/mod.rs b/asg/tests/fail/integers/u128/mod.rs deleted file mode 100644 index 3fe52ea09d..0000000000 --- a/asg/tests/fail/integers/u128/mod.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_uint!(TestU128); - -#[test] -fn test_u128_min_fail() { - TestU128::test_min_fail(); -} - -#[test] -fn test_u128_max_fail() { - TestU128::test_max_fail(); -} diff --git a/asg/tests/fail/integers/u16/max_fail.leo b/asg/tests/fail/integers/u16/max_fail.leo deleted file mode 100644 index bb703210e3..0000000000 --- a/asg/tests/fail/integers/u16/max_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u16 = 65536; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/u16/min_fail.leo b/asg/tests/fail/integers/u16/min_fail.leo deleted file mode 100644 index 0c61dd7ddf..0000000000 --- a/asg/tests/fail/integers/u16/min_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u16 = -1; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/u16/mod.rs b/asg/tests/fail/integers/u16/mod.rs deleted file mode 100644 index f2def8f598..0000000000 --- a/asg/tests/fail/integers/u16/mod.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_uint!(TestU16); - -#[test] -fn test_u16_min_fail() { - TestU16::test_min_fail(); -} - -#[test] -fn test_u16_max_fail() { - TestU16::test_max_fail(); -} diff --git a/asg/tests/fail/integers/u32/max_fail.leo b/asg/tests/fail/integers/u32/max_fail.leo deleted file mode 100644 index 6b1631876e..0000000000 --- a/asg/tests/fail/integers/u32/max_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u32 = 4294967296; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/u32/min_fail.leo b/asg/tests/fail/integers/u32/min_fail.leo deleted file mode 100644 index c3e3f33225..0000000000 --- a/asg/tests/fail/integers/u32/min_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u32 = -1; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/u32/mod.rs b/asg/tests/fail/integers/u32/mod.rs deleted file mode 100644 index 967257bd52..0000000000 --- a/asg/tests/fail/integers/u32/mod.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_uint!(TestU32); - -#[test] -fn test_u32_min_fail() { - TestU32::test_min_fail(); -} - -#[test] -fn test_u32_max_fail() { - TestU32::test_max_fail(); -} diff --git a/asg/tests/fail/integers/u64/max_fail.leo b/asg/tests/fail/integers/u64/max_fail.leo deleted file mode 100644 index d606c83585..0000000000 --- a/asg/tests/fail/integers/u64/max_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u64 = 18446744073709551616; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/u64/min_fail.leo b/asg/tests/fail/integers/u64/min_fail.leo deleted file mode 100644 index e58f1897e6..0000000000 --- a/asg/tests/fail/integers/u64/min_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u64 = -1; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/u64/mod.rs b/asg/tests/fail/integers/u64/mod.rs deleted file mode 100644 index 6705c17392..0000000000 --- a/asg/tests/fail/integers/u64/mod.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_uint!(TestU64); - -#[test] -fn test_u64_min_fail() { - TestU64::test_min_fail(); -} - -#[test] -fn test_u64_max_fail() { - TestU64::test_max_fail(); -} diff --git a/asg/tests/fail/integers/u8/max_fail.leo b/asg/tests/fail/integers/u8/max_fail.leo deleted file mode 100644 index 01bb544601..0000000000 --- a/asg/tests/fail/integers/u8/max_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u8 = 256; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/u8/min_fail.leo b/asg/tests/fail/integers/u8/min_fail.leo deleted file mode 100644 index 3cd8d46de7..0000000000 --- a/asg/tests/fail/integers/u8/min_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u8 = -1; -} \ No newline at end of file diff --git a/asg/tests/fail/integers/u8/mod.rs b/asg/tests/fail/integers/u8/mod.rs deleted file mode 100644 index 14ea74d5f9..0000000000 --- a/asg/tests/fail/integers/u8/mod.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_uint!(TestU8); - -#[test] -fn test_u8_min_fail() { - TestU8::test_min_fail(); -} - -#[test] -fn test_u8_max_fail() { - TestU8::test_max_fail(); -} diff --git a/asg/tests/fail/integers/uint_macro.rs b/asg/tests/fail/integers/uint_macro.rs deleted file mode 100644 index 6b718dbeda..0000000000 --- a/asg/tests/fail/integers/uint_macro.rs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -macro_rules! test_uint { - ($name: ident) => { - pub struct $name {} - - impl super::IntegerTester for $name { - fn test_min_fail() { - let program_string = include_str!("min_fail.leo"); - crate::load_asg(program_string).err().unwrap(); - } - - fn test_max_fail() { - let program_string = include_str!("max_fail.leo"); - crate::load_asg(program_string).err().unwrap(); - } - } - }; -} diff --git a/asg/tests/fail/mod.rs b/asg/tests/fail/mod.rs deleted file mode 100644 index 102b00b7dc..0000000000 --- a/asg/tests/fail/mod.rs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub mod address; -pub mod array; -pub mod boolean; -pub mod circuits; -pub mod console; -pub mod core; -pub mod definition; -pub mod field; -pub mod function; -// pub mod group; // we dont do context-specific type checking for groups -pub mod integers; -pub mod mutability; -pub mod statements; -pub mod tuples; diff --git a/asg/tests/fail/mutability/array.leo b/asg/tests/fail/mutability/array.leo deleted file mode 100644 index ea63baaad2..0000000000 --- a/asg/tests/fail/mutability/array.leo +++ /dev/null @@ -1,5 +0,0 @@ -// Arrays are immutable by default. -function main() { - const a = [1u32]; - a[0] = 0; -} \ No newline at end of file diff --git a/asg/tests/fail/mutability/circuit.leo b/asg/tests/fail/mutability/circuit.leo deleted file mode 100644 index 29f2096a03..0000000000 --- a/asg/tests/fail/mutability/circuit.leo +++ /dev/null @@ -1,9 +0,0 @@ -// Circuits are immutable by default. -circuit Foo { - x: u32; -} - -function main() { - const a = Foo { x: 1 }; - a.x = 0; -} \ No newline at end of file diff --git a/asg/tests/fail/mutability/circuit_function_mut.leo b/asg/tests/fail/mutability/circuit_function_mut.leo deleted file mode 100644 index c1bc941c94..0000000000 --- a/asg/tests/fail/mutability/circuit_function_mut.leo +++ /dev/null @@ -1,9 +0,0 @@ -// Adding the `mut` keyword makes a circuit variable mutable. -circuit Foo { - function bar() {} -} - -function main() { - let a = Foo { x: 1 }; - a.bar = 0; -} \ No newline at end of file diff --git a/asg/tests/fail/mutability/circuit_static_function_mut.leo b/asg/tests/fail/mutability/circuit_static_function_mut.leo deleted file mode 100644 index c1bc941c94..0000000000 --- a/asg/tests/fail/mutability/circuit_static_function_mut.leo +++ /dev/null @@ -1,9 +0,0 @@ -// Adding the `mut` keyword makes a circuit variable mutable. -circuit Foo { - function bar() {} -} - -function main() { - let a = Foo { x: 1 }; - a.bar = 0; -} \ No newline at end of file diff --git a/asg/tests/fail/mutability/const.leo b/asg/tests/fail/mutability/const.leo deleted file mode 100644 index 6201e7c5af..0000000000 --- a/asg/tests/fail/mutability/const.leo +++ /dev/null @@ -1,5 +0,0 @@ -// Let variables are immutable by default. -function main() { - const a = 1u32; - a = 0; -} \ No newline at end of file diff --git a/asg/tests/fail/mutability/function_input.leo b/asg/tests/fail/mutability/function_input.leo deleted file mode 100644 index 18d035574b..0000000000 --- a/asg/tests/fail/mutability/function_input.leo +++ /dev/null @@ -1,4 +0,0 @@ -// Const function input are immutable. -function main(const a: bool) { - a = false; -} \ No newline at end of file diff --git a/asg/tests/fail/mutability/let.leo b/asg/tests/fail/mutability/let.leo deleted file mode 100644 index 105730adb7..0000000000 --- a/asg/tests/fail/mutability/let.leo +++ /dev/null @@ -1,5 +0,0 @@ -// Variables are immutable by default. -function main() { - const a = 1u32; - a = 0; -} \ No newline at end of file diff --git a/asg/tests/fail/mutability/mod.rs b/asg/tests/fail/mutability/mod.rs deleted file mode 100644 index 81a270d7e1..0000000000 --- a/asg/tests/fail/mutability/mod.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_let() { - let program_string = include_str!("let.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_const_fail() { - let program_string = include_str!("const.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_array() { - let program_string = include_str!("array.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_circuit() { - let program_string = include_str!("circuit.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_circuit_function_mut() { - let program_string = include_str!("circuit_function_mut.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_circuit_static_function_mut() { - let program_string = include_str!("circuit_static_function_mut.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_function_input() { - let program_string = include_str!("function_input.leo"); - load_asg(program_string).err().unwrap(); -} diff --git a/asg/tests/fail/statements/let_mut_declaration_fail.leo b/asg/tests/fail/statements/let_mut_declaration_fail.leo deleted file mode 100644 index ea80a7bc0d..0000000000 --- a/asg/tests/fail/statements/let_mut_declaration_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - let mut x = 1u32; -} \ No newline at end of file diff --git a/asg/tests/fail/statements/mod.rs b/asg/tests/fail/statements/mod.rs deleted file mode 100644 index 106af9dfe7..0000000000 --- a/asg/tests/fail/statements/mod.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_num_returns_fail() { - let program_string = include_str!("num_returns_fail.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_let_mut_declaration_fail() { - let program_string = include_str!("let_mut_declaration_fail.leo"); - load_asg(program_string).err().unwrap(); -} diff --git a/asg/tests/fail/statements/num_returns_fail.leo b/asg/tests/fail/statements/num_returns_fail.leo deleted file mode 100644 index e8d491caed..0000000000 --- a/asg/tests/fail/statements/num_returns_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() -> (bool, bool) { - return true; -} \ No newline at end of file diff --git a/asg/tests/fail/tuples/mod.rs b/asg/tests/fail/tuples/mod.rs deleted file mode 100644 index ff53f73aae..0000000000 --- a/asg/tests/fail/tuples/mod.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . diff --git a/asg/tests/mod.rs b/asg/tests/mod.rs deleted file mode 100644 index 0b94d115c2..0000000000 --- a/asg/tests/mod.rs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use leo_asg::*; -use leo_errors::LeoError; -use leo_parser::parse_ast; - -mod fail; -mod pass; - -const TESTING_FILEPATH: &str = "input.leo"; - -fn load_asg(program_string: &str) -> Result, LeoError> { - load_asg_imports(make_test_context(), program_string) -} - -fn load_asg_imports<'a>(context: AsgContext<'a>, program_string: &str) -> Result, LeoError> { - let ast = parse_ast(&TESTING_FILEPATH, program_string)?; - Program::new(context, &ast.as_repr()) -} - -//convenience function for tests, leaks memory -pub(crate) fn make_test_context() -> AsgContext<'static> { - let allocator = Box::leak(Box::new(new_alloc_context())); - new_context(allocator) -} diff --git a/asg/tests/pass/address/console_assert_pass.leo b/asg/tests/pass/address/console_assert_pass.leo deleted file mode 100644 index 214d01c4a8..0000000000 --- a/asg/tests/pass/address/console_assert_pass.leo +++ /dev/null @@ -1,6 +0,0 @@ -function main() { - const address_1 = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8; - const address_2 = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8; - - console.assert(address_1 == address_2); -} \ No newline at end of file diff --git a/asg/tests/pass/address/equal.leo b/asg/tests/pass/address/equal.leo deleted file mode 100644 index 856f5cc843..0000000000 --- a/asg/tests/pass/address/equal.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: address, b: address, c: bool) { - console.assert((a == b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/address/implicit_invalid.leo b/asg/tests/pass/address/implicit_invalid.leo deleted file mode 100644 index aadc38a6d8..0000000000 --- a/asg/tests/pass/address/implicit_invalid.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const public_key_string: address = zleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8; -} \ No newline at end of file diff --git a/asg/tests/pass/address/implicit_valid.leo b/asg/tests/pass/address/implicit_valid.leo deleted file mode 100644 index 75bcbaa8a1..0000000000 --- a/asg/tests/pass/address/implicit_valid.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const public_key_string: address = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8; -} \ No newline at end of file diff --git a/asg/tests/pass/address/input.leo b/asg/tests/pass/address/input.leo deleted file mode 100644 index 506abb0fff..0000000000 --- a/asg/tests/pass/address/input.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main(owner: address) { - const sender = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8; - - console.assert(owner == sender); -} \ No newline at end of file diff --git a/asg/tests/pass/address/mod.rs b/asg/tests/pass/address/mod.rs deleted file mode 100644 index 7cd18d57a2..0000000000 --- a/asg/tests/pass/address/mod.rs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_valid() { - let program_string = include_str!("valid.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_implicit_valid() { - let program_string = include_str!("implicit_valid.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_console_assert_pass() { - let program_string = include_str!("console_assert_pass.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_ternary() { - let program_string = include_str!("ternary.leo"); - - load_asg(program_string).unwrap(); -} - -#[test] -fn test_equal() { - let program_string = include_str!("equal.leo"); - load_asg(program_string).unwrap(); -} diff --git a/asg/tests/pass/address/ternary.leo b/asg/tests/pass/address/ternary.leo deleted file mode 100644 index 65a8eea1e7..0000000000 --- a/asg/tests/pass/address/ternary.leo +++ /dev/null @@ -1,8 +0,0 @@ -function main(s: bool, c: address) { - const a = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8; - const b = aleo18qgam03qe483tdrcc3fkqwpp38ehff4a2xma6lu7hams6lfpgcpq3dq05r; - - let r = s ? a: b; - - console.assert(r == c); -} \ No newline at end of file diff --git a/asg/tests/pass/address/valid.leo b/asg/tests/pass/address/valid.leo deleted file mode 100644 index 6d693efe78..0000000000 --- a/asg/tests/pass/address/valid.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const public_key_string = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8; -} \ No newline at end of file diff --git a/asg/tests/pass/array/implicit.leo b/asg/tests/pass/array/implicit.leo deleted file mode 100644 index cfb4281e35..0000000000 --- a/asg/tests/pass/array/implicit.leo +++ /dev/null @@ -1,6 +0,0 @@ -function main(){ - const a = [1u8, 2u8, 3u8, 4]; - const b = [1u8, 2u8, 3, 4u8]; - const c = [1u8, 2, 3u8, 4u8]; - const d = [1, 2u8, 3u8, 4u8]; -} \ No newline at end of file diff --git a/asg/tests/pass/array/index_u8.leo b/asg/tests/pass/array/index_u8.leo deleted file mode 100644 index 24d52ba82e..0000000000 --- a/asg/tests/pass/array/index_u8.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main() { - const x = 0u8; - const a = [0u8; 4]; - console.assert(a[x] == 0); -} diff --git a/asg/tests/pass/array/initializer.leo b/asg/tests/pass/array/initializer.leo deleted file mode 100644 index 51ac19f68f..0000000000 --- a/asg/tests/pass/array/initializer.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: [u8; 3]) { - console.assert(a == [1u8; 3]); -} \ No newline at end of file diff --git a/asg/tests/pass/array/initializer_input.leo b/asg/tests/pass/array/initializer_input.leo deleted file mode 100644 index 4b886159dc..0000000000 --- a/asg/tests/pass/array/initializer_input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: [u8; (3, 2)]) { - console.assert(a == [0u8; (3, 2)]); -} \ No newline at end of file diff --git a/asg/tests/pass/array/inline.leo b/asg/tests/pass/array/inline.leo deleted file mode 100644 index 8c5c98ae50..0000000000 --- a/asg/tests/pass/array/inline.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: [u8; 3]) { - console.assert(a == [1u8, 1u8, 1u8]); -} \ No newline at end of file diff --git a/asg/tests/pass/array/input_nested_3x2.leo b/asg/tests/pass/array/input_nested_3x2.leo deleted file mode 100644 index b7e59a5dc0..0000000000 --- a/asg/tests/pass/array/input_nested_3x2.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: [u8; (3, 2)]) { - console.assert(a == [[0u8; 2]; 3]); -} diff --git a/asg/tests/pass/array/input_tuple_3x2.leo b/asg/tests/pass/array/input_tuple_3x2.leo deleted file mode 100644 index 4c3c001f41..0000000000 --- a/asg/tests/pass/array/input_tuple_3x2.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: [u8; (3, 2)]) { - console.assert(a == [0u8; (3, 2)]); -} diff --git a/asg/tests/pass/array/mod.rs b/asg/tests/pass/array/mod.rs deleted file mode 100644 index 60caab461d..0000000000 --- a/asg/tests/pass/array/mod.rs +++ /dev/null @@ -1,207 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -// Registers - -#[test] -fn test_registers() { - let program_string = include_str!("registers.leo"); - load_asg(program_string).unwrap(); -} - -// Expressions - -#[test] -fn test_inline() { - let program_string = include_str!("inline.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_initializer() { - let program_string = include_str!("initializer.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_initializer_input() { - let program_string = include_str!("initializer_input.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_input_nested_3x2() { - let program_string = include_str!("input_nested_3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_input_tuple_3x2() { - let program_string = include_str!("input_tuple_3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_multi_initializer() { - let program_string = include_str!("multi_initializer.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_nested_3x2_value() { - let program_string = include_str!("nested_3x2_value.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_tuple_3x2_value() { - let program_string = include_str!("tuple_3x2_value.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_spread() { - let program_string = include_str!("spread.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_slice() { - let program_string = include_str!("slice.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_index_u8() { - let program_string = include_str!("index_u8.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_slice_i8() { - let program_string = include_str!("slice_i8.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_slice_lower() { - let program_string = include_str!("slice_lower.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_implicit() { - let program_string = include_str!("implicit.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_type_nested_value_nested_3x2() { - let program_string = include_str!("type_nested_value_nested_3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_type_nested_value_nested_4x3x2() { - let program_string = include_str!("type_nested_value_nested_4x3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_type_nested_value_tuple_3x2() { - let program_string = include_str!("type_nested_value_tuple_3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_type_nested_value_tuple_4x3x2() { - let program_string = include_str!("type_nested_value_tuple_4x3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_type_tuple_value_nested_3x2() { - let program_string = include_str!("type_tuple_value_nested_3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_type_tuple_value_nested_4x3x2() { - let program_string = include_str!("type_tuple_value_nested_4x3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_type_tuple_value_tuple_3x2() { - let program_string = include_str!("type_tuple_value_tuple_3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_type_tuple_value_tuple_4x3x2() { - let program_string = include_str!("type_tuple_value_tuple_4x3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_input_type_nested_value_nested_3x2() { - let program_string = include_str!("type_input_3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_input_type_nested_value_nested_4x3x2() { - let program_string = include_str!("type_input_4x3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_input_type_nested_value_tuple_3x2() { - let program_string = include_str!("type_input_3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_input_type_nested_value_tuple_4x3x2() { - let program_string = include_str!("type_input_4x3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_input_type_tuple_value_nested_3x2() { - let program_string = include_str!("type_input_3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_input_type_tuple_value_nested_4x3x2() { - let program_string = include_str!("type_input_4x3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_input_type_tuple_value_tuple_3x2() { - let program_string = include_str!("type_input_3x2.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_input_type_tuple_value_tuple_4x3x2() { - let program_string = include_str!("type_input_4x3x2.leo"); - load_asg(program_string).unwrap(); -} diff --git a/asg/tests/pass/array/multi_initializer.leo b/asg/tests/pass/array/multi_initializer.leo deleted file mode 100644 index 6133542ef0..0000000000 --- a/asg/tests/pass/array/multi_initializer.leo +++ /dev/null @@ -1,7 +0,0 @@ -function main() { - const a: [u8; (2, 2, 2)] = [1u8; (2, 2, 2)]; - - const b: [u8; (2, 2, 2)] = [[[1u8; 2]; 2]; 2]; - - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/array/nested_3x2_value.leo b/asg/tests/pass/array/nested_3x2_value.leo deleted file mode 100644 index c5f64c997e..0000000000 --- a/asg/tests/pass/array/nested_3x2_value.leo +++ /dev/null @@ -1,8 +0,0 @@ -// Multidimensional array syntax in leo -function main() { - const a = [[0u32, 0u32], [0u32, 0u32], [0u32, 0u32]]; // inline - - const b: [u32; (3, 2)] = [[0; 2]; 3]; // initializer - - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/array/registers.leo b/asg/tests/pass/array/registers.leo deleted file mode 100644 index 98d129207f..0000000000 --- a/asg/tests/pass/array/registers.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() -> [u8; 3] { - return input.registers.r; -} diff --git a/asg/tests/pass/array/slice.leo b/asg/tests/pass/array/slice.leo deleted file mode 100644 index 9ff83dbbb8..0000000000 --- a/asg/tests/pass/array/slice.leo +++ /dev/null @@ -1,6 +0,0 @@ -// `{from}..{to}` copies the elements of one array into another exclusively -function main(a: [u8; 3]) { - const b = [1u8; 4]; - - console.assert(a == b[0..3]); -} diff --git a/asg/tests/pass/array/slice_i8.leo b/asg/tests/pass/array/slice_i8.leo deleted file mode 100644 index 18f090e6f0..0000000000 --- a/asg/tests/pass/array/slice_i8.leo +++ /dev/null @@ -1,6 +0,0 @@ -// `{from}..{to}` copies the elements of one array into another exclusively -function main(a: [u8; 3]) { - const b = [1u8; 4]; - - console.assert(a == b[0u8..3i8]); -} diff --git a/asg/tests/pass/array/slice_lower.leo b/asg/tests/pass/array/slice_lower.leo deleted file mode 100644 index 0af6fbd937..0000000000 --- a/asg/tests/pass/array/slice_lower.leo +++ /dev/null @@ -1,8 +0,0 @@ -function main() { - const arr: [u32; 9] = [0, 1, 2, 3, 4, 5, 6, 7, 8]; - const expected: [u32; 2] = [0, 1]; - - const actual = arr[..2]; // Should produce [0, 1] - - console.assert(expected == actual); -} \ No newline at end of file diff --git a/asg/tests/pass/array/spread.leo b/asg/tests/pass/array/spread.leo deleted file mode 100644 index 8bd2861aae..0000000000 --- a/asg/tests/pass/array/spread.leo +++ /dev/null @@ -1,7 +0,0 @@ -// A spread operator `...` copies the elements of one array into another -function main(a: [u8; 3]) { - const b = [1u8, 1u8]; - const c = [1u8, ...b]; - - console.assert(a == c); -} \ No newline at end of file diff --git a/asg/tests/pass/array/tuple_3x2_value.leo b/asg/tests/pass/array/tuple_3x2_value.leo deleted file mode 100644 index b6659539d5..0000000000 --- a/asg/tests/pass/array/tuple_3x2_value.leo +++ /dev/null @@ -1,8 +0,0 @@ -// Multidimensional array syntax in leo -function main() { - const a = [[0u32, 0u32], [0u32, 0u32], [0u32, 0u32]]; // inline - - const b: [u32; (3, 2)] = [0; (3, 2)]; // initializer - - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/array/type_input_3x2.leo b/asg/tests/pass/array/type_input_3x2.leo deleted file mode 100644 index ea60a0cc24..0000000000 --- a/asg/tests/pass/array/type_input_3x2.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main(a: [[u8; 2]; 3]) { - const b = [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]]; // inline - - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/array/type_input_4x3x2.leo b/asg/tests/pass/array/type_input_4x3x2.leo deleted file mode 100644 index 2d9c4cff22..0000000000 --- a/asg/tests/pass/array/type_input_4x3x2.leo +++ /dev/null @@ -1,8 +0,0 @@ -function main(a: [[[u8; 2]; 3]; 4]) { - const b = [[[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]], - [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]], - [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]], - [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]]]; // inline - - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/array/type_nested_value_nested_3x2.leo b/asg/tests/pass/array/type_nested_value_nested_3x2.leo deleted file mode 100644 index bcf5bae674..0000000000 --- a/asg/tests/pass/array/type_nested_value_nested_3x2.leo +++ /dev/null @@ -1,7 +0,0 @@ -function main() { - const a = [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]]; // inline - - const b: [[u8; 2]; 3] = [[0; 2]; 3]; // initializer - - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/array/type_nested_value_nested_4x3x2.leo b/asg/tests/pass/array/type_nested_value_nested_4x3x2.leo deleted file mode 100644 index 1691fa26c7..0000000000 --- a/asg/tests/pass/array/type_nested_value_nested_4x3x2.leo +++ /dev/null @@ -1,10 +0,0 @@ -function main() { - const a = [[[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]], - [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]], - [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]], - [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]]]; // inline - - const b: [[[u8; 2]; 3]; 4] = [[[0; 2]; 3]; 4]; // initializer - - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/array/type_nested_value_tuple_3x2.leo b/asg/tests/pass/array/type_nested_value_tuple_3x2.leo deleted file mode 100644 index 5f14084d55..0000000000 --- a/asg/tests/pass/array/type_nested_value_tuple_3x2.leo +++ /dev/null @@ -1,7 +0,0 @@ -function main() { - const a = [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]]; // inline - - const b: [[u8; 2]; 3] = [0; (3, 2)]; // initializer - - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/array/type_nested_value_tuple_4x3x2.leo b/asg/tests/pass/array/type_nested_value_tuple_4x3x2.leo deleted file mode 100644 index 88a5143bd2..0000000000 --- a/asg/tests/pass/array/type_nested_value_tuple_4x3x2.leo +++ /dev/null @@ -1,10 +0,0 @@ -function main() { - const a = [[[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]], - [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]], - [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]], - [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]]]; // inline - - const b: [[[u8; 2]; 3]; 4] = [0; (4, 3, 2)]; // initializer - - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/array/type_tuple_value_nested_3x2.leo b/asg/tests/pass/array/type_tuple_value_nested_3x2.leo deleted file mode 100644 index 81195e03a1..0000000000 --- a/asg/tests/pass/array/type_tuple_value_nested_3x2.leo +++ /dev/null @@ -1,7 +0,0 @@ -function main() { - const a = [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]]; // inline - - const b: [u8; (3, 2)] = [[0; 2]; 3]; // initializer - - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/array/type_tuple_value_nested_4x3x2.leo b/asg/tests/pass/array/type_tuple_value_nested_4x3x2.leo deleted file mode 100644 index 322a6f7601..0000000000 --- a/asg/tests/pass/array/type_tuple_value_nested_4x3x2.leo +++ /dev/null @@ -1,10 +0,0 @@ -function main() { - const a = [[[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]], - [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]], - [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]], - [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]]]; // inline - - const b: [u8; (4, 3, 2)] = [[[0; 2]; 3]; 4]; // initializer - - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/array/type_tuple_value_tuple_3x2.leo b/asg/tests/pass/array/type_tuple_value_tuple_3x2.leo deleted file mode 100644 index d451a9c1a8..0000000000 --- a/asg/tests/pass/array/type_tuple_value_tuple_3x2.leo +++ /dev/null @@ -1,7 +0,0 @@ -function main() { - const a = [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]]; // inline - - const b: [u8; (3, 2)] = [0; (3, 2)]; // initializer - - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/array/type_tuple_value_tuple_4x3x2.leo b/asg/tests/pass/array/type_tuple_value_tuple_4x3x2.leo deleted file mode 100644 index 1205b1dc9c..0000000000 --- a/asg/tests/pass/array/type_tuple_value_tuple_4x3x2.leo +++ /dev/null @@ -1,10 +0,0 @@ -function main() { - const a = [[[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]], - [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]], - [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]], - [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]]]; // inline - - const b: [u8; (4, 3, 2)] = [0; (4, 3, 2)]; // initializer - - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/boolean/all.leo b/asg/tests/pass/boolean/all.leo deleted file mode 100644 index 64fe8a795a..0000000000 --- a/asg/tests/pass/boolean/all.leo +++ /dev/null @@ -1,8 +0,0 @@ -// !(true && (false || true)) -function main() { - const a = true; - const b = false || a; - const c = !(true && b); - - console.assert(c == false); -} \ No newline at end of file diff --git a/asg/tests/pass/boolean/assert_eq_input.leo b/asg/tests/pass/boolean/assert_eq_input.leo deleted file mode 100644 index 8a796e5bbd..0000000000 --- a/asg/tests/pass/boolean/assert_eq_input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: bool, b: bool) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/boolean/false_and_false.leo b/asg/tests/pass/boolean/false_and_false.leo deleted file mode 100644 index 03dfabab4d..0000000000 --- a/asg/tests/pass/boolean/false_and_false.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main() { - const a = false && false; - - console.assert(a == false); -} \ No newline at end of file diff --git a/asg/tests/pass/boolean/false_or_false.leo b/asg/tests/pass/boolean/false_or_false.leo deleted file mode 100644 index 7ea710802c..0000000000 --- a/asg/tests/pass/boolean/false_or_false.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main() { - const a = false || false; - - console.assert(a == false); -} \ No newline at end of file diff --git a/asg/tests/pass/boolean/mod.rs b/asg/tests/pass/boolean/mod.rs deleted file mode 100644 index 64f9172507..0000000000 --- a/asg/tests/pass/boolean/mod.rs +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_input_pass() { - let program_string = include_str!("assert_eq_input.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_registers() { - let program_string = include_str!("output_register.leo"); - load_asg(program_string).unwrap(); -} - -// Boolean not ! - -#[test] -fn test_not_true() { - let program_string = include_str!("not_true.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_not_false() { - let program_string = include_str!("not_false.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_not_mutable() { - let program_string = include_str!("not_mutable.leo"); - load_asg(program_string).unwrap(); -} - -// Boolean or || - -#[test] -fn test_true_or_true() { - let program_string = include_str!("true_or_true.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_true_or_false() { - let program_string = include_str!("true_or_false.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_false_or_false() { - let program_string = include_str!("false_or_false.leo"); - load_asg(program_string).unwrap(); -} - -// Boolean and && - -#[test] -fn test_true_and_true() { - let program_string = include_str!("true_and_true.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_true_and_false() { - let program_string = include_str!("true_and_false.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_false_and_false() { - let program_string = include_str!("false_and_false.leo"); - load_asg(program_string).unwrap(); -} - -// All - -#[test] -fn test_all() { - let program_string = include_str!("all.leo"); - load_asg(program_string).unwrap(); -} diff --git a/asg/tests/pass/boolean/not_false.leo b/asg/tests/pass/boolean/not_false.leo deleted file mode 100644 index 796b616871..0000000000 --- a/asg/tests/pass/boolean/not_false.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.assert(!false == true); -} \ No newline at end of file diff --git a/asg/tests/pass/boolean/not_mutable.leo b/asg/tests/pass/boolean/not_mutable.leo deleted file mode 100644 index 92588434e4..0000000000 --- a/asg/tests/pass/boolean/not_mutable.leo +++ /dev/null @@ -1,4 +0,0 @@ -function main () { - const b = false; - const a = !b; -} \ No newline at end of file diff --git a/asg/tests/pass/boolean/not_true.leo b/asg/tests/pass/boolean/not_true.leo deleted file mode 100644 index 8c87dffabb..0000000000 --- a/asg/tests/pass/boolean/not_true.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.assert(!true == false); -} \ No newline at end of file diff --git a/asg/tests/pass/boolean/output_register.leo b/asg/tests/pass/boolean/output_register.leo deleted file mode 100644 index 6273b0a1df..0000000000 --- a/asg/tests/pass/boolean/output_register.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() -> bool { - return input.registers.r; -} diff --git a/asg/tests/pass/boolean/true_and_false.leo b/asg/tests/pass/boolean/true_and_false.leo deleted file mode 100644 index 336dde7558..0000000000 --- a/asg/tests/pass/boolean/true_and_false.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main() { - const a = true && false; - - console.assert(a == false); -} \ No newline at end of file diff --git a/asg/tests/pass/boolean/true_and_true.leo b/asg/tests/pass/boolean/true_and_true.leo deleted file mode 100644 index dae445dcf8..0000000000 --- a/asg/tests/pass/boolean/true_and_true.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main() { - const a = true && true; - - console.assert(a == true); -} \ No newline at end of file diff --git a/asg/tests/pass/boolean/true_or_false.leo b/asg/tests/pass/boolean/true_or_false.leo deleted file mode 100644 index 216e473cdb..0000000000 --- a/asg/tests/pass/boolean/true_or_false.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main() { - const a = true || false; - - console.assert(a == true); -} \ No newline at end of file diff --git a/asg/tests/pass/boolean/true_or_true.leo b/asg/tests/pass/boolean/true_or_true.leo deleted file mode 100644 index fea8628b9f..0000000000 --- a/asg/tests/pass/boolean/true_or_true.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main() { - const a = true || true; - - console.assert(a == true); -} \ No newline at end of file diff --git a/asg/tests/pass/circuits/define_circuit_inside_circuit_function.leo b/asg/tests/pass/circuits/define_circuit_inside_circuit_function.leo deleted file mode 100644 index a15259b1d4..0000000000 --- a/asg/tests/pass/circuits/define_circuit_inside_circuit_function.leo +++ /dev/null @@ -1,13 +0,0 @@ -circuit Foo { - a: u32; -} - -circuit Bar { - function bar() { - const f = Foo { a: 0u32 }; - } -} - -function main() { - const b = Bar::bar(); -} \ No newline at end of file diff --git a/asg/tests/pass/circuits/inline.leo b/asg/tests/pass/circuits/inline.leo deleted file mode 100644 index 19f3d5cfb2..0000000000 --- a/asg/tests/pass/circuits/inline.leo +++ /dev/null @@ -1,7 +0,0 @@ -circuit Foo { - x: u32; -} - -function main() { - const a = Foo { x: 1u32 }; -} \ No newline at end of file diff --git a/asg/tests/pass/circuits/member_function.leo b/asg/tests/pass/circuits/member_function.leo deleted file mode 100644 index b7879b5bf7..0000000000 --- a/asg/tests/pass/circuits/member_function.leo +++ /dev/null @@ -1,11 +0,0 @@ -circuit Foo { - function echo(self, x: u32) -> u32 { - return x; - } -} - -function main() { - const a = Foo { }; - - console.assert(a.echo(1u32) == 1u32); -} \ No newline at end of file diff --git a/asg/tests/pass/circuits/member_function_nested.leo b/asg/tests/pass/circuits/member_function_nested.leo deleted file mode 100644 index 77b0d83bb9..0000000000 --- a/asg/tests/pass/circuits/member_function_nested.leo +++ /dev/null @@ -1,18 +0,0 @@ -circuit Foo { - x: u32; - - function add_x(self, y: u32) -> u32 { - return self.x + y; - } - - function call_add_x(self, y: u32) -> u32 { - return self.add_x(y); - } -} - -function main() { - const a = Foo { x: 1u32 }; - const b = a.add_x(1u32); - - console.assert(b == 2u32); -} diff --git a/asg/tests/pass/circuits/member_static_function.leo b/asg/tests/pass/circuits/member_static_function.leo deleted file mode 100644 index 68f6065754..0000000000 --- a/asg/tests/pass/circuits/member_static_function.leo +++ /dev/null @@ -1,11 +0,0 @@ -circuit Foo { - function echo(x: u32) -> u32 { - return x; - } -} - -function main() { - const a = Foo::echo(1u32); - - console.assert(a == 1u32); -} \ No newline at end of file diff --git a/asg/tests/pass/circuits/member_variable.leo b/asg/tests/pass/circuits/member_variable.leo deleted file mode 100644 index c1f5812dce..0000000000 --- a/asg/tests/pass/circuits/member_variable.leo +++ /dev/null @@ -1,9 +0,0 @@ -circuit Foo { - x: u32; -} - -function main() { - const a = Foo { x: 1u32 }; - - console.assert(a.x == 1u32); -} \ No newline at end of file diff --git a/asg/tests/pass/circuits/member_variable_and_function.leo b/asg/tests/pass/circuits/member_variable_and_function.leo deleted file mode 100644 index d579f3fbf5..0000000000 --- a/asg/tests/pass/circuits/member_variable_and_function.leo +++ /dev/null @@ -1,15 +0,0 @@ -circuit Foo { - foo: u32; - - function bar() -> u32 { - return 1u32; - } -} - -function main() { - const a = Foo { foo: 1 }; - - const b = a.foo + Foo::bar(); - - console.assert(b == 2u32); -} diff --git a/asg/tests/pass/circuits/mod.rs b/asg/tests/pass/circuits/mod.rs deleted file mode 100644 index 21bd99ffa6..0000000000 --- a/asg/tests/pass/circuits/mod.rs +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -// Expressions - -#[test] -fn test_inline() { - let program_string = include_str!("inline.leo"); - load_asg(program_string).unwrap(); -} - -// Members - -#[test] -fn test_member_variable() { - let program_string = include_str!("member_variable.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_member_variable_and_function() { - let program_string = include_str!("member_variable_and_function.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_member_function() { - let program_string = include_str!("member_function.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_mut_member_function() { - let program_string = r#" - circuit Foo { - function echo(mut self, x: u32) -> u32 { - return x; - } - } - - function main() { - let a = Foo { }; - - console.assert(a.echo(1u32) == 1u32); - }"#; - load_asg(program_string).unwrap(); -} - -#[test] -fn test_member_function_nested() { - let program_string = include_str!("member_function_nested.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_member_static_function() { - let program_string = include_str!("member_static_function.leo"); - load_asg(program_string).unwrap(); -} - -// Mutability - -#[test] -fn test_mutate_self_variable() { - let program_string = include_str!("mut_self_variable.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_mutate_self_variable_conditional() { - let program_string = include_str!("mut_self_variable_conditional.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_mutate_variable() { - let program_string = include_str!("mut_variable.leo"); - load_asg(program_string).unwrap(); -} - -// Self - -#[test] -fn test_self_member_pass() { - let program_string = include_str!("self_member.leo"); - load_asg(program_string).unwrap(); -} - -// All - -#[test] -fn test_define_circuit_inside_circuit_function() { - let program_string = include_str!("define_circuit_inside_circuit_function.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_circuit_explicit_define() { - let program_string = r#" - circuit One { - x: u8, - } - function main () { - let x: One = One {x: 5}; - } - "#; - load_asg(program_string).unwrap(); -} diff --git a/asg/tests/pass/circuits/mut_self_variable.leo b/asg/tests/pass/circuits/mut_self_variable.leo deleted file mode 100644 index cfe7e10ef5..0000000000 --- a/asg/tests/pass/circuits/mut_self_variable.leo +++ /dev/null @@ -1,22 +0,0 @@ -circuit Foo { - a: u8; - - function set_a(mut self, new: u8) { - self.a = new; - console.assert(self.a == new); - } -} - -function main() { - let f = Foo { a: 0u8 }; - - console.assert(f.a == 0u8); - - f.set_a(1u8); - - console.assert(f.a == 1u8); - - f.set_a(2u8); - - console.assert(f.a == 2u8); -} \ No newline at end of file diff --git a/asg/tests/pass/circuits/mut_self_variable_conditional.leo b/asg/tests/pass/circuits/mut_self_variable_conditional.leo deleted file mode 100644 index fec92fef93..0000000000 --- a/asg/tests/pass/circuits/mut_self_variable_conditional.leo +++ /dev/null @@ -1,15 +0,0 @@ -function main() { - let f = Foo { a: 0u32 }; - - f.bar(); -} - -circuit Foo { - a: u32; - - function bar(mut self) { - if true { - self.a = 5u32; // Mutating a variable inside a conditional statement should work. - } - } -} \ No newline at end of file diff --git a/asg/tests/pass/circuits/mut_variable.leo b/asg/tests/pass/circuits/mut_variable.leo deleted file mode 100644 index a8cb60d989..0000000000 --- a/asg/tests/pass/circuits/mut_variable.leo +++ /dev/null @@ -1,17 +0,0 @@ -circuit Foo { - a: u8; -} - -function main() { - let f = Foo { a: 0u8 }; - - console.assert(f.a == 0u8); - - f.a = 1u8; - - console.assert(f.a == 1u8); - - f.a = 2u8; - - console.assert(f.a == 2u8); -} \ No newline at end of file diff --git a/asg/tests/pass/circuits/self_circuit.leo b/asg/tests/pass/circuits/self_circuit.leo deleted file mode 100644 index 6faa42278b..0000000000 --- a/asg/tests/pass/circuits/self_circuit.leo +++ /dev/null @@ -1,9 +0,0 @@ -circuit Foo { - static function new() -> Self { - return Self { }; - } -} - -function main() { - const a = Foo::new(); -} \ No newline at end of file diff --git a/asg/tests/pass/circuits/self_member.leo b/asg/tests/pass/circuits/self_member.leo deleted file mode 100644 index a21fbfc5cf..0000000000 --- a/asg/tests/pass/circuits/self_member.leo +++ /dev/null @@ -1,14 +0,0 @@ -circuit Foo { - f: u32; - - function bar(self) -> u32 { - return self.f; - } -} - -function main() { - const a = Foo { f: 1u32 }; - const b = a.bar(); - - console.assert(b == 1u32); -} \ No newline at end of file diff --git a/asg/tests/pass/console/assert.leo b/asg/tests/pass/console/assert.leo deleted file mode 100644 index ba6be77256..0000000000 --- a/asg/tests/pass/console/assert.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: bool) { - console.assert(a == true); -} \ No newline at end of file diff --git a/asg/tests/pass/console/conditional_assert.leo b/asg/tests/pass/console/conditional_assert.leo deleted file mode 100644 index f2c1591e9c..0000000000 --- a/asg/tests/pass/console/conditional_assert.leo +++ /dev/null @@ -1,7 +0,0 @@ -function main(a: bool) { - if a { - console.assert(a == true); - } else { - console.assert(a == false); - } -} \ No newline at end of file diff --git a/asg/tests/pass/console/error.leo b/asg/tests/pass/console/error.leo deleted file mode 100644 index 86d13f8cee..0000000000 --- a/asg/tests/pass/console/error.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.error("hello error"); -} \ No newline at end of file diff --git a/asg/tests/pass/console/log.leo b/asg/tests/pass/console/log.leo deleted file mode 100644 index a190ca4ba9..0000000000 --- a/asg/tests/pass/console/log.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.log("hello world"); -} \ No newline at end of file diff --git a/asg/tests/pass/console/log_fail.leo b/asg/tests/pass/console/log_fail.leo deleted file mode 100644 index dafa6bea8e..0000000000 --- a/asg/tests/pass/console/log_fail.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.log( hello ); -} \ No newline at end of file diff --git a/asg/tests/pass/console/log_input.leo b/asg/tests/pass/console/log_input.leo deleted file mode 100644 index c4fd0a8b12..0000000000 --- a/asg/tests/pass/console/log_input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: bool) { - console.log("a = {}", a); -} \ No newline at end of file diff --git a/asg/tests/pass/console/log_parameter.leo b/asg/tests/pass/console/log_parameter.leo deleted file mode 100644 index ebcb931a2b..0000000000 --- a/asg/tests/pass/console/log_parameter.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.log("{}", 1u32); -} \ No newline at end of file diff --git a/asg/tests/pass/console/log_parameter_fail_empty.leo b/asg/tests/pass/console/log_parameter_fail_empty.leo deleted file mode 100644 index 81b42c0919..0000000000 --- a/asg/tests/pass/console/log_parameter_fail_empty.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.log("{}"); -} \ No newline at end of file diff --git a/asg/tests/pass/console/log_parameter_fail_none.leo b/asg/tests/pass/console/log_parameter_fail_none.leo deleted file mode 100644 index c92fdfbb2d..0000000000 --- a/asg/tests/pass/console/log_parameter_fail_none.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.log("", 1u32); -} \ No newline at end of file diff --git a/asg/tests/pass/console/log_parameter_fail_unknown.leo b/asg/tests/pass/console/log_parameter_fail_unknown.leo deleted file mode 100644 index 757f4c27c3..0000000000 --- a/asg/tests/pass/console/log_parameter_fail_unknown.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.log("{}", a); -} \ No newline at end of file diff --git a/asg/tests/pass/console/log_parameter_many.leo b/asg/tests/pass/console/log_parameter_many.leo deleted file mode 100644 index 60455ebbb0..0000000000 --- a/asg/tests/pass/console/log_parameter_many.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.log("{} {}", 1u32, true); -} \ No newline at end of file diff --git a/asg/tests/pass/console/mod.rs b/asg/tests/pass/console/mod.rs deleted file mode 100644 index 43d3c0e0cb..0000000000 --- a/asg/tests/pass/console/mod.rs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_log() { - let program_string = include_str!("log.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_log_parameter() { - let program_string = include_str!("log_parameter.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_log_parameter_many() { - let program_string = include_str!("log_parameter_many.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_log_input() { - let program_string = include_str!("log_input.leo"); - load_asg(program_string).unwrap(); -} - -// Error - -#[test] -fn test_error() { - let program_string = include_str!("error.leo"); - load_asg(program_string).unwrap(); -} - -// Assertion - -#[test] -fn test_assert() { - let program_string = include_str!("assert.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_conditional_assert() { - let program_string = include_str!("conditional_assert.leo"); - load_asg(program_string).unwrap(); -} diff --git a/asg/tests/pass/core/mod.rs b/asg/tests/pass/core/mod.rs deleted file mode 100644 index ff53f73aae..0000000000 --- a/asg/tests/pass/core/mod.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . diff --git a/asg/tests/pass/definition/mod.rs b/asg/tests/pass/definition/mod.rs deleted file mode 100644 index 921dc3e16d..0000000000 --- a/asg/tests/pass/definition/mod.rs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_out_of_order() { - let program_string = include_str!("out_of_order.leo"); - load_asg(program_string).unwrap(); -} - -// #[test] -// #[ignore] -// fn test_out_of_order_with_import() { -// let program_string = include_str!("out_of_order_with_import.leo"); -// load_asg(program_string).unwrap(); -// } diff --git a/asg/tests/pass/definition/out_of_order.leo b/asg/tests/pass/definition/out_of_order.leo deleted file mode 100644 index 69d46d0e74..0000000000 --- a/asg/tests/pass/definition/out_of_order.leo +++ /dev/null @@ -1,6 +0,0 @@ -@test -function fake_test() {} - -function main() {} - -circuit Foo {} \ No newline at end of file diff --git a/asg/tests/pass/definition/out_of_order_with_import.leo b/asg/tests/pass/definition/out_of_order_with_import.leo deleted file mode 100644 index 9da2938c08..0000000000 --- a/asg/tests/pass/definition/out_of_order_with_import.leo +++ /dev/null @@ -1,8 +0,0 @@ -@test -function fake_test() {} - -function main() {} - -import test_import.foo; - -circuit Foo {} \ No newline at end of file diff --git a/asg/tests/pass/field/add.leo b/asg/tests/pass/field/add.leo deleted file mode 100644 index 8dc2c7df4e..0000000000 --- a/asg/tests/pass/field/add.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: field, b: field, c: field) { - console.assert(a + b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/field/console_assert.leo b/asg/tests/pass/field/console_assert.leo deleted file mode 100644 index c7224bcea5..0000000000 --- a/asg/tests/pass/field/console_assert.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: field, b: field) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/field/div.leo b/asg/tests/pass/field/div.leo deleted file mode 100644 index 028b06fad2..0000000000 --- a/asg/tests/pass/field/div.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: field, b: field, c: field) { - console.assert(a / b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/field/eq.leo b/asg/tests/pass/field/eq.leo deleted file mode 100644 index 91d6d3c14d..0000000000 --- a/asg/tests/pass/field/eq.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: field, b: field, c: bool) { - console.assert((a == b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/field/mod.rs b/asg/tests/pass/field/mod.rs deleted file mode 100644 index 8c895b0c92..0000000000 --- a/asg/tests/pass/field/mod.rs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_negate() { - let program_string = include_str!("negate.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_add() { - let program_string = include_str!("add.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_add_explicit() { - let program_string = r#" - function main() { - let c: field = 0field + 1field; - } - "#; - load_asg(program_string).unwrap(); -} - -#[test] -fn test_sub() { - let program_string = include_str!("sub.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_div() { - let program_string = include_str!("div.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_mul() { - let program_string = include_str!("mul.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_eq() { - let program_string = include_str!("eq.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_console_assert_pass() { - let program_string = include_str!("console_assert.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_ternary() { - let program_string = include_str!("ternary.leo"); - load_asg(program_string).unwrap(); -} diff --git a/asg/tests/pass/field/mul.leo b/asg/tests/pass/field/mul.leo deleted file mode 100644 index 7df7c83830..0000000000 --- a/asg/tests/pass/field/mul.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: field, b: field, c: field) { - console.assert(a * b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/field/negate.leo b/asg/tests/pass/field/negate.leo deleted file mode 100644 index 94c730207a..0000000000 --- a/asg/tests/pass/field/negate.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: field, b: field) { - console.assert(-a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/field/sub.leo b/asg/tests/pass/field/sub.leo deleted file mode 100644 index 2c84b24647..0000000000 --- a/asg/tests/pass/field/sub.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: field, b: field, c: field) { - console.assert(a - b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/field/ternary.leo b/asg/tests/pass/field/ternary.leo deleted file mode 100644 index f193ad82a3..0000000000 --- a/asg/tests/pass/field/ternary.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main(s: bool, a: field, b: field, c: field) { - let r = s ? a : b; - - console.assert(r == c); -} \ No newline at end of file diff --git a/asg/tests/pass/function/array_input.leo b/asg/tests/pass/function/array_input.leo deleted file mode 100644 index 899c0e4af6..0000000000 --- a/asg/tests/pass/function/array_input.leo +++ /dev/null @@ -1,6 +0,0 @@ -function foo(a: [u8; 1]) {} - -function main() { - const a: [u16; 1] = [1; 1]; - foo(a); -} \ No newline at end of file diff --git a/asg/tests/pass/function/empty.leo b/asg/tests/pass/function/empty.leo deleted file mode 100644 index f06c976158..0000000000 --- a/asg/tests/pass/function/empty.leo +++ /dev/null @@ -1,5 +0,0 @@ -function empty() { } - -function main() { - empty(); -} \ No newline at end of file diff --git a/asg/tests/pass/function/iteration.leo b/asg/tests/pass/function/iteration.leo deleted file mode 100644 index 9be86b5a7c..0000000000 --- a/asg/tests/pass/function/iteration.leo +++ /dev/null @@ -1,13 +0,0 @@ -function one() -> u32 { - return 1u32; -} - -function main() { - let a = 0u32; - - for i in 0..10 { - a += one(); - } - - console.assert(a == 10u32); -} \ No newline at end of file diff --git a/asg/tests/pass/function/iteration_repeated.leo b/asg/tests/pass/function/iteration_repeated.leo deleted file mode 100644 index ef4f992d96..0000000000 --- a/asg/tests/pass/function/iteration_repeated.leo +++ /dev/null @@ -1,15 +0,0 @@ -function iteration() -> u32 { - let a = 0u32; - - for i in 0..10 { - a += 1; - } - - return a; -} - -function main() { - const total = iteration() + iteration(); - - console.assert(total == 20); -} \ No newline at end of file diff --git a/asg/tests/pass/function/mod.rs b/asg/tests/pass/function/mod.rs deleted file mode 100644 index 9f5a05f44a..0000000000 --- a/asg/tests/pass/function/mod.rs +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_empty() { - let program_string = include_str!("empty.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_iteration() { - let program_string = include_str!("iteration.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_const_args() { - let program_string = r#" - function one(const value: u32) -> u32 { - return value + 1; - } - - function main() { - let a = 0u32; - - for i in 0..10 { - a += one(i); - } - - console.assert(a == 20u32); - } - "#; - load_asg(program_string).unwrap(); -} - -#[test] -fn test_const_args_used() { - let program_string = r#" - function index(arr: [u8; 3], const value: u32) -> u8 { - return arr[value]; - } - - function main() { - let a = 0u8; - const arr = [1u8, 2, 3]; - - for i in 0..3 { - a += index(arr, i); - } - - console.assert(a == 6u8); - } - "#; - load_asg(program_string).unwrap(); -} - -#[test] -fn test_const_args_fail() { - let program_string = r#" - function index(arr: [u8; 3], const value: u32) -> u8 { - return arr[value]; - } - - function main(x_value: u32) { - let a = 0u8; - const arr = [1u8, 2, 3]; - - a += index(arr, x_value); - - console.assert(a == 1u8); - } - "#; - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_iteration_repeated() { - let program_string = include_str!("iteration_repeated.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_newlines() { - let program_string = include_str!("newlines.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_multiple_returns() { - let program_string = include_str!("multiple_returns.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_multiple_returns_main() { - let program_string = include_str!("multiple_returns_main.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_repeated_function_call() { - let program_string = include_str!("repeated.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_return() { - let program_string = include_str!("return.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_undefined() { - let program_string = include_str!("undefined.leo"); - load_asg(program_string).err().unwrap(); -} - -#[test] -fn test_value_unchanged() { - let program_string = include_str!("value_unchanged.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_array_input() { - let program_string = include_str!("array_input.leo"); - load_asg(program_string).err().unwrap(); -} - -// Test return multidimensional arrays - -#[test] -fn test_return_array_nested_pass() { - let program_string = include_str!("return_array_nested_pass.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_return_array_tuple_pass() { - let program_string = include_str!("return_array_tuple_pass.leo"); - load_asg(program_string).unwrap(); -} - -// Test return tuples - -#[test] -fn test_return_tuple() { - let program_string = include_str!("return_tuple.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_return_tuple_conditional() { - let program_string = include_str!("return_tuple_conditional.leo"); - load_asg(program_string).unwrap(); -} diff --git a/asg/tests/pass/function/multiple_returns.leo b/asg/tests/pass/function/multiple_returns.leo deleted file mode 100644 index 73797c6ca3..0000000000 --- a/asg/tests/pass/function/multiple_returns.leo +++ /dev/null @@ -1,10 +0,0 @@ -function tuple() -> (bool, bool) { - return (true, false); -} - -function main() { - const (a, b) = tuple(); - - console.assert(a == true); - console.assert(b == false); -} \ No newline at end of file diff --git a/asg/tests/pass/function/multiple_returns_main.leo b/asg/tests/pass/function/multiple_returns_main.leo deleted file mode 100644 index 8590cdd71e..0000000000 --- a/asg/tests/pass/function/multiple_returns_main.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() -> (bool, bool) { - return (input.registers.a, input.registers.b); -} diff --git a/asg/tests/pass/function/newlines.leo b/asg/tests/pass/function/newlines.leo deleted file mode 100644 index e0b10dead1..0000000000 --- a/asg/tests/pass/function/newlines.leo +++ /dev/null @@ -1,9 +0,0 @@ -function main( - a: u32, - b: u32, -) -> ( - u32, - u32, -) { - return (a, b); -} \ No newline at end of file diff --git a/asg/tests/pass/function/repeated.leo b/asg/tests/pass/function/repeated.leo deleted file mode 100644 index 2f9bc43d77..0000000000 --- a/asg/tests/pass/function/repeated.leo +++ /dev/null @@ -1,9 +0,0 @@ -function one() -> bool { - return true; -} - -function main() { - const a = one() && one(); - - console.assert(a == true); -} \ No newline at end of file diff --git a/asg/tests/pass/function/return.leo b/asg/tests/pass/function/return.leo deleted file mode 100644 index e839700ee3..0000000000 --- a/asg/tests/pass/function/return.leo +++ /dev/null @@ -1,7 +0,0 @@ -function one() -> u32 { - return 1u32; -} - -function main() { - console.assert(one() == 1u32); -} \ No newline at end of file diff --git a/asg/tests/pass/function/return_array_nested_pass.leo b/asg/tests/pass/function/return_array_nested_pass.leo deleted file mode 100644 index c7586f3f08..0000000000 --- a/asg/tests/pass/function/return_array_nested_pass.leo +++ /dev/null @@ -1,12 +0,0 @@ -function array_3x2_nested() -> [[u8; 2]; 3] { - return [[0u8; 2]; 3]; -} - -function array_3x2_tuple() -> [[u8; 2]; 3] { - return [0u8; (3, 2)]; -} - -function main() { - const a = array_3x2_nested(); - const b = array_3x2_tuple(); -} \ No newline at end of file diff --git a/asg/tests/pass/function/return_array_tuple_pass.leo b/asg/tests/pass/function/return_array_tuple_pass.leo deleted file mode 100644 index 6f5a63e806..0000000000 --- a/asg/tests/pass/function/return_array_tuple_pass.leo +++ /dev/null @@ -1,12 +0,0 @@ -function array_3x2_nested() -> [u8; (3, 2)] { - return [[0u8; 2]; 3]; -} - -function array_3x2_tuple() -> [u8; (3, 2)] { - return [0u8; (3, 2)]; -} - -function main() { - const a = array_3x2_nested(); - const b = array_3x2_tuple(); -} \ No newline at end of file diff --git a/asg/tests/pass/function/return_tuple.leo b/asg/tests/pass/function/return_tuple.leo deleted file mode 100644 index 24328aeaaa..0000000000 --- a/asg/tests/pass/function/return_tuple.leo +++ /dev/null @@ -1,11 +0,0 @@ -// Returns a tuple of tuples. -function tuples() -> ((u8, u8), u32) { - const a: (u8, u8) = (1, 2); - const b: u32 = 3; - - return (a, b); -} - -function main() { - const t = tuples(); -} \ No newline at end of file diff --git a/asg/tests/pass/function/return_tuple_conditional.leo b/asg/tests/pass/function/return_tuple_conditional.leo deleted file mode 100644 index b8040d47ec..0000000000 --- a/asg/tests/pass/function/return_tuple_conditional.leo +++ /dev/null @@ -1,15 +0,0 @@ -// Returns a tuple using a conditional "if" statement. -function tuple_conditional () -> ( - i64, - i64 -) { - if true { - return (1, 1); - } else { - return (2, 2); - } -} - -function main() { - const t = tuple_conditional(); -} \ No newline at end of file diff --git a/asg/tests/pass/function/undefined.leo b/asg/tests/pass/function/undefined.leo deleted file mode 100644 index e1db3b9f09..0000000000 --- a/asg/tests/pass/function/undefined.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - my_function(); -} \ No newline at end of file diff --git a/asg/tests/pass/function/value_unchanged.leo b/asg/tests/pass/function/value_unchanged.leo deleted file mode 100644 index e116736316..0000000000 --- a/asg/tests/pass/function/value_unchanged.leo +++ /dev/null @@ -1,19 +0,0 @@ -// Functions input in leo are pass-by-value. -// -// Program execution: -// line 15: variable `a` is defined with value `1`. -// line 16: value `1` is copied and passed into function `bad_mutate()`. -// line 10: variable `x` is defined with value `1`. -// line 11: variable `x` is set to value `0`. -// line 18: program returns the value of `a`. - -function bad_mutate(x: u32) { - x = 0; // <- does not change `a` -} - -function main() { - const a = 1u32; - bad_mutate(a); - - console.assert(a == 1u32); // <- value `a` is still `1u32` -} \ No newline at end of file diff --git a/asg/tests/pass/group/add.leo b/asg/tests/pass/group/add.leo deleted file mode 100644 index bb84df2d6c..0000000000 --- a/asg/tests/pass/group/add.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: group, b: group, c: group) { - console.assert(a + b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/group/assert_eq.leo b/asg/tests/pass/group/assert_eq.leo deleted file mode 100644 index 3886a07bbf..0000000000 --- a/asg/tests/pass/group/assert_eq.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: group, b: group) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/group/both_sign_high.leo b/asg/tests/pass/group/both_sign_high.leo deleted file mode 100644 index 4c93573e1e..0000000000 --- a/asg/tests/pass/group/both_sign_high.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const element = (+, +)group; -} \ No newline at end of file diff --git a/asg/tests/pass/group/both_sign_inferred.leo b/asg/tests/pass/group/both_sign_inferred.leo deleted file mode 100644 index 0bbd360ba0..0000000000 --- a/asg/tests/pass/group/both_sign_inferred.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const element = (_, _)group; -} \ No newline at end of file diff --git a/asg/tests/pass/group/both_sign_low.leo b/asg/tests/pass/group/both_sign_low.leo deleted file mode 100644 index 1cb4f46c55..0000000000 --- a/asg/tests/pass/group/both_sign_low.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const element = (-, -)group; -} \ No newline at end of file diff --git a/asg/tests/pass/group/eq.leo b/asg/tests/pass/group/eq.leo deleted file mode 100644 index 09f6210ac3..0000000000 --- a/asg/tests/pass/group/eq.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: group, b: group, c: bool) { - console.assert((a == b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/group/input.leo b/asg/tests/pass/group/input.leo deleted file mode 100644 index 3886a07bbf..0000000000 --- a/asg/tests/pass/group/input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: group, b: group) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/group/mod.rs b/asg/tests/pass/group/mod.rs deleted file mode 100644 index a8a213e37a..0000000000 --- a/asg/tests/pass/group/mod.rs +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_one() { - let program_string = include_str!("one.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_implicit() { - let program_string = r#" - function main() { - let element: group = 0; - } - "#; - load_asg(program_string).unwrap(); -} - -#[test] -fn test_zero() { - let program_string = include_str!("zero.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_point() { - let program_string = include_str!("point.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_x_sign_high() { - let program_string = include_str!("x_sign_high.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_x_sign_low() { - let program_string = include_str!("x_sign_low.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_x_sign_inferred() { - let program_string = include_str!("x_sign_inferred.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_y_sign_high() { - let program_string = include_str!("y_sign_high.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_y_sign_low() { - let program_string = include_str!("y_sign_low.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_y_sign_inferred() { - let program_string = include_str!("y_sign_inferred.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_point_input() { - let program_string = include_str!("point_input.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_input() { - let program_string = include_str!("input.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_negate() { - let program_string = include_str!("negate.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_add() { - let program_string = include_str!("add.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_add_explicit() { - let program_string = r#" - function main() { - let c: group = 0group + 1group; - } - "#; - load_asg(program_string).unwrap(); -} - -#[test] -fn test_sub() { - let program_string = include_str!("sub.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_console_assert_pass() { - let program_string = include_str!("assert_eq.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_eq() { - let program_string = include_str!("eq.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_ternary() { - let program_string = include_str!("ternary.leo"); - load_asg(program_string).unwrap(); -} diff --git a/asg/tests/pass/group/negate.leo b/asg/tests/pass/group/negate.leo deleted file mode 100644 index 506d8d73ce..0000000000 --- a/asg/tests/pass/group/negate.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: group, b: group) { - console.assert(-a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/group/one.leo b/asg/tests/pass/group/one.leo deleted file mode 100644 index 510110150b..0000000000 --- a/asg/tests/pass/group/one.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const element = 1group; -} \ No newline at end of file diff --git a/asg/tests/pass/group/point.leo b/asg/tests/pass/group/point.leo deleted file mode 100644 index 5e68415a0d..0000000000 --- a/asg/tests/pass/group/point.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const point = (7374112779530666882856915975292384652154477718021969292781165691637980424078, 3435195339177955418892975564890903138308061187980579490487898366607011481796)group; -} \ No newline at end of file diff --git a/asg/tests/pass/group/point_input.leo b/asg/tests/pass/group/point_input.leo deleted file mode 100644 index 68d8c458a3..0000000000 --- a/asg/tests/pass/group/point_input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: group) { - let b = a; -} \ No newline at end of file diff --git a/asg/tests/pass/group/sub.leo b/asg/tests/pass/group/sub.leo deleted file mode 100644 index dfe82d8e31..0000000000 --- a/asg/tests/pass/group/sub.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: group, b: group, c: group) { - console.assert(a - b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/group/ternary.leo b/asg/tests/pass/group/ternary.leo deleted file mode 100644 index fb69b74521..0000000000 --- a/asg/tests/pass/group/ternary.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main(s: bool, a: group, b: group, c: group) { - let r = s ? a : b; - - console.assert(r == c); -} \ No newline at end of file diff --git a/asg/tests/pass/group/x_and_y.leo b/asg/tests/pass/group/x_and_y.leo deleted file mode 100644 index a350a7ad6b..0000000000 --- a/asg/tests/pass/group/x_and_y.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(element: group) { - const b = element; -} \ No newline at end of file diff --git a/asg/tests/pass/group/x_sign_high.leo b/asg/tests/pass/group/x_sign_high.leo deleted file mode 100644 index f38b54ad9a..0000000000 --- a/asg/tests/pass/group/x_sign_high.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const element = (0, +)group; -} \ No newline at end of file diff --git a/asg/tests/pass/group/x_sign_inferred.leo b/asg/tests/pass/group/x_sign_inferred.leo deleted file mode 100644 index 02c5ac988b..0000000000 --- a/asg/tests/pass/group/x_sign_inferred.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const element = (0, _)group; -} \ No newline at end of file diff --git a/asg/tests/pass/group/x_sign_low.leo b/asg/tests/pass/group/x_sign_low.leo deleted file mode 100644 index ad74d18b64..0000000000 --- a/asg/tests/pass/group/x_sign_low.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const element = (0, -)group; -} \ No newline at end of file diff --git a/asg/tests/pass/group/y_sign_high.leo b/asg/tests/pass/group/y_sign_high.leo deleted file mode 100644 index af2a20149d..0000000000 --- a/asg/tests/pass/group/y_sign_high.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const element = (+, 1)group; -} \ No newline at end of file diff --git a/asg/tests/pass/group/y_sign_inferred.leo b/asg/tests/pass/group/y_sign_inferred.leo deleted file mode 100644 index a4efa6a982..0000000000 --- a/asg/tests/pass/group/y_sign_inferred.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const element = (_, 1)group; -} \ No newline at end of file diff --git a/asg/tests/pass/group/y_sign_low.leo b/asg/tests/pass/group/y_sign_low.leo deleted file mode 100644 index f557ed0d35..0000000000 --- a/asg/tests/pass/group/y_sign_low.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const element = (-, 1)group; -} \ No newline at end of file diff --git a/asg/tests/pass/group/zero.leo b/asg/tests/pass/group/zero.leo deleted file mode 100644 index 6cdd4c960e..0000000000 --- a/asg/tests/pass/group/zero.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const element = 0group; -} \ No newline at end of file diff --git a/asg/tests/pass/input_files/mod.rs b/asg/tests/pass/input_files/mod.rs deleted file mode 100644 index 46817206d2..0000000000 --- a/asg/tests/pass/input_files/mod.rs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -mod program_input; -mod program_input_and_program_state; -mod program_state; diff --git a/asg/tests/pass/input_files/program_input/main.leo b/asg/tests/pass/input_files/program_input/main.leo deleted file mode 100644 index ba6be77256..0000000000 --- a/asg/tests/pass/input_files/program_input/main.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: bool) { - console.assert(a == true); -} \ No newline at end of file diff --git a/asg/tests/pass/input_files/program_input/main_multiple.leo b/asg/tests/pass/input_files/program_input/main_multiple.leo deleted file mode 100644 index eb5ef8d1f6..0000000000 --- a/asg/tests/pass/input_files/program_input/main_multiple.leo +++ /dev/null @@ -1,4 +0,0 @@ -function main(a: bool, b: bool) { - console.assert(a == true); - console.assert(b == false); -} \ No newline at end of file diff --git a/asg/tests/pass/input_files/program_input/mod.rs b/asg/tests/pass/input_files/program_input/mod.rs deleted file mode 100644 index a223bd970e..0000000000 --- a/asg/tests/pass/input_files/program_input/mod.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_input_pass() { - let program_string = include_str!("main.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_input_multiple() { - let program_string = include_str!("main_multiple.leo"); - load_asg(program_string).unwrap(); -} diff --git a/asg/tests/pass/input_files/program_input_and_program_state/access.leo b/asg/tests/pass/input_files/program_input_and_program_state/access.leo deleted file mode 100644 index 819f6c6c1e..0000000000 --- a/asg/tests/pass/input_files/program_input_and_program_state/access.leo +++ /dev/null @@ -1,11 +0,0 @@ -function main(data: [u8; 32]) { - console.assert(input.registers.value_balance == 0u64); - - console.assert(input.state.leaf_index == 0u32); - - console.assert(input.record.value == 5u64); - - console.assert(input.state_leaf.network_id == 0u8); - - console.assert(data == [0u8; 32]); -} \ No newline at end of file diff --git a/asg/tests/pass/input_files/program_input_and_program_state/mod.rs b/asg/tests/pass/input_files/program_input_and_program_state/mod.rs deleted file mode 100644 index 0df6849508..0000000000 --- a/asg/tests/pass/input_files/program_input_and_program_state/mod.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_access() { - let program_string = include_str!("access.leo"); - load_asg(program_string).unwrap(); -} diff --git a/asg/tests/pass/input_files/program_state/access_all.leo b/asg/tests/pass/input_files/program_state/access_all.leo deleted file mode 100644 index bf85a3f722..0000000000 --- a/asg/tests/pass/input_files/program_state/access_all.leo +++ /dev/null @@ -1,8 +0,0 @@ -function main() { - console.assert(input.state.root == [0u8; 32]); - - const expected: address = aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8; - //console.assert(input.record.owner, expected); - - console.assert(input.state_leaf.network_id == 0u8); -} \ No newline at end of file diff --git a/asg/tests/pass/input_files/program_state/access_state.leo b/asg/tests/pass/input_files/program_state/access_state.leo deleted file mode 100644 index a7afe50a5f..0000000000 --- a/asg/tests/pass/input_files/program_state/access_state.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - console.assert(input.state.root == [0u8; 32]); -} \ No newline at end of file diff --git a/asg/tests/pass/input_files/program_state/mod.rs b/asg/tests/pass/input_files/program_state/mod.rs deleted file mode 100644 index ce09adf28d..0000000000 --- a/asg/tests/pass/input_files/program_state/mod.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_access_state() { - let program_string = include_str!("access_state.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_access_all() { - let program_string = include_str!("access_all.leo"); - load_asg(program_string).unwrap(); -} diff --git a/asg/tests/pass/integers/i128/add.leo b/asg/tests/pass/integers/i128/add.leo deleted file mode 100644 index e35648f545..0000000000 --- a/asg/tests/pass/integers/i128/add.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i128, b: i128, c: i128) { - console.assert(a + b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/console_assert.leo b/asg/tests/pass/integers/i128/console_assert.leo deleted file mode 100644 index c89021f609..0000000000 --- a/asg/tests/pass/integers/i128/console_assert.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i128, b: i128) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/div.leo b/asg/tests/pass/integers/i128/div.leo deleted file mode 100644 index ffaeae19a8..0000000000 --- a/asg/tests/pass/integers/i128/div.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i128, b: i128, c: i128) { - console.assert(a / b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/eq.leo b/asg/tests/pass/integers/i128/eq.leo deleted file mode 100644 index 2491a1a5b4..0000000000 --- a/asg/tests/pass/integers/i128/eq.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i128, b: i128, c: bool) { - console.assert((a == b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/ge.leo b/asg/tests/pass/integers/i128/ge.leo deleted file mode 100644 index 1fbbd68073..0000000000 --- a/asg/tests/pass/integers/i128/ge.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i128, b: i128, c: bool) { - console.assert(a >= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/gt.leo b/asg/tests/pass/integers/i128/gt.leo deleted file mode 100644 index 27849afbe8..0000000000 --- a/asg/tests/pass/integers/i128/gt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i128, b: i128, c: bool) { - console.assert(a > b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/input.leo b/asg/tests/pass/integers/i128/input.leo deleted file mode 100644 index c89021f609..0000000000 --- a/asg/tests/pass/integers/i128/input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i128, b: i128) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/le.leo b/asg/tests/pass/integers/i128/le.leo deleted file mode 100644 index ea0c3c9e1d..0000000000 --- a/asg/tests/pass/integers/i128/le.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i128, b: i128, c: bool) { - console.assert(a <= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/lt.leo b/asg/tests/pass/integers/i128/lt.leo deleted file mode 100644 index bde4def85c..0000000000 --- a/asg/tests/pass/integers/i128/lt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i128, b: i128, c: bool) { - console.assert(a < b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/max.leo b/asg/tests/pass/integers/i128/max.leo deleted file mode 100644 index 5ba44213e1..0000000000 --- a/asg/tests/pass/integers/i128/max.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i128 = 170141183460469231731687303715884105727; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/min.leo b/asg/tests/pass/integers/i128/min.leo deleted file mode 100644 index 19509a3fb0..0000000000 --- a/asg/tests/pass/integers/i128/min.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i128 = -170141183460469231731687303715884105728; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/mod.rs b/asg/tests/pass/integers/i128/mod.rs deleted file mode 100644 index 410e399df2..0000000000 --- a/asg/tests/pass/integers/i128/mod.rs +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_int!(TestI128); - -#[test] -fn test_i128_min() { - TestI128::test_min(); -} - -#[test] -fn test_i128_max() { - TestI128::test_max(); -} - -#[test] -fn test_i128_neg() { - TestI128::test_negate(); -} - -#[test] -fn test_i128_neg_zero() { - TestI128::test_negate_zero(); -} - -#[test] -fn test_i128_add() { - TestI128::test_add(); -} - -#[test] -fn test_i128_sub() { - TestI128::test_sub(); -} - -#[test] -fn test_i128_mul() { - TestI128::test_mul(); -} - -#[test] -#[ignore] // takes several minutes -fn test_i128_div() { - TestI128::test_div(); -} - -#[test] -fn test_i128_pow() { - TestI128::test_pow(); -} - -#[test] -fn test_i128_eq() { - TestI128::test_eq(); -} - -#[test] -fn test_i128_ne() { - TestI128::test_ne(); -} - -#[test] -fn test_i128_ge() { - TestI128::test_ge(); -} - -#[test] -fn test_i128_gt() { - TestI128::test_gt(); -} - -#[test] -fn test_i128_le() { - TestI128::test_le(); -} - -#[test] -fn test_i128_lt() { - TestI128::test_lt(); -} - -#[test] -fn test_i128_assert_eq() { - TestI128::test_console_assert(); -} - -#[test] -fn test_i128_ternary() { - TestI128::test_ternary(); -} diff --git a/asg/tests/pass/integers/i128/mul.leo b/asg/tests/pass/integers/i128/mul.leo deleted file mode 100644 index 25b902d53c..0000000000 --- a/asg/tests/pass/integers/i128/mul.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i128, b: i128, c: i128) { - console.assert(a * b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/ne.leo b/asg/tests/pass/integers/i128/ne.leo deleted file mode 100644 index beabf5672a..0000000000 --- a/asg/tests/pass/integers/i128/ne.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i128, b: i128, c: bool) { - console.assert((a != b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/negate.leo b/asg/tests/pass/integers/i128/negate.leo deleted file mode 100644 index 437ee06390..0000000000 --- a/asg/tests/pass/integers/i128/negate.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i128, b: i128) { - console.assert(-a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/negate_zero.leo b/asg/tests/pass/integers/i128/negate_zero.leo deleted file mode 100644 index e079baf393..0000000000 --- a/asg/tests/pass/integers/i128/negate_zero.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main() { - const a = 0i128; - - console.assert(-a == 0i128); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/pow.leo b/asg/tests/pass/integers/i128/pow.leo deleted file mode 100644 index 05536aad51..0000000000 --- a/asg/tests/pass/integers/i128/pow.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i128, b: i128, c: i128) { - console.assert(a ** b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/sub.leo b/asg/tests/pass/integers/i128/sub.leo deleted file mode 100644 index 3a723eec49..0000000000 --- a/asg/tests/pass/integers/i128/sub.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i128, b: i128, c: i128) { - console.assert(a - b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i128/ternary.leo b/asg/tests/pass/integers/i128/ternary.leo deleted file mode 100644 index a923c428e6..0000000000 --- a/asg/tests/pass/integers/i128/ternary.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main(s: bool, a: i128, b: i128, c: i128) { - let r = s ? a : b; - - console.assert(r == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/add.leo b/asg/tests/pass/integers/i16/add.leo deleted file mode 100644 index 556ae65c3a..0000000000 --- a/asg/tests/pass/integers/i16/add.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i16, b: i16, c: i16) { - console.assert(a + b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/console_assert.leo b/asg/tests/pass/integers/i16/console_assert.leo deleted file mode 100644 index 3afb25b207..0000000000 --- a/asg/tests/pass/integers/i16/console_assert.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i16, b: i16) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/div.leo b/asg/tests/pass/integers/i16/div.leo deleted file mode 100644 index 6d0c8f4614..0000000000 --- a/asg/tests/pass/integers/i16/div.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i16, b: i16, c: i16) { - console.assert(a / b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/eq.leo b/asg/tests/pass/integers/i16/eq.leo deleted file mode 100644 index 7577061061..0000000000 --- a/asg/tests/pass/integers/i16/eq.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i16, b: i16, c: bool) { - console.assert((a == b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/ge.leo b/asg/tests/pass/integers/i16/ge.leo deleted file mode 100644 index 68a4d40bf8..0000000000 --- a/asg/tests/pass/integers/i16/ge.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i16, b: i16, c: bool) { - console.assert(a >= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/gt.leo b/asg/tests/pass/integers/i16/gt.leo deleted file mode 100644 index 75d9bfb612..0000000000 --- a/asg/tests/pass/integers/i16/gt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i16, b: i16, c: bool) { - console.assert(a > b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/input.leo b/asg/tests/pass/integers/i16/input.leo deleted file mode 100644 index 3afb25b207..0000000000 --- a/asg/tests/pass/integers/i16/input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i16, b: i16) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/le.leo b/asg/tests/pass/integers/i16/le.leo deleted file mode 100644 index ff112c7fbc..0000000000 --- a/asg/tests/pass/integers/i16/le.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i16, b: i16, c: bool) { - console.assert(a <= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/lt.leo b/asg/tests/pass/integers/i16/lt.leo deleted file mode 100644 index 46c57aabe6..0000000000 --- a/asg/tests/pass/integers/i16/lt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i16, b: i16, c: bool) { - console.assert(a < b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/max.leo b/asg/tests/pass/integers/i16/max.leo deleted file mode 100644 index 2b70b3cc56..0000000000 --- a/asg/tests/pass/integers/i16/max.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i16 = 32767; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/min.leo b/asg/tests/pass/integers/i16/min.leo deleted file mode 100644 index 3d05bef95a..0000000000 --- a/asg/tests/pass/integers/i16/min.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i16 = -32768; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/mod.rs b/asg/tests/pass/integers/i16/mod.rs deleted file mode 100644 index 7da2ab7038..0000000000 --- a/asg/tests/pass/integers/i16/mod.rs +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_int!(TestI16); - -#[test] -fn test_i16_min() { - TestI16::test_min(); -} - -#[test] -fn test_i16_max() { - TestI16::test_max(); -} - -#[test] -fn test_i16_neg() { - TestI16::test_negate(); -} - -#[test] -fn test_i16_neg_zero() { - TestI16::test_negate_zero(); -} - -#[test] -fn test_i16_add() { - TestI16::test_add(); -} - -#[test] -fn test_i16_sub() { - TestI16::test_sub(); -} - -#[test] -fn test_i16_mul() { - TestI16::test_mul(); -} - -#[test] -fn test_i16_div() { - TestI16::test_div(); -} - -#[test] -fn test_i16_pow() { - TestI16::test_pow(); -} - -#[test] -fn test_i16_eq() { - TestI16::test_eq(); -} - -#[test] -fn test_i16_ne() { - TestI16::test_ne(); -} - -#[test] -fn test_i16_ge() { - TestI16::test_ge(); -} - -#[test] -fn test_i16_gt() { - TestI16::test_gt(); -} - -#[test] -fn test_i16_le() { - TestI16::test_le(); -} - -#[test] -fn test_i16_lt() { - TestI16::test_lt(); -} - -#[test] -fn test_i16_console_assert() { - TestI16::test_console_assert(); -} - -#[test] -fn test_i16_ternary() { - TestI16::test_ternary(); -} diff --git a/asg/tests/pass/integers/i16/mul.leo b/asg/tests/pass/integers/i16/mul.leo deleted file mode 100644 index 6fd19b703a..0000000000 --- a/asg/tests/pass/integers/i16/mul.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i16, b: i16, c: i16) { - console.assert(a * b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/ne.leo b/asg/tests/pass/integers/i16/ne.leo deleted file mode 100644 index 9a749d22ba..0000000000 --- a/asg/tests/pass/integers/i16/ne.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i16, b: i16, c: bool) { - console.assert((a != b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/negate.leo b/asg/tests/pass/integers/i16/negate.leo deleted file mode 100644 index 1d2644dce7..0000000000 --- a/asg/tests/pass/integers/i16/negate.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i16, b: i16) { - console.assert(-a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/negate_zero.leo b/asg/tests/pass/integers/i16/negate_zero.leo deleted file mode 100644 index 20f8a4fba7..0000000000 --- a/asg/tests/pass/integers/i16/negate_zero.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main() { - const a = 0i16; - - console.assert(-a == 0i16); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/pow.leo b/asg/tests/pass/integers/i16/pow.leo deleted file mode 100644 index 769d2d2fbb..0000000000 --- a/asg/tests/pass/integers/i16/pow.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i16, b: i16, c: i16) { - console.assert(a ** b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/sub.leo b/asg/tests/pass/integers/i16/sub.leo deleted file mode 100644 index e935935187..0000000000 --- a/asg/tests/pass/integers/i16/sub.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i16, b: i16, c: i16) { - console.assert(a - b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i16/ternary.leo b/asg/tests/pass/integers/i16/ternary.leo deleted file mode 100644 index 4586b87bb4..0000000000 --- a/asg/tests/pass/integers/i16/ternary.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main(s: bool, a: i16, b: i16, c: i16) { - let r = s ? a : b; - - console.assert(r == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/add.leo b/asg/tests/pass/integers/i32/add.leo deleted file mode 100644 index 3d8fb1b1d2..0000000000 --- a/asg/tests/pass/integers/i32/add.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i32, b: i32, c: i32) { - console.assert(a + b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/console_assert.leo b/asg/tests/pass/integers/i32/console_assert.leo deleted file mode 100644 index a2d6980e9a..0000000000 --- a/asg/tests/pass/integers/i32/console_assert.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i32, b: i32) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/div.leo b/asg/tests/pass/integers/i32/div.leo deleted file mode 100644 index 3189a354f0..0000000000 --- a/asg/tests/pass/integers/i32/div.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i32, b: i32, c: i32) { - console.assert(a / b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/eq.leo b/asg/tests/pass/integers/i32/eq.leo deleted file mode 100644 index eb91dad4df..0000000000 --- a/asg/tests/pass/integers/i32/eq.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i32, b: i32, c: bool) { - console.assert((a == b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/ge.leo b/asg/tests/pass/integers/i32/ge.leo deleted file mode 100644 index 362521fc82..0000000000 --- a/asg/tests/pass/integers/i32/ge.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i32, b: i32, c: bool) { - console.assert(a >= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/gt.leo b/asg/tests/pass/integers/i32/gt.leo deleted file mode 100644 index 63ddcaa85c..0000000000 --- a/asg/tests/pass/integers/i32/gt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i32, b: i32, c: bool) { - console.assert(a > b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/input.leo b/asg/tests/pass/integers/i32/input.leo deleted file mode 100644 index a2d6980e9a..0000000000 --- a/asg/tests/pass/integers/i32/input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i32, b: i32) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/le.leo b/asg/tests/pass/integers/i32/le.leo deleted file mode 100644 index 948c66b1fc..0000000000 --- a/asg/tests/pass/integers/i32/le.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i32, b: i32, c: bool) { - console.assert(a <= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/lt.leo b/asg/tests/pass/integers/i32/lt.leo deleted file mode 100644 index 72a8fb0d53..0000000000 --- a/asg/tests/pass/integers/i32/lt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i32, b: i32, c: bool) { - console.assert(a < b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/max.leo b/asg/tests/pass/integers/i32/max.leo deleted file mode 100644 index 074c75f1a6..0000000000 --- a/asg/tests/pass/integers/i32/max.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i32 = 2147483647; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/min.leo b/asg/tests/pass/integers/i32/min.leo deleted file mode 100644 index 8436268ce6..0000000000 --- a/asg/tests/pass/integers/i32/min.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i32 = -2147483648; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/mod.rs b/asg/tests/pass/integers/i32/mod.rs deleted file mode 100644 index e890904bb5..0000000000 --- a/asg/tests/pass/integers/i32/mod.rs +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_int!(TestI32); - -#[test] -fn test_i32_min() { - TestI32::test_min(); -} - -#[test] -fn test_i32_max() { - TestI32::test_max(); -} - -#[test] -fn test_i32_neg() { - TestI32::test_negate(); -} - -#[test] -fn test_i32_neg_zero() { - TestI32::test_negate_zero(); -} - -#[test] -fn test_i32_add() { - TestI32::test_add(); -} - -#[test] -fn test_i32_sub() { - TestI32::test_sub(); -} - -#[test] -fn test_i32_mul() { - TestI32::test_mul(); -} - -#[test] -fn test_i32_div() { - TestI32::test_div(); -} - -#[test] -fn test_i32_pow() { - TestI32::test_pow(); -} - -#[test] -fn test_i32_eq() { - TestI32::test_eq(); -} - -#[test] -fn test_i32_ne() { - TestI32::test_ne(); -} - -#[test] -fn test_i32_ge() { - TestI32::test_ge(); -} - -#[test] -fn test_i32_gt() { - TestI32::test_gt(); -} - -#[test] -fn test_i32_le() { - TestI32::test_le(); -} - -#[test] -fn test_i32_lt() { - TestI32::test_lt(); -} - -#[test] -fn test_i32_console_assert() { - TestI32::test_console_assert(); -} - -#[test] -fn test_i32_ternary() { - TestI32::test_ternary(); -} diff --git a/asg/tests/pass/integers/i32/mul.leo b/asg/tests/pass/integers/i32/mul.leo deleted file mode 100644 index 50ba5b4128..0000000000 --- a/asg/tests/pass/integers/i32/mul.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i32, b: i32, c: i32) { - console.assert(a * b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/ne.leo b/asg/tests/pass/integers/i32/ne.leo deleted file mode 100644 index 1ea8c38ef7..0000000000 --- a/asg/tests/pass/integers/i32/ne.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i32, b: i32, c: bool) { - console.assert((a != b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/negate.leo b/asg/tests/pass/integers/i32/negate.leo deleted file mode 100644 index eef94c934f..0000000000 --- a/asg/tests/pass/integers/i32/negate.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i32, b: i32) { - console.assert(-a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/negate_zero.leo b/asg/tests/pass/integers/i32/negate_zero.leo deleted file mode 100644 index a3807b1f8a..0000000000 --- a/asg/tests/pass/integers/i32/negate_zero.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main() { - const a = 0i32; - - console.assert(-a == 0i32); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/pow.leo b/asg/tests/pass/integers/i32/pow.leo deleted file mode 100644 index ebb131e30b..0000000000 --- a/asg/tests/pass/integers/i32/pow.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i32, b: i32, c: i32) { - console.assert(a ** b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/sub.leo b/asg/tests/pass/integers/i32/sub.leo deleted file mode 100644 index 1f054a5ddf..0000000000 --- a/asg/tests/pass/integers/i32/sub.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i32, b: i32, c: i32) { - console.assert(a - b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i32/ternary.leo b/asg/tests/pass/integers/i32/ternary.leo deleted file mode 100644 index 7927c2998b..0000000000 --- a/asg/tests/pass/integers/i32/ternary.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main(s: bool, a: i32, b: i32, c: i32) { - let r = s ? a : b; - - console.assert(r == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/add.leo b/asg/tests/pass/integers/i64/add.leo deleted file mode 100644 index aefdbb178f..0000000000 --- a/asg/tests/pass/integers/i64/add.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i64, b: i64, c: i64) { - console.assert(a + b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/console_assert.leo b/asg/tests/pass/integers/i64/console_assert.leo deleted file mode 100644 index ab9a5d6e91..0000000000 --- a/asg/tests/pass/integers/i64/console_assert.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i64, b: i64) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/div.leo b/asg/tests/pass/integers/i64/div.leo deleted file mode 100644 index 142e4ab801..0000000000 --- a/asg/tests/pass/integers/i64/div.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i64, b: i64, c: i64) { - console.assert(a / b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/eq.leo b/asg/tests/pass/integers/i64/eq.leo deleted file mode 100644 index 1ef39c659a..0000000000 --- a/asg/tests/pass/integers/i64/eq.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i64, b: i64, c: bool) { - console.assert((a == b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/ge.leo b/asg/tests/pass/integers/i64/ge.leo deleted file mode 100644 index e7b453c5dc..0000000000 --- a/asg/tests/pass/integers/i64/ge.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i64, b: i64, c: bool) { - console.assert(a >= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/gt.leo b/asg/tests/pass/integers/i64/gt.leo deleted file mode 100644 index 9709bad012..0000000000 --- a/asg/tests/pass/integers/i64/gt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i64, b: i64, c: bool) { - console.assert(a > b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/input.leo b/asg/tests/pass/integers/i64/input.leo deleted file mode 100644 index ab9a5d6e91..0000000000 --- a/asg/tests/pass/integers/i64/input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i64, b: i64) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/le.leo b/asg/tests/pass/integers/i64/le.leo deleted file mode 100644 index 3e2cfcb711..0000000000 --- a/asg/tests/pass/integers/i64/le.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i64, b: i64, c: bool) { - console.assert(a <= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/lt.leo b/asg/tests/pass/integers/i64/lt.leo deleted file mode 100644 index ef4e38eb76..0000000000 --- a/asg/tests/pass/integers/i64/lt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i64, b: i64, c: bool) { - console.assert(a < b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/max.leo b/asg/tests/pass/integers/i64/max.leo deleted file mode 100644 index 593f91e110..0000000000 --- a/asg/tests/pass/integers/i64/max.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i64 = 9223372036854775807; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/min.leo b/asg/tests/pass/integers/i64/min.leo deleted file mode 100644 index 794d8fbfac..0000000000 --- a/asg/tests/pass/integers/i64/min.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i64 = -9223372036854775808; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/mod.rs b/asg/tests/pass/integers/i64/mod.rs deleted file mode 100644 index 1446308045..0000000000 --- a/asg/tests/pass/integers/i64/mod.rs +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_int!(TestI64); - -#[test] -fn test_i64_min() { - TestI64::test_min(); -} - -#[test] -fn test_i64_max() { - TestI64::test_max(); -} - -#[test] -fn test_i64_neg() { - TestI64::test_negate(); -} - -#[test] -fn test_i64_neg_zero() { - TestI64::test_negate_zero(); -} - -#[test] -fn test_i64_add() { - TestI64::test_add(); -} - -#[test] -fn test_i64_sub() { - TestI64::test_sub(); -} - -#[test] -fn test_i64_mul() { - TestI64::test_mul(); -} - -#[test] -#[ignore] // takes 2 minutes -fn test_i64_div() { - TestI64::test_div(); -} - -#[test] -fn test_i64_pow() { - TestI64::test_pow(); -} - -#[test] -fn test_i64_eq() { - TestI64::test_eq(); -} - -#[test] -fn test_i64_ne() { - TestI64::test_ne(); -} - -#[test] -fn test_i64_ge() { - TestI64::test_ge(); -} - -#[test] -fn test_i64_gt() { - TestI64::test_gt(); -} - -#[test] -fn test_i64_le() { - TestI64::test_le(); -} - -#[test] -fn test_i64_lt() { - TestI64::test_lt(); -} - -#[test] -fn test_i64_console_assert() { - TestI64::test_console_assert(); -} - -#[test] -fn test_i64_ternary() { - TestI64::test_ternary(); -} diff --git a/asg/tests/pass/integers/i64/mul.leo b/asg/tests/pass/integers/i64/mul.leo deleted file mode 100644 index a3b8bd1da5..0000000000 --- a/asg/tests/pass/integers/i64/mul.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i64, b: i64, c: i64) { - console.assert(a * b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/ne.leo b/asg/tests/pass/integers/i64/ne.leo deleted file mode 100644 index 956b2a0a45..0000000000 --- a/asg/tests/pass/integers/i64/ne.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i64, b: i64, c: bool) { - console.assert((a != b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/negate.leo b/asg/tests/pass/integers/i64/negate.leo deleted file mode 100644 index fe0cdc4d97..0000000000 --- a/asg/tests/pass/integers/i64/negate.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i64, b: i64) { - console.assert(-a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/negate_zero.leo b/asg/tests/pass/integers/i64/negate_zero.leo deleted file mode 100644 index 81f09c19a3..0000000000 --- a/asg/tests/pass/integers/i64/negate_zero.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main() { - const a = 0i64; - - console.assert(-a == 0i64); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/pow.leo b/asg/tests/pass/integers/i64/pow.leo deleted file mode 100644 index dca2dace74..0000000000 --- a/asg/tests/pass/integers/i64/pow.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i64, b: i64, c: i64) { - console.assert(a ** b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/sub.leo b/asg/tests/pass/integers/i64/sub.leo deleted file mode 100644 index 4d335e504b..0000000000 --- a/asg/tests/pass/integers/i64/sub.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i64, b: i64, c: i64) { - console.assert(a - b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i64/ternary.leo b/asg/tests/pass/integers/i64/ternary.leo deleted file mode 100644 index 1a2d03a77f..0000000000 --- a/asg/tests/pass/integers/i64/ternary.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main(s: bool, a: i64, b: i64, c: i64) { - let r = s ? a : b; - - console.assert(r == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/add.leo b/asg/tests/pass/integers/i8/add.leo deleted file mode 100644 index dd71bc7f53..0000000000 --- a/asg/tests/pass/integers/i8/add.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i8, b: i8, c: i8) { - console.assert(a + b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/console_assert.leo b/asg/tests/pass/integers/i8/console_assert.leo deleted file mode 100644 index 1fc09cb57d..0000000000 --- a/asg/tests/pass/integers/i8/console_assert.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i8, b: i8) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/div.leo b/asg/tests/pass/integers/i8/div.leo deleted file mode 100644 index a80d8e6319..0000000000 --- a/asg/tests/pass/integers/i8/div.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i8, b: i8, c: i8) { - console.assert(a / b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/eq.leo b/asg/tests/pass/integers/i8/eq.leo deleted file mode 100644 index e844a220b1..0000000000 --- a/asg/tests/pass/integers/i8/eq.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i8, b: i8, c: bool) { - console.assert((a == b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/ge.leo b/asg/tests/pass/integers/i8/ge.leo deleted file mode 100644 index 3084692c0c..0000000000 --- a/asg/tests/pass/integers/i8/ge.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i8, b: i8, c: bool) { - console.assert(a >= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/gt.leo b/asg/tests/pass/integers/i8/gt.leo deleted file mode 100644 index d3913b8b24..0000000000 --- a/asg/tests/pass/integers/i8/gt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i8, b: i8, c: bool) { - console.assert(a > b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/input.leo b/asg/tests/pass/integers/i8/input.leo deleted file mode 100644 index 1fc09cb57d..0000000000 --- a/asg/tests/pass/integers/i8/input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i8, b: i8) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/le.leo b/asg/tests/pass/integers/i8/le.leo deleted file mode 100644 index 92e011f206..0000000000 --- a/asg/tests/pass/integers/i8/le.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i8, b: i8, c: bool) { - console.assert(a <= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/lt.leo b/asg/tests/pass/integers/i8/lt.leo deleted file mode 100644 index eb34b7148e..0000000000 --- a/asg/tests/pass/integers/i8/lt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i8, b: i8, c: bool) { - console.assert(a < b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/max.leo b/asg/tests/pass/integers/i8/max.leo deleted file mode 100644 index f20d59ddf4..0000000000 --- a/asg/tests/pass/integers/i8/max.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i8 = 127; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/min.leo b/asg/tests/pass/integers/i8/min.leo deleted file mode 100644 index 7b6db025ea..0000000000 --- a/asg/tests/pass/integers/i8/min.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: i8 = -128; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/mod.rs b/asg/tests/pass/integers/i8/mod.rs deleted file mode 100644 index 85402e7628..0000000000 --- a/asg/tests/pass/integers/i8/mod.rs +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_int!(TestI8); - -#[test] -fn test_i8_min() { - TestI8::test_min(); -} - -#[test] -fn test_i8_max() { - TestI8::test_max(); -} - -#[test] -fn test_i8_neg() { - TestI8::test_negate(); -} - -#[test] -fn test_i8_neg_zero() { - TestI8::test_negate_zero(); -} - -#[test] -fn test_i8_add() { - TestI8::test_add(); -} - -#[test] -fn test_i8_sub() { - TestI8::test_sub(); -} - -#[test] -fn test_i8_mul() { - TestI8::test_mul(); -} - -#[test] -fn test_i8_div() { - TestI8::test_div(); -} - -#[test] -fn test_i8_pow() { - TestI8::test_pow(); -} - -#[test] -fn test_i8_eq() { - TestI8::test_eq(); -} - -#[test] -fn test_i8_ne() { - TestI8::test_ne(); -} - -#[test] -fn test_i8_ge() { - TestI8::test_ge(); -} - -#[test] -fn test_i8_gt() { - TestI8::test_gt(); -} - -#[test] -fn test_i8_le() { - TestI8::test_le(); -} - -#[test] -fn test_i8_lt() { - TestI8::test_lt(); -} - -#[test] -fn test_i8_console_assert() { - TestI8::test_console_assert(); -} - -#[test] -fn test_i8_ternary() { - TestI8::test_ternary(); -} diff --git a/asg/tests/pass/integers/i8/mul.leo b/asg/tests/pass/integers/i8/mul.leo deleted file mode 100644 index 34726fff92..0000000000 --- a/asg/tests/pass/integers/i8/mul.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i8, b: i8, c: i8) { - console.assert(a * b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/ne.leo b/asg/tests/pass/integers/i8/ne.leo deleted file mode 100644 index 2ab15c8fe6..0000000000 --- a/asg/tests/pass/integers/i8/ne.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i8, b: i8, c: bool) { - console.assert((a != b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/negate.leo b/asg/tests/pass/integers/i8/negate.leo deleted file mode 100644 index 2a2266bc56..0000000000 --- a/asg/tests/pass/integers/i8/negate.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i8, b: i8) { - console.assert(-a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/negate_zero.leo b/asg/tests/pass/integers/i8/negate_zero.leo deleted file mode 100644 index cc3f4a0828..0000000000 --- a/asg/tests/pass/integers/i8/negate_zero.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main() { - const a = 0i8; - - console.assert(-a == 0i8); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/pow.leo b/asg/tests/pass/integers/i8/pow.leo deleted file mode 100644 index 18aeb44b46..0000000000 --- a/asg/tests/pass/integers/i8/pow.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i8, b: i8, c: i8) { - console.assert(a ** b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/sub.leo b/asg/tests/pass/integers/i8/sub.leo deleted file mode 100644 index a795bed153..0000000000 --- a/asg/tests/pass/integers/i8/sub.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: i8, b: i8, c: i8) { - console.assert(a - b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/i8/ternary.leo b/asg/tests/pass/integers/i8/ternary.leo deleted file mode 100644 index e1ec1943c9..0000000000 --- a/asg/tests/pass/integers/i8/ternary.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main(s: bool, a: i8, b: i8, c: i8) { - let r = s ? a : b; - - console.assert(r == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/int_macro.rs b/asg/tests/pass/integers/int_macro.rs deleted file mode 100644 index b9c7e7bc28..0000000000 --- a/asg/tests/pass/integers/int_macro.rs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -macro_rules! test_int { - ($name: ident) => { - pub struct $name {} - - impl $name { - fn test_negate() { - let program_string = include_str!("negate.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_negate_zero() { - let program_string = include_str!("negate_zero.leo"); - crate::load_asg(program_string).unwrap(); - } - } - - impl super::IntegerTester for $name { - fn test_min() { - let program_string = include_str!("min.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_max() { - let program_string = include_str!("max.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_add() { - let program_string = include_str!("add.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_sub() { - let program_string = include_str!("sub.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_mul() { - let program_string = include_str!("mul.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_div() { - let program_string = include_str!("div.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_pow() { - let program_string = include_str!("pow.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_eq() { - let program_string = include_str!("eq.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_ne() { - let program_string = include_str!("ne.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_ge() { - let program_string = include_str!("ge.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_gt() { - let program_string = include_str!("gt.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_le() { - let program_string = include_str!("le.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_lt() { - let program_string = include_str!("lt.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_console_assert() { - let program_string = include_str!("console_assert.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_ternary() { - let program_string = include_str!("ternary.leo"); - crate::load_asg(program_string).unwrap(); - } - } - }; -} diff --git a/asg/tests/pass/integers/integer_tester.rs b/asg/tests/pass/integers/integer_tester.rs deleted file mode 100644 index 4eb177b42b..0000000000 --- a/asg/tests/pass/integers/integer_tester.rs +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub trait IntegerTester { - /// Tests defining the smalled value that can be represented by the integer type - fn test_min(); - - /// Tests defining the largest value that can be represented by the integer type - fn test_max(); - - /// Tests a non-wrapping addition - fn test_add(); - - /// Tests a non-wrapping subtraction - fn test_sub(); - - /// Tests a non-wrapping multiplication - fn test_mul(); - - /// Tests a non-wrapping division - fn test_div(); - - /// Tests a non-wrapping exponentiation - fn test_pow(); - - /// Tests == evaluation - fn test_eq(); - - /// Tests != evaluation - fn test_ne(); - - /// Tests >= evaluation - fn test_ge(); - - /// Tests > evaluation - fn test_gt(); - - /// Tests <= evaluation - fn test_le(); - - /// Tests < evaluation - fn test_lt(); - - /// Test assert equals constraint keyword - fn test_console_assert(); - - /// Test ternary if bool ? num_1 : num_2; - fn test_ternary(); -} diff --git a/asg/tests/pass/integers/mod.rs b/asg/tests/pass/integers/mod.rs deleted file mode 100644 index 0cfd4f643c..0000000000 --- a/asg/tests/pass/integers/mod.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -#[macro_use] -pub mod int_macro; - -#[macro_use] -pub mod uint_macro; - -pub mod integer_tester; -pub use self::integer_tester::*; - -// must be below macro definitions! -pub mod u128; -pub mod u16; -pub mod u32; -pub mod u64; -pub mod u8; - -pub mod i128; -pub mod i16; -pub mod i32; -pub mod i64; -pub mod i8; diff --git a/asg/tests/pass/integers/u128/add.leo b/asg/tests/pass/integers/u128/add.leo deleted file mode 100644 index 6b32042fd5..0000000000 --- a/asg/tests/pass/integers/u128/add.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u128, b: u128, c: u128) { - console.assert(a + b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u128/console_assert.leo b/asg/tests/pass/integers/u128/console_assert.leo deleted file mode 100644 index adab295385..0000000000 --- a/asg/tests/pass/integers/u128/console_assert.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u128, b: u128) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u128/div.leo b/asg/tests/pass/integers/u128/div.leo deleted file mode 100644 index 0d62054eca..0000000000 --- a/asg/tests/pass/integers/u128/div.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u128, b: u128, c: u128) { - console.assert(a / b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u128/eq.leo b/asg/tests/pass/integers/u128/eq.leo deleted file mode 100644 index ad8faf0461..0000000000 --- a/asg/tests/pass/integers/u128/eq.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u128, b: u128, c: bool) { - console.assert((a == b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u128/ge.leo b/asg/tests/pass/integers/u128/ge.leo deleted file mode 100644 index bff7cd321b..0000000000 --- a/asg/tests/pass/integers/u128/ge.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u128, b: u128, c: bool) { - console.assert(a >= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u128/gt.leo b/asg/tests/pass/integers/u128/gt.leo deleted file mode 100644 index e8aec0faf2..0000000000 --- a/asg/tests/pass/integers/u128/gt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u128, b: u128, c: bool) { - console.assert(a > b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u128/input.leo b/asg/tests/pass/integers/u128/input.leo deleted file mode 100644 index adab295385..0000000000 --- a/asg/tests/pass/integers/u128/input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u128, b: u128) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u128/le.leo b/asg/tests/pass/integers/u128/le.leo deleted file mode 100644 index c9e4609136..0000000000 --- a/asg/tests/pass/integers/u128/le.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u128, b: u128, c: bool) { - console.assert(a <= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u128/lt.leo b/asg/tests/pass/integers/u128/lt.leo deleted file mode 100644 index b37057c895..0000000000 --- a/asg/tests/pass/integers/u128/lt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u128, b: u128, c: bool) { - console.assert(a < b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u128/max.leo b/asg/tests/pass/integers/u128/max.leo deleted file mode 100644 index b166ede06b..0000000000 --- a/asg/tests/pass/integers/u128/max.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u128 = 340282366920938463463374607431768211455; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u128/min.leo b/asg/tests/pass/integers/u128/min.leo deleted file mode 100644 index 41fbf1a2fe..0000000000 --- a/asg/tests/pass/integers/u128/min.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u128 = 0; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u128/mod.rs b/asg/tests/pass/integers/u128/mod.rs deleted file mode 100644 index 7de4918199..0000000000 --- a/asg/tests/pass/integers/u128/mod.rs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_uint!(TestU128); - -#[test] -fn test_u128_min() { - TestU128::test_min(); -} - -#[test] -fn test_u128_max() { - TestU128::test_max(); -} - -#[test] -fn test_u128_add() { - TestU128::test_add(); -} - -#[test] -fn test_u128_sub() { - TestU128::test_sub(); -} - -#[test] -fn test_u128_mul() { - TestU128::test_mul(); -} - -#[test] -fn test_u128_div() { - TestU128::test_div(); -} - -#[test] -fn test_u128_pow() { - TestU128::test_pow(); -} - -#[test] -fn test_u128_eq() { - TestU128::test_eq(); -} - -#[test] -fn test_u128_ne() { - TestU128::test_ne(); -} - -#[test] -fn test_u128_ge() { - TestU128::test_ge(); -} - -#[test] -fn test_u128_gt() { - TestU128::test_gt(); -} - -#[test] -fn test_u128_le() { - TestU128::test_le(); -} - -#[test] -fn test_u128_lt() { - TestU128::test_lt(); -} - -#[test] -fn test_u128_console_assert() { - TestU128::test_console_assert(); -} - -#[test] -fn test_u128_ternary() { - TestU128::test_ternary(); -} diff --git a/asg/tests/pass/integers/u128/mul.leo b/asg/tests/pass/integers/u128/mul.leo deleted file mode 100644 index c7fdc1530c..0000000000 --- a/asg/tests/pass/integers/u128/mul.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u128, b: u128, c: u128) { - console.assert(a * b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u128/ne.leo b/asg/tests/pass/integers/u128/ne.leo deleted file mode 100644 index 1752361c3f..0000000000 --- a/asg/tests/pass/integers/u128/ne.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u128, b: u128, c: bool) { - console.assert((a != b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u128/pow.leo b/asg/tests/pass/integers/u128/pow.leo deleted file mode 100644 index 27614bfa56..0000000000 --- a/asg/tests/pass/integers/u128/pow.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u128, b: u128, c: u128) { - console.assert(a ** b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u128/sub.leo b/asg/tests/pass/integers/u128/sub.leo deleted file mode 100644 index 2374413505..0000000000 --- a/asg/tests/pass/integers/u128/sub.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u128, b: u128, c: u128) { - console.assert(a - b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u128/ternary.leo b/asg/tests/pass/integers/u128/ternary.leo deleted file mode 100644 index 22e2e67058..0000000000 --- a/asg/tests/pass/integers/u128/ternary.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main(s: bool, a: u128, b: u128, c: u128) { - let r = s ? a : b; - - console.assert(r == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u16/add.leo b/asg/tests/pass/integers/u16/add.leo deleted file mode 100644 index f00701181b..0000000000 --- a/asg/tests/pass/integers/u16/add.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u16, b: u16, c: u16) { - console.assert(a + b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u16/console_assert.leo b/asg/tests/pass/integers/u16/console_assert.leo deleted file mode 100644 index 761f0639d0..0000000000 --- a/asg/tests/pass/integers/u16/console_assert.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u16, b: u16) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u16/div.leo b/asg/tests/pass/integers/u16/div.leo deleted file mode 100644 index f1dd3fa463..0000000000 --- a/asg/tests/pass/integers/u16/div.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u16, b: u16, c: u16) { - console.assert(a / b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u16/eq.leo b/asg/tests/pass/integers/u16/eq.leo deleted file mode 100644 index 589c6fb81f..0000000000 --- a/asg/tests/pass/integers/u16/eq.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u16, b: u16, c: bool) { - console.assert((a == b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u16/ge.leo b/asg/tests/pass/integers/u16/ge.leo deleted file mode 100644 index 4b1da1b27b..0000000000 --- a/asg/tests/pass/integers/u16/ge.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u16, b: u16, c: bool) { - console.assert(a >= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u16/gt.leo b/asg/tests/pass/integers/u16/gt.leo deleted file mode 100644 index 2c5ffbe8eb..0000000000 --- a/asg/tests/pass/integers/u16/gt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u16, b: u16, c: bool) { - console.assert(a > b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u16/input.leo b/asg/tests/pass/integers/u16/input.leo deleted file mode 100644 index 761f0639d0..0000000000 --- a/asg/tests/pass/integers/u16/input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u16, b: u16) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u16/le.leo b/asg/tests/pass/integers/u16/le.leo deleted file mode 100644 index 49713482d0..0000000000 --- a/asg/tests/pass/integers/u16/le.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u16, b: u16, c: bool) { - console.assert(a <= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u16/lt.leo b/asg/tests/pass/integers/u16/lt.leo deleted file mode 100644 index dae1951231..0000000000 --- a/asg/tests/pass/integers/u16/lt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u16, b: u16, c: bool) { - console.assert(a < b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u16/max.leo b/asg/tests/pass/integers/u16/max.leo deleted file mode 100644 index 56cb2af18d..0000000000 --- a/asg/tests/pass/integers/u16/max.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u16 = 65535; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u16/min.leo b/asg/tests/pass/integers/u16/min.leo deleted file mode 100644 index 4dee94a1a4..0000000000 --- a/asg/tests/pass/integers/u16/min.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u16 = 0; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u16/mod.rs b/asg/tests/pass/integers/u16/mod.rs deleted file mode 100644 index 1544e09e00..0000000000 --- a/asg/tests/pass/integers/u16/mod.rs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_uint!(TestU16); - -#[test] -fn test_u16_min() { - TestU16::test_min(); -} - -#[test] -fn test_u16_max() { - TestU16::test_max(); -} - -#[test] -fn test_u16_add() { - TestU16::test_add(); -} - -#[test] -fn test_u16_sub() { - TestU16::test_sub(); -} - -#[test] -fn test_u16_mul() { - TestU16::test_mul(); -} - -#[test] -fn test_u16_div() { - TestU16::test_div(); -} - -#[test] -fn test_u16_pow() { - TestU16::test_pow(); -} - -#[test] -fn test_u16_eq() { - TestU16::test_eq(); -} - -#[test] -fn test_u16_ne() { - TestU16::test_ne(); -} - -#[test] -fn test_u16_ge() { - TestU16::test_ge(); -} - -#[test] -fn test_u16_gt() { - TestU16::test_gt(); -} - -#[test] -fn test_u16_le() { - TestU16::test_le(); -} - -#[test] -fn test_u16_lt() { - TestU16::test_lt(); -} - -#[test] -fn test_u16_console_assert() { - TestU16::test_console_assert(); -} - -#[test] -fn test_u16_ternary() { - TestU16::test_ternary(); -} diff --git a/asg/tests/pass/integers/u16/mul.leo b/asg/tests/pass/integers/u16/mul.leo deleted file mode 100644 index f2c6f0aac8..0000000000 --- a/asg/tests/pass/integers/u16/mul.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u16, b: u16, c: u16) { - console.assert(a * b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u16/ne.leo b/asg/tests/pass/integers/u16/ne.leo deleted file mode 100644 index 206c777be5..0000000000 --- a/asg/tests/pass/integers/u16/ne.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u16, b: u16, c: bool) { - console.assert((a != b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u16/pow.leo b/asg/tests/pass/integers/u16/pow.leo deleted file mode 100644 index 564c1c51fe..0000000000 --- a/asg/tests/pass/integers/u16/pow.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u16, b: u16, c: u16) { - console.assert(a ** b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u16/sub.leo b/asg/tests/pass/integers/u16/sub.leo deleted file mode 100644 index 92aae9ac2c..0000000000 --- a/asg/tests/pass/integers/u16/sub.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u16, b: u16, c: u16) { - console.assert(a - b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u16/ternary.leo b/asg/tests/pass/integers/u16/ternary.leo deleted file mode 100644 index 11d836570d..0000000000 --- a/asg/tests/pass/integers/u16/ternary.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main(s: bool, a: u16, b: u16, c: u16) { - let r = s ? a : b; - - console.assert(r == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u32/add.leo b/asg/tests/pass/integers/u32/add.leo deleted file mode 100644 index 6f6a2454b4..0000000000 --- a/asg/tests/pass/integers/u32/add.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u32, b: u32, c: u32) { - console.assert(a + b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u32/console_assert.leo b/asg/tests/pass/integers/u32/console_assert.leo deleted file mode 100644 index 32604eb3b8..0000000000 --- a/asg/tests/pass/integers/u32/console_assert.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u32, b: u32) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u32/div.leo b/asg/tests/pass/integers/u32/div.leo deleted file mode 100644 index ed689bd408..0000000000 --- a/asg/tests/pass/integers/u32/div.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u32, b: u32, c: u32) { - console.assert(a / b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u32/eq.leo b/asg/tests/pass/integers/u32/eq.leo deleted file mode 100644 index 1c90d7cf73..0000000000 --- a/asg/tests/pass/integers/u32/eq.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u32, b: u32, c: bool) { - console.assert((a == b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u32/ge.leo b/asg/tests/pass/integers/u32/ge.leo deleted file mode 100644 index 35c1c71829..0000000000 --- a/asg/tests/pass/integers/u32/ge.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u32, b: u32, c: bool) { - console.assert(a >= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u32/gt.leo b/asg/tests/pass/integers/u32/gt.leo deleted file mode 100644 index f76df415c4..0000000000 --- a/asg/tests/pass/integers/u32/gt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u32, b: u32, c: bool) { - console.assert(a > b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u32/input.leo b/asg/tests/pass/integers/u32/input.leo deleted file mode 100644 index 32604eb3b8..0000000000 --- a/asg/tests/pass/integers/u32/input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u32, b: u32) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u32/le.leo b/asg/tests/pass/integers/u32/le.leo deleted file mode 100644 index 9a802f896d..0000000000 --- a/asg/tests/pass/integers/u32/le.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u32, b: u32, c: bool) { - console.assert(a <= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u32/lt.leo b/asg/tests/pass/integers/u32/lt.leo deleted file mode 100644 index 73e5654470..0000000000 --- a/asg/tests/pass/integers/u32/lt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u32, b: u32, c: bool) { - console.assert(a < b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u32/max.leo b/asg/tests/pass/integers/u32/max.leo deleted file mode 100644 index 4a07281b5d..0000000000 --- a/asg/tests/pass/integers/u32/max.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u32 = 4294967295; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u32/min.leo b/asg/tests/pass/integers/u32/min.leo deleted file mode 100644 index 8077e0ec02..0000000000 --- a/asg/tests/pass/integers/u32/min.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u32 = 0; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u32/mod.rs b/asg/tests/pass/integers/u32/mod.rs deleted file mode 100644 index 0fe1d534db..0000000000 --- a/asg/tests/pass/integers/u32/mod.rs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_uint!(TestU32); - -#[test] -fn test_u32_min() { - TestU32::test_min(); -} - -#[test] -fn test_u32_max() { - TestU32::test_max(); -} - -#[test] -fn test_u32_add() { - TestU32::test_add(); -} - -#[test] -fn test_u32_sub() { - TestU32::test_sub(); -} - -#[test] -fn test_u32_mul() { - TestU32::test_mul(); -} - -#[test] -fn test_u32_div() { - TestU32::test_div(); -} - -#[test] -fn test_u32_pow() { - TestU32::test_pow(); -} - -#[test] -fn test_u32_eq() { - TestU32::test_eq(); -} - -#[test] -fn test_u32_ne() { - TestU32::test_ne(); -} - -#[test] -fn test_u32_ge() { - TestU32::test_ge(); -} - -#[test] -fn test_u32_gt() { - TestU32::test_gt(); -} - -#[test] -fn test_u32_le() { - TestU32::test_le(); -} - -#[test] -fn test_u32_lt() { - TestU32::test_lt(); -} - -#[test] -fn test_u32_console_assert() { - TestU32::test_console_assert(); -} - -#[test] -fn test_u32_ternary() { - TestU32::test_ternary(); -} diff --git a/asg/tests/pass/integers/u32/mul.leo b/asg/tests/pass/integers/u32/mul.leo deleted file mode 100644 index a77a85477b..0000000000 --- a/asg/tests/pass/integers/u32/mul.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u32, b: u32, c: u32) { - console.assert(a * b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u32/ne.leo b/asg/tests/pass/integers/u32/ne.leo deleted file mode 100644 index f086aa0639..0000000000 --- a/asg/tests/pass/integers/u32/ne.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u32, b: u32, c: bool) { - console.assert((a != b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u32/pow.leo b/asg/tests/pass/integers/u32/pow.leo deleted file mode 100644 index b82496ff77..0000000000 --- a/asg/tests/pass/integers/u32/pow.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u32, b: u32, c: u32) { - console.assert(a ** b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u32/sub.leo b/asg/tests/pass/integers/u32/sub.leo deleted file mode 100644 index 54480bd4bc..0000000000 --- a/asg/tests/pass/integers/u32/sub.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u32, b: u32, c: u32) { - console.assert(a - b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u32/ternary.leo b/asg/tests/pass/integers/u32/ternary.leo deleted file mode 100644 index 3c96a7236c..0000000000 --- a/asg/tests/pass/integers/u32/ternary.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main(s: bool, a: u32, b: u32, c: u32) { - let r = s ? a : b; - - console.assert(r == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u64/add.leo b/asg/tests/pass/integers/u64/add.leo deleted file mode 100644 index 28abe51201..0000000000 --- a/asg/tests/pass/integers/u64/add.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u64, b: u64, c: u64) { - console.assert(a + b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u64/console_assert.leo b/asg/tests/pass/integers/u64/console_assert.leo deleted file mode 100644 index ac1d6d40c3..0000000000 --- a/asg/tests/pass/integers/u64/console_assert.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u64, b: u64) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u64/div.leo b/asg/tests/pass/integers/u64/div.leo deleted file mode 100644 index 059da236bb..0000000000 --- a/asg/tests/pass/integers/u64/div.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u64, b: u64, c: u64) { - console.assert(a / b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u64/eq.leo b/asg/tests/pass/integers/u64/eq.leo deleted file mode 100644 index e69a2802de..0000000000 --- a/asg/tests/pass/integers/u64/eq.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u64, b: u64, c: bool) { - console.assert((a == b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u64/ge.leo b/asg/tests/pass/integers/u64/ge.leo deleted file mode 100644 index 46ba36ceff..0000000000 --- a/asg/tests/pass/integers/u64/ge.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u64, b: u64, c: bool) { - console.assert(a >= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u64/gt.leo b/asg/tests/pass/integers/u64/gt.leo deleted file mode 100644 index 7d3032c7f5..0000000000 --- a/asg/tests/pass/integers/u64/gt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u64, b: u64, c: bool) { - console.assert(a > b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u64/input.leo b/asg/tests/pass/integers/u64/input.leo deleted file mode 100644 index ac1d6d40c3..0000000000 --- a/asg/tests/pass/integers/u64/input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u64, b: u64) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u64/le.leo b/asg/tests/pass/integers/u64/le.leo deleted file mode 100644 index 625b38d2d9..0000000000 --- a/asg/tests/pass/integers/u64/le.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u64, b: u64, c: bool) { - console.assert(a <= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u64/lt.leo b/asg/tests/pass/integers/u64/lt.leo deleted file mode 100644 index ed379f7341..0000000000 --- a/asg/tests/pass/integers/u64/lt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u64, b: u64, c: bool) { - console.assert(a < b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u64/max.leo b/asg/tests/pass/integers/u64/max.leo deleted file mode 100644 index f14ac7ce64..0000000000 --- a/asg/tests/pass/integers/u64/max.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u64 = 18446744073709551615; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u64/min.leo b/asg/tests/pass/integers/u64/min.leo deleted file mode 100644 index b1da40b14c..0000000000 --- a/asg/tests/pass/integers/u64/min.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u64 = 0; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u64/mod.rs b/asg/tests/pass/integers/u64/mod.rs deleted file mode 100644 index 146aaa5415..0000000000 --- a/asg/tests/pass/integers/u64/mod.rs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_uint!(TestU64); - -#[test] -fn test_u64_min() { - TestU64::test_min(); -} - -#[test] -fn test_u64_max() { - TestU64::test_max(); -} - -#[test] -fn test_u64_add() { - TestU64::test_add(); -} - -#[test] -fn test_u64_sub() { - TestU64::test_sub(); -} - -#[test] -fn test_u64_mul() { - TestU64::test_mul(); -} - -#[test] -fn test_u64_div() { - TestU64::test_div(); -} - -#[test] -fn test_u64_pow() { - TestU64::test_pow(); -} - -#[test] -fn test_u64_eq() { - TestU64::test_eq(); -} - -#[test] -fn test_u64_ne() { - TestU64::test_ne(); -} - -#[test] -fn test_u64_ge() { - TestU64::test_ge(); -} - -#[test] -fn test_u64_gt() { - TestU64::test_gt(); -} - -#[test] -fn test_u64_le() { - TestU64::test_le(); -} - -#[test] -fn test_u64_lt() { - TestU64::test_lt(); -} - -#[test] -fn test_u64_console_assert() { - TestU64::test_console_assert(); -} - -#[test] -fn test_u64_ternary() { - TestU64::test_ternary(); -} diff --git a/asg/tests/pass/integers/u64/mul.leo b/asg/tests/pass/integers/u64/mul.leo deleted file mode 100644 index 2633e6780c..0000000000 --- a/asg/tests/pass/integers/u64/mul.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u64, b: u64, c: u64) { - console.assert(a * b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u64/ne.leo b/asg/tests/pass/integers/u64/ne.leo deleted file mode 100644 index 4c94f15023..0000000000 --- a/asg/tests/pass/integers/u64/ne.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u64, b: u64, c: bool) { - console.assert((a != b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u64/pow.leo b/asg/tests/pass/integers/u64/pow.leo deleted file mode 100644 index 64f0694ed1..0000000000 --- a/asg/tests/pass/integers/u64/pow.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u64, b: u64, c: u64) { - console.assert(a ** b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u64/sub.leo b/asg/tests/pass/integers/u64/sub.leo deleted file mode 100644 index 9961f0f7b7..0000000000 --- a/asg/tests/pass/integers/u64/sub.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u64, b: u64, c: u64) { - console.assert(a - b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u64/ternary.leo b/asg/tests/pass/integers/u64/ternary.leo deleted file mode 100644 index 4c4ddd8e0c..0000000000 --- a/asg/tests/pass/integers/u64/ternary.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main(s: bool, a: u64, b: u64, c: u64) { - let r = s ? a : b; - - console.assert(r == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u8/add.leo b/asg/tests/pass/integers/u8/add.leo deleted file mode 100644 index 1b40e304d2..0000000000 --- a/asg/tests/pass/integers/u8/add.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u8, b: u8, c: u8) { - console.assert(a + b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u8/console_assert.leo b/asg/tests/pass/integers/u8/console_assert.leo deleted file mode 100644 index 4d99dc106c..0000000000 --- a/asg/tests/pass/integers/u8/console_assert.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u8, b: u8) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u8/div.leo b/asg/tests/pass/integers/u8/div.leo deleted file mode 100644 index 945aa94c30..0000000000 --- a/asg/tests/pass/integers/u8/div.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u8, b: u8, c: u8) { - console.assert(a / b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u8/eq.leo b/asg/tests/pass/integers/u8/eq.leo deleted file mode 100644 index 6fae190f8a..0000000000 --- a/asg/tests/pass/integers/u8/eq.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u8, b: u8, c: bool) { - console.assert((a == b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u8/ge.leo b/asg/tests/pass/integers/u8/ge.leo deleted file mode 100644 index d819422276..0000000000 --- a/asg/tests/pass/integers/u8/ge.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u8, b: u8, c: bool) { - console.assert(a >= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u8/gt.leo b/asg/tests/pass/integers/u8/gt.leo deleted file mode 100644 index 87843f575f..0000000000 --- a/asg/tests/pass/integers/u8/gt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u8, b: u8, c: bool) { - console.assert(a > b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u8/input.leo b/asg/tests/pass/integers/u8/input.leo deleted file mode 100644 index 4d99dc106c..0000000000 --- a/asg/tests/pass/integers/u8/input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u8, b: u8) { - console.assert(a == b); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u8/le.leo b/asg/tests/pass/integers/u8/le.leo deleted file mode 100644 index 2607b7f3d1..0000000000 --- a/asg/tests/pass/integers/u8/le.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u8, b: u8, c: bool) { - console.assert(a <= b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u8/lt.leo b/asg/tests/pass/integers/u8/lt.leo deleted file mode 100644 index 7495d0fe37..0000000000 --- a/asg/tests/pass/integers/u8/lt.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u8, b: u8, c: bool) { - console.assert(a < b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u8/max.leo b/asg/tests/pass/integers/u8/max.leo deleted file mode 100644 index 03e82c9a5e..0000000000 --- a/asg/tests/pass/integers/u8/max.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u8 = 255; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u8/min.leo b/asg/tests/pass/integers/u8/min.leo deleted file mode 100644 index 1db08a07b5..0000000000 --- a/asg/tests/pass/integers/u8/min.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: u8 = 0; -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u8/mod.rs b/asg/tests/pass/integers/u8/mod.rs deleted file mode 100644 index 27fd40ed97..0000000000 --- a/asg/tests/pass/integers/u8/mod.rs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::IntegerTester; - -test_uint!(TestU8); - -#[test] -fn test_u8_min() { - TestU8::test_min(); -} - -#[test] -fn test_u8_max() { - TestU8::test_max(); -} - -#[test] -fn test_u8_add() { - TestU8::test_add(); -} - -#[test] -fn test_u8_sub() { - TestU8::test_sub(); -} - -#[test] -fn test_u8_mul() { - TestU8::test_mul(); -} - -#[test] -fn test_u8_div() { - TestU8::test_div(); -} - -#[test] -fn test_u8_pow() { - TestU8::test_pow(); -} - -#[test] -fn test_u8_eq() { - TestU8::test_eq(); -} - -#[test] -fn test_u8_ne() { - TestU8::test_ne(); -} - -#[test] -fn test_u8_ge() { - TestU8::test_ge(); -} - -#[test] -fn test_u8_gt() { - TestU8::test_gt(); -} - -#[test] -fn test_u8_le() { - TestU8::test_le(); -} - -#[test] -fn test_u8_lt() { - TestU8::test_lt(); -} - -#[test] -fn test_u8_console_assert() { - TestU8::test_console_assert(); -} - -#[test] -fn test_u8_ternary() { - TestU8::test_ternary(); -} diff --git a/asg/tests/pass/integers/u8/mul.leo b/asg/tests/pass/integers/u8/mul.leo deleted file mode 100644 index 11acf4688b..0000000000 --- a/asg/tests/pass/integers/u8/mul.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u8, b: u8, c: u8) { - console.assert(a * b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u8/ne.leo b/asg/tests/pass/integers/u8/ne.leo deleted file mode 100644 index 1ef74d8b35..0000000000 --- a/asg/tests/pass/integers/u8/ne.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u8, b: u8, c: bool) { - console.assert((a != b) == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u8/pow.leo b/asg/tests/pass/integers/u8/pow.leo deleted file mode 100644 index 928ab73b0d..0000000000 --- a/asg/tests/pass/integers/u8/pow.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u8, b: u8, c: u8) { - console.assert(a ** b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u8/sub.leo b/asg/tests/pass/integers/u8/sub.leo deleted file mode 100644 index 1335409c29..0000000000 --- a/asg/tests/pass/integers/u8/sub.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: u8, b: u8, c: u8) { - console.assert(a - b == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/u8/ternary.leo b/asg/tests/pass/integers/u8/ternary.leo deleted file mode 100644 index 1b436aa054..0000000000 --- a/asg/tests/pass/integers/u8/ternary.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main(s: bool, a: u8, b: u8, c: u8) { - let r = s ? a : b; - - console.assert(r == c); -} \ No newline at end of file diff --git a/asg/tests/pass/integers/uint_macro.rs b/asg/tests/pass/integers/uint_macro.rs deleted file mode 100644 index 7d555f10e3..0000000000 --- a/asg/tests/pass/integers/uint_macro.rs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -macro_rules! test_uint { - ($name: ident) => { - pub struct $name {} - - impl super::IntegerTester for $name { - fn test_min() { - let program_string = include_str!("min.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_max() { - let program_string = include_str!("max.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_add() { - let program_string = include_str!("add.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_sub() { - let program_string = include_str!("sub.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_mul() { - let program_string = include_str!("mul.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_div() { - let program_string = include_str!("div.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_pow() { - let program_string = include_str!("pow.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_eq() { - let program_string = include_str!("eq.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_ne() { - let program_string = include_str!("ne.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_ge() { - let program_string = include_str!("ge.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_gt() { - let program_string = include_str!("gt.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_le() { - let program_string = include_str!("le.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_lt() { - let program_string = include_str!("lt.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_console_assert() { - let program_string = include_str!("console_assert.leo"); - crate::load_asg(program_string).unwrap(); - } - - fn test_ternary() { - let program_string = include_str!("ternary.leo"); - crate::load_asg(program_string).unwrap(); - } - } - }; -} diff --git a/asg/tests/pass/mod.rs b/asg/tests/pass/mod.rs deleted file mode 100644 index 531b04cf0b..0000000000 --- a/asg/tests/pass/mod.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub mod address; -pub mod array; -pub mod boolean; -pub mod circuits; -pub mod console; -pub mod core; -pub mod definition; -pub mod field; -pub mod function; -pub mod group; -pub mod input_files; -pub mod integers; -pub mod mutability; -pub mod statements; -pub mod tuples; diff --git a/asg/tests/pass/mutability/array_mut.leo b/asg/tests/pass/mutability/array_mut.leo deleted file mode 100644 index 5d4db3b68a..0000000000 --- a/asg/tests/pass/mutability/array_mut.leo +++ /dev/null @@ -1,7 +0,0 @@ -// Adding the `mut` keyword makes an array variable mutable. -function main() { - let a = [1u32]; - a[0] = 0; - - console.assert(a[0] == 0u32); -} \ No newline at end of file diff --git a/asg/tests/pass/mutability/array_splice_mut.leo b/asg/tests/pass/mutability/array_splice_mut.leo deleted file mode 100644 index d13216600a..0000000000 --- a/asg/tests/pass/mutability/array_splice_mut.leo +++ /dev/null @@ -1,9 +0,0 @@ -// Adding the `mut` keyword makes an array variable mutable. -function main() { - let a = [1u32, 2u32, 3u32]; - a[0u32..2u32] = [4u32, 5u32]; - - console.assert(a[0] == 4u32); - console.assert(a[1] == 5u32); - console.assert(a[2] == 3u32); -} \ No newline at end of file diff --git a/asg/tests/pass/mutability/array_tuple_mut.leo b/asg/tests/pass/mutability/array_tuple_mut.leo deleted file mode 100644 index ed323d46da..0000000000 --- a/asg/tests/pass/mutability/array_tuple_mut.leo +++ /dev/null @@ -1,8 +0,0 @@ -// Adding the `mut` keyword makes an array variable mutable. -function main() { - let a = [(1u32, 2u32)]; - a[0u32].1 = 3u32; - - console.assert(a[0u32].0 == 1u32); - console.assert(a[0u32].1 == 3u32); -} \ No newline at end of file diff --git a/asg/tests/pass/mutability/circuit_mut.leo b/asg/tests/pass/mutability/circuit_mut.leo deleted file mode 100644 index 4ce2ea7c54..0000000000 --- a/asg/tests/pass/mutability/circuit_mut.leo +++ /dev/null @@ -1,11 +0,0 @@ -// Adding the `mut` keyword makes a circuit variable mutable. -circuit Foo { - x: u32; -} - -function main() { - let a = Foo { x: 1 }; - a.x = 0; - - console.assert(a.x == 0u32); -} \ No newline at end of file diff --git a/asg/tests/pass/mutability/circuit_variable_mut.leo b/asg/tests/pass/mutability/circuit_variable_mut.leo deleted file mode 100644 index 4ce2ea7c54..0000000000 --- a/asg/tests/pass/mutability/circuit_variable_mut.leo +++ /dev/null @@ -1,11 +0,0 @@ -// Adding the `mut` keyword makes a circuit variable mutable. -circuit Foo { - x: u32; -} - -function main() { - let a = Foo { x: 1 }; - a.x = 0; - - console.assert(a.x == 0u32); -} \ No newline at end of file diff --git a/asg/tests/pass/mutability/function_input_mut.leo b/asg/tests/pass/mutability/function_input_mut.leo deleted file mode 100644 index 98739d78c7..0000000000 --- a/asg/tests/pass/mutability/function_input_mut.leo +++ /dev/null @@ -1,6 +0,0 @@ -// Function input are mutable by default. -function main(a: bool) { - a = true; - - console.assert(a == true); -} \ No newline at end of file diff --git a/asg/tests/pass/mutability/let_mut.leo b/asg/tests/pass/mutability/let_mut.leo deleted file mode 100644 index cd1060d0d2..0000000000 --- a/asg/tests/pass/mutability/let_mut.leo +++ /dev/null @@ -1,7 +0,0 @@ -// Adding the `mut` keyword makes a variable mutable. -function main() { - let a = 1u32; - a = 0; - - console.assert(a == 0u32); -} \ No newline at end of file diff --git a/asg/tests/pass/mutability/let_mut_nested.leo b/asg/tests/pass/mutability/let_mut_nested.leo deleted file mode 100644 index ace4bfb8b4..0000000000 --- a/asg/tests/pass/mutability/let_mut_nested.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main () { - let x = 2u8; - let y = x; - let z = y / 2u8; -} \ No newline at end of file diff --git a/asg/tests/pass/mutability/mod.rs b/asg/tests/pass/mutability/mod.rs deleted file mode 100644 index 5da14da0ae..0000000000 --- a/asg/tests/pass/mutability/mod.rs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_let_mut() { - let program_string = include_str!("let_mut.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_let_mut_nested() { - let program_string = include_str!("let_mut_nested.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_array_mut() { - let program_string = include_str!("array_mut.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_array_tuple_mut() { - let program_string = include_str!("array_tuple_mut.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_array_splice_mut() { - let program_string = include_str!("array_splice_mut.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_circuit_mut() { - let program_string = include_str!("circuit_mut.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_circuit_variable_mut() { - let program_string = include_str!("circuit_variable_mut.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_function_input_mut() { - let program_string = include_str!("function_input_mut.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_swap() { - let program_string = include_str!("swap.leo"); - load_asg(program_string).unwrap(); -} diff --git a/asg/tests/pass/mutability/swap.leo b/asg/tests/pass/mutability/swap.leo deleted file mode 100644 index 05fb661085..0000000000 --- a/asg/tests/pass/mutability/swap.leo +++ /dev/null @@ -1,20 +0,0 @@ -// Swap two elements of an array. -function swap(a: [u32; 2], const i: u32, const j: u32) -> [u32; 2] { - let t = a[i]; - a[i] = a[j]; - a[j] = t; - return a; -} - -function main() { - let arr: [u32; 2] = [0, 1]; - const expected: [u32; 2] = [1, 0]; - - // Do swap. - let actual = swap(arr, 0, 1); - - // Check result. - for i in 0..2 { - console.assert(expected[i] == actual[i]); - } -} \ No newline at end of file diff --git a/asg/tests/pass/statements/block.leo b/asg/tests/pass/statements/block.leo deleted file mode 100644 index ca8da645ec..0000000000 --- a/asg/tests/pass/statements/block.leo +++ /dev/null @@ -1,9 +0,0 @@ -function main() { - let x = 4u32; - - { - x = 5u32; - } - - console.assert(x == 5u32); -} \ No newline at end of file diff --git a/asg/tests/pass/statements/conditional/assert.leo b/asg/tests/pass/statements/conditional/assert.leo deleted file mode 100644 index f3d20b461d..0000000000 --- a/asg/tests/pass/statements/conditional/assert.leo +++ /dev/null @@ -1,7 +0,0 @@ -function main(a: u32) { - if a == 1 { - console.assert(a == 1); - } else { - console.assert(a == 0); - } -} diff --git a/asg/tests/pass/statements/conditional/chain.leo b/asg/tests/pass/statements/conditional/chain.leo deleted file mode 100644 index 44d4e86243..0000000000 --- a/asg/tests/pass/statements/conditional/chain.leo +++ /dev/null @@ -1,13 +0,0 @@ -function main(a: u32, b: u32) { - let c = 0u32; - - if a == 1 { - c = 1; - } else if a == 2 { - c = 2; - } else { - c = 3; - } - - console.assert(c == b); -} \ No newline at end of file diff --git a/asg/tests/pass/statements/conditional/for_loop.leo b/asg/tests/pass/statements/conditional/for_loop.leo deleted file mode 100644 index 79df649236..0000000000 --- a/asg/tests/pass/statements/conditional/for_loop.leo +++ /dev/null @@ -1,13 +0,0 @@ -function main(a: bool) { - let b = 0u32; - - if a { - for i in 0..4 { - b += i; - } - } - - let r: u32 = a ? 6 : 0; - - console.assert(r == b); -} diff --git a/asg/tests/pass/statements/conditional/mod.rs b/asg/tests/pass/statements/conditional/mod.rs deleted file mode 100644 index 73a987bb94..0000000000 --- a/asg/tests/pass/statements/conditional/mod.rs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_assert() { - let program_string = include_str!("assert.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_mutate() { - let program_string = include_str!("mutate.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_for_loop() { - let program_string = include_str!("for_loop.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_chain() { - let program_string = include_str!("chain.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_nested() { - let program_string = include_str!("nested.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_multiple_returns() { - let program_string = include_str!("multiple_returns.leo"); - load_asg(program_string).unwrap(); -} diff --git a/asg/tests/pass/statements/conditional/multiple_returns.leo b/asg/tests/pass/statements/conditional/multiple_returns.leo deleted file mode 100644 index f2b9e499c2..0000000000 --- a/asg/tests/pass/statements/conditional/multiple_returns.leo +++ /dev/null @@ -1,7 +0,0 @@ -function main() -> u32 { - if input.registers.a == 0u32 { - return 0u32; - } else { - return 1u32; - } -} \ No newline at end of file diff --git a/asg/tests/pass/statements/conditional/mutate.leo b/asg/tests/pass/statements/conditional/mutate.leo deleted file mode 100644 index 9bb124eefd..0000000000 --- a/asg/tests/pass/statements/conditional/mutate.leo +++ /dev/null @@ -1,15 +0,0 @@ -function main(a: u32) { - let b = 5u32; - - if a == 1 { - b = 1; - } else { - b = 0; - } - - if a == 1 { - console.assert(b == 1); - } else { - console.assert(b == 0); - } -} diff --git a/asg/tests/pass/statements/conditional/nested.leo b/asg/tests/pass/statements/conditional/nested.leo deleted file mode 100644 index 1849c2a339..0000000000 --- a/asg/tests/pass/statements/conditional/nested.leo +++ /dev/null @@ -1,12 +0,0 @@ -function main(a: bool, b: bool, c: u32) { - let d = 0u32; - - if a { - d += 1; - if b { - d += 2; - } - } - - console.assert(d == c); -} \ No newline at end of file diff --git a/asg/tests/pass/statements/iteration_basic.leo b/asg/tests/pass/statements/iteration_basic.leo deleted file mode 100644 index 5d74e69a1f..0000000000 --- a/asg/tests/pass/statements/iteration_basic.leo +++ /dev/null @@ -1,8 +0,0 @@ -function main() { - let x = 4u32; - for i in 0..3 { - x -= 1; - } - - console.assert(x == 1u32); -} \ No newline at end of file diff --git a/asg/tests/pass/statements/mod.rs b/asg/tests/pass/statements/mod.rs deleted file mode 100644 index f6123b86db..0000000000 --- a/asg/tests/pass/statements/mod.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -pub mod conditional; - -// Ternary if {bool}? {expression} : {expression}; - -#[test] -fn test_ternary_basic() { - let program_string = include_str!("ternary_basic.leo"); - load_asg(program_string).unwrap(); -} - -// Iteration for i {start}..{stop} { statements } - -#[test] -fn test_iteration_basic() { - let program_string = include_str!("iteration_basic.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_block() { - let program_string = include_str!("block.leo"); - load_asg(program_string).unwrap(); -} diff --git a/asg/tests/pass/statements/ternary_basic.leo b/asg/tests/pass/statements/ternary_basic.leo deleted file mode 100644 index 675b681fa9..0000000000 --- a/asg/tests/pass/statements/ternary_basic.leo +++ /dev/null @@ -1,5 +0,0 @@ -function main(a: bool, b: bool) { - let c = a ? true : false; - - let d = c == b; -} \ No newline at end of file diff --git a/asg/tests/pass/tuples/access.leo b/asg/tests/pass/tuples/access.leo deleted file mode 100644 index 9277f4ecc5..0000000000 --- a/asg/tests/pass/tuples/access.leo +++ /dev/null @@ -1,6 +0,0 @@ -function main() { - const a = (true, false); - - console.assert(a.0 == true); - console.assert(a.1 == false); -} \ No newline at end of file diff --git a/asg/tests/pass/tuples/basic.leo b/asg/tests/pass/tuples/basic.leo deleted file mode 100644 index 2e777f2797..0000000000 --- a/asg/tests/pass/tuples/basic.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a = (true, false); -} \ No newline at end of file diff --git a/asg/tests/pass/tuples/function.leo b/asg/tests/pass/tuples/function.leo deleted file mode 100644 index a5a0dda085..0000000000 --- a/asg/tests/pass/tuples/function.leo +++ /dev/null @@ -1,10 +0,0 @@ -function foo() -> (bool, bool) { - return (true, false); -} - -function main() { - const a = foo(); - - console.assert(a.0 == true); - console.assert(a.1 == false); -} \ No newline at end of file diff --git a/asg/tests/pass/tuples/function_multiple.leo b/asg/tests/pass/tuples/function_multiple.leo deleted file mode 100644 index 09688207cd..0000000000 --- a/asg/tests/pass/tuples/function_multiple.leo +++ /dev/null @@ -1,10 +0,0 @@ -function foo() -> (bool, bool) { - return (true, false); -} - -function main() { - const (a, b) = foo(); - - console.assert(a == true); - console.assert(b == false); -} \ No newline at end of file diff --git a/asg/tests/pass/tuples/function_typed.leo b/asg/tests/pass/tuples/function_typed.leo deleted file mode 100644 index ebd2e1201d..0000000000 --- a/asg/tests/pass/tuples/function_typed.leo +++ /dev/null @@ -1,10 +0,0 @@ -function foo() -> (bool, bool) { - return (true, false); -} - -function main() { - const a: (bool, bool) = foo(); - - console.assert(a.0 == true); - console.assert(a.1 == false); -} \ No newline at end of file diff --git a/asg/tests/pass/tuples/input.leo b/asg/tests/pass/tuples/input.leo deleted file mode 100644 index f7672a3b03..0000000000 --- a/asg/tests/pass/tuples/input.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main(a: (bool, bool)) { - -} \ No newline at end of file diff --git a/asg/tests/pass/tuples/mod.rs b/asg/tests/pass/tuples/mod.rs deleted file mode 100644 index 19f5dc5267..0000000000 --- a/asg/tests/pass/tuples/mod.rs +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::load_asg; - -#[test] -fn test_tuple_basic() { - let program_string = include_str!("basic.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_tuple_access() { - let program_string = include_str!("access.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_tuple_typed() { - let program_string = include_str!("typed.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_multiple() { - let program_string = include_str!("multiple.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_multiple_typed() { - let program_string = include_str!("multiple_typed.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_function() { - let program_string = include_str!("function.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_function_typed() { - let program_string = include_str!("function_typed.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_function_multiple() { - let program_string = include_str!("function_multiple.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_nested() { - let program_string = include_str!("nested.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_nested_access() { - let program_string = include_str!("nested_access.leo"); - load_asg(program_string).unwrap(); -} - -#[test] -fn test_nested_typed() { - let program_string = include_str!("nested_typed.leo"); - load_asg(program_string).unwrap(); -} diff --git a/asg/tests/pass/tuples/multiple.leo b/asg/tests/pass/tuples/multiple.leo deleted file mode 100644 index 2cb003b0e1..0000000000 --- a/asg/tests/pass/tuples/multiple.leo +++ /dev/null @@ -1,6 +0,0 @@ -function main() { - const (a, b) = (true, false); - - console.assert(a == true); - console.assert(b == false); -} \ No newline at end of file diff --git a/asg/tests/pass/tuples/multiple_typed.leo b/asg/tests/pass/tuples/multiple_typed.leo deleted file mode 100644 index bbe4a01858..0000000000 --- a/asg/tests/pass/tuples/multiple_typed.leo +++ /dev/null @@ -1,6 +0,0 @@ -function main() { - const (a, b): (bool, bool) = (true, false); - - console.assert(a == true); - console.assert(b == false); -} \ No newline at end of file diff --git a/asg/tests/pass/tuples/nested.leo b/asg/tests/pass/tuples/nested.leo deleted file mode 100644 index bbdb2394a8..0000000000 --- a/asg/tests/pass/tuples/nested.leo +++ /dev/null @@ -1,4 +0,0 @@ -function main() { - const a = (true, false); - const b = (true, a); -} \ No newline at end of file diff --git a/asg/tests/pass/tuples/nested_access.leo b/asg/tests/pass/tuples/nested_access.leo deleted file mode 100644 index f21fa59bba..0000000000 --- a/asg/tests/pass/tuples/nested_access.leo +++ /dev/null @@ -1,8 +0,0 @@ -function main() { - const a = (true, false); - const b = (true, a); - - console.assert(b.0 == true); - console.assert(b.1.0 == true); - console.assert(b.1.1 == false); -} \ No newline at end of file diff --git a/asg/tests/pass/tuples/nested_typed.leo b/asg/tests/pass/tuples/nested_typed.leo deleted file mode 100644 index 44a10b2a3e..0000000000 --- a/asg/tests/pass/tuples/nested_typed.leo +++ /dev/null @@ -1,4 +0,0 @@ -function main() { - const a = (true, false); - const b: (bool, (bool, bool)) = (true, a); -} \ No newline at end of file diff --git a/asg/tests/pass/tuples/typed.leo b/asg/tests/pass/tuples/typed.leo deleted file mode 100644 index 8f623fc148..0000000000 --- a/asg/tests/pass/tuples/typed.leo +++ /dev/null @@ -1,3 +0,0 @@ -function main() { - const a: (bool, bool) = (true, false); -} \ No newline at end of file diff --git a/ast-passes/Cargo.toml b/compiler/ast-passes/Cargo.toml similarity index 94% rename from ast-passes/Cargo.toml rename to compiler/ast-passes/Cargo.toml index 57f6d387dd..bb1680fcb9 100644 --- a/ast-passes/Cargo.toml +++ b/compiler/ast-passes/Cargo.toml @@ -29,7 +29,7 @@ path = "../ast" version = "1.5.3" [dependencies.leo-errors] -path = "../errors" +path = "../../leo/errors" version = "1.5.3" [dependencies.leo-parser] @@ -37,7 +37,7 @@ path = "../parser" version = "1.5.3" [dependencies.leo-span] -path = "../span" +path = "../../leo/span" version = "1.5.3" #[dependencies.leo-stdlib] diff --git a/asg/LICENSE.md b/compiler/ast-passes/LICENSE.md similarity index 100% rename from asg/LICENSE.md rename to compiler/ast-passes/LICENSE.md diff --git a/ast-passes/README.md b/compiler/ast-passes/README.md similarity index 100% rename from ast-passes/README.md rename to compiler/ast-passes/README.md diff --git a/ast-passes/src/canonicalization/canonicalizer.rs b/compiler/ast-passes/src/canonicalization/canonicalizer.rs similarity index 100% rename from ast-passes/src/canonicalization/canonicalizer.rs rename to compiler/ast-passes/src/canonicalization/canonicalizer.rs diff --git a/ast-passes/src/canonicalization/mod.rs b/compiler/ast-passes/src/canonicalization/mod.rs similarity index 100% rename from ast-passes/src/canonicalization/mod.rs rename to compiler/ast-passes/src/canonicalization/mod.rs diff --git a/ast-passes/src/import_resolution/importer.rs b/compiler/ast-passes/src/import_resolution/importer.rs similarity index 100% rename from ast-passes/src/import_resolution/importer.rs rename to compiler/ast-passes/src/import_resolution/importer.rs diff --git a/ast-passes/src/import_resolution/mod.rs b/compiler/ast-passes/src/import_resolution/mod.rs similarity index 100% rename from ast-passes/src/import_resolution/mod.rs rename to compiler/ast-passes/src/import_resolution/mod.rs diff --git a/ast-passes/src/import_resolution/resolver.rs b/compiler/ast-passes/src/import_resolution/resolver.rs similarity index 100% rename from ast-passes/src/import_resolution/resolver.rs rename to compiler/ast-passes/src/import_resolution/resolver.rs diff --git a/ast-passes/src/lib.rs b/compiler/ast-passes/src/lib.rs similarity index 100% rename from ast-passes/src/lib.rs rename to compiler/ast-passes/src/lib.rs diff --git a/ast/Cargo.toml b/compiler/ast/Cargo.toml similarity index 95% rename from ast/Cargo.toml rename to compiler/ast/Cargo.toml index 368ffc1d51..e364b81515 100644 --- a/ast/Cargo.toml +++ b/compiler/ast/Cargo.toml @@ -26,11 +26,11 @@ path = "../input" version = "1.5.3" [dependencies.leo-errors] -path = "../errors" +path = "../../leo/errors" version = "1.5.3" [dependencies.leo-span] -path = "../span" +path = "../../leo/span" version = "1.5.3" [dependencies.indexmap] diff --git a/ast-passes/LICENSE.md b/compiler/ast/LICENSE.md similarity index 100% rename from ast-passes/LICENSE.md rename to compiler/ast/LICENSE.md diff --git a/ast/README.md b/compiler/ast/README.md similarity index 100% rename from ast/README.md rename to compiler/ast/README.md diff --git a/ast/src/accesses/array_access.rs b/compiler/ast/src/accesses/array_access.rs similarity index 100% rename from ast/src/accesses/array_access.rs rename to compiler/ast/src/accesses/array_access.rs diff --git a/ast/src/accesses/array_range_access.rs b/compiler/ast/src/accesses/array_range_access.rs similarity index 100% rename from ast/src/accesses/array_range_access.rs rename to compiler/ast/src/accesses/array_range_access.rs diff --git a/ast/src/accesses/member_access.rs b/compiler/ast/src/accesses/member_access.rs similarity index 100% rename from ast/src/accesses/member_access.rs rename to compiler/ast/src/accesses/member_access.rs diff --git a/ast/src/accesses/mod.rs b/compiler/ast/src/accesses/mod.rs similarity index 100% rename from ast/src/accesses/mod.rs rename to compiler/ast/src/accesses/mod.rs diff --git a/ast/src/accesses/static_access.rs b/compiler/ast/src/accesses/static_access.rs similarity index 100% rename from ast/src/accesses/static_access.rs rename to compiler/ast/src/accesses/static_access.rs diff --git a/ast/src/accesses/tuple_access.rs b/compiler/ast/src/accesses/tuple_access.rs similarity index 100% rename from ast/src/accesses/tuple_access.rs rename to compiler/ast/src/accesses/tuple_access.rs diff --git a/ast/src/aliases/alias.rs b/compiler/ast/src/aliases/alias.rs similarity index 100% rename from ast/src/aliases/alias.rs rename to compiler/ast/src/aliases/alias.rs diff --git a/ast/src/aliases/mod.rs b/compiler/ast/src/aliases/mod.rs similarity index 100% rename from ast/src/aliases/mod.rs rename to compiler/ast/src/aliases/mod.rs diff --git a/ast/src/annotation.rs b/compiler/ast/src/annotation.rs similarity index 100% rename from ast/src/annotation.rs rename to compiler/ast/src/annotation.rs diff --git a/ast/src/chars/char_value.rs b/compiler/ast/src/chars/char_value.rs similarity index 100% rename from ast/src/chars/char_value.rs rename to compiler/ast/src/chars/char_value.rs diff --git a/ast/src/chars/mod.rs b/compiler/ast/src/chars/mod.rs similarity index 100% rename from ast/src/chars/mod.rs rename to compiler/ast/src/chars/mod.rs diff --git a/ast/src/circuits/circuit.rs b/compiler/ast/src/circuits/circuit.rs similarity index 100% rename from ast/src/circuits/circuit.rs rename to compiler/ast/src/circuits/circuit.rs diff --git a/ast/src/circuits/circuit_implied_variable_definition.rs b/compiler/ast/src/circuits/circuit_implied_variable_definition.rs similarity index 100% rename from ast/src/circuits/circuit_implied_variable_definition.rs rename to compiler/ast/src/circuits/circuit_implied_variable_definition.rs diff --git a/ast/src/circuits/circuit_member.rs b/compiler/ast/src/circuits/circuit_member.rs similarity index 100% rename from ast/src/circuits/circuit_member.rs rename to compiler/ast/src/circuits/circuit_member.rs diff --git a/ast/src/circuits/circuit_variable_definition.rs b/compiler/ast/src/circuits/circuit_variable_definition.rs similarity index 100% rename from ast/src/circuits/circuit_variable_definition.rs rename to compiler/ast/src/circuits/circuit_variable_definition.rs diff --git a/ast/src/circuits/mod.rs b/compiler/ast/src/circuits/mod.rs similarity index 100% rename from ast/src/circuits/mod.rs rename to compiler/ast/src/circuits/mod.rs diff --git a/ast/src/common/array_dimensions.rs b/compiler/ast/src/common/array_dimensions.rs similarity index 100% rename from ast/src/common/array_dimensions.rs rename to compiler/ast/src/common/array_dimensions.rs diff --git a/ast/src/common/const_self_keyword.rs b/compiler/ast/src/common/const_self_keyword.rs similarity index 100% rename from ast/src/common/const_self_keyword.rs rename to compiler/ast/src/common/const_self_keyword.rs diff --git a/ast/src/common/global_consts_json.rs b/compiler/ast/src/common/global_consts_json.rs similarity index 100% rename from ast/src/common/global_consts_json.rs rename to compiler/ast/src/common/global_consts_json.rs diff --git a/ast/src/common/identifier.rs b/compiler/ast/src/common/identifier.rs similarity index 100% rename from ast/src/common/identifier.rs rename to compiler/ast/src/common/identifier.rs diff --git a/ast/src/common/imported_modules.rs b/compiler/ast/src/common/imported_modules.rs similarity index 100% rename from ast/src/common/imported_modules.rs rename to compiler/ast/src/common/imported_modules.rs diff --git a/ast/src/common/mod.rs b/compiler/ast/src/common/mod.rs similarity index 100% rename from ast/src/common/mod.rs rename to compiler/ast/src/common/mod.rs diff --git a/ast/src/common/mut_self_keyword.rs b/compiler/ast/src/common/mut_self_keyword.rs similarity index 100% rename from ast/src/common/mut_self_keyword.rs rename to compiler/ast/src/common/mut_self_keyword.rs diff --git a/ast/src/common/positive_number.rs b/compiler/ast/src/common/positive_number.rs similarity index 100% rename from ast/src/common/positive_number.rs rename to compiler/ast/src/common/positive_number.rs diff --git a/ast/src/common/self_keyword.rs b/compiler/ast/src/common/self_keyword.rs similarity index 100% rename from ast/src/common/self_keyword.rs rename to compiler/ast/src/common/self_keyword.rs diff --git a/ast/src/common/spread_or_expression.rs b/compiler/ast/src/common/spread_or_expression.rs similarity index 100% rename from ast/src/common/spread_or_expression.rs rename to compiler/ast/src/common/spread_or_expression.rs diff --git a/ast/src/common/vec_tendril_json.rs b/compiler/ast/src/common/vec_tendril_json.rs similarity index 100% rename from ast/src/common/vec_tendril_json.rs rename to compiler/ast/src/common/vec_tendril_json.rs diff --git a/ast/src/expression/accesses.rs b/compiler/ast/src/expression/accesses.rs similarity index 100% rename from ast/src/expression/accesses.rs rename to compiler/ast/src/expression/accesses.rs diff --git a/ast/src/expression/array_init.rs b/compiler/ast/src/expression/array_init.rs similarity index 100% rename from ast/src/expression/array_init.rs rename to compiler/ast/src/expression/array_init.rs diff --git a/ast/src/expression/array_inline.rs b/compiler/ast/src/expression/array_inline.rs similarity index 100% rename from ast/src/expression/array_inline.rs rename to compiler/ast/src/expression/array_inline.rs diff --git a/ast/src/expression/binary.rs b/compiler/ast/src/expression/binary.rs similarity index 100% rename from ast/src/expression/binary.rs rename to compiler/ast/src/expression/binary.rs diff --git a/ast/src/expression/call.rs b/compiler/ast/src/expression/call.rs similarity index 100% rename from ast/src/expression/call.rs rename to compiler/ast/src/expression/call.rs diff --git a/ast/src/expression/cast.rs b/compiler/ast/src/expression/cast.rs similarity index 100% rename from ast/src/expression/cast.rs rename to compiler/ast/src/expression/cast.rs diff --git a/ast/src/expression/circuit_init.rs b/compiler/ast/src/expression/circuit_init.rs similarity index 100% rename from ast/src/expression/circuit_init.rs rename to compiler/ast/src/expression/circuit_init.rs diff --git a/ast/src/expression/err.rs b/compiler/ast/src/expression/err.rs similarity index 100% rename from ast/src/expression/err.rs rename to compiler/ast/src/expression/err.rs diff --git a/ast/src/expression/mod.rs b/compiler/ast/src/expression/mod.rs similarity index 100% rename from ast/src/expression/mod.rs rename to compiler/ast/src/expression/mod.rs diff --git a/ast/src/expression/ternary.rs b/compiler/ast/src/expression/ternary.rs similarity index 100% rename from ast/src/expression/ternary.rs rename to compiler/ast/src/expression/ternary.rs diff --git a/ast/src/expression/tuple_init.rs b/compiler/ast/src/expression/tuple_init.rs similarity index 100% rename from ast/src/expression/tuple_init.rs rename to compiler/ast/src/expression/tuple_init.rs diff --git a/ast/src/expression/unary.rs b/compiler/ast/src/expression/unary.rs similarity index 100% rename from ast/src/expression/unary.rs rename to compiler/ast/src/expression/unary.rs diff --git a/ast/src/expression/value.rs b/compiler/ast/src/expression/value.rs similarity index 100% rename from ast/src/expression/value.rs rename to compiler/ast/src/expression/value.rs diff --git a/ast/src/functions/function.rs b/compiler/ast/src/functions/function.rs similarity index 100% rename from ast/src/functions/function.rs rename to compiler/ast/src/functions/function.rs diff --git a/ast/src/functions/input/function_input.rs b/compiler/ast/src/functions/input/function_input.rs similarity index 100% rename from ast/src/functions/input/function_input.rs rename to compiler/ast/src/functions/input/function_input.rs diff --git a/ast/src/functions/input/input_variable.rs b/compiler/ast/src/functions/input/input_variable.rs similarity index 100% rename from ast/src/functions/input/input_variable.rs rename to compiler/ast/src/functions/input/input_variable.rs diff --git a/ast/src/functions/input/mod.rs b/compiler/ast/src/functions/input/mod.rs similarity index 100% rename from ast/src/functions/input/mod.rs rename to compiler/ast/src/functions/input/mod.rs diff --git a/ast/src/functions/mod.rs b/compiler/ast/src/functions/mod.rs similarity index 100% rename from ast/src/functions/mod.rs rename to compiler/ast/src/functions/mod.rs diff --git a/ast/src/groups/group_coordinate.rs b/compiler/ast/src/groups/group_coordinate.rs similarity index 100% rename from ast/src/groups/group_coordinate.rs rename to compiler/ast/src/groups/group_coordinate.rs diff --git a/ast/src/groups/group_value.rs b/compiler/ast/src/groups/group_value.rs similarity index 100% rename from ast/src/groups/group_value.rs rename to compiler/ast/src/groups/group_value.rs diff --git a/ast/src/groups/mod.rs b/compiler/ast/src/groups/mod.rs similarity index 100% rename from ast/src/groups/mod.rs rename to compiler/ast/src/groups/mod.rs diff --git a/ast/src/imports/mod.rs b/compiler/ast/src/imports/mod.rs similarity index 100% rename from ast/src/imports/mod.rs rename to compiler/ast/src/imports/mod.rs diff --git a/ast/src/input/input.rs b/compiler/ast/src/input/input.rs similarity index 100% rename from ast/src/input/input.rs rename to compiler/ast/src/input/input.rs diff --git a/ast/src/input/input_value.rs b/compiler/ast/src/input/input_value.rs similarity index 100% rename from ast/src/input/input_value.rs rename to compiler/ast/src/input/input_value.rs diff --git a/ast/src/input/macros.rs b/compiler/ast/src/input/macros.rs similarity index 100% rename from ast/src/input/macros.rs rename to compiler/ast/src/input/macros.rs diff --git a/ast/src/input/mod.rs b/compiler/ast/src/input/mod.rs similarity index 100% rename from ast/src/input/mod.rs rename to compiler/ast/src/input/mod.rs diff --git a/ast/src/input/parameters/mod.rs b/compiler/ast/src/input/parameters/mod.rs similarity index 100% rename from ast/src/input/parameters/mod.rs rename to compiler/ast/src/input/parameters/mod.rs diff --git a/ast/src/input/parameters/parameter.rs b/compiler/ast/src/input/parameters/parameter.rs similarity index 100% rename from ast/src/input/parameters/parameter.rs rename to compiler/ast/src/input/parameters/parameter.rs diff --git a/ast/src/input/program_input/constant_input.rs b/compiler/ast/src/input/program_input/constant_input.rs similarity index 100% rename from ast/src/input/program_input/constant_input.rs rename to compiler/ast/src/input/program_input/constant_input.rs diff --git a/ast/src/input/program_input/main_input.rs b/compiler/ast/src/input/program_input/main_input.rs similarity index 100% rename from ast/src/input/program_input/main_input.rs rename to compiler/ast/src/input/program_input/main_input.rs diff --git a/ast/src/input/program_input/mod.rs b/compiler/ast/src/input/program_input/mod.rs similarity index 100% rename from ast/src/input/program_input/mod.rs rename to compiler/ast/src/input/program_input/mod.rs diff --git a/ast/src/input/program_input/program_input.rs b/compiler/ast/src/input/program_input/program_input.rs similarity index 100% rename from ast/src/input/program_input/program_input.rs rename to compiler/ast/src/input/program_input/program_input.rs diff --git a/ast/src/input/program_input/registers.rs b/compiler/ast/src/input/program_input/registers.rs similarity index 100% rename from ast/src/input/program_input/registers.rs rename to compiler/ast/src/input/program_input/registers.rs diff --git a/ast/src/input/program_state/mod.rs b/compiler/ast/src/input/program_state/mod.rs similarity index 100% rename from ast/src/input/program_state/mod.rs rename to compiler/ast/src/input/program_state/mod.rs diff --git a/ast/src/input/program_state/private_state/mod.rs b/compiler/ast/src/input/program_state/private_state/mod.rs similarity index 100% rename from ast/src/input/program_state/private_state/mod.rs rename to compiler/ast/src/input/program_state/private_state/mod.rs diff --git a/ast/src/input/program_state/private_state/private_state.rs b/compiler/ast/src/input/program_state/private_state/private_state.rs similarity index 100% rename from ast/src/input/program_state/private_state/private_state.rs rename to compiler/ast/src/input/program_state/private_state/private_state.rs diff --git a/ast/src/input/program_state/private_state/record.rs b/compiler/ast/src/input/program_state/private_state/record.rs similarity index 100% rename from ast/src/input/program_state/private_state/record.rs rename to compiler/ast/src/input/program_state/private_state/record.rs diff --git a/ast/src/input/program_state/private_state/state_leaf.rs b/compiler/ast/src/input/program_state/private_state/state_leaf.rs similarity index 100% rename from ast/src/input/program_state/private_state/state_leaf.rs rename to compiler/ast/src/input/program_state/private_state/state_leaf.rs diff --git a/ast/src/input/program_state/program_state.rs b/compiler/ast/src/input/program_state/program_state.rs similarity index 100% rename from ast/src/input/program_state/program_state.rs rename to compiler/ast/src/input/program_state/program_state.rs diff --git a/ast/src/input/program_state/public_state/mod.rs b/compiler/ast/src/input/program_state/public_state/mod.rs similarity index 100% rename from ast/src/input/program_state/public_state/mod.rs rename to compiler/ast/src/input/program_state/public_state/mod.rs diff --git a/ast/src/input/program_state/public_state/public_state.rs b/compiler/ast/src/input/program_state/public_state/public_state.rs similarity index 100% rename from ast/src/input/program_state/public_state/public_state.rs rename to compiler/ast/src/input/program_state/public_state/public_state.rs diff --git a/ast/src/input/program_state/public_state/state.rs b/compiler/ast/src/input/program_state/public_state/state.rs similarity index 100% rename from ast/src/input/program_state/public_state/state.rs rename to compiler/ast/src/input/program_state/public_state/state.rs diff --git a/ast/src/lib.rs b/compiler/ast/src/lib.rs similarity index 100% rename from ast/src/lib.rs rename to compiler/ast/src/lib.rs diff --git a/ast/src/node.rs b/compiler/ast/src/node.rs similarity index 100% rename from ast/src/node.rs rename to compiler/ast/src/node.rs diff --git a/ast/src/pass.rs b/compiler/ast/src/pass.rs similarity index 100% rename from ast/src/pass.rs rename to compiler/ast/src/pass.rs diff --git a/ast/src/program.rs b/compiler/ast/src/program.rs similarity index 100% rename from ast/src/program.rs rename to compiler/ast/src/program.rs diff --git a/ast/src/reducer/mod.rs b/compiler/ast/src/reducer/mod.rs similarity index 100% rename from ast/src/reducer/mod.rs rename to compiler/ast/src/reducer/mod.rs diff --git a/ast/src/reducer/reconstructing_director.rs b/compiler/ast/src/reducer/reconstructing_director.rs similarity index 100% rename from ast/src/reducer/reconstructing_director.rs rename to compiler/ast/src/reducer/reconstructing_director.rs diff --git a/ast/src/reducer/reconstructing_reducer.rs b/compiler/ast/src/reducer/reconstructing_reducer.rs similarity index 100% rename from ast/src/reducer/reconstructing_reducer.rs rename to compiler/ast/src/reducer/reconstructing_reducer.rs diff --git a/ast/src/statements/assign/assignee.rs b/compiler/ast/src/statements/assign/assignee.rs similarity index 100% rename from ast/src/statements/assign/assignee.rs rename to compiler/ast/src/statements/assign/assignee.rs diff --git a/ast/src/statements/assign/mod.rs b/compiler/ast/src/statements/assign/mod.rs similarity index 100% rename from ast/src/statements/assign/mod.rs rename to compiler/ast/src/statements/assign/mod.rs diff --git a/ast/src/statements/block.rs b/compiler/ast/src/statements/block.rs similarity index 100% rename from ast/src/statements/block.rs rename to compiler/ast/src/statements/block.rs diff --git a/ast/src/statements/conditional.rs b/compiler/ast/src/statements/conditional.rs similarity index 100% rename from ast/src/statements/conditional.rs rename to compiler/ast/src/statements/conditional.rs diff --git a/ast/src/statements/console/console_args.rs b/compiler/ast/src/statements/console/console_args.rs similarity index 100% rename from ast/src/statements/console/console_args.rs rename to compiler/ast/src/statements/console/console_args.rs diff --git a/ast/src/statements/console/console_function.rs b/compiler/ast/src/statements/console/console_function.rs similarity index 100% rename from ast/src/statements/console/console_function.rs rename to compiler/ast/src/statements/console/console_function.rs diff --git a/ast/src/statements/console/console_statement.rs b/compiler/ast/src/statements/console/console_statement.rs similarity index 100% rename from ast/src/statements/console/console_statement.rs rename to compiler/ast/src/statements/console/console_statement.rs diff --git a/ast/src/statements/console/mod.rs b/compiler/ast/src/statements/console/mod.rs similarity index 100% rename from ast/src/statements/console/mod.rs rename to compiler/ast/src/statements/console/mod.rs diff --git a/ast/src/statements/definition/declare.rs b/compiler/ast/src/statements/definition/declare.rs similarity index 100% rename from ast/src/statements/definition/declare.rs rename to compiler/ast/src/statements/definition/declare.rs diff --git a/ast/src/statements/definition/mod.rs b/compiler/ast/src/statements/definition/mod.rs similarity index 100% rename from ast/src/statements/definition/mod.rs rename to compiler/ast/src/statements/definition/mod.rs diff --git a/ast/src/statements/definition/variable_name.rs b/compiler/ast/src/statements/definition/variable_name.rs similarity index 100% rename from ast/src/statements/definition/variable_name.rs rename to compiler/ast/src/statements/definition/variable_name.rs diff --git a/ast/src/statements/expression.rs b/compiler/ast/src/statements/expression.rs similarity index 100% rename from ast/src/statements/expression.rs rename to compiler/ast/src/statements/expression.rs diff --git a/ast/src/statements/iteration.rs b/compiler/ast/src/statements/iteration.rs similarity index 100% rename from ast/src/statements/iteration.rs rename to compiler/ast/src/statements/iteration.rs diff --git a/ast/src/statements/mod.rs b/compiler/ast/src/statements/mod.rs similarity index 100% rename from ast/src/statements/mod.rs rename to compiler/ast/src/statements/mod.rs diff --git a/ast/src/statements/return_statement.rs b/compiler/ast/src/statements/return_statement.rs similarity index 100% rename from ast/src/statements/return_statement.rs rename to compiler/ast/src/statements/return_statement.rs diff --git a/ast/src/statements/statement.rs b/compiler/ast/src/statements/statement.rs similarity index 100% rename from ast/src/statements/statement.rs rename to compiler/ast/src/statements/statement.rs diff --git a/ast/src/types/integer_type.rs b/compiler/ast/src/types/integer_type.rs similarity index 100% rename from ast/src/types/integer_type.rs rename to compiler/ast/src/types/integer_type.rs diff --git a/ast/src/types/mod.rs b/compiler/ast/src/types/mod.rs similarity index 100% rename from ast/src/types/mod.rs rename to compiler/ast/src/types/mod.rs diff --git a/ast/src/types/type_.rs b/compiler/ast/src/types/type_.rs similarity index 100% rename from ast/src/types/type_.rs rename to compiler/ast/src/types/type_.rs diff --git a/compiler/Cargo.toml b/compiler/compiler/Cargo.toml similarity index 94% rename from compiler/Cargo.toml rename to compiler/compiler/Cargo.toml index 8047dfe638..a8cfc91982 100644 --- a/compiler/Cargo.toml +++ b/compiler/compiler/Cargo.toml @@ -27,7 +27,7 @@ path = "../ast-passes" version = "1.5.3" [dependencies.leo-errors] -path = "../errors" +path = "../../leo/errors" version = "1.5.3" [dependencies.leo-parser] @@ -35,7 +35,7 @@ path = "../parser" version = "1.5.3" [dependencies.leo-span] -path = "../span" +path = "../../leo/span" version = "1.5.3" [dependencies.sha2] diff --git a/ast/LICENSE.md b/compiler/compiler/LICENSE.md similarity index 100% rename from ast/LICENSE.md rename to compiler/compiler/LICENSE.md diff --git a/compiler/README.md b/compiler/compiler/README.md similarity index 100% rename from compiler/README.md rename to compiler/compiler/README.md diff --git a/compiler/src/lib.rs b/compiler/compiler/src/lib.rs similarity index 99% rename from compiler/src/lib.rs rename to compiler/compiler/src/lib.rs index d5679ad9b9..96401e11d6 100644 --- a/compiler/src/lib.rs +++ b/compiler/compiler/src/lib.rs @@ -22,6 +22,7 @@ #![allow(clippy::upper_case_acronyms)] #![doc = include_str!("../README.md")] +pub use leo_ast::Ast; use leo_ast::AstPass; use leo_errors::emitter::Handler; use leo_errors::{CompilerError, Result}; diff --git a/imports/Cargo.toml b/compiler/imports/Cargo.toml similarity index 94% rename from imports/Cargo.toml rename to compiler/imports/Cargo.toml index 04f47c9def..7e59a3ea9d 100644 --- a/imports/Cargo.toml +++ b/compiler/imports/Cargo.toml @@ -27,7 +27,7 @@ path = "../ast-passes" version = "1.5.3" [dependencies.leo-errors] -path = "../errors" +path = "../../leo/errors" version = "1.5.3" [dependencies.leo-parser] @@ -35,7 +35,7 @@ path = "../parser" version = "1.5.3" [dependencies.leo-span] -path = "../span" +path = "../../leo/span" version = "1.5.3" [dependencies.indexmap] diff --git a/compiler/LICENSE.md b/compiler/imports/LICENSE.md similarity index 100% rename from compiler/LICENSE.md rename to compiler/imports/LICENSE.md diff --git a/imports/README.md b/compiler/imports/README.md similarity index 100% rename from imports/README.md rename to compiler/imports/README.md diff --git a/imports/src/lib.rs b/compiler/imports/src/lib.rs similarity index 100% rename from imports/src/lib.rs rename to compiler/imports/src/lib.rs diff --git a/imports/src/parser/import_parser.rs b/compiler/imports/src/parser/import_parser.rs similarity index 100% rename from imports/src/parser/import_parser.rs rename to compiler/imports/src/parser/import_parser.rs diff --git a/imports/src/parser/mod.rs b/compiler/imports/src/parser/mod.rs similarity index 100% rename from imports/src/parser/mod.rs rename to compiler/imports/src/parser/mod.rs diff --git a/imports/src/parser/parse_package.rs b/compiler/imports/src/parser/parse_package.rs similarity index 100% rename from imports/src/parser/parse_package.rs rename to compiler/imports/src/parser/parse_package.rs diff --git a/imports/src/parser/parse_symbol.rs b/compiler/imports/src/parser/parse_symbol.rs similarity index 100% rename from imports/src/parser/parse_symbol.rs rename to compiler/imports/src/parser/parse_symbol.rs diff --git a/input/Cargo.toml b/compiler/input/Cargo.toml similarity index 100% rename from input/Cargo.toml rename to compiler/input/Cargo.toml diff --git a/errors/LICENSE.md b/compiler/input/LICENSE.md similarity index 100% rename from errors/LICENSE.md rename to compiler/input/LICENSE.md diff --git a/input/README.md b/compiler/input/README.md similarity index 100% rename from input/README.md rename to compiler/input/README.md diff --git a/input/src/ast.rs b/compiler/input/src/ast.rs similarity index 100% rename from input/src/ast.rs rename to compiler/input/src/ast.rs diff --git a/input/src/common/eoi.rs b/compiler/input/src/common/eoi.rs similarity index 100% rename from input/src/common/eoi.rs rename to compiler/input/src/common/eoi.rs diff --git a/input/src/common/identifier.rs b/compiler/input/src/common/identifier.rs similarity index 100% rename from input/src/common/identifier.rs rename to compiler/input/src/common/identifier.rs diff --git a/input/src/common/line_end.rs b/compiler/input/src/common/line_end.rs similarity index 100% rename from input/src/common/line_end.rs rename to compiler/input/src/common/line_end.rs diff --git a/input/src/common/mod.rs b/compiler/input/src/common/mod.rs similarity index 100% rename from input/src/common/mod.rs rename to compiler/input/src/common/mod.rs diff --git a/input/src/definitions/definition.rs b/compiler/input/src/definitions/definition.rs similarity index 100% rename from input/src/definitions/definition.rs rename to compiler/input/src/definitions/definition.rs diff --git a/input/src/definitions/mod.rs b/compiler/input/src/definitions/mod.rs similarity index 100% rename from input/src/definitions/mod.rs rename to compiler/input/src/definitions/mod.rs diff --git a/input/src/errors/mod.rs b/compiler/input/src/errors/mod.rs similarity index 100% rename from input/src/errors/mod.rs rename to compiler/input/src/errors/mod.rs diff --git a/input/src/errors/parser.rs b/compiler/input/src/errors/parser.rs similarity index 100% rename from input/src/errors/parser.rs rename to compiler/input/src/errors/parser.rs diff --git a/input/src/errors/syntax.rs b/compiler/input/src/errors/syntax.rs similarity index 100% rename from input/src/errors/syntax.rs rename to compiler/input/src/errors/syntax.rs diff --git a/input/src/expressions/array_initializer_expression.rs b/compiler/input/src/expressions/array_initializer_expression.rs similarity index 100% rename from input/src/expressions/array_initializer_expression.rs rename to compiler/input/src/expressions/array_initializer_expression.rs diff --git a/input/src/expressions/array_inline_expression.rs b/compiler/input/src/expressions/array_inline_expression.rs similarity index 100% rename from input/src/expressions/array_inline_expression.rs rename to compiler/input/src/expressions/array_inline_expression.rs diff --git a/input/src/expressions/expression.rs b/compiler/input/src/expressions/expression.rs similarity index 100% rename from input/src/expressions/expression.rs rename to compiler/input/src/expressions/expression.rs diff --git a/input/src/expressions/mod.rs b/compiler/input/src/expressions/mod.rs similarity index 100% rename from input/src/expressions/mod.rs rename to compiler/input/src/expressions/mod.rs diff --git a/input/src/expressions/string_expression.rs b/compiler/input/src/expressions/string_expression.rs similarity index 100% rename from input/src/expressions/string_expression.rs rename to compiler/input/src/expressions/string_expression.rs diff --git a/input/src/expressions/tuple_expression.rs b/compiler/input/src/expressions/tuple_expression.rs similarity index 100% rename from input/src/expressions/tuple_expression.rs rename to compiler/input/src/expressions/tuple_expression.rs diff --git a/input/src/files/file.rs b/compiler/input/src/files/file.rs similarity index 100% rename from input/src/files/file.rs rename to compiler/input/src/files/file.rs diff --git a/input/src/files/mod.rs b/compiler/input/src/files/mod.rs similarity index 100% rename from input/src/files/mod.rs rename to compiler/input/src/files/mod.rs diff --git a/input/src/files/table_or_section.rs b/compiler/input/src/files/table_or_section.rs similarity index 100% rename from input/src/files/table_or_section.rs rename to compiler/input/src/files/table_or_section.rs diff --git a/input/src/leo-input.pest b/compiler/input/src/leo-input.pest similarity index 100% rename from input/src/leo-input.pest rename to compiler/input/src/leo-input.pest diff --git a/input/src/lib.rs b/compiler/input/src/lib.rs similarity index 100% rename from input/src/lib.rs rename to compiler/input/src/lib.rs diff --git a/input/src/parameters/mod.rs b/compiler/input/src/parameters/mod.rs similarity index 100% rename from input/src/parameters/mod.rs rename to compiler/input/src/parameters/mod.rs diff --git a/input/src/parameters/parameter.rs b/compiler/input/src/parameters/parameter.rs similarity index 100% rename from input/src/parameters/parameter.rs rename to compiler/input/src/parameters/parameter.rs diff --git a/input/src/sections/constants.rs b/compiler/input/src/sections/constants.rs similarity index 100% rename from input/src/sections/constants.rs rename to compiler/input/src/sections/constants.rs diff --git a/input/src/sections/header.rs b/compiler/input/src/sections/header.rs similarity index 100% rename from input/src/sections/header.rs rename to compiler/input/src/sections/header.rs diff --git a/input/src/sections/main_.rs b/compiler/input/src/sections/main_.rs similarity index 100% rename from input/src/sections/main_.rs rename to compiler/input/src/sections/main_.rs diff --git a/input/src/sections/mod.rs b/compiler/input/src/sections/mod.rs similarity index 100% rename from input/src/sections/mod.rs rename to compiler/input/src/sections/mod.rs diff --git a/input/src/sections/record.rs b/compiler/input/src/sections/record.rs similarity index 100% rename from input/src/sections/record.rs rename to compiler/input/src/sections/record.rs diff --git a/input/src/sections/registers.rs b/compiler/input/src/sections/registers.rs similarity index 100% rename from input/src/sections/registers.rs rename to compiler/input/src/sections/registers.rs diff --git a/input/src/sections/section.rs b/compiler/input/src/sections/section.rs similarity index 100% rename from input/src/sections/section.rs rename to compiler/input/src/sections/section.rs diff --git a/input/src/sections/state.rs b/compiler/input/src/sections/state.rs similarity index 100% rename from input/src/sections/state.rs rename to compiler/input/src/sections/state.rs diff --git a/input/src/sections/state_leaf.rs b/compiler/input/src/sections/state_leaf.rs similarity index 100% rename from input/src/sections/state_leaf.rs rename to compiler/input/src/sections/state_leaf.rs diff --git a/input/src/tables/mod.rs b/compiler/input/src/tables/mod.rs similarity index 100% rename from input/src/tables/mod.rs rename to compiler/input/src/tables/mod.rs diff --git a/input/src/tables/private.rs b/compiler/input/src/tables/private.rs similarity index 100% rename from input/src/tables/private.rs rename to compiler/input/src/tables/private.rs diff --git a/input/src/tables/public.rs b/compiler/input/src/tables/public.rs similarity index 100% rename from input/src/tables/public.rs rename to compiler/input/src/tables/public.rs diff --git a/input/src/tables/table.rs b/compiler/input/src/tables/table.rs similarity index 100% rename from input/src/tables/table.rs rename to compiler/input/src/tables/table.rs diff --git a/input/src/tables/visibility.rs b/compiler/input/src/tables/visibility.rs similarity index 100% rename from input/src/tables/visibility.rs rename to compiler/input/src/tables/visibility.rs diff --git a/input/src/types/address_type.rs b/compiler/input/src/types/address_type.rs similarity index 100% rename from input/src/types/address_type.rs rename to compiler/input/src/types/address_type.rs diff --git a/input/src/types/array_dimensions.rs b/compiler/input/src/types/array_dimensions.rs similarity index 100% rename from input/src/types/array_dimensions.rs rename to compiler/input/src/types/array_dimensions.rs diff --git a/input/src/types/array_type.rs b/compiler/input/src/types/array_type.rs similarity index 100% rename from input/src/types/array_type.rs rename to compiler/input/src/types/array_type.rs diff --git a/input/src/types/boolean_type.rs b/compiler/input/src/types/boolean_type.rs similarity index 100% rename from input/src/types/boolean_type.rs rename to compiler/input/src/types/boolean_type.rs diff --git a/input/src/types/char_type.rs b/compiler/input/src/types/char_type.rs similarity index 100% rename from input/src/types/char_type.rs rename to compiler/input/src/types/char_type.rs diff --git a/input/src/types/data_type.rs b/compiler/input/src/types/data_type.rs similarity index 100% rename from input/src/types/data_type.rs rename to compiler/input/src/types/data_type.rs diff --git a/input/src/types/field_type.rs b/compiler/input/src/types/field_type.rs similarity index 100% rename from input/src/types/field_type.rs rename to compiler/input/src/types/field_type.rs diff --git a/input/src/types/group_type.rs b/compiler/input/src/types/group_type.rs similarity index 100% rename from input/src/types/group_type.rs rename to compiler/input/src/types/group_type.rs diff --git a/input/src/types/integer_type.rs b/compiler/input/src/types/integer_type.rs similarity index 100% rename from input/src/types/integer_type.rs rename to compiler/input/src/types/integer_type.rs diff --git a/input/src/types/mod.rs b/compiler/input/src/types/mod.rs similarity index 100% rename from input/src/types/mod.rs rename to compiler/input/src/types/mod.rs diff --git a/input/src/types/signed_integer_type.rs b/compiler/input/src/types/signed_integer_type.rs similarity index 100% rename from input/src/types/signed_integer_type.rs rename to compiler/input/src/types/signed_integer_type.rs diff --git a/input/src/types/tuple_type.rs b/compiler/input/src/types/tuple_type.rs similarity index 100% rename from input/src/types/tuple_type.rs rename to compiler/input/src/types/tuple_type.rs diff --git a/input/src/types/type_.rs b/compiler/input/src/types/type_.rs similarity index 100% rename from input/src/types/type_.rs rename to compiler/input/src/types/type_.rs diff --git a/input/src/types/unsigned_integer_type.rs b/compiler/input/src/types/unsigned_integer_type.rs similarity index 100% rename from input/src/types/unsigned_integer_type.rs rename to compiler/input/src/types/unsigned_integer_type.rs diff --git a/input/src/values/address.rs b/compiler/input/src/values/address.rs similarity index 100% rename from input/src/values/address.rs rename to compiler/input/src/values/address.rs diff --git a/input/src/values/address_typed.rs b/compiler/input/src/values/address_typed.rs similarity index 100% rename from input/src/values/address_typed.rs rename to compiler/input/src/values/address_typed.rs diff --git a/input/src/values/address_value.rs b/compiler/input/src/values/address_value.rs similarity index 100% rename from input/src/values/address_value.rs rename to compiler/input/src/values/address_value.rs diff --git a/input/src/values/boolean_value.rs b/compiler/input/src/values/boolean_value.rs similarity index 100% rename from input/src/values/boolean_value.rs rename to compiler/input/src/values/boolean_value.rs diff --git a/input/src/values/char_types.rs b/compiler/input/src/values/char_types.rs similarity index 100% rename from input/src/values/char_types.rs rename to compiler/input/src/values/char_types.rs diff --git a/input/src/values/char_value.rs b/compiler/input/src/values/char_value.rs similarity index 100% rename from input/src/values/char_value.rs rename to compiler/input/src/values/char_value.rs diff --git a/input/src/values/field_value.rs b/compiler/input/src/values/field_value.rs similarity index 100% rename from input/src/values/field_value.rs rename to compiler/input/src/values/field_value.rs diff --git a/input/src/values/group_coordinate.rs b/compiler/input/src/values/group_coordinate.rs similarity index 100% rename from input/src/values/group_coordinate.rs rename to compiler/input/src/values/group_coordinate.rs diff --git a/input/src/values/group_value.rs b/compiler/input/src/values/group_value.rs similarity index 100% rename from input/src/values/group_value.rs rename to compiler/input/src/values/group_value.rs diff --git a/input/src/values/integer_value.rs b/compiler/input/src/values/integer_value.rs similarity index 100% rename from input/src/values/integer_value.rs rename to compiler/input/src/values/integer_value.rs diff --git a/input/src/values/mod.rs b/compiler/input/src/values/mod.rs similarity index 100% rename from input/src/values/mod.rs rename to compiler/input/src/values/mod.rs diff --git a/input/src/values/negative_number.rs b/compiler/input/src/values/negative_number.rs similarity index 100% rename from input/src/values/negative_number.rs rename to compiler/input/src/values/negative_number.rs diff --git a/input/src/values/number_value.rs b/compiler/input/src/values/number_value.rs similarity index 100% rename from input/src/values/number_value.rs rename to compiler/input/src/values/number_value.rs diff --git a/input/src/values/positive_number.rs b/compiler/input/src/values/positive_number.rs similarity index 100% rename from input/src/values/positive_number.rs rename to compiler/input/src/values/positive_number.rs diff --git a/input/src/values/signed_integer_value.rs b/compiler/input/src/values/signed_integer_value.rs similarity index 100% rename from input/src/values/signed_integer_value.rs rename to compiler/input/src/values/signed_integer_value.rs diff --git a/input/src/values/unsigned_integer_value.rs b/compiler/input/src/values/unsigned_integer_value.rs similarity index 100% rename from input/src/values/unsigned_integer_value.rs rename to compiler/input/src/values/unsigned_integer_value.rs diff --git a/input/src/values/value.rs b/compiler/input/src/values/value.rs similarity index 100% rename from input/src/values/value.rs rename to compiler/input/src/values/value.rs diff --git a/parser/Cargo.toml b/compiler/parser/Cargo.toml similarity index 93% rename from parser/Cargo.toml rename to compiler/parser/Cargo.toml index e3556c89b5..12c844a75e 100644 --- a/parser/Cargo.toml +++ b/compiler/parser/Cargo.toml @@ -31,7 +31,7 @@ path = "../ast" version = "1.5.3" [dependencies.leo-errors] -path = "../errors" +path = "../../leo/errors" version = "1.5.3" [dependencies.leo-input] @@ -39,7 +39,7 @@ path = "../input" version = "1.5.1" [dependencies.leo-span] -path = "../span" +path = "../../leo/span" version = "1.5.3" [dependencies.indexmap] @@ -59,7 +59,7 @@ version = "0.4" version = "0.1" [dev-dependencies.leo-test-framework] -path = "../test-framework" +path = "../../tools/test-framework" version = "1.4.0" [dev-dependencies.criterion] diff --git a/parser/README.md b/compiler/parser/README.md similarity index 100% rename from parser/README.md rename to compiler/parser/README.md diff --git a/parser/benches/big_circuit.leo b/compiler/parser/benches/big_circuit.leo similarity index 100% rename from parser/benches/big_circuit.leo rename to compiler/parser/benches/big_circuit.leo diff --git a/parser/benches/big_if_else.leo b/compiler/parser/benches/big_if_else.leo similarity index 100% rename from parser/benches/big_if_else.leo rename to compiler/parser/benches/big_if_else.leo diff --git a/parser/benches/big_ternary.leo b/compiler/parser/benches/big_ternary.leo similarity index 100% rename from parser/benches/big_ternary.leo rename to compiler/parser/benches/big_ternary.leo diff --git a/parser/benches/large_1.leo b/compiler/parser/benches/large_1.leo similarity index 100% rename from parser/benches/large_1.leo rename to compiler/parser/benches/large_1.leo diff --git a/parser/benches/large_2.leo b/compiler/parser/benches/large_2.leo similarity index 100% rename from parser/benches/large_2.leo rename to compiler/parser/benches/large_2.leo diff --git a/parser/benches/large_3.leo b/compiler/parser/benches/large_3.leo similarity index 100% rename from parser/benches/large_3.leo rename to compiler/parser/benches/large_3.leo diff --git a/parser/benches/large_4.leo b/compiler/parser/benches/large_4.leo similarity index 100% rename from parser/benches/large_4.leo rename to compiler/parser/benches/large_4.leo diff --git a/parser/benches/large_5.leo b/compiler/parser/benches/large_5.leo similarity index 100% rename from parser/benches/large_5.leo rename to compiler/parser/benches/large_5.leo diff --git a/parser/benches/leo_ast.rs b/compiler/parser/benches/leo_ast.rs similarity index 100% rename from parser/benches/leo_ast.rs rename to compiler/parser/benches/leo_ast.rs diff --git a/parser/benches/long_array.leo b/compiler/parser/benches/long_array.leo similarity index 100% rename from parser/benches/long_array.leo rename to compiler/parser/benches/long_array.leo diff --git a/parser/benches/long_expr.leo b/compiler/parser/benches/long_expr.leo similarity index 100% rename from parser/benches/long_expr.leo rename to compiler/parser/benches/long_expr.leo diff --git a/parser/benches/many_assigns.leo b/compiler/parser/benches/many_assigns.leo similarity index 100% rename from parser/benches/many_assigns.leo rename to compiler/parser/benches/many_assigns.leo diff --git a/parser/benches/many_foos.leo b/compiler/parser/benches/many_foos.leo similarity index 100% rename from parser/benches/many_foos.leo rename to compiler/parser/benches/many_foos.leo diff --git a/parser/benches/massive.leo b/compiler/parser/benches/massive.leo similarity index 100% rename from parser/benches/massive.leo rename to compiler/parser/benches/massive.leo diff --git a/parser/benches/medium_1.leo b/compiler/parser/benches/medium_1.leo similarity index 100% rename from parser/benches/medium_1.leo rename to compiler/parser/benches/medium_1.leo diff --git a/parser/benches/medium_2.leo b/compiler/parser/benches/medium_2.leo similarity index 100% rename from parser/benches/medium_2.leo rename to compiler/parser/benches/medium_2.leo diff --git a/parser/benches/medium_3.leo b/compiler/parser/benches/medium_3.leo similarity index 100% rename from parser/benches/medium_3.leo rename to compiler/parser/benches/medium_3.leo diff --git a/parser/benches/medium_4.leo b/compiler/parser/benches/medium_4.leo similarity index 100% rename from parser/benches/medium_4.leo rename to compiler/parser/benches/medium_4.leo diff --git a/parser/benches/medium_5.leo b/compiler/parser/benches/medium_5.leo similarity index 100% rename from parser/benches/medium_5.leo rename to compiler/parser/benches/medium_5.leo diff --git a/parser/benches/small_1.leo b/compiler/parser/benches/small_1.leo similarity index 100% rename from parser/benches/small_1.leo rename to compiler/parser/benches/small_1.leo diff --git a/parser/benches/small_2.leo b/compiler/parser/benches/small_2.leo similarity index 100% rename from parser/benches/small_2.leo rename to compiler/parser/benches/small_2.leo diff --git a/parser/benches/small_3.leo b/compiler/parser/benches/small_3.leo similarity index 100% rename from parser/benches/small_3.leo rename to compiler/parser/benches/small_3.leo diff --git a/parser/benches/small_4.leo b/compiler/parser/benches/small_4.leo similarity index 100% rename from parser/benches/small_4.leo rename to compiler/parser/benches/small_4.leo diff --git a/parser/benches/small_5.leo b/compiler/parser/benches/small_5.leo similarity index 100% rename from parser/benches/small_5.leo rename to compiler/parser/benches/small_5.leo diff --git a/parser/examples/parser.rs b/compiler/parser/examples/parser.rs similarity index 100% rename from parser/examples/parser.rs rename to compiler/parser/examples/parser.rs diff --git a/parser/src/lib.rs b/compiler/parser/src/lib.rs similarity index 100% rename from parser/src/lib.rs rename to compiler/parser/src/lib.rs diff --git a/parser/src/parser/context.rs b/compiler/parser/src/parser/context.rs similarity index 100% rename from parser/src/parser/context.rs rename to compiler/parser/src/parser/context.rs diff --git a/parser/src/parser/expression.rs b/compiler/parser/src/parser/expression.rs similarity index 100% rename from parser/src/parser/expression.rs rename to compiler/parser/src/parser/expression.rs diff --git a/parser/src/parser/file.rs b/compiler/parser/src/parser/file.rs similarity index 100% rename from parser/src/parser/file.rs rename to compiler/parser/src/parser/file.rs diff --git a/parser/src/parser/mod.rs b/compiler/parser/src/parser/mod.rs similarity index 100% rename from parser/src/parser/mod.rs rename to compiler/parser/src/parser/mod.rs diff --git a/parser/src/parser/statement.rs b/compiler/parser/src/parser/statement.rs similarity index 100% rename from parser/src/parser/statement.rs rename to compiler/parser/src/parser/statement.rs diff --git a/parser/src/parser/type_.rs b/compiler/parser/src/parser/type_.rs similarity index 100% rename from parser/src/parser/type_.rs rename to compiler/parser/src/parser/type_.rs diff --git a/parser/src/test.rs b/compiler/parser/src/test.rs similarity index 100% rename from parser/src/test.rs rename to compiler/parser/src/test.rs diff --git a/parser/src/tokenizer/lexer.rs b/compiler/parser/src/tokenizer/lexer.rs similarity index 100% rename from parser/src/tokenizer/lexer.rs rename to compiler/parser/src/tokenizer/lexer.rs diff --git a/parser/src/tokenizer/mod.rs b/compiler/parser/src/tokenizer/mod.rs similarity index 100% rename from parser/src/tokenizer/mod.rs rename to compiler/parser/src/tokenizer/mod.rs diff --git a/parser/src/tokenizer/token.rs b/compiler/parser/src/tokenizer/token.rs similarity index 100% rename from parser/src/tokenizer/token.rs rename to compiler/parser/src/tokenizer/token.rs diff --git a/parser/tests/serialization/json.rs b/compiler/parser/tests/serialization/json.rs similarity index 100% rename from parser/tests/serialization/json.rs rename to compiler/parser/tests/serialization/json.rs diff --git a/compiler/src/deprecated/blake2s.rs b/compiler/src/deprecated/blake2s.rs deleted file mode 100644 index d8d2502194..0000000000 --- a/compiler/src/deprecated/blake2s.rs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use super::CoreCircuit; -use crate::{ConstrainedValue, GroupType, Integer}; -use leo_asg::Function; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::{ - algorithms::prf::Blake2sGadget, bits::ToBytesGadget, integers::uint::UInt8, traits::algorithms::PRFGadget, -}; -use snarkvm_r1cs::ConstraintSystem; - -pub struct Blake2s; - -fn unwrap_argument>(arg: ConstrainedValue) -> Vec { - if let ConstrainedValue::Array(args) = arg { - assert_eq!(args.len(), 32); // asg enforced - args.into_iter() - .map(|item| { - if let ConstrainedValue::Integer(Integer::U8(item)) = item { - item - } else { - panic!("illegal non-u8 type in blake2s call"); - } - }) - .collect() - } else { - panic!("illegal non-array type in blake2s call"); - } -} - -impl<'a, F: PrimeField, G: GroupType> CoreCircuit<'a, F, G> for Blake2s { - fn call_function>( - &self, - cs: &mut CS, - function: &'a Function<'a>, - span: &Span, - target: Option>, - mut arguments: Vec>, - ) -> Result> { - assert_eq!(arguments.len(), 2); // asg enforced - assert!(function.name.borrow().name.as_ref() == "hash"); // asg enforced - assert!(target.is_none()); // asg enforced - let input = unwrap_argument(arguments.remove(1)); - let seed = unwrap_argument(arguments.remove(0)); - - let digest = Blake2sGadget::check_evaluation_gadget(cs.ns(|| "blake2s hash"), &seed[..], &input[..]) - .map_err(|e| CompilerError::cannot_enforce_expression("Blake2s check evaluation gadget", e, span))?; - - Ok(ConstrainedValue::Array( - digest - .to_bytes(cs) - .map_err(|e| CompilerError::cannot_enforce_expression("Vec ToBytes", e, span))? - .into_iter() - .map(Integer::U8) - .map(ConstrainedValue::Integer) - .collect(), - )) - } -} diff --git a/compiler/src/unused/Cargo.toml b/compiler/src/unused/Cargo.toml deleted file mode 100644 index f775271447..0000000000 --- a/compiler/src/unused/Cargo.toml +++ /dev/null @@ -1,146 +0,0 @@ -[package] -name = "leo-compiler" -version = "1.5.3" -authors = [ "The Aleo Team " ] -description = "Compiler of the Leo programming language" -homepage = "https://aleo.org" -repository = "https://github.com/AleoHQ/leo" -keywords = [ - "aleo", - "cryptography", - "leo", - "programming-language", - "zero-knowledge" -] -categories = [ "cryptography::cryptocurrencies", "web-programming" ] -include = [ "Cargo.toml", "src", "README.md", "LICENSE.md" ] -license = "GPL-3.0" -edition = "2021" -rust-version = "1.56.1" - -[dependencies.leo-ast] -path = "../ast" -version = "1.5.3" - -[dependencies.leo-errors] -path = "../errors" -version = "1.5.3" -# -#[dependencies.leo-imports] -#path = "../imports" -#version = "1.5.3" -# -#[dependencies.leo-input] -#path = "../input" -#version = "1.5.3" -# -#[dependencies.leo-package] -#path = "../package" -#version = "1.5.3" - -[dependencies.leo-parser] -path = "../parser" -version = "1.5.3" -# -#[dependencies.leo-asg-passes] -#path = "../asg-passes" -#version = "1.5.3" -# -#[dependencies.leo-ast-passes] -#path = "../ast-passes" -#version = "1.5.3" -# -#[dependencies.leo-synthesizer] -#path = "../synthesizer" -#version = "1.5.3" - -[dev-dependencies.snarkvm-algorithms] -git = "https://github.com/AleoHQ/snarkVM.git" -rev = "51633e2" -default-features = false - -[dependencies.snarkvm-curves] -git = "https://github.com/AleoHQ/snarkVM.git" -rev = "51633e2" -default-features = false - -[dependencies.snarkvm-fields] -git = "https://github.com/AleoHQ/snarkVM.git" -rev = "51633e2" -default-features = false - -[dependencies.snarkvm-dpc] -git = "https://github.com/AleoHQ/snarkVM.git" -rev = "51633e2" -features = ["testnet2"] - -[dependencies.snarkvm-gadgets] -git = "https://github.com/AleoHQ/snarkVM.git" -rev = "51633e2" -default-features = false -features = [ "curves" ] - -[dependencies.snarkvm-r1cs] -git = "https://github.com/AleoHQ/snarkVM.git" -rev = "51633e2" -default-features = false - -[dependencies.snarkvm-utilities] -git = "https://github.com/AleoHQ/snarkVM.git" -rev = "51633e2" - -[dependencies.bech32] -version = "0.8" - -[dependencies.bincode] -version = "1.3" - -[dependencies.indexmap] -version = "1.8.0" -features = [ "serde-1" ] - -[dependencies.num-bigint] -version = "0.4" - -[dependencies.pest] -version = "2.0" - -[dependencies.rand] -version = "0.8" - -[dependencies.serde] -version = "1.0" - -[dependencies.serde_json] -version = "1.0" -features = [ "preserve_order" ] - -[dependencies.sha2] -version = "0.10" - -[dependencies.tendril] -version = "0.4" - -[dependencies.tracing] -version = "0.1" - -[dev-dependencies.leo-test-framework] -path = "../test-framework" -version = "1.4.0" - -[dev-dependencies.rand_core] -version = "0.6.3" - -[dev-dependencies.rand_xorshift] -version = "0.3" -default-features = false - -[dev-dependencies.serde_yaml] -version = "0.8" - -[dev-dependencies.tempfile] -version = "3.3.0" - -[features] -default = [ ] -ci_skip = [ "leo-ast/ci_skip" ] diff --git a/compiler/src/unused/compiler.rs b/compiler/src/unused/compiler.rs deleted file mode 100644 index 969cf8bec0..0000000000 --- a/compiler/src/unused/compiler.rs +++ /dev/null @@ -1,410 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Compiles a Leo program from a file path. -use crate::{ - constraints::{generate_constraints, generate_test_constraints}, - AstSnapshotOptions, CompilerOptions, GroupType, Output, OutputFile, TypeInferencePhase, -}; -pub use leo_asg::{new_context, AsgContext as Context, AsgContext}; -use leo_asg::{Asg, AsgPass, Program as AsgProgram}; -use leo_ast::{AstPass, Input, MainInput, Program as AstProgram}; -use leo_errors::{CompilerError, Result}; -use leo_imports::ImportParser; -use leo_input::LeoInputParser; -use leo_package::inputs::InputPairs; -use leo_parser::parse_ast; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::{ConstraintSynthesizer, ConstraintSystem, SynthesisError}; - -use sha2::{Digest, Sha256}; -use std::{ - fs, - marker::PhantomData, - path::{Path, PathBuf}, -}; - -use indexmap::IndexMap; - -thread_local! { - static THREAD_GLOBAL_CONTEXT: AsgContext<'static> = { - let leaked = Box::leak(Box::new(leo_asg::new_alloc_context())); - leo_asg::new_context(leaked) - } -} - -/// Convenience function to return a leaked thread-local global context. Should only be used for transient programs (like cli). -pub fn thread_leaked_context() -> AsgContext<'static> { - THREAD_GLOBAL_CONTEXT.with(|f| *f) -} - -/// Stores information to compile a Leo program. -#[derive(Clone)] -pub struct Compiler<'a, F: PrimeField, G: GroupType> { - program_name: String, - main_file_path: PathBuf, - output_directory: PathBuf, - program: AstProgram, - program_input: Input, - context: AsgContext<'a>, - asg: Option>, - options: CompilerOptions, - imports_map: IndexMap, - ast_snapshot_options: AstSnapshotOptions, - _engine: PhantomData, - _group: PhantomData, -} - -impl<'a, F: PrimeField, G: GroupType> Compiler<'a, F, G> { - /// - /// Returns a new Leo program compiler. - /// - pub fn new( - package_name: String, - main_file_path: PathBuf, - output_directory: PathBuf, - context: AsgContext<'a>, - options: Option, - imports_map: IndexMap, - ast_snapshot_options: Option, - ) -> Self { - Self { - program_name: package_name.clone(), - main_file_path, - output_directory, - program: AstProgram::new(package_name), - program_input: Input::new(), - asg: None, - context, - options: options.unwrap_or_default(), - imports_map, - ast_snapshot_options: ast_snapshot_options.unwrap_or_default(), - _engine: PhantomData, - _group: PhantomData, - } - } - - /// - /// Returns a new `Compiler` from the given main file path. - /// - /// Parses and stores a program from the main file path. - /// Parses and stores all imported programs. - /// Performs type inference checking on the program and imported programs. - /// - pub fn parse_program_without_input( - package_name: String, - main_file_path: PathBuf, - output_directory: PathBuf, - context: AsgContext<'a>, - options: Option, - imports_map: IndexMap, - ast_snapshot_options: Option, - ) -> Result { - let mut compiler = Self::new( - package_name, - main_file_path, - output_directory, - context, - options, - imports_map, - ast_snapshot_options, - ); - - compiler.parse_program()?; - - Ok(compiler) - } - - pub fn set_options(&mut self, options: CompilerOptions) { - self.options = options; - } - - /// - /// Returns a new `Compiler` from the given main file path. - /// - /// Parses and stores program input from from the input file path and state file path - /// Parses and stores a program from the main file path. - /// Parses and stores all imported programs. - /// Performs type inference checking on the program, imported programs, and program input. - /// - #[allow(clippy::too_many_arguments)] - pub fn parse_program_with_input( - package_name: String, - main_file_path: PathBuf, - output_directory: PathBuf, - input_string: &str, - input_path: &Path, - state_string: &str, - state_path: &Path, - context: AsgContext<'a>, - options: Option, - imports_map: IndexMap, - ast_snapshot_options: Option, - ) -> Result { - let mut compiler = Self::new( - package_name, - main_file_path, - output_directory, - context, - options, - imports_map, - ast_snapshot_options, - ); - - compiler.parse_input(input_string, input_path, state_string, state_path)?; - - compiler.parse_program()?; - - Ok(compiler) - } - - /// - /// Parses and stores program input from from the input file path and state file path - /// - /// Calls `set_path()` on compiler errors with the given input file path or state file path - /// - pub fn parse_input( - &mut self, - input_string: &str, - input_path: &Path, - state_string: &str, - state_path: &Path, - ) -> Result<()> { - let input_syntax_tree = LeoInputParser::parse_file(input_string).map_err(|mut e| { - e.set_path( - input_path.to_str().unwrap_or_default(), - &input_string.lines().map(|x| x.to_string()).collect::>()[..], - ); - - e - })?; - let state_syntax_tree = LeoInputParser::parse_file(state_string).map_err(|mut e| { - e.set_path( - state_path.to_str().unwrap_or_default(), - &state_string.lines().map(|x| x.to_string()).collect::>()[..], - ); - - e - })?; - - self.program_input.parse_input(input_syntax_tree).map_err(|mut e| { - e.set_path( - input_path.to_str().unwrap_or_default(), - &input_string.lines().map(|x| x.to_string()).collect::>()[..], - ); - - e - })?; - self.program_input.parse_state(state_syntax_tree).map_err(|mut e| { - e.set_path( - state_path.to_str().unwrap_or_default(), - &state_string.lines().map(|x| x.to_string()).collect::>()[..], - ); - - e - })?; - - Ok(()) - } - - /// - /// Parses and stores the main program file, constructs a syntax tree, and generates a program. - /// - /// Parses and stores all programs imported by the main program file. - /// - pub fn parse_program(&mut self) -> Result<()> { - // Load the program file. - let content = fs::read_to_string(&self.main_file_path) - .map_err(|e| CompilerError::file_read_error(self.main_file_path.clone(), e))?; - - self.parse_program_from_string(&content) - } - - /// - /// Equivalent to parse_and_check_program but uses the given program_string instead of a main - /// file path. - /// - pub fn parse_program_from_string(&mut self, program_string: &str) -> Result<()> { - // Use the parser to construct the abstract syntax tree (ast). - - let mut ast: leo_ast::Ast = parse_ast(self.main_file_path.to_str().unwrap_or_default(), program_string)?; - - if self.ast_snapshot_options.initial { - if self.ast_snapshot_options.spans_enabled { - ast.to_json_file(self.output_directory.clone(), "initial_ast.json")?; - } else { - ast.to_json_file_without_keys(self.output_directory.clone(), "initial_ast.json", &["span"])?; - } - } - - // Preform import resolution. - ast = leo_ast_passes::Importer::do_pass( - ast.into_repr(), - &mut ImportParser::new(self.main_file_path.clone(), self.imports_map.clone()), - )?; - - if self.ast_snapshot_options.imports_resolved { - if self.ast_snapshot_options.spans_enabled { - ast.to_json_file(self.output_directory.clone(), "imports_resolved_ast.json")?; - } else { - ast.to_json_file_without_keys(self.output_directory.clone(), "imports_resolved_ast.json", &["span"])?; - } - } - - // Preform canonicalization of AST always. - ast = leo_ast_passes::Canonicalizer::do_pass(ast.into_repr())?; - - if self.ast_snapshot_options.canonicalized { - if self.ast_snapshot_options.spans_enabled { - ast.to_json_file(self.output_directory.clone(), "canonicalization_ast.json")?; - } else { - ast.to_json_file_without_keys(self.output_directory.clone(), "canonicalization_ast.json", &["span"])?; - } - } - - // Store the main program file. - self.program = ast.into_repr(); - self.program.name = self.program_name.clone(); - - tracing::debug!("Program parsing complete\n{:#?}", self.program); - - // Create a new symbol table from the program, imported_programs, and program_input. - let asg = Asg::new(self.context, &self.program)?; - - if self.ast_snapshot_options.type_inferenced { - let new_ast = TypeInferencePhase::default() - .phase_ast(&self.program, &asg.clone().into_repr()) - .expect("Failed to produce type inference ast."); - - if self.ast_snapshot_options.spans_enabled { - new_ast.to_json_file(self.output_directory.clone(), "type_inferenced_ast.json")?; - } else { - new_ast.to_json_file_without_keys( - self.output_directory.clone(), - "type_inferenced_ast.json", - &["span"], - )?; - } - } - - tracing::debug!("ASG generation complete"); - - // Store the ASG. - self.asg = Some(asg.into_repr()); - - self.do_asg_passes()?; - - Ok(()) - } - - /// - /// Run compiler optimization passes on the program in asg format. - /// - fn do_asg_passes(&mut self) -> Result<()> { - assert!(self.asg.is_some()); - - // Do constant folding. - if self.options.constant_folding_enabled { - let asg = self.asg.take().unwrap(); - self.asg = Some(leo_asg_passes::ConstantFolding::do_pass(asg)?); - } - - // Do dead code elimination. - if self.options.dead_code_elimination_enabled { - let asg = self.asg.take().unwrap(); - self.asg = Some(leo_asg_passes::DeadCodeElimination::do_pass(asg)?); - } - - Ok(()) - } - - /// - /// Synthesizes the circuit with program input to verify correctness. - /// - pub fn compile_constraints>(&self, cs: &mut CS) -> Result { - generate_constraints::(cs, self.asg.as_ref().unwrap(), &self.program_input) - } - - /// - /// Synthesizes the circuit for test functions with program input. - /// - pub fn compile_test_constraints(self, input_pairs: InputPairs) -> Result<(u32, u32)> { - generate_test_constraints::(self.asg.as_ref().unwrap(), input_pairs, &self.output_directory) - } - - /// - /// Returns a SHA256 checksum of the program file. - /// - pub fn checksum(&self) -> Result { - // Read in the main file as string - let unparsed_file = fs::read_to_string(&self.main_file_path) - .map_err(|e| CompilerError::file_read_error(self.main_file_path.clone(), e))?; - - // Hash the file contents - let mut hasher = Sha256::new(); - hasher.update(unparsed_file.as_bytes()); - let hash = hasher.finalize(); - - Ok(format!("{:x}", hash)) - } - - // /// TODO (howardwu): Incorporate this for real program executions and intentionally-real - // /// test executions. Exclude it for test executions on dummy data. - // /// - // /// Verifies the input to the program. - // /// - // pub fn verify_local_data_commitment(&self, system_parameters: &SystemParameters) -> Result { - // let result = verify_local_data_commitment(system_parameters, &self.program_input)?; - // - // Ok(result) - // } - - /// - /// Manually sets main function input. - /// - /// Used for testing only. - /// - pub fn set_main_input(&mut self, input: MainInput) { - self.program_input.set_main_input(input); - } -} - -impl<'a, F: PrimeField, G: GroupType> ConstraintSynthesizer for Compiler<'a, F, G> { - /// - /// Synthesizes the circuit with program input. - /// - fn generate_constraints>(&self, cs: &mut CS) -> Result<(), SynthesisError> { - let output_directory = self.output_directory.clone(); - let package_name = self.program_name.clone(); - - let result = match self.compile_constraints(cs) { - Err(err) => { - eprintln!("{}", err); - std::process::exit(err.exit_code()) - } - Ok(result) => result, - }; - - // Write results to file - let output_file = OutputFile::new(&package_name); - output_file - .write(&output_directory, result.to_string().as_bytes()) - .unwrap(); - - Ok(()) - } -} diff --git a/compiler/src/unused/console/assert.rs b/compiler/src/unused/console/assert.rs deleted file mode 100644 index 5ec8b5d001..0000000000 --- a/compiler/src/unused/console/assert.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces an assert equals statement in a compiled Leo program. - -use crate::{get_indicator_value, program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::Expression; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::boolean::Boolean; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub fn evaluate_console_assert>( - &mut self, - cs: &mut CS, - indicator: &Boolean, - expression: &'a Expression<'a>, - span: &Span, - ) -> Result<()> { - // Evaluate assert expression - let assert_expression = self.enforce_expression(cs, expression)?; - - // If the indicator bit is false, do not evaluate the assertion - // This is okay since we are not enforcing any constraints - if !get_indicator_value(indicator) { - return Ok(()); // Continue execution. - } - - // Unwrap assertion value and handle errors - let result_option = match assert_expression { - ConstrainedValue::Boolean(boolean) => boolean.get_value(), - _ => { - return Err(CompilerError::console_assertion_must_be_boolean(span).into()); - } - }; - let result_bool = result_option.ok_or_else(|| CompilerError::console_assertion_depends_on_input(span))?; - - if !result_bool { - return Err(CompilerError::console_assertion_failed(span).into()); - } - - Ok(()) - } -} diff --git a/compiler/src/unused/console/console.rs b/compiler/src/unused/console/console.rs deleted file mode 100644 index 89184f91af..0000000000 --- a/compiler/src/unused/console/console.rs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Evaluates a macro in a compiled Leo program. - -use crate::{program::ConstrainedProgram, statement::get_indicator_value, GroupType}; -use leo_asg::{ConsoleFunction, ConsoleStatement}; -use leo_errors::Result; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::boolean::Boolean; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub fn evaluate_console_function_call>( - &mut self, - cs: &mut CS, - indicator: &Boolean, - console: &ConsoleStatement<'a>, - ) -> Result<()> { - match &console.function { - ConsoleFunction::Assert(expression) => { - self.evaluate_console_assert( - cs, - indicator, - expression.get(), - &console.span.clone().unwrap_or_default(), - )?; - } - ConsoleFunction::Error(string) => { - let string = self.format(cs, string)?; - - if get_indicator_value(indicator) { - tracing::error!("{}", string); - } - } - ConsoleFunction::Log(string) => { - let string = self.format(cs, string)?; - - if get_indicator_value(indicator) { - tracing::info!("{}", string); - } - } - } - - Ok(()) - } -} diff --git a/compiler/src/unused/console/format.rs b/compiler/src/unused/console/format.rs deleted file mode 100644 index 560bb4444f..0000000000 --- a/compiler/src/unused/console/format.rs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Evaluates a formatted string in a compiled Leo program. - -use crate::{program::ConstrainedProgram, GroupType}; -use leo_asg::{CharValue, ConsoleArgs}; -use leo_errors::{CompilerError, Result}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub fn format>(&mut self, cs: &mut CS, args: &ConsoleArgs<'a>) -> Result { - let mut out = Vec::new(); - let mut in_container = false; - let mut substring = String::new(); - let mut arg_index = 0; - let mut escape_right_bracket = false; - for (index, character) in args.string.iter().enumerate() { - match character { - _ if escape_right_bracket => { - escape_right_bracket = false; - continue; - } - CharValue::Scalar(scalar) => match scalar { - '{' if !in_container => { - out.push(substring.clone()); - substring.clear(); - in_container = true; - } - '{' if in_container => { - substring.push('{'); - in_container = false; - } - '}' if in_container => { - in_container = false; - let parameter = match args.parameters.get(arg_index) { - Some(index) => index, - None => { - return Err(CompilerError::console_container_parameter_length_mismatch( - arg_index + 1, - args.parameters.len(), - &args.span, - ) - .into()); - } - }; - out.push(self.enforce_expression(cs, parameter.get())?.to_string()); - arg_index += 1; - } - '}' if !in_container => { - if let Some(CharValue::Scalar(next)) = args.string.get(index + 1) { - if *next == '}' { - substring.push('}'); - escape_right_bracket = true; - } else { - return Err(CompilerError::console_fmt_expected_escaped_right_brace(&args.span).into()); - } - } - } - _ if in_container => { - return Err(CompilerError::console_fmt_expected_left_or_right_brace(&args.span).into()); - } - _ => substring.push(*scalar), - }, - CharValue::NonScalar(non_scalar) => { - substring.push_str(format!("\\u{{{:x}}}", non_scalar).as_str()); - in_container = false; - } - } - } - out.push(substring); - - // Check that containers and parameters match - if arg_index != args.parameters.len() { - return Err(CompilerError::console_container_parameter_length_mismatch( - arg_index, - args.parameters.len(), - &args.span, - ) - .into()); - } - - Ok(out.join("")) - } -} diff --git a/compiler/src/unused/console/mod.rs b/compiler/src/unused/console/mod.rs deleted file mode 100644 index 3e2dc3dd35..0000000000 --- a/compiler/src/unused/console/mod.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub mod assert; -pub use assert::*; - -pub mod console; -pub use self::console::*; - -pub mod format; -pub use self::format::*; diff --git a/compiler/src/unused/constraints/constraints.rs b/compiler/src/unused/constraints/constraints.rs deleted file mode 100644 index 8f740ae175..0000000000 --- a/compiler/src/unused/constraints/constraints.rs +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Generates R1CS constraints for a compiled Leo program. - -use crate::{ConstrainedProgram, GroupType, Output, OutputFile}; -use leo_asg::Program; -use leo_ast::Input; -use leo_errors::{CompilerError, Result}; -use leo_input::LeoInputParser; -use leo_package::inputs::InputPairs; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::{ConstraintSystem, TestConstraintSystem}; -use std::path::Path; - -pub fn generate_constraints<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - program: &Program<'a>, - input: &Input, -) -> Result { - let mut resolved_program = ConstrainedProgram::::new(program.clone()); - - for (_, global_const) in program.global_consts.iter() { - resolved_program.enforce_definition_statement(cs, global_const)?; - } - - let main = { - let program = program; - program.functions.get("main").cloned() - }; - - match main { - Some(function) => { - let result = resolved_program.enforce_main_function(cs, function, input)?; - Ok(result) - } - _ => Err(CompilerError::no_main_function().into()), - } -} - -pub fn generate_test_constraints<'a, F: PrimeField, G: GroupType>( - program: &Program<'a>, - input: InputPairs, - output_directory: &Path, -) -> Result<(u32, u32)> { - let mut resolved_program = ConstrainedProgram::::new(program.clone()); - let program_name = program.name.clone(); - - // Get default input - let default = input.pairs.get(&program_name); - - let tests = program - .functions - .iter() - .filter(|(_name, func)| func.is_test()) - .collect::>(); - tracing::info!("Running {} tests", tests.len()); - - // Count passed and failed tests - let mut passed = 0; - let mut failed = 0; - - for (test_name, function) in tests.into_iter() { - let cs = &mut TestConstraintSystem::::new(); - let full_test_name = format!("{}::{}", program_name.clone(), test_name); - let mut output_file_name = program_name.clone(); - - let input_file = function - .annotations - .iter() - .find(|x| x.name.name.as_ref() == "test") - .unwrap() - .arguments - .get(0); - // get input file name from annotation or use test_name - let input_pair = match input_file { - Some(file_id) => { - let file_name = file_id.clone(); - let file_name_kebab = file_name.to_string().replace("_", "-"); - - // transform "test_name" into "test-name" - output_file_name = file_name.to_string(); - - // searches for test_input (snake case) or for test-input (kebab case) - match input - .pairs - .get(&file_name_kebab) - .or_else(|| input.pairs.get(&file_name_kebab)) - { - Some(pair) => pair.to_owned(), - None => { - return Err(CompilerError::invalid_test_context(file_name).into()); - } - } - } - None => default.ok_or_else(CompilerError::no_test_input)?, - }; - - // parse input files to abstract syntax trees - let input_file = &input_pair.input_file; - let state_file = &input_pair.state_file; - - let input_ast = LeoInputParser::parse_file(input_file)?; - let state_ast = LeoInputParser::parse_file(state_file)?; - - // parse input files into input struct - let mut input = Input::new(); - input.parse_input(input_ast)?; - input.parse_state(state_ast)?; - - // run test function on new program with input - let result = resolved_program.enforce_main_function( - cs, function, &input, // pass program input into every test - ); - - match (result.is_ok(), cs.is_satisfied()) { - (true, true) => { - tracing::info!("{} ... ok\n", full_test_name); - - // write result to file - let output = result?; - let output_file = OutputFile::new(&output_file_name); - - output_file - .write(output_directory, output.to_string().as_bytes()) - .unwrap(); - - // increment passed tests - passed += 1; - } - (true, false) => { - tracing::error!("{} constraint system not satisfied\n", full_test_name); - - // increment failed tests - failed += 1; - } - (false, _) => { - // Set file location of error - let error = result.unwrap_err(); - - tracing::error!("{} failed due to error\n\n{}\n", full_test_name, error); - - // increment failed tests - failed += 1; - } - } - } - - Ok((passed, failed)) -} diff --git a/compiler/src/unused/constraints/mod.rs b/compiler/src/unused/constraints/mod.rs deleted file mode 100644 index 9b03486939..0000000000 --- a/compiler/src/unused/constraints/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Module containing methods to enforce constraints in an Leo program - -pub mod constraints; -pub use self::constraints::*; diff --git a/compiler/src/unused/definition/definition.rs b/compiler/src/unused/definition/definition.rs deleted file mode 100644 index 06bff35fd9..0000000000 --- a/compiler/src/unused/definition/definition.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Stores all defined names in a compiled Leo program. - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::Variable; - -use snarkvm_fields::PrimeField; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub fn store_definition(&mut self, variable: &Variable, value: ConstrainedValue<'a, F, G>) { - let variable = variable.borrow(); - self.store(variable.id, value); - } -} diff --git a/compiler/src/unused/definition/mod.rs b/compiler/src/unused/definition/mod.rs deleted file mode 100644 index 04e8f77665..0000000000 --- a/compiler/src/unused/definition/mod.rs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub mod definition; -pub use self::definition::*; diff --git a/compiler/src/unused/expression/arithmetic/add.rs b/compiler/src/unused/expression/arithmetic/add.rs deleted file mode 100644 index 187a6377f8..0000000000 --- a/compiler/src/unused/expression/arithmetic/add.rs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces an arithmetic `+` operator in a resolved Leo program. - -use crate::{value::ConstrainedValue, GroupType}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -pub fn enforce_add<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - left: ConstrainedValue<'a, F, G>, - right: ConstrainedValue<'a, F, G>, - span: &Span, -) -> Result> { - match (left, right) { - (ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => { - Ok(ConstrainedValue::Integer(num_1.add(cs, num_2, span)?)) - } - (ConstrainedValue::Field(field_1), ConstrainedValue::Field(field_2)) => { - Ok(ConstrainedValue::Field(field_1.add(cs, &field_2, span)?)) - } - (ConstrainedValue::Group(point_1), ConstrainedValue::Group(point_2)) => { - Ok(ConstrainedValue::Group(point_1.add(cs, &point_2, span)?)) - } - (val_1, val_2) => { - return Err(CompilerError::incompatible_types(format!("{} + {}", val_1, val_2), span).into()); - } - } -} diff --git a/compiler/src/unused/expression/arithmetic/bit_not.rs b/compiler/src/unused/expression/arithmetic/bit_not.rs deleted file mode 100644 index 639fb5aac1..0000000000 --- a/compiler/src/unused/expression/arithmetic/bit_not.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a logical `!` operator in a resolved Leo program. - -use crate::{value::ConstrainedValue, GroupType}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; - -pub fn evaluate_bit_not<'a, F: PrimeField, G: GroupType>( - value: ConstrainedValue<'a, F, G>, - span: &Span, -) -> Result> { - return Err(CompilerError::cannot_evaluate_expression(format!("!{}", value), span).into()); -} diff --git a/compiler/src/unused/expression/arithmetic/div.rs b/compiler/src/unused/expression/arithmetic/div.rs deleted file mode 100644 index b7020fa73a..0000000000 --- a/compiler/src/unused/expression/arithmetic/div.rs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces an arithmetic `/` operator in a resolved Leo program. - -use crate::{value::ConstrainedValue, GroupType}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -pub fn enforce_div<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - left: ConstrainedValue<'a, F, G>, - right: ConstrainedValue<'a, F, G>, - span: &Span, -) -> Result> { - match (left, right) { - (ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => { - Ok(ConstrainedValue::Integer(num_1.div(cs, num_2, span)?)) - } - (ConstrainedValue::Field(field_1), ConstrainedValue::Field(field_2)) => { - Ok(ConstrainedValue::Field(field_1.div(cs, &field_2, span)?)) - } - (val_1, val_2) => { - return Err(CompilerError::incompatible_types(format!("{} / {}", val_1, val_2,), span).into()); - } - } -} diff --git a/compiler/src/unused/expression/arithmetic/mod.rs b/compiler/src/unused/expression/arithmetic/mod.rs deleted file mode 100644 index ac3b50d26b..0000000000 --- a/compiler/src/unused/expression/arithmetic/mod.rs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce arithmetic expressions in a compiled Leo program. - -pub mod add; -pub use self::add::*; - -pub mod sub; -pub use self::sub::*; - -pub mod negate; -pub use self::negate::*; - -pub mod mul; -pub use self::mul::*; - -pub mod div; -pub use self::div::*; - -pub mod pow; -pub use self::pow::*; - -pub mod bit_not; -pub use self::bit_not::*; diff --git a/compiler/src/unused/expression/arithmetic/mul.rs b/compiler/src/unused/expression/arithmetic/mul.rs deleted file mode 100644 index 3ccb38dda6..0000000000 --- a/compiler/src/unused/expression/arithmetic/mul.rs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces an arithmetic `*` operator in a resolved Leo program. - -use crate::{value::ConstrainedValue, GroupType}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -pub fn enforce_mul<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - left: ConstrainedValue<'a, F, G>, - right: ConstrainedValue<'a, F, G>, - span: &Span, -) -> Result> { - match (left, right) { - (ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => { - Ok(ConstrainedValue::Integer(num_1.mul(cs, num_2, span)?)) - } - (ConstrainedValue::Field(field_1), ConstrainedValue::Field(field_2)) => { - Ok(ConstrainedValue::Field(field_1.mul(cs, &field_2, span)?)) - } - (val_1, val_2) => { - return Err(CompilerError::incompatible_types(format!("{} * {}", val_1, val_2), span).into()); - } - } -} diff --git a/compiler/src/unused/expression/arithmetic/negate.rs b/compiler/src/unused/expression/arithmetic/negate.rs deleted file mode 100644 index 165f99ec73..0000000000 --- a/compiler/src/unused/expression/arithmetic/negate.rs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a unary negate `-` operator in a resolved Leo program. - -use crate::{value::ConstrainedValue, GroupType}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -pub fn enforce_negate<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - value: ConstrainedValue<'a, F, G>, - span: &Span, -) -> Result> { - match value { - ConstrainedValue::Integer(integer) => Ok(ConstrainedValue::Integer(integer.negate(cs, span)?)), - ConstrainedValue::Field(field) => Ok(ConstrainedValue::Field(field.negate(cs, span)?)), - ConstrainedValue::Group(group) => Ok(ConstrainedValue::Group(group.negate(cs, span)?)), - value => return Err(CompilerError::incompatible_types(format!("-{}", value), span).into()), - } -} diff --git a/compiler/src/unused/expression/arithmetic/pow.rs b/compiler/src/unused/expression/arithmetic/pow.rs deleted file mode 100644 index 6202b98277..0000000000 --- a/compiler/src/unused/expression/arithmetic/pow.rs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces an arithmetic `**` operator in a resolved Leo program. - -use crate::{value::ConstrainedValue, GroupType}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -pub fn enforce_pow<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - left: ConstrainedValue<'a, F, G>, - right: ConstrainedValue<'a, F, G>, - span: &Span, -) -> Result> { - match (left, right) { - (ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => { - Ok(ConstrainedValue::Integer(num_1.pow(cs, num_2, span)?)) - } - (val_1, val_2) => { - return Err(CompilerError::incompatible_types(format!("{} ** {}", val_1, val_2,), span).into()); - } - } -} diff --git a/compiler/src/unused/expression/arithmetic/sub.rs b/compiler/src/unused/expression/arithmetic/sub.rs deleted file mode 100644 index 5c2a4b3b8a..0000000000 --- a/compiler/src/unused/expression/arithmetic/sub.rs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces an arithmetic `-` operator in a resolved Leo program. - -use crate::{value::ConstrainedValue, GroupType}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -pub fn enforce_sub<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - left: ConstrainedValue<'a, F, G>, - right: ConstrainedValue<'a, F, G>, - span: &Span, -) -> Result> { - match (left, right) { - (ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => { - Ok(ConstrainedValue::Integer(num_1.sub(cs, num_2, span)?)) - } - (ConstrainedValue::Field(field_1), ConstrainedValue::Field(field_2)) => { - Ok(ConstrainedValue::Field(field_1.sub(cs, &field_2, span)?)) - } - (ConstrainedValue::Group(point_1), ConstrainedValue::Group(point_2)) => { - Ok(ConstrainedValue::Group(point_1.sub(cs, &point_2, span)?)) - } - (val_1, val_2) => { - return Err(CompilerError::incompatible_types(format!("{} - {}", val_1, val_2), span).into()); - } - } -} diff --git a/compiler/src/unused/expression/array/access.rs b/compiler/src/unused/expression/array/access.rs deleted file mode 100644 index 340d412561..0000000000 --- a/compiler/src/unused/expression/array/access.rs +++ /dev/null @@ -1,241 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces array access in a compiled Leo program. - -use std::convert::TryInto; - -use crate::{ - arithmetic::*, - program::ConstrainedProgram, - relational::*, - value::{ConstrainedValue, Integer}, - GroupType, -}; -use leo_asg::{ConstInt, Expression}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::{ - boolean::Boolean, - traits::{ - eq::{EqGadget, EvaluateEqGadget}, - select::CondSelectGadget, - }, -}; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub fn array_bounds_check>( - &mut self, - cs: &mut CS, - index_resolved: &Integer, - array_len: u32, - span: &Span, - ) -> Result<()> { - let bounds_check = evaluate_lt::( - cs, - ConstrainedValue::Integer(index_resolved.clone()), - ConstrainedValue::Integer(Integer::new( - &ConstInt::U32(array_len).cast_to(&index_resolved.get_type()), - )), - span, - )?; - let bounds_check = match bounds_check { - ConstrainedValue::Boolean(b) => b, - _ => unimplemented!("illegal non-Integer returned from lt"), - }; - let namespace_string = format!("evaluate array access bounds {}:{}", span.line_start, span.col_start); - let mut unique_namespace = cs.ns(|| namespace_string); - bounds_check - .enforce_equal(&mut unique_namespace, &Boolean::Constant(true)) - .map_err(|e| CompilerError::cannot_enforce_expression("array bounds check", e, span))?; - Ok(()) - } - - #[allow(clippy::too_many_arguments)] - pub fn enforce_array_access>( - &mut self, - cs: &mut CS, - array: &'a Expression<'a>, - index: &'a Expression<'a>, - span: &Span, - ) -> Result> { - let mut array = match self.enforce_expression(cs, array)? { - ConstrainedValue::Array(array) => array, - value => return Err(CompilerError::undefined_array(value.to_string(), span).into()), - }; - - let index_resolved = self.enforce_index(cs, index, span)?; - if let Some(resolved) = index_resolved.to_usize() { - if resolved >= array.len() { - return Err(CompilerError::array_index_out_of_bounds(resolved, span).into()); - } - Ok(array[resolved].to_owned()) - } else { - if array.is_empty() { - return Err(CompilerError::array_index_out_of_bounds(0, span).into()); - } - - { - let array_len: u32 = array - .len() - .try_into() - .map_err(|_| CompilerError::array_length_out_of_bounds(span))?; - self.array_bounds_check(cs, &index_resolved, array_len, span)?; - } - - let mut current_value = array.pop().unwrap(); - for (i, item) in array.into_iter().enumerate() { - let namespace_string = format!("evaluate array access eq {} {}:{}", i, span.line_start, span.col_start); - let eq_namespace = cs.ns(|| namespace_string); - - let index_bounded = i - .try_into() - .map_err(|_| CompilerError::array_index_out_of_legal_bounds(span))?; - let const_index = ConstInt::U32(index_bounded).cast_to(&index_resolved.get_type()); - let index_comparison = index_resolved - .evaluate_equal(eq_namespace, &Integer::new(&const_index)) - .map_err(|_| CompilerError::cannot_evaluate_expression("==", span))?; - - let unique_namespace = - cs.ns(|| format!("select array access {} {}:{}", i, span.line_start, span.col_start)); - let value = - ConstrainedValue::conditionally_select(unique_namespace, &index_comparison, &item, ¤t_value) - .map_err(|e| CompilerError::cannot_enforce_expression("conditional select", e, span))?; - current_value = value; - } - Ok(current_value) - } - } - - #[allow(clippy::too_many_arguments)] - pub fn enforce_array_range_access>( - &mut self, - cs: &mut CS, - array: &'a Expression<'a>, - left: Option<&'a Expression<'a>>, - right: Option<&'a Expression<'a>>, - length: usize, - span: &Span, - ) -> Result> { - let array = match self.enforce_expression(cs, array)? { - ConstrainedValue::Array(array) => array, - value => return Err(CompilerError::undefined_array(value, span).into()), - }; - - let from_resolved = match left { - Some(from_index) => self.enforce_index(cs, from_index, span)?, - None => Integer::new(&ConstInt::U32(0)), // Array slice starts at index 0 - }; - let to_resolved = match right { - Some(to_index) => self.enforce_index(cs, to_index, span)?, - None => { - let index_bounded: u32 = array - .len() - .try_into() - .map_err(|_| CompilerError::array_length_out_of_bounds(span))?; - Integer::new(&ConstInt::U32(index_bounded)) - } // Array slice ends at array length - }; - let const_dimensions = match (from_resolved.to_usize(), to_resolved.to_usize()) { - (Some(from), Some(to)) => Some((from, to)), - (Some(from), None) => Some((from, from + length)), - (None, Some(to)) => Some((to - length, to)), - (None, None) => None, - }; - Ok(if let Some((left, right)) = const_dimensions { - if right - left != length { - return Err(CompilerError::array_invalid_slice_length(span).into()); - } - if right > array.len() { - return Err(CompilerError::array_index_out_of_bounds(right, span).into()); - } - ConstrainedValue::Array(array[left..right].to_owned()) - } else { - { - let calc_len = enforce_sub::( - cs, - ConstrainedValue::Integer(to_resolved.clone()), - ConstrainedValue::Integer(from_resolved.clone()), - span, - )?; - let calc_len = match calc_len { - ConstrainedValue::Integer(i) => i, - _ => unimplemented!("illegal non-Integer returned from sub"), - }; - let namespace_string = format!( - "evaluate array range access length check {}:{}", - span.line_start, span.col_start - ); - let mut unique_namespace = cs.ns(|| namespace_string); - calc_len - .enforce_equal(&mut unique_namespace, &Integer::new(&ConstInt::U32(length as u32))) - .map_err(|e| CompilerError::cannot_enforce_expression("array length check", e, span))?; - } - { - let bounds_check = evaluate_le::( - cs, - ConstrainedValue::Integer(to_resolved), - ConstrainedValue::Integer(Integer::new(&ConstInt::U32(array.len() as u32))), - span, - )?; - let bounds_check = match bounds_check { - ConstrainedValue::Boolean(b) => b, - _ => unimplemented!("illegal non-Integer returned from le"), - }; - let namespace_string = format!( - "evaluate array range access bounds {}:{}", - span.line_start, span.col_start - ); - let mut unique_namespace = cs.ns(|| namespace_string); - bounds_check - .enforce_equal(&mut unique_namespace, &Boolean::Constant(true)) - .map_err(|e| CompilerError::cannot_enforce_expression("array bounds check", e, span))?; - } - let mut windows = array.windows(length); - let mut result = ConstrainedValue::Array(vec![]); - - for i in 0..length { - let window = if let Some(window) = windows.next() { - window - } else { - break; - }; - let array_value = ConstrainedValue::Array(window.to_vec()); - let mut unique_namespace = - cs.ns(|| format!("array index eq-check {} {}:{}", i, span.line_start, span.col_start)); - - let equality = evaluate_eq::( - &mut unique_namespace, - ConstrainedValue::Integer(from_resolved.clone()), - ConstrainedValue::Integer(Integer::new(&ConstInt::U32(i as u32))), - span, - )?; - let equality = match equality { - ConstrainedValue::Boolean(b) => b, - _ => unimplemented!("unexpected non-Boolean for evaluate_eq"), - }; - - let unique_namespace = - unique_namespace.ns(|| format!("array index {} {}:{}", i, span.line_start, span.col_start)); - result = ConstrainedValue::conditionally_select(unique_namespace, &equality, &array_value, &result) - .map_err(|e| CompilerError::cannot_enforce_expression("conditional select", e, span))?; - } - result - }) - } -} diff --git a/compiler/src/unused/expression/array/array.rs b/compiler/src/unused/expression/array/array.rs deleted file mode 100644 index e8c3979c39..0000000000 --- a/compiler/src/unused/expression/array/array.rs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces an array expression in a compiled Leo program. - -use std::cell::Cell; - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::Expression; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - /// Enforce array expressions - pub fn enforce_array>( - &mut self, - cs: &mut CS, - array: &[(Cell<&'a Expression<'a>>, bool)], - span: &Span, - ) -> Result> { - let expected_dimension: Option = None; - - let mut result = vec![]; - for (element, is_spread) in array.iter() { - let element_value = self.enforce_expression(cs, element.get())?; - if *is_spread { - match element_value { - ConstrainedValue::Array(array) => result.extend(array), - _ => unimplemented!(), // type should already be checked - } - } else { - result.push(element_value); - } - } - - // Check expected_dimension if given. - if let Some(dimension) = expected_dimension { - // Return an error if the expected dimension != the actual dimension. - if dimension != result.len() { - return Err(CompilerError::unexpected_array_length(dimension, result.len(), span).into()); - } - } - - Ok(ConstrainedValue::Array(result)) - } - - /// - /// Returns an array value from an array initializer expression. - /// - #[allow(clippy::too_many_arguments)] - pub fn enforce_array_initializer>( - &mut self, - cs: &mut CS, - element_expression: &'a Expression<'a>, - actual_size: usize, - ) -> Result> { - let mut value = self.enforce_expression(cs, element_expression)?; - - // Allocate the array. - let array = vec![value; actual_size]; - - // Set the array value. - value = ConstrainedValue::Array(array); - - Ok(value) - } -} diff --git a/compiler/src/unused/expression/array/index.rs b/compiler/src/unused/expression/array/index.rs deleted file mode 100644 index 8873325eb8..0000000000 --- a/compiler/src/unused/expression/array/index.rs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces an array index expression in a compiled Leo program. - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType, Integer}; -use leo_asg::Expression; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub(crate) fn enforce_index>( - &mut self, - cs: &mut CS, - index: &'a Expression<'a>, - span: &Span, - ) -> Result { - match self.enforce_expression(cs, index)? { - ConstrainedValue::Integer(number) => Ok(number), - value => Err(CompilerError::invalid_index_expression(value, span).into()), - } - } -} diff --git a/compiler/src/unused/expression/array/mod.rs b/compiler/src/unused/expression/array/mod.rs deleted file mode 100644 index c2cf2af54a..0000000000 --- a/compiler/src/unused/expression/array/mod.rs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce array expressions in a compiled Leo program. - -pub mod array; -pub use self::array::*; - -pub mod access; -pub use self::access::*; - -pub mod index; -pub use self::index::*; diff --git a/compiler/src/unused/expression/binary/binary.rs b/compiler/src/unused/expression/binary/binary.rs deleted file mode 100644 index be91649e3f..0000000000 --- a/compiler/src/unused/expression/binary/binary.rs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a binary expression in a compiled Leo program. - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::Expression; -use leo_errors::Result; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -type ConstrainedValuePair<'a, T, U> = (ConstrainedValue<'a, T, U>, ConstrainedValue<'a, T, U>); - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - #[allow(clippy::too_many_arguments)] - pub fn enforce_binary_expression>( - &mut self, - cs: &mut CS, - left: &'a Expression<'a>, - right: &'a Expression<'a>, - ) -> Result> { - let resolved_left = { - let mut left_namespace = cs.ns(|| "left".to_string()); - self.enforce_expression(&mut left_namespace, left)? - }; - - let resolved_right = { - let mut right_namespace = cs.ns(|| "right".to_string()); - self.enforce_expression(&mut right_namespace, right)? - }; - - Ok((resolved_left, resolved_right)) - } -} diff --git a/compiler/src/unused/expression/binary/mod.rs b/compiler/src/unused/expression/binary/mod.rs deleted file mode 100644 index 8e7eb904d4..0000000000 --- a/compiler/src/unused/expression/binary/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce binary expressions in a compiled Leo program. - -pub mod binary; -pub use self::binary::*; diff --git a/compiler/src/unused/expression/circuit/access.rs b/compiler/src/unused/expression/circuit/access.rs deleted file mode 100644 index 58c0aa9a08..0000000000 --- a/compiler/src/unused/expression/circuit/access.rs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a circuit access expression in a compiled Leo program. - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::{CircuitAccessExpression, Node}; -use leo_errors::{CompilerError, Result}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - #[allow(clippy::too_many_arguments)] - pub fn enforce_circuit_access>( - &mut self, - cs: &mut CS, - expr: &CircuitAccessExpression<'a>, - ) -> Result> { - if let Some(target) = expr.target.get() { - //todo: we can prob pass values by ref here to avoid copying the entire circuit on access - let target_value = self.enforce_expression(cs, target)?; - match target_value { - ConstrainedValue::CircuitExpression(def, members) => { - assert!(def == expr.circuit.get()); - if let Some(member) = members.into_iter().find(|x| x.0.name == expr.member.name) { - Ok(member.1) - } else { - return Err(CompilerError::undefined_circuit_member_access( - expr.circuit.get().name.borrow(), - &expr.member.name, - &expr.member.span, - ) - .into()); - } - } - value => { - return Err( - CompilerError::undefined_circuit(value, &target.span().cloned().unwrap_or_default()).into(), - ); - } - } - } else { - Err(CompilerError::invalid_circuit_static_member_access(&expr.member.name, &expr.member.span).into()) - } - } -} diff --git a/compiler/src/unused/expression/circuit/circuit.rs b/compiler/src/unused/expression/circuit/circuit.rs deleted file mode 100644 index 7732d9b938..0000000000 --- a/compiler/src/unused/expression/circuit/circuit.rs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a circuit expression in a compiled Leo program. - -use crate::{ - program::ConstrainedProgram, - value::{ConstrainedCircuitMember, ConstrainedValue}, - GroupType, -}; -use leo_asg::{CircuitInitExpression, CircuitMember}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub fn enforce_circuit>( - &mut self, - cs: &mut CS, - expr: &CircuitInitExpression<'a>, - span: &Span, - ) -> Result> { - let circuit = expr.circuit.get(); - let members = circuit.members.borrow(); - - let mut resolved_members = Vec::with_capacity(members.len()); - - // type checking is already done in asg - for (name, inner) in expr.values.iter() { - let target = members - .get(name.name.as_ref()) - .expect("illegal name in asg circuit init expression"); - match target { - CircuitMember::Variable(_type_) => { - let variable_value = self.enforce_expression(cs, inner.get())?; - resolved_members.push(ConstrainedCircuitMember(name.clone(), variable_value)); - } - _ => { - return Err(CompilerError::expected_circuit_member(name, span).into()); - } - } - } - - let value = ConstrainedValue::CircuitExpression(circuit, resolved_members); - Ok(value) - } -} diff --git a/compiler/src/unused/expression/circuit/mod.rs b/compiler/src/unused/expression/circuit/mod.rs deleted file mode 100644 index 321ffea674..0000000000 --- a/compiler/src/unused/expression/circuit/mod.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce circuit expressions in a compiled Leo program. - -pub mod access; -pub use self::access::*; - -pub mod circuit; -pub use self::circuit::*; diff --git a/compiler/src/unused/expression/conditional/conditional.rs b/compiler/src/unused/expression/conditional/conditional.rs deleted file mode 100644 index 661aef7335..0000000000 --- a/compiler/src/unused/expression/conditional/conditional.rs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a conditional expression in a compiled Leo program. - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::Expression; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::traits::select::CondSelectGadget; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - /// Enforce ternary conditional expression - #[allow(clippy::too_many_arguments)] - pub fn enforce_conditional_expression>( - &mut self, - cs: &mut CS, - conditional: &'a Expression<'a>, - first: &'a Expression<'a>, - second: &'a Expression<'a>, - span: &Span, - ) -> Result> { - let conditional_value = match self.enforce_expression(cs, conditional)? { - ConstrainedValue::Boolean(resolved) => resolved, - value => { - return Err(CompilerError::conditional_boolean_expression_fails_to_resolve_to_bool(value, span).into()); - } - }; - - let first_value = self.enforce_expression(cs, first)?; - - let second_value = self.enforce_expression(cs, second)?; - - let unique_namespace = cs.ns(|| { - format!( - "select {} or {} {}:{}", - first_value, second_value, span.line_start, span.col_start - ) - }); - - Ok( - ConstrainedValue::conditionally_select(unique_namespace, &conditional_value, &first_value, &second_value) - .map_err(|e| CompilerError::cannot_enforce_expression("conditional select", e, span))?, - ) - } -} diff --git a/compiler/src/unused/expression/conditional/mod.rs b/compiler/src/unused/expression/conditional/mod.rs deleted file mode 100644 index 8e0f8d1b32..0000000000 --- a/compiler/src/unused/expression/conditional/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce conditional expressions in a compiled Leo program. - -pub mod conditional; -pub use self::conditional::*; diff --git a/compiler/src/unused/expression/expression.rs b/compiler/src/unused/expression/expression.rs deleted file mode 100644 index c9be0b60cd..0000000000 --- a/compiler/src/unused/expression/expression.rs +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforce constraints on an expression in a compiled Leo program. - -use crate::{ - arithmetic::*, - logical::*, - program::ConstrainedProgram, - relational::*, - // resolve_core_circuit, - value::{Address, Char, CharType, ConstrainedCircuitMember, ConstrainedValue, Integer}, - FieldType, - GroupType, -}; -use leo_asg::{expression::*, ConstValue, Expression, Node}; -use leo_errors::{Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::boolean::Boolean; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub(crate) fn enforce_const_value>( - &mut self, - cs: &mut CS, - value: &'a ConstValue<'a>, - span: &Span, - ) -> Result> { - Ok(match value { - ConstValue::Address(value) => ConstrainedValue::Address(Address::constant(value.to_string(), span)?), - ConstValue::Boolean(value) => ConstrainedValue::Boolean(Boolean::Constant(*value)), - ConstValue::Char(value) => { - use leo_asg::CharValue::*; - match value { - Scalar(scalar) => ConstrainedValue::Char(Char::constant( - cs, - CharType::Scalar(*scalar), - format!("{}", *scalar as u32), - span, - )?), - NonScalar(non_scalar) => ConstrainedValue::Char(Char::constant( - cs, - CharType::NonScalar(*non_scalar), - format!("{}", *non_scalar), - span, - )?), - } - } - ConstValue::Field(value) => ConstrainedValue::Field(FieldType::constant(cs, value.to_string(), span)?), - ConstValue::Group(value) => ConstrainedValue::Group(G::constant(value, span)?), - ConstValue::Int(value) => ConstrainedValue::Integer(Integer::new(value)), - ConstValue::Tuple(values) => ConstrainedValue::Tuple( - values - .iter() - .map(|x| self.enforce_const_value(cs, x, span)) - .collect::, _>>()?, - ), - ConstValue::Array(values) => ConstrainedValue::Array( - values - .iter() - .map(|x| self.enforce_const_value(cs, x, span)) - .collect::, _>>()?, - ), - ConstValue::Circuit(circuit, members) => { - let mut constrained_members = Vec::new(); - for (_, (identifier, member)) in members.iter() { - constrained_members.push(ConstrainedCircuitMember( - identifier.clone(), - self.enforce_const_value(cs, member, span)?, - )); - } - - ConstrainedValue::CircuitExpression(circuit, constrained_members) - } - }) - } - - pub(crate) fn enforce_expression>( - &mut self, - cs: &mut CS, - expression: &'a Expression<'a>, - ) -> Result> { - let span = &expression.span().cloned().unwrap_or_default(); - match expression { - // Cast - Expression::Cast(_) => unimplemented!("casts not implemented"), - - // LengthOf - Expression::LengthOf(lengthof) => self.enforce_lengthof(cs, lengthof, span), - - // Variables - Expression::VariableRef(variable_ref) => self.evaluate_ref(variable_ref), - - // Values - Expression::Constant(Constant { value, .. }) => self.enforce_const_value(cs, value, span), - - // Binary operations - Expression::Binary(BinaryExpression { - left, right, operation, .. - }) => { - let (resolved_left, resolved_right) = self.enforce_binary_expression(cs, left.get(), right.get())?; - - match operation { - BinaryOperation::Add => enforce_add(cs, resolved_left, resolved_right, span), - BinaryOperation::Sub => enforce_sub(cs, resolved_left, resolved_right, span), - BinaryOperation::Mul => enforce_mul(cs, resolved_left, resolved_right, span), - BinaryOperation::Div => enforce_div(cs, resolved_left, resolved_right, span), - BinaryOperation::Pow => enforce_pow(cs, resolved_left, resolved_right, span), - BinaryOperation::Or => enforce_or(cs, resolved_left, resolved_right, span), - BinaryOperation::And => enforce_and(cs, resolved_left, resolved_right, span), - BinaryOperation::Eq => evaluate_eq(cs, resolved_left, resolved_right, span), - BinaryOperation::Ne => evaluate_not(evaluate_eq(cs, resolved_left, resolved_right, span)?, span), - BinaryOperation::Ge => evaluate_ge(cs, resolved_left, resolved_right, span), - BinaryOperation::Gt => evaluate_gt(cs, resolved_left, resolved_right, span), - BinaryOperation::Le => evaluate_le(cs, resolved_left, resolved_right, span), - BinaryOperation::Lt => evaluate_lt(cs, resolved_left, resolved_right, span), - _ => unimplemented!("unimplemented binary operator"), - } - } - - // Unary operations - Expression::Unary(UnaryExpression { inner, operation, .. }) => match operation { - UnaryOperation::Negate => { - let resolved_inner = self.enforce_expression(cs, inner.get())?; - enforce_negate(cs, resolved_inner, span) - } - UnaryOperation::Not => Ok(evaluate_not(self.enforce_expression(cs, inner.get())?, span)?), - _ => unimplemented!("unimplemented unary operator"), - }, - - Expression::Ternary(TernaryExpression { - condition, - if_true, - if_false, - .. - }) => self.enforce_conditional_expression(cs, condition.get(), if_true.get(), if_false.get(), span), - - // Arrays - Expression::ArrayInline(ArrayInlineExpression { elements, .. }) => { - self.enforce_array(cs, &elements[..], span) - } - Expression::ArrayInit(ArrayInitExpression { element, len, .. }) => { - self.enforce_array_initializer(cs, element.get(), *len) - } - Expression::ArrayAccess(ArrayAccessExpression { array, index, .. }) => { - self.enforce_array_access(cs, array.get(), index.get(), span) - } - Expression::ArrayRangeAccess(ArrayRangeAccessExpression { - array, - left, - right, - length, - .. - }) => self.enforce_array_range_access(cs, array.get(), left.get(), right.get(), *length, span), - - // Tuples - Expression::TupleInit(TupleInitExpression { elements, .. }) => self.enforce_tuple(cs, &elements[..]), - Expression::TupleAccess(TupleAccessExpression { tuple_ref, index, .. }) => { - self.enforce_tuple_access(cs, tuple_ref.get(), *index, span) - } - - // Circuits - Expression::CircuitInit(expr) => self.enforce_circuit(cs, expr, span), - Expression::CircuitAccess(expr) => self.enforce_circuit_access(cs, expr), - - // Functions - Expression::Call(CallExpression { - function, - target, - arguments, - .. - }) => { - if let Some(circuit) = function.get().circuit.get() { - let core_mapping = circuit.core_mapping.borrow(); - if let Some(core_mapping) = core_mapping.as_deref() { - unimplemented!("core circuits are not supported yet {}", core_mapping) - } - } - self.enforce_function_call_expression(cs, function.get(), target.get(), &arguments[..], span) - } - } - } -} diff --git a/compiler/src/unused/expression/function/core_circuit.rs b/compiler/src/unused/expression/function/core_circuit.rs deleted file mode 100644 index 3a596b132c..0000000000 --- a/compiler/src/unused/expression/function/core_circuit.rs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use std::cell::Cell; - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, CoreCircuit, GroupType}; - -use leo_asg::{Expression, Function}; -use leo_errors::{Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - /// Call a default core circuit function with arguments - #[allow(clippy::too_many_arguments)] - pub fn enforce_core_circuit_call_expression, C: CoreCircuit<'a, F, G>>( - &mut self, - cs: &mut CS, - core_circuit: &C, - function: &'a Function<'a>, - target: Option<&'a Expression<'a>>, - arguments: &[Cell<&'a Expression<'a>>], - span: &Span, - ) -> Result> { - let target_value = target.map(|target| self.enforce_expression(cs, target)).transpose()?; - - // Get the value of each core function argument - let arguments = arguments - .iter() - .map(|argument| self.enforce_expression(cs, argument.get())) - .collect::, _>>()?; - - // Call the core function - let return_value = core_circuit.call_function(cs, function, span, target_value, arguments)?; - - Ok(return_value) - } -} diff --git a/compiler/src/unused/expression/function/function.rs b/compiler/src/unused/expression/function/function.rs deleted file mode 100644 index 538945ef81..0000000000 --- a/compiler/src/unused/expression/function/function.rs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforce a function call expression in a compiled Leo program. - -use std::cell::Cell; - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::{Expression, Function}; -use leo_errors::{Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - #[allow(clippy::too_many_arguments)] - pub fn enforce_function_call_expression>( - &mut self, - cs: &mut CS, - function: &'a Function<'a>, - target: Option<&'a Expression<'a>>, - arguments: &[Cell<&'a Expression<'a>>], - span: &Span, - ) -> Result> { - let name_unique = || { - format!( - "function call {} {}:{}", - function.name.borrow().clone(), - span.line_start, - span.col_start, - ) - }; - - let return_value = self.enforce_function(&mut cs.ns(name_unique), function, target, arguments)?; - - Ok(return_value) - } -} diff --git a/compiler/src/unused/expression/function/mod.rs b/compiler/src/unused/expression/function/mod.rs deleted file mode 100644 index 89e0cf4543..0000000000 --- a/compiler/src/unused/expression/function/mod.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce function call expressions in a compiled Leo program. - -pub mod core_circuit; -pub use self::core_circuit::*; - -pub mod function; -pub use self::function::*; diff --git a/compiler/src/unused/expression/logical/and.rs b/compiler/src/unused/expression/logical/and.rs deleted file mode 100644 index 50c1526eff..0000000000 --- a/compiler/src/unused/expression/logical/and.rs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a logical `&&` operator in a resolved Leo program. - -use crate::{value::ConstrainedValue, GroupType}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::boolean::Boolean; -use snarkvm_r1cs::ConstraintSystem; - -pub fn enforce_and<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - left: ConstrainedValue<'a, F, G>, - right: ConstrainedValue<'a, F, G>, - span: &Span, -) -> Result> { - let name = format!("{} && {}", left, right); - - if let (ConstrainedValue::Boolean(left_bool), ConstrainedValue::Boolean(right_bool)) = (left, right) { - let result = Boolean::and( - cs.ns(|| format!("{} {}:{}", name, span.line_start, span.col_start)), - &left_bool, - &right_bool, - ) - .map_err(|e| CompilerError::cannot_enforce_expression("&&", e, span))?; - - return Ok(ConstrainedValue::Boolean(result)); - } - - Err(CompilerError::cannot_evaluate_expression(name, span).into()) -} diff --git a/compiler/src/unused/expression/logical/mod.rs b/compiler/src/unused/expression/logical/mod.rs deleted file mode 100644 index 699e39da6b..0000000000 --- a/compiler/src/unused/expression/logical/mod.rs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce logical expressions in a compiled Leo program. - -pub mod and; -pub use self::and::*; - -pub mod not; -pub use self::not::*; - -pub mod or; -pub use self::or::*; diff --git a/compiler/src/unused/expression/logical/not.rs b/compiler/src/unused/expression/logical/not.rs deleted file mode 100644 index 8ebc132037..0000000000 --- a/compiler/src/unused/expression/logical/not.rs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a logical `!` operator in a resolved Leo program. - -use crate::{value::ConstrainedValue, GroupType}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; - -pub fn evaluate_not<'a, F: PrimeField, G: GroupType>( - value: ConstrainedValue<'a, F, G>, - span: &Span, -) -> Result> { - match value { - ConstrainedValue::Boolean(boolean) => Ok(ConstrainedValue::Boolean(boolean.not())), - value => { - return Err(CompilerError::cannot_evaluate_expression(format!("!{}", value), span).into()); - } - } -} diff --git a/compiler/src/unused/expression/logical/or.rs b/compiler/src/unused/expression/logical/or.rs deleted file mode 100644 index f8ab3a9f84..0000000000 --- a/compiler/src/unused/expression/logical/or.rs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a logical `||` operator in a resolved Leo program. - -use crate::{value::ConstrainedValue, GroupType}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::boolean::Boolean; -use snarkvm_r1cs::ConstraintSystem; - -pub fn enforce_or<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - left: ConstrainedValue<'a, F, G>, - right: ConstrainedValue<'a, F, G>, - span: &Span, -) -> Result> { - let name = format!("{} || {}", left, right); - - if let (ConstrainedValue::Boolean(left_bool), ConstrainedValue::Boolean(right_bool)) = (left, right) { - let result = Boolean::or( - cs.ns(|| format!("{} {}:{}", name, span.line_start, span.col_start)), - &left_bool, - &right_bool, - ) - .map_err(|e| CompilerError::cannot_enforce_expression("||", e, span))?; - - return Ok(ConstrainedValue::Boolean(result)); - } - - Err(CompilerError::cannot_evaluate_expression(name, span).into()) -} diff --git a/compiler/src/unused/expression/mod.rs b/compiler/src/unused/expression/mod.rs deleted file mode 100644 index 6db73571d6..0000000000 --- a/compiler/src/unused/expression/mod.rs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce expressions in a compiled Leo program. - -pub mod arithmetic; -pub use self::arithmetic::*; - -pub mod array; -pub use self::array::*; - -pub mod binary; -pub use self::binary::*; - -pub mod circuit; -pub use self::circuit::*; - -pub mod conditional; -pub use self::conditional::*; - -pub mod expression; -pub use self::expression::*; - -pub mod function; -pub use self::function::*; - -pub mod variable_ref; -pub use self::variable_ref::*; - -pub mod logical; -pub use self::logical::*; - -pub mod operator; -pub use self::operator::*; - -pub mod relational; -pub use self::relational::*; - -pub mod tuple; -pub use self::tuple::*; diff --git a/compiler/src/unused/expression/operator/lengthof.rs b/compiler/src/unused/expression/operator/lengthof.rs deleted file mode 100644 index 8e4b8dc401..0000000000 --- a/compiler/src/unused/expression/operator/lengthof.rs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a lengthof operator in a compiled Leo program. - -use crate::{ - program::ConstrainedProgram, - value::{ConstrainedValue, Integer}, - GroupType, -}; -use leo_asg::{ConstInt, LengthOfExpression}; -use leo_errors::{Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - /// Enforce array expressions - pub fn enforce_lengthof>( - &mut self, - cs: &mut CS, - lengthof: &'a LengthOfExpression<'a>, - span: &Span, - ) -> Result> { - let value = self.enforce_expression(cs, lengthof.inner.get())?; - - Ok(match value { - ConstrainedValue::Array(array) => { - ConstrainedValue::Integer(Integer::new(&ConstInt::U32(array.len() as u32))) - } - _ => return Err(leo_errors::CompilerError::lengthof_can_only_be_used_on_arrays(span).into()), - }) - } -} diff --git a/compiler/src/unused/expression/operator/mod.rs b/compiler/src/unused/expression/operator/mod.rs deleted file mode 100644 index 2d0e37ccc3..0000000000 --- a/compiler/src/unused/expression/operator/mod.rs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub mod lengthof; -pub use self::lengthof::*; diff --git a/compiler/src/unused/expression/relational/eq.rs b/compiler/src/unused/expression/relational/eq.rs deleted file mode 100644 index 7cd39de84f..0000000000 --- a/compiler/src/unused/expression/relational/eq.rs +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a relational `==` operator in a resolved Leo program. - -use crate::{enforce_and, value::ConstrainedValue, GroupType}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::{boolean::Boolean, traits::eq::EvaluateEqGadget}; -use snarkvm_r1cs::ConstraintSystem; - -pub fn evaluate_eq<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - left: ConstrainedValue<'a, F, G>, - right: ConstrainedValue<'a, F, G>, - span: &Span, -) -> Result> { - let namespace_string = format!("evaluate {} == {} {}:{}", left, right, span.line_start, span.col_start); - let constraint_result = match (left, right) { - (ConstrainedValue::Address(address_1), ConstrainedValue::Address(address_2)) => { - let unique_namespace = cs.ns(|| namespace_string); - address_1.evaluate_equal(unique_namespace, &address_2) - } - (ConstrainedValue::Boolean(bool_1), ConstrainedValue::Boolean(bool_2)) => { - let unique_namespace = cs.ns(|| namespace_string); - bool_1.evaluate_equal(unique_namespace, &bool_2) - } - (ConstrainedValue::Char(char_1), ConstrainedValue::Char(char_2)) => { - let unique_namespace = cs.ns(|| namespace_string); - char_1.evaluate_equal(unique_namespace, &char_2) - } - (ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => { - let unique_namespace = cs.ns(|| namespace_string); - num_1.evaluate_equal(unique_namespace, &num_2) - } - (ConstrainedValue::Field(field_1), ConstrainedValue::Field(field_2)) => { - let unique_namespace = cs.ns(|| namespace_string); - field_1.evaluate_equal(unique_namespace, &field_2) - } - (ConstrainedValue::Group(point_1), ConstrainedValue::Group(point_2)) => { - let unique_namespace = cs.ns(|| namespace_string); - point_1.evaluate_equal(unique_namespace, &point_2) - } - (ConstrainedValue::Array(arr_1), ConstrainedValue::Array(arr_2)) => { - let mut current = ConstrainedValue::Boolean(Boolean::constant(true)); - - if arr_1.len() != arr_2.len() { - return Err(CompilerError::array_sizes_must_match_in_eq(arr_1.len(), arr_2.len(), span).into()); - } - - for (i, (left, right)) in arr_1.into_iter().zip(arr_2.into_iter()).enumerate() { - let next = evaluate_eq(&mut cs.ns(|| format!("array[{}]", i)), left, right, span)?; - - current = enforce_and(&mut cs.ns(|| format!("array result {}", i)), current, next, span)?; - } - return Ok(current); - } - (ConstrainedValue::Tuple(tuple_1), ConstrainedValue::Tuple(tuple_2)) => { - let mut current = ConstrainedValue::Boolean(Boolean::constant(true)); - - for (i, (left, right)) in tuple_1.into_iter().zip(tuple_2.into_iter()).enumerate() { - let next = evaluate_eq(&mut cs.ns(|| format!("tuple_index {}", i)), left, right, span)?; - - current = enforce_and(&mut cs.ns(|| format!("array result {}", i)), current, next, span)?; - } - return Ok(current); - } - (val_1, val_2) => { - return Err(CompilerError::incompatible_types(format!("{} == {}", val_1, val_2,), span).into()); - } - }; - - let boolean = constraint_result.map_err(|_| CompilerError::cannot_evaluate_expression("==", span))?; - - Ok(ConstrainedValue::Boolean(boolean)) -} diff --git a/compiler/src/unused/expression/relational/ge.rs b/compiler/src/unused/expression/relational/ge.rs deleted file mode 100644 index 958588dce9..0000000000 --- a/compiler/src/unused/expression/relational/ge.rs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a relational `>=` operator in a resolved Leo program. - -use crate::{value::ConstrainedValue, GroupType}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::traits::bits::ComparatorGadget; -use snarkvm_r1cs::ConstraintSystem; - -pub fn evaluate_ge<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - left: ConstrainedValue<'a, F, G>, - right: ConstrainedValue<'a, F, G>, - span: &Span, -) -> Result> { - let unique_namespace = cs.ns(|| format!("evaluate {} >= {} {}:{}", left, right, span.line_start, span.col_start)); - let constraint_result = match (left, right) { - (ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => { - num_1.greater_than_or_equal(unique_namespace, &num_2) - } - (val_1, val_2) => { - return Err(CompilerError::incompatible_types(format!("{} >= {}", val_1, val_2), span).into()); - } - }; - - let boolean = constraint_result.map_err(|_| CompilerError::cannot_evaluate_expression(">=", span))?; - - Ok(ConstrainedValue::Boolean(boolean)) -} diff --git a/compiler/src/unused/expression/relational/gt.rs b/compiler/src/unused/expression/relational/gt.rs deleted file mode 100644 index ab3f06868c..0000000000 --- a/compiler/src/unused/expression/relational/gt.rs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a relational `>` operator in a resolved Leo program. - -use crate::{value::ConstrainedValue, GroupType}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::traits::bits::ComparatorGadget; -use snarkvm_r1cs::ConstraintSystem; - -pub fn evaluate_gt<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - left: ConstrainedValue<'a, F, G>, - right: ConstrainedValue<'a, F, G>, - span: &Span, -) -> Result> { - let unique_namespace = cs.ns(|| format!("evaluate {} > {} {}:{}", left, right, span.line_start, span.col_start)); - let constraint_result = match (left, right) { - (ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => { - num_1.greater_than(unique_namespace, &num_2) - } - (val_1, val_2) => { - return Err(CompilerError::incompatible_types(format!("{} > {}", val_1, val_2), span).into()); - } - }; - - let boolean = constraint_result.map_err(|_| CompilerError::cannot_evaluate_expression(">", span))?; - - Ok(ConstrainedValue::Boolean(boolean)) -} diff --git a/compiler/src/unused/expression/relational/le.rs b/compiler/src/unused/expression/relational/le.rs deleted file mode 100644 index e1f1e57131..0000000000 --- a/compiler/src/unused/expression/relational/le.rs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a relational `<=` operator in a resolved Leo program. - -use crate::{value::ConstrainedValue, GroupType}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::traits::bits::ComparatorGadget; -use snarkvm_r1cs::ConstraintSystem; - -pub fn evaluate_le<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - left: ConstrainedValue<'a, F, G>, - right: ConstrainedValue<'a, F, G>, - span: &Span, -) -> Result> { - let unique_namespace = cs.ns(|| format!("evaluate {} <= {} {}:{}", left, right, span.line_start, span.col_start)); - let constraint_result = match (left, right) { - (ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => { - num_1.less_than_or_equal(unique_namespace, &num_2) - } - (val_1, val_2) => { - return Err(CompilerError::incompatible_types(format!("{} <= {}", val_1, val_2), span).into()); - } - }; - - let boolean = constraint_result.map_err(|_| CompilerError::cannot_evaluate_expression("<=", span))?; - - Ok(ConstrainedValue::Boolean(boolean)) -} diff --git a/compiler/src/unused/expression/relational/lt.rs b/compiler/src/unused/expression/relational/lt.rs deleted file mode 100644 index 839ea7fb7a..0000000000 --- a/compiler/src/unused/expression/relational/lt.rs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a relational `<` operator in a resolved Leo program. - -use crate::{value::ConstrainedValue, GroupType}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::traits::bits::EvaluateLtGadget; -use snarkvm_r1cs::ConstraintSystem; - -pub fn evaluate_lt<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - left: ConstrainedValue<'a, F, G>, - right: ConstrainedValue<'a, F, G>, - span: &Span, -) -> Result> { - let unique_namespace = cs.ns(|| format!("evaluate {} < {} {}:{}", left, right, span.line_start, span.col_start)); - let constraint_result = match (left, right) { - (ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => { - num_1.less_than(unique_namespace, &num_2) - } - (val_1, val_2) => { - return Err(CompilerError::incompatible_types(format!("{} < {}", val_1, val_2), span).into()); - } - }; - - let boolean = constraint_result.map_err(|_| CompilerError::cannot_evaluate_expression("<", span))?; - - Ok(ConstrainedValue::Boolean(boolean)) -} diff --git a/compiler/src/unused/expression/relational/mod.rs b/compiler/src/unused/expression/relational/mod.rs deleted file mode 100644 index 0f064a5d8e..0000000000 --- a/compiler/src/unused/expression/relational/mod.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce constraints on relational expressions in a compiled Leo program. - -pub mod eq; -pub use self::eq::*; - -pub mod ge; -pub use self::ge::*; - -pub mod gt; -pub use self::gt::*; - -pub mod le; -pub use self::le::*; - -pub mod lt; -pub use self::lt::*; diff --git a/compiler/src/unused/expression/tuple/access.rs b/compiler/src/unused/expression/tuple/access.rs deleted file mode 100644 index 59a823ae3b..0000000000 --- a/compiler/src/unused/expression/tuple/access.rs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces array access in a compiled Leo program. - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::Expression; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - #[allow(clippy::too_many_arguments)] - pub fn enforce_tuple_access>( - &mut self, - cs: &mut CS, - tuple: &'a Expression<'a>, - index: usize, - span: &Span, - ) -> Result> { - // Get the tuple values. - let tuple = match self.enforce_expression(cs, tuple)? { - ConstrainedValue::Tuple(tuple) => tuple, - value => return Err(CompilerError::undefined_array(value, span).into()), - }; - - // Check for out of bounds access. - if index > tuple.len() - 1 { - // probably safe to be a panic here - return Err(CompilerError::tuple_index_out_of_bounds(index, span).into()); - } - - Ok(tuple[index].to_owned()) - } -} diff --git a/compiler/src/unused/expression/tuple/mod.rs b/compiler/src/unused/expression/tuple/mod.rs deleted file mode 100644 index ab52716476..0000000000 --- a/compiler/src/unused/expression/tuple/mod.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce tuple expressions in a compiled Leo program. - -pub mod access; -pub use self::access::*; - -pub mod tuple; -pub use self::tuple::*; diff --git a/compiler/src/unused/expression/tuple/tuple.rs b/compiler/src/unused/expression/tuple/tuple.rs deleted file mode 100644 index 95dc276d79..0000000000 --- a/compiler/src/unused/expression/tuple/tuple.rs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces an tuple expression in a compiled Leo program. - -use std::cell::Cell; - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::Expression; -use leo_errors::Result; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - /// Enforce tuple expressions - pub fn enforce_tuple>( - &mut self, - cs: &mut CS, - tuple: &[Cell<&'a Expression<'a>>], - ) -> Result> { - let mut result = Vec::with_capacity(tuple.len()); - for expression in tuple.iter() { - result.push(self.enforce_expression(cs, expression.get())?); - } - - Ok(ConstrainedValue::Tuple(result)) - } -} diff --git a/compiler/src/unused/expression/variable_ref/mod.rs b/compiler/src/unused/expression/variable_ref/mod.rs deleted file mode 100644 index d674eb1d50..0000000000 --- a/compiler/src/unused/expression/variable_ref/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce identifier expressions in a compiled Leo program. - -pub mod variable_ref; -pub use self::variable_ref::*; diff --git a/compiler/src/unused/expression/variable_ref/variable_ref.rs b/compiler/src/unused/expression/variable_ref/variable_ref.rs deleted file mode 100644 index a27f3d13e6..0000000000 --- a/compiler/src/unused/expression/variable_ref/variable_ref.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces an identifier expression in a compiled Leo program. - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::VariableRef; -use leo_errors::{CompilerError, Result}; - -use snarkvm_fields::PrimeField; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - /// Enforce a variable expression by getting the resolved value - pub fn evaluate_ref(&mut self, variable_ref: &VariableRef) -> Result> { - // Evaluate the identifier name in the current function scope - let span = variable_ref.span.clone(); - let variable = variable_ref.variable.borrow(); - - let result_value = if let Some(value) = self.get(variable.id) { - value.clone() - } else { - return Err( - CompilerError::undefined_identifier(&variable.name.clone().name, &span.unwrap_or_default()).into(), - ); - // todo: probably can be a panic here instead - }; - - Ok(result_value) - } -} diff --git a/compiler/src/unused/function/function.rs b/compiler/src/unused/function/function.rs deleted file mode 100644 index 4bbf4fa87f..0000000000 --- a/compiler/src/unused/function/function.rs +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces constraints on a function in a compiled Leo program. - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; - -use leo_asg::{Expression, Function, FunctionQualifier}; -use leo_errors::{CompilerError, Result}; -use std::cell::Cell; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::boolean::Boolean; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub(crate) fn enforce_function>( - &mut self, - cs: &mut CS, - function: &'a Function<'a>, - target: Option<&'a Expression<'a>>, - arguments: &[Cell<&'a Expression<'a>>], - ) -> Result> { - let target_value = target.map(|target| self.enforce_expression(cs, target)).transpose()?; - - let self_var = if let Some(target) = &target_value { - let self_var = function - .scope - .resolve_variable("self") - .expect("attempted to call static function from non-static context"); - self.store(self_var.borrow().id, target.clone()); - Some(self_var) - } else { - None - }; - - if function.arguments.len() != arguments.len() { - return Err(CompilerError::function_input_not_found( - &function.name.borrow().name.to_string(), - "arguments length invalid", - &function.span.clone().unwrap_or_default(), - ) - .into()); - } - - // Store input values as new variables in resolved program - for ((_, variable), input_expression) in function.arguments.iter().zip(arguments.iter()) { - let input_value = self.enforce_expression(cs, input_expression.get())?; - let variable = variable.get().borrow(); - - self.store(variable.id, input_value); - } - - // Evaluate every statement in the function and save all potential results - let mut results = vec![]; - let indicator = Boolean::constant(true); - - let output = function.output.clone(); - - let mut result = self.enforce_statement( - cs, - &indicator, - function.body.get().expect("attempted to call function header"), - )?; - - results.append(&mut result); - - if function.qualifier == FunctionQualifier::MutSelfRef { - if let (Some(self_var), Some(target)) = (self_var, target) { - let new_self = self - .get(self_var.borrow().id) - .expect("no self variable found in mut self context") - .clone(); - - if !self.resolve_mut_ref(cs, target, new_self, &indicator)? { - // todo: we should report a warning for calling a mutable function on an effectively copied self (i.e. wasn't assignable `tempStruct {x: 5}.myMutSelfFunction()`) - } - } - } - - // Conditionally select a result based on returned indicators - Self::conditionally_select_result(cs, &output, results, &function.span.clone().unwrap_or_default()) - } -} diff --git a/compiler/src/unused/function/input/array.rs b/compiler/src/unused/function/input/array.rs deleted file mode 100644 index 47da5b93f8..0000000000 --- a/compiler/src/unused/function/input/array.rs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Allocates an array as a main function input parameter in a compiled Leo program. - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; - -use leo_asg::Type; -use leo_ast::InputValue; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub fn allocate_array>( - &mut self, - cs: &mut CS, - name: &str, - array_type: &Type, - array_len: usize, - input_value: Option, - span: &Span, - ) -> Result> { - // Build the array value using the expected types. - let mut array_value = vec![]; - - match input_value { - Some(InputValue::Array(arr)) => { - if array_len != arr.len() { - return Err(CompilerError::invalid_input_array_dimensions(arr.len(), array_len, span).into()); - } - - // Allocate each value in the current row - for (i, value) in arr.into_iter().enumerate() { - let value_name = format!("{}_{}", &name, &i.to_string()); - - array_value.push(self.allocate_main_function_input( - cs, - array_type, - &value_name, - Some(value), - span, - )?) - } - } - None => { - // Allocate all row values as none - for i in 0..array_len { - let value_name = format!("{}_{}", &name, &i.to_string()); - - array_value.push(self.allocate_main_function_input(cs, array_type, &value_name, None, span)?); - } - } - _ => { - return Err(CompilerError::invalid_function_input_array(input_value.unwrap(), span).into()); - } - } - - Ok(ConstrainedValue::Array(array_value)) - } -} diff --git a/compiler/src/unused/function/input/input_keyword.rs b/compiler/src/unused/function/input/input_keyword.rs deleted file mode 100644 index 17c218d564..0000000000 --- a/compiler/src/unused/function/input/input_keyword.rs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ConstrainedCircuitMember, ConstrainedProgram, ConstrainedValue, GroupType}; -use leo_asg::{Circuit, CircuitMember, Type}; -use leo_ast::{Identifier, Input}; -use leo_errors::{Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -pub const RECORD_VARIABLE_NAME: &str = "record"; -pub const REGISTERS_VARIABLE_NAME: &str = "registers"; -pub const STATE_VARIABLE_NAME: &str = "state"; -pub const STATE_LEAF_VARIABLE_NAME: &str = "state_leaf"; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - #[allow(clippy::vec_init_then_push)] - pub fn allocate_input_keyword>( - &mut self, - cs: &mut CS, - span: &Span, - expected_type: &'a Circuit<'a>, - input: &Input, - ) -> Result> { - // Create an identifier for each input variable - - let registers_name = Identifier { - name: REGISTERS_VARIABLE_NAME.into(), - span: span.clone(), - }; - let record_name = Identifier { - name: RECORD_VARIABLE_NAME.into(), - span: span.clone(), - }; - let state_name = Identifier { - name: STATE_VARIABLE_NAME.into(), - span: span.clone(), - }; - let state_leaf_name = Identifier { - name: STATE_LEAF_VARIABLE_NAME.into(), - span: span.clone(), - }; - - // Fetch each input variable's definitions - - let registers_values = input.get_registers().values(); - let record_values = input.get_record().values(); - let state_values = input.get_state().values(); - let state_leaf_values = input.get_state_leaf().values(); - - // Allocate each input variable as a circuit expression - - let mut sections = Vec::with_capacity(4); - - sections.push((registers_name, registers_values)); - sections.push((record_name, record_values)); - sections.push((state_name, state_values)); - sections.push((state_leaf_name, state_leaf_values)); - - let mut members = Vec::with_capacity(sections.len()); - - for (name, values) in sections { - let sub_circuit = match expected_type.members.borrow().get(name.name.as_ref()) { - Some(CircuitMember::Variable(Type::Circuit(circuit))) => *circuit, - _ => panic!("illegal input type definition from asg"), - }; - - let member_name = name.clone(); - let member_value = self.allocate_input_section(cs, name, sub_circuit, values)?; - - let member = ConstrainedCircuitMember(member_name, member_value); - - members.push(member) - } - - // Return input variable keyword as circuit expression - - Ok(ConstrainedValue::CircuitExpression(expected_type, members)) - } -} diff --git a/compiler/src/unused/function/input/input_section.rs b/compiler/src/unused/function/input/input_section.rs deleted file mode 100644 index 72b1d7856a..0000000000 --- a/compiler/src/unused/function/input/input_section.rs +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ConstrainedCircuitMember, ConstrainedProgram, ConstrainedValue, GroupType}; -use leo_asg::{Circuit, CircuitMember}; -use leo_ast::{Identifier, InputValue, Parameter}; -use leo_errors::{AsgError, Result}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -use indexmap::IndexMap; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub fn allocate_input_section>( - &mut self, - cs: &mut CS, - identifier: Identifier, - expected_type: &'a Circuit<'a>, - section: IndexMap>, - ) -> Result> { - let mut members = Vec::with_capacity(section.len()); - - // Allocate each section definition as a circuit member value - for (parameter, option) in section.into_iter() { - let section_members = expected_type.members.borrow(); - let expected_type = match section_members.get(parameter.variable.name.as_ref()) { - Some(CircuitMember::Variable(inner)) => inner, - _ => continue, // present, but unused - }; - let declared_type = self.asg.scope.resolve_ast_type(¶meter.type_, ¶meter.span)?; - if !expected_type.is_assignable_from(&declared_type) { - return Err(AsgError::unexpected_type(expected_type, declared_type, &identifier.span).into()); - } - let member_name = parameter.variable.clone(); - let member_value = self.allocate_main_function_input( - cs, - &declared_type, - ¶meter.variable.name, - option, - ¶meter.span, - )?; - let member = ConstrainedCircuitMember(member_name, member_value); - - members.push(member) - } - - // Return section as circuit expression - - Ok(ConstrainedValue::CircuitExpression(expected_type, members)) - } -} diff --git a/compiler/src/unused/function/input/main_function_input.rs b/compiler/src/unused/function/input/main_function_input.rs deleted file mode 100644 index bfa2765182..0000000000 --- a/compiler/src/unused/function/input/main_function_input.rs +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Allocates a main function input parameter in a compiled Leo program. - -use crate::{ - address::Address, - program::ConstrainedProgram, - value::{ - boolean::input::bool_from_input, char::char_from_input, field::input::field_from_input, - group::input::group_from_input, ConstrainedValue, - }, - CharType, FieldType, GroupType, Integer, -}; -use leo_asg::{ConstInt, Type}; -use leo_ast::{Char, InputValue}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::boolean::Boolean; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub fn allocate_main_function_input>( - &mut self, - cs: &mut CS, - type_: &Type, - name: &str, - input_option: Option, - span: &Span, - ) -> Result> { - match type_ { - Type::Address => Ok(Address::from_input(cs, name, input_option, span)?), - Type::Boolean => Ok(bool_from_input(cs, name, input_option, span)?), - Type::Char => Ok(char_from_input(cs, name, input_option, span)?), - Type::Field => Ok(field_from_input(cs, name, input_option, span)?), - Type::Group => Ok(group_from_input(cs, name, input_option, span)?), - Type::Integer(integer_type) => Ok(ConstrainedValue::Integer(Integer::from_input( - cs, - integer_type, - name, - input_option, - span, - )?)), - Type::Array(type_, len) => self.allocate_array(cs, name, &*type_, *len, input_option, span), - Type::Tuple(types) => self.allocate_tuple(cs, name, types, input_option, span), - _ => unimplemented!("main function input not implemented for type {}", type_), // Should not happen. - } - } -} - -/// Process constant inputs and return ConstrainedValue with constant value in it. -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub fn constant_main_function_input>( - &mut self, - cs: &mut CS, - type_: &Type, - name: &str, - input_option: Option, - span: &Span, - ) -> Result> { - let input = input_option.ok_or_else(|| CompilerError::function_input_not_found("main", name, span))?; - - match (type_, input) { - (Type::Address, InputValue::Address(addr)) => Ok(ConstrainedValue::Address(Address::constant(addr, span)?)), - (Type::Boolean, InputValue::Boolean(value)) => Ok(ConstrainedValue::Boolean(Boolean::constant(value))), - (Type::Char, InputValue::Char(character)) => match character.character { - Char::Scalar(scalar) => Ok(ConstrainedValue::Char(crate::Char::constant( - cs, - CharType::Scalar(scalar), - format!("{}", scalar as u32), - span, - )?)), - Char::NonScalar(non_scalar) => Ok(ConstrainedValue::Char(crate::Char::constant( - cs, - CharType::NonScalar(non_scalar), - format!("{}", non_scalar), - span, - )?)), - }, - (Type::Field, InputValue::Field(value)) => { - Ok(ConstrainedValue::Field(FieldType::constant(cs, value, span)?)) - } - (Type::Group, InputValue::Group(value)) => Ok(ConstrainedValue::Group(G::constant(&value.into(), span)?)), - (Type::Integer(integer_type), InputValue::Integer(input_type, value)) => { - let parsed = ConstInt::parse(integer_type, &value, span)?; - let parsed_type = parsed.get_int_type(); - let input_type = input_type.into(); - if std::mem::discriminant(&parsed_type) != std::mem::discriminant(&input_type) { - return Err( - CompilerError::integer_value_integer_type_mismatch(input_type, parsed_type, span).into(), - ); - } - Ok(ConstrainedValue::Integer(Integer::new(&parsed))) - } - (Type::Array(type_, arr_len), InputValue::Array(values)) => { - if *arr_len != values.len() { - return Err(CompilerError::invalid_input_array_dimensions(*arr_len, values.len(), span).into()); - } - - Ok(ConstrainedValue::Array( - values - .iter() - .map(|x| self.constant_main_function_input(cs, type_, name, Some(x.clone()), span)) - .collect::, _>>()?, - )) - } - (Type::Tuple(types), InputValue::Tuple(values)) => { - if values.len() != types.len() { - return Err(CompilerError::input_tuple_size_mismatch(types.len(), values.len(), span).into()); - } - - Ok(ConstrainedValue::Tuple( - values - .iter() - .enumerate() - .map(|(i, x)| { - self.constant_main_function_input(cs, types.get(i).unwrap(), name, Some(x.clone()), span) - }) - .collect::, _>>()?, - )) - } - (Type::Circuit(_), _) => unimplemented!("main function input not implemented for type {}", type_), // Should not happen. - - // Return an error if the input type and input value do not match. - (_, input) => Err(CompilerError::input_variable_type_mismatch(type_, input, name, span).into()), - } - } -} diff --git a/compiler/src/unused/function/input/mod.rs b/compiler/src/unused/function/input/mod.rs deleted file mode 100644 index eb45b640d5..0000000000 --- a/compiler/src/unused/function/input/mod.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce function input variables in a compiled Leo program. - -pub mod array; -pub use self::array::*; - -pub mod main_function_input; -pub use self::main_function_input::*; - -pub mod input_keyword; -pub use self::input_keyword::*; - -pub mod input_section; -pub use self::input_section::*; - -pub mod tuple; -pub use self::tuple::*; diff --git a/compiler/src/unused/function/input/tuple.rs b/compiler/src/unused/function/input/tuple.rs deleted file mode 100644 index 8bd4b8e220..0000000000 --- a/compiler/src/unused/function/input/tuple.rs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Allocates an array as a main function input parameter in a compiled Leo program. - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; - -use leo_asg::Type; -use leo_ast::InputValue; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub fn allocate_tuple>( - &mut self, - cs: &mut CS, - name: &str, - types: &[Type], - input_value: Option, - span: &Span, - ) -> Result> { - let mut tuple_values = vec![]; - - match input_value { - Some(InputValue::Tuple(values)) => { - if values.len() != types.len() { - return Err(CompilerError::input_tuple_size_mismatch(types.len(), values.len(), span).into()); - } - - // Allocate each value in the tuple. - for (i, (value, type_)) in values.into_iter().zip(types.iter()).enumerate() { - let value_name = format!("{}_{}", &name, &i.to_string()); - - tuple_values.push(self.allocate_main_function_input(cs, type_, &value_name, Some(value), span)?) - } - } - None => { - // Allocate all tuple values as none - for (i, type_) in types.iter().enumerate() { - let value_name = format!("{}_{}", &name, &i.to_string()); - - tuple_values.push(self.allocate_main_function_input(cs, type_, &value_name, None, span)?); - } - } - _ => { - return Err(CompilerError::invalid_function_input_tuple(input_value.unwrap(), span).into()); - } - } - - Ok(ConstrainedValue::Tuple(tuple_values)) - } -} diff --git a/compiler/src/unused/function/main_function.rs b/compiler/src/unused/function/main_function.rs deleted file mode 100644 index 7aefd335ff..0000000000 --- a/compiler/src/unused/function/main_function.rs +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces constraints on the main function of a compiled Leo program. - -use crate::{program::ConstrainedProgram, GroupType, Output}; - -use leo_asg::{Expression, Function, FunctionQualifier}; -use leo_ast::Input; -use leo_errors::{CompilerError, Result}; -use std::cell::Cell; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub fn enforce_main_function>( - &mut self, - cs: &mut CS, - function: &'a Function<'a>, - input: &Input, - ) -> Result { - let registers = input.get_registers(); - - // Iterate over main function input variables and allocate new values - let asg_input = function.scope.resolve_input(); - - if let Some(asg_input) = asg_input { - let value = - self.allocate_input_keyword(cs, &function.name.borrow().span, asg_input.container_circuit, input)?; - - self.store(asg_input.container.borrow().id, value); - } - - match function.qualifier { - FunctionQualifier::SelfRef | FunctionQualifier::ConstSelfRef | FunctionQualifier::MutSelfRef => { - unimplemented!("cannot access self variable in main function") - } - FunctionQualifier::Static => (), - } - - let mut arguments = vec![]; - - for (_, input_variable) in function.arguments.iter() { - { - let input_variable = input_variable.get().borrow(); - let name = input_variable.name.name.clone(); - - let input_value = match ( - input_variable.const_, - input.get(&name), - input.get_constant(name.as_ref()), - ) { - // If variable is in both [main] and [constants] sections - error. - (_, Some(_), Some(_)) => { - return Err(CompilerError::double_input_declaration(name, &input_variable.name.span).into()); - } - // If input option is found in [main] section and input is not const. - (false, Some(input_option), _) => self.allocate_main_function_input( - cs, - &input_variable.type_.clone(), - &name, - input_option, - &input_variable.name.span, - )?, - // If input option is found in [constants] section and function argument is const. - (true, _, Some(input_option)) => self.constant_main_function_input( - cs, - &input_variable.type_.clone(), - &name, - input_option, - &input_variable.name.span, - )?, - // Function argument is const, input is not. - (true, Some(_), None) => { - return Err( - CompilerError::expected_const_input_variable(name, &input_variable.name.span).into(), - ); - } - // Input is const, function argument is not. - (false, None, Some(_)) => { - return Err( - CompilerError::expected_non_const_input_variable(name, &input_variable.name.span).into(), - ); - } - // When not found - Error out. - (_, _, _) => { - return Err(CompilerError::function_input_not_found( - function.name.borrow().name.to_string(), - name, - &input_variable.name.span, - ) - .into()); - } - }; - - // Store a new variable for every function input. - self.store(input_variable.id, input_value); - } - arguments.push(Cell::new(&*function.scope.context.alloc_expression( - Expression::VariableRef(leo_asg::VariableRef { - parent: Cell::new(None), - span: Some(input_variable.get().borrow().name.span.clone()), - variable: input_variable.get(), - }), - ))); - } - - let span = function.span.clone().unwrap_or_default(); - let result_value = self.enforce_function(cs, function, None, &arguments)?; - let output = Output::new(&self.asg, registers, result_value, &span)?; - - Ok(output) - } -} diff --git a/compiler/src/unused/function/mod.rs b/compiler/src/unused/function/mod.rs deleted file mode 100644 index 19fa978e6c..0000000000 --- a/compiler/src/unused/function/mod.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce constraints on functions in a compiled Leo program. - -pub mod input; -pub use self::input::*; - -pub mod function; -pub use self::function::*; - -pub mod main_function; -pub use self::main_function::*; - -pub mod result; -pub use self::result::*; - -mod mut_target; diff --git a/compiler/src/unused/function/mut_target.rs b/compiler/src/unused/function/mut_target.rs deleted file mode 100644 index 8d6a080889..0000000000 --- a/compiler/src/unused/function/mut_target.rs +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Resolves assignees in a compiled Leo program. - -use std::cell::Cell; - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::{ - ArrayAccessExpression, ArrayRangeAccessExpression, AssignAccess, AssignOperation, AssignStatement, - CircuitAccessExpression, Expression, Node, TupleAccessExpression, Variable, -}; -use leo_errors::Result; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::boolean::Boolean; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - fn prepare_mut_access( - out: &mut Vec>, - expr: &'a Expression<'a>, - ) -> Result>> { - match expr { - Expression::ArrayRangeAccess(ArrayRangeAccessExpression { array, left, right, .. }) => { - let inner = Self::prepare_mut_access(out, array.get())?; - - out.push(AssignAccess::ArrayRange(left.clone(), right.clone())); - - Ok(inner) - } - Expression::ArrayAccess(ArrayAccessExpression { array, index, .. }) => { - let inner = Self::prepare_mut_access(out, array.get())?; - - out.push(AssignAccess::ArrayIndex(index.clone())); - Ok(inner) - } - Expression::TupleAccess(TupleAccessExpression { tuple_ref, index, .. }) => { - let inner = Self::prepare_mut_access(out, tuple_ref.get())?; - - out.push(AssignAccess::Tuple(*index)); - Ok(inner) - } - Expression::CircuitAccess(CircuitAccessExpression { target, member, .. }) => { - if let Some(target) = target.get() { - let inner = Self::prepare_mut_access(out, target)?; - - out.push(AssignAccess::Member(member.clone())); - Ok(inner) - } else { - Ok(None) - } - } - Expression::VariableRef(variable_ref) => Ok(Some(variable_ref.variable)), - _ => Ok(None), // not a valid reference to mutable variable, we copy - } - } - - // resolve a mutable reference from an expression - // return false if no valid mutable reference, or Err(_) on more critical error - pub fn resolve_mut_ref>( - &mut self, - cs: &mut CS, - assignee: &'a Expression<'a>, - target_value: ConstrainedValue<'a, F, G>, - indicator: &Boolean, - ) -> Result { - let mut accesses = vec![]; - let target = Self::prepare_mut_access(&mut accesses, assignee)?; - if target.is_none() { - return Ok(false); - } - let variable = target.unwrap(); - - self.resolve_assign( - cs, - &AssignStatement { - parent: Cell::new(None), - span: assignee.span().cloned(), - operation: AssignOperation::Assign, - target_variable: Cell::new(variable), - target_accesses: accesses, - value: Cell::new(assignee), - }, - target_value, - indicator, - )?; - - Ok(true) - } -} diff --git a/compiler/src/unused/function/result/mod.rs b/compiler/src/unused/function/result/mod.rs deleted file mode 100644 index bfb03b4072..0000000000 --- a/compiler/src/unused/function/result/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce constraints on a function result in a compiled Leo program. - -pub mod result; -pub use self::result::*; diff --git a/compiler/src/unused/function/result/result.rs b/compiler/src/unused/function/result/result.rs deleted file mode 100644 index 1de4e6b449..0000000000 --- a/compiler/src/unused/function/result/result.rs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces that one return value is produced in a compiled Leo program. - -use crate::{get_indicator_value, program::ConstrainedProgram, value::ConstrainedValue, GroupType}; - -use leo_asg::Type; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::{boolean::Boolean, traits::select::CondSelectGadget}; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - /// - /// Returns a conditionally selected result from the given possible function returns and - /// given function return type. - /// - pub fn conditionally_select_result>( - cs: &mut CS, - expected_return: &Type<'a>, - results: Vec<(Boolean, ConstrainedValue<'a, F, G>)>, - span: &Span, - ) -> Result> { - // Initialize empty return value. - let mut return_value = None; - - // Find the return value - let mut ignored = vec![]; - for (indicator, result) in results.into_iter() { - // Error if a statement returned a result with an incorrect type - let result_type = result.to_type(span)?; - if !expected_return.is_assignable_from(&result_type) { - panic!( - "failed type resolution for function return: expected '{}', got '{}'", - expected_return, result_type, - ); - } - - if get_indicator_value(&indicator) { - // Error if we already have a return value. - if return_value.is_some() { - return Err(CompilerError::statement_multiple_returns(span).into()); - } else { - // Set the function return value. - return_value = Some(result); - } - } else { - // Ignore a possible function return value. - ignored.push((indicator, result)) - } - } - - // Conditionally select out the ignored results in the circuit. - // - // If there are branches in the function we need to use the `ConditionalSelectGadget` to parse through and select the correct one. - // This can be thought of as de-multiplexing all previous wires that may have returned results into one. - for (i, (indicator, result)) in ignored.into_iter().enumerate() { - if let Some(value) = &return_value { - return_value = Some( - ConstrainedValue::conditionally_select( - cs.ns(|| format!("select result {} {}:{}", i, span.line_start, span.col_start)), - &indicator, - &result, - value, - ) - .map_err(|_| CompilerError::statement_select_fail(result, value, span))?, - ); - } else { - return_value = Some(result); // we ignore indicator for default -- questionable - } - } - - if expected_return.is_unit() { - Ok(ConstrainedValue::Tuple(vec![])) - } else { - Ok(return_value.ok_or_else(|| CompilerError::statement_no_returns(expected_return.to_string(), span))?) - } - } -} diff --git a/compiler/src/unused/lib.rs b/compiler/src/unused/lib.rs deleted file mode 100644 index d020bfb780..0000000000 --- a/compiler/src/unused/lib.rs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! The compiler for Leo programs. -//! -//! The [`Compiler`] type compiles Leo programs into R1CS circuits. - -#![allow(clippy::module_inception)] -#![allow(clippy::upper_case_acronyms)] -#![doc = include_str!("../README.md")] - -pub mod compiler; - -pub mod console; -pub use console::*; - -pub mod constraints; -pub use constraints::*; - -pub mod definition; - -pub mod expression; -pub use expression::*; - -pub mod function; -pub use function::*; - -pub mod output; -pub use output::*; - -pub mod program; -pub use program::*; - -pub mod statement; -pub use statement::*; - -pub mod prelude; -pub use prelude::*; - -pub mod value; -pub use value::*; - -pub mod phase; -pub use phase::*; - -pub mod phases; -pub use phases::*; - -pub mod option; -pub use option::*; - -#[cfg(test)] -mod test; diff --git a/compiler/src/unused/option.rs b/compiler/src/unused/option.rs deleted file mode 100644 index 5aeb780fe8..0000000000 --- a/compiler/src/unused/option.rs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -/// -/// Toggles compiler optimizations on the program. -/// -#[derive(Clone, Debug)] -pub struct CompilerOptions { - pub constant_folding_enabled: bool, - pub dead_code_elimination_enabled: bool, -} - -impl Default for CompilerOptions { - /// - /// All compiler optimizations are enabled by default. - /// - fn default() -> Self { - CompilerOptions { - constant_folding_enabled: true, - dead_code_elimination_enabled: true, - } - } -} - -#[derive(Clone, Default)] -pub struct AstSnapshotOptions { - pub spans_enabled: bool, - pub initial: bool, - pub imports_resolved: bool, - pub canonicalized: bool, - pub type_inferenced: bool, -} diff --git a/compiler/src/unused/output/mod.rs b/compiler/src/unused/output/mod.rs deleted file mode 100644 index 0e3c322d65..0000000000 --- a/compiler/src/unused/output/mod.rs +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub mod output_file; -use std::{collections::BTreeMap, fmt}; - -pub use self::output_file::*; - -pub mod output_bytes; -pub use self::output_bytes::*; - -use crate::{Char, CharType, ConstrainedValue, GroupType, REGISTERS_VARIABLE_NAME}; -use leo_asg::Program; -use leo_ast::{Parameter, Registers}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; - -use serde::{Deserialize, Serialize}; - -#[derive(Deserialize, Serialize, Debug)] -pub struct OutputRegister { - #[serde(rename = "type")] - pub type_: String, - pub value: String, -} - -#[derive(Deserialize, Serialize, Debug)] -pub struct Output { - pub registers: BTreeMap, -} - -impl fmt::Display for Output { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - writeln!(f, "[{}]", REGISTERS_VARIABLE_NAME)?; - // format: "token_id: u64 = 1u64;" - for (name, register) in self.registers.iter() { - writeln!(f, "{}: {} = {};", name, register.type_, register.value)?; - } - Ok(()) - } -} - -#[allow(clippy::from_over_into)] -impl Into for Output { - fn into(self) -> OutputBytes { - OutputBytes::from(self.to_string().into_bytes()) - } -} - -fn char_to_output_string(character: &Char, quote: bool) -> String { - let mut string = String::new(); - if quote { - string.push('\''); - } - - match character.character { - CharType::Scalar(scalar) => { - if scalar.is_alphanumeric() { - string.push(scalar); - } else { - string.push_str(format!("{}", char::escape_default(scalar)).as_str()); - } - } - CharType::NonScalar(non_scalar) => string.push_str(format!("\\u{{{:x}}}", non_scalar).as_str()), - } - if quote { - string.push('\''); - } - string -} - -impl Output { - pub fn new<'a, F: PrimeField, G: GroupType>( - program: &Program<'a>, - registers: &Registers, - value: ConstrainedValue<'a, F, G>, - span: &Span, - ) -> Result { - let return_values = match value { - ConstrainedValue::Tuple(tuple) => tuple, - value => vec![value], - }; - let register_hashmap = registers.values(); - - // Create vector of parameter values in alphabetical order - let mut register_values = register_hashmap - .into_iter() - .map(|register| register.0) - .collect::>(); - - register_values.sort_by(|a, b| a.variable.name.cmp(&b.variable.name)); - - // Return an error if we do not have enough return registers - if register_values.len() < return_values.len() { - return Err(CompilerError::output_not_enough_registers(span).into()); - } - - let mut registers = BTreeMap::new(); - - for (parameter, value) in register_values.into_iter().zip(return_values.into_iter()) { - let name = parameter.variable.name; - - // Check register type == return value type. - let register_type = program.scope.resolve_ast_type(¶meter.type_, ¶meter.span)?; - let return_value_type = value.to_type(span)?; - - if !register_type.is_assignable_from(&return_value_type) { - return Err(CompilerError::output_mismatched_types(register_type, return_value_type, span).into()); - } - - let value = match value { - ConstrainedValue::Char(c) => char_to_output_string(&c, true), - ConstrainedValue::Array(array) => { - let mut string = String::new(); - string.push('"'); - for e in array.iter() { - if let ConstrainedValue::Char(c) = e { - string.push_str(char_to_output_string(c, false).as_str()); - } else { - string.push_str(e.to_string().as_str()); - } - } - string.push('"'); - string - } - ConstrainedValue::Tuple(tuple) => { - let values = tuple - .iter() - .map(|e| { - if let ConstrainedValue::Char(c) = e { - char_to_output_string(c, true) - } else { - e.to_string() - } - }) - .collect::>() - .join(", "); - - format!("({})", values) - } - _ => value.to_string(), - }; - - registers.insert( - name.to_string(), - OutputRegister { - type_: register_type.to_string(), - value, - }, - ); - } - - Ok(Output { registers }) - } -} diff --git a/compiler/src/unused/output/output_bytes.rs b/compiler/src/unused/output/output_bytes.rs deleted file mode 100644 index 7ca118a3f3..0000000000 --- a/compiler/src/unused/output/output_bytes.rs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ConstrainedValue, GroupType, REGISTERS_VARIABLE_NAME}; -use leo_asg::Program; -use leo_ast::{Parameter, Registers}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; - -use serde::{Deserialize, Serialize}; - -/// Serialized program return output. -#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)] -pub struct OutputBytes(Vec); - -impl OutputBytes { - pub fn bytes(&self) -> &Vec { - &self.0 - } - - pub fn new_from_constrained_value<'a, F: PrimeField, G: GroupType>( - program: &Program<'a>, - registers: &Registers, - value: ConstrainedValue<'a, F, G>, - - span: &Span, - ) -> Result { - let return_values = match value { - ConstrainedValue::Tuple(values) => values, - value => vec![value], - }; - let register_hashmap = registers.values(); - - // Create vector of parameter values in alphabetical order - let mut register_values = register_hashmap - .into_iter() - .map(|register| register.0) - .collect::>(); - - register_values.sort_by(|a, b| a.variable.name.cmp(&b.variable.name)); - - // Return an error if we do not have enough return registers - if register_values.len() < return_values.len() { - return Err(CompilerError::output_not_enough_registers(span).into()); - } - - // Manually construct result string - let mut string = String::new(); - let header = format!("[{}]\n", REGISTERS_VARIABLE_NAME); - - string.push_str(&header); - - // format: "token_id: u64 = 1u64;" - for (parameter, value) in register_values.into_iter().zip(return_values.into_iter()) { - let name = parameter.variable.name; - - // Check register type == return value type. - let register_type = program.scope.resolve_ast_type(¶meter.type_, ¶meter.span)?; - let return_value_type = value.to_type(span)?; - - if !register_type.is_assignable_from(&return_value_type) { - return Err(CompilerError::output_mismatched_types(register_type, return_value_type, span).into()); - } - - let value = value.to_string(); - - let format = format!("{}: {} = {};\n", name, register_type, value,); - - string.push_str(&format); - } - - let bytes = string.into_bytes(); - - Ok(Self(bytes)) - } -} - -impl From> for OutputBytes { - fn from(bytes: Vec) -> Self { - Self(bytes) - } -} diff --git a/compiler/src/unused/output/output_file.rs b/compiler/src/unused/output/output_file.rs deleted file mode 100644 index 62250bc1f1..0000000000 --- a/compiler/src/unused/output/output_file.rs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! The `program.out` file. - -use leo_errors::{CompilerError, Result}; - -use std::{ - borrow::Cow, - fs::{ - File, {self}, - }, - io::Write, - path::Path, -}; - -pub static OUTPUTS_DIRECTORY_NAME: &str = "outputs/"; -pub static OUTPUT_FILE_EXTENSION: &str = ".out"; - -pub struct OutputFile { - pub package_name: String, -} - -impl OutputFile { - pub fn new(package_name: &str) -> Self { - Self { - package_name: package_name.to_string(), - } - } - - /// Writes output to a file. - pub fn write(&self, path: &Path, bytes: &[u8]) -> Result<()> { - // create output file - let path = self.setup_file_path(path); - let mut file = File::create(&path).map_err(CompilerError::output_file_io_error)?; - - Ok(file.write_all(bytes).map_err(CompilerError::output_file_io_error)?) - } - - /// Removes the output file at the given path if it exists. Returns `true` on success, - /// `false` if the file doesn't exist, and `Error` if the file system fails during operation. - pub fn remove(&self, path: &Path) -> Result { - let path = self.setup_file_path(path); - if !path.exists() { - return Ok(false); - } - - fs::remove_file(&path).map_err(|_| CompilerError::output_file_cannot_remove(path))?; - Ok(true) - } - - fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> { - let mut path = Cow::from(path); - if path.is_dir() { - if !path.ends_with(OUTPUTS_DIRECTORY_NAME) { - path.to_mut().push(OUTPUTS_DIRECTORY_NAME); - } - path.to_mut() - .push(format!("{}{}", self.package_name, OUTPUT_FILE_EXTENSION)); - } - path - } -} - -#[cfg(test)] -mod test_output_file { - use crate::{OutputFile, OUTPUTS_DIRECTORY_NAME}; - use std::{error::Error, fs}; - - #[test] - fn test_all() -> Result<(), Box> { - let dir = tempfile::tempdir()?; - let file = OutputFile::new("test"); - let path = dir.path(); - - assert!(file.write(path, Default::default()).is_err()); - assert!(!(file.remove(path)?)); - - fs::create_dir(dir.path().join(OUTPUTS_DIRECTORY_NAME))?; - - assert!(file.write(path, Default::default()).is_ok()); - assert!(file.remove(path)?); - - Ok(()) - } -} diff --git a/compiler/src/unused/phase.rs b/compiler/src/unused/phase.rs deleted file mode 100644 index 6cb8510605..0000000000 --- a/compiler/src/unused/phase.rs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use leo_asg::Program as AsgProgram; -use leo_ast::Program as AstProgram; - -pub trait ASGPhase { - fn apply(asg: &mut AsgProgram); -} - -pub trait ASTPhase { - fn apply(asg: &mut AstProgram); -} diff --git a/compiler/src/unused/phases/mod.rs b/compiler/src/unused/phases/mod.rs deleted file mode 100644 index c409e2f4d5..0000000000 --- a/compiler/src/unused/phases/mod.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Compiles a Leo program from a file path. - -pub mod reducing_director; -pub use reducing_director::*; - -pub mod phase; -pub use phase::*; diff --git a/compiler/src/unused/phases/phase.rs b/compiler/src/unused/phases/phase.rs deleted file mode 100644 index c5d7d1424c..0000000000 --- a/compiler/src/unused/phases/phase.rs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Compiles a Leo program from a file path. - -use crate::{CombineAstAsgDirector, CombinerOptions}; -use leo_asg::Program as AsgProgram; -use leo_ast::{Ast, Program as AstProgram, ReconstructingReducer}; -use leo_errors::Result; - -macro_rules! phase { - ($phase_name:ident, $function:item) => { - pub struct $phase_name { - in_circuit: bool, - } - - pub struct Options; - - impl CombinerOptions for Options { - $function - } - - impl ReconstructingReducer for $phase_name { - fn in_circuit(&self) -> bool { - self.in_circuit - } - - fn swap_in_circuit(&mut self) { - self.in_circuit = !self.in_circuit; - } - } - - impl Default for $phase_name { - fn default() -> Self { - Self { in_circuit: false } - } - } - - impl $phase_name { - pub fn phase_ast(&self, ast: &AstProgram, asg: &AsgProgram) -> Result { - Ok(Ast::new(CombineAstAsgDirector::new(Self::default(), Options{}) - .reduce_program(ast, asg)?)) - } - } - }; -} - -phase!( - TypeInferencePhase, - fn type_inference_enabled(&self) -> bool { - true - } -); diff --git a/compiler/src/unused/phases/reducing_director.rs b/compiler/src/unused/phases/reducing_director.rs deleted file mode 100644 index a3092c326c..0000000000 --- a/compiler/src/unused/phases/reducing_director.rs +++ /dev/null @@ -1,725 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Compiles a Leo program from a file path. - -use indexmap::IndexMap; -use leo_asg::{ - ArrayAccessExpression as AsgArrayAccessExpression, ArrayInitExpression as AsgArrayInitExpression, - ArrayInlineExpression as AsgArrayInlineExpression, ArrayRangeAccessExpression as AsgArrayRangeAccessExpression, - AssignAccess as AsgAssignAccess, AssignStatement as AsgAssignStatement, BinaryExpression as AsgBinaryExpression, - BlockStatement as AsgBlockStatement, CallExpression as AsgCallExpression, CastExpression as AsgCastExpression, - CharValue as AsgCharValue, Circuit as AsgCircuit, CircuitAccessExpression as AsgCircuitAccessExpression, - CircuitInitExpression as AsgCircuitInitExpression, CircuitMember as AsgCircuitMember, - ConditionalStatement as AsgConditionalStatement, ConsoleFunction as AsgConsoleFunction, - ConsoleStatement as AsgConsoleStatement, ConstValue, Constant as AsgConstant, - DefinitionStatement as AsgDefinitionStatement, Expression as AsgExpression, - ExpressionStatement as AsgExpressionStatement, Function as AsgFunction, GroupValue as AsgGroupValue, - IterationStatement as AsgIterationStatement, ReturnStatement as AsgReturnStatement, Statement as AsgStatement, - TernaryExpression as AsgTernaryExpression, TupleAccessExpression as AsgTupleAccessExpression, - TupleInitExpression as AsgTupleInitExpression, Type as AsgType, UnaryExpression as AsgUnaryExpression, - VariableRef as AsgVariableRef, -}; -use leo_ast::{ - ArrayAccessExpression as AstArrayAccessExpression, ArrayDimensions, ArrayInitExpression as AstArrayInitExpression, - ArrayInlineExpression as AstArrayInlineExpression, ArrayRangeAccessExpression as AstArrayRangeAccessExpression, - AssignStatement as AstAssignStatement, Assignee, AssigneeAccess as AstAssignAccess, - BinaryExpression as AstBinaryExpression, Block as AstBlockStatement, CallExpression as AstCallExpression, - CastExpression as AstCastExpression, Char, CharValue as AstCharValue, Circuit as AstCircuit, - CircuitImpliedVariableDefinition, CircuitInitExpression as AstCircuitInitExpression, - CircuitMember as AstCircuitMember, CircuitMemberAccessExpression, CircuitStaticFunctionAccessExpression, - ConditionalStatement as AstConditionalStatement, ConsoleArgs as AstConsoleArgs, - ConsoleFunction as AstConsoleFunction, ConsoleStatement as AstConsoleStatement, - DefinitionStatement as AstDefinitionStatement, Expression as AstExpression, - ExpressionStatement as AstExpressionStatement, Function as AstFunction, GroupTuple, GroupValue as AstGroupValue, - IterationStatement as AstIterationStatement, PositiveNumber, ReconstructingReducer, - ReturnStatement as AstReturnStatement, SpreadOrExpression, Statement as AstStatement, - TernaryExpression as AstTernaryExpression, TupleAccessExpression as AstTupleAccessExpression, - TupleInitExpression as AstTupleInitExpression, Type as AstType, UnaryExpression as AstUnaryExpression, - ValueExpression, -}; -use leo_errors::{AstError, Result, Span}; -use tendril::StrTendril; - -pub trait CombinerOptions { - fn type_inference_enabled(&self) -> bool { - false - } -} - -pub struct CombineAstAsgDirector { - ast_reducer: R, - options: O, -} - -impl CombineAstAsgDirector { - pub fn new(ast_reducer: R, options: O) -> Self { - Self { ast_reducer, options } - } - - pub fn reduce_type(&mut self, ast: &AstType, asg: &AsgType, span: &Span) -> Result { - let new = match (ast, asg) { - (AstType::Array(ast_type, ast_dimensions), AsgType::Array(asg_type, asg_dimensions)) => { - if self.options.type_inference_enabled() { - AstType::Array( - Box::new(self.reduce_type(ast_type, asg_type, span)?), - Some(ArrayDimensions(vec![PositiveNumber { - value: StrTendril::from(format!("{}", asg_dimensions)), - }])), - ) - } else { - AstType::Array( - Box::new(self.reduce_type(ast_type, asg_type, span)?), - ast_dimensions.clone(), - ) - } - } - (AstType::Tuple(ast_types), AsgType::Tuple(asg_types)) => { - let mut reduced_types = vec![]; - for (ast_type, asg_type) in ast_types.iter().zip(asg_types) { - reduced_types.push(self.reduce_type(ast_type, asg_type, span)?); - } - - AstType::Tuple(reduced_types) - } - _ if self.options.type_inference_enabled() => asg.into(), - _ => ast.clone(), - }; - - self.ast_reducer.reduce_type(ast, new, span) - } - - pub fn reduce_expression(&mut self, ast: &AstExpression, asg: &AsgExpression) -> Result { - let new = match (ast, asg) { - (AstExpression::Value(value), AsgExpression::Constant(const_)) => self.reduce_value(value, const_)?, - (AstExpression::Binary(ast), AsgExpression::Binary(asg)) => { - AstExpression::Binary(self.reduce_binary(ast, asg)?) - } - (AstExpression::Unary(ast), AsgExpression::Unary(asg)) => { - AstExpression::Unary(self.reduce_unary(ast, asg)?) - } - (AstExpression::Ternary(ast), AsgExpression::Ternary(asg)) => { - AstExpression::Ternary(self.reduce_ternary(ast, asg)?) - } - (AstExpression::Cast(ast), AsgExpression::Cast(asg)) => AstExpression::Cast(self.reduce_cast(ast, asg)?), - - (AstExpression::ArrayInline(ast), AsgExpression::ArrayInline(asg)) => { - AstExpression::ArrayInline(self.reduce_array_inline(ast, asg)?) - } - (AstExpression::ArrayInit(ast), AsgExpression::ArrayInit(asg)) => { - AstExpression::ArrayInit(self.reduce_array_init(ast, asg)?) - } - (AstExpression::ArrayAccess(ast), AsgExpression::ArrayAccess(asg)) => { - AstExpression::ArrayAccess(self.reduce_array_access(ast, asg)?) - } - (AstExpression::ArrayRangeAccess(ast), AsgExpression::ArrayRangeAccess(asg)) => { - AstExpression::ArrayRangeAccess(self.reduce_array_range_access(ast, asg)?) - } - - (AstExpression::TupleInit(ast), AsgExpression::TupleInit(asg)) => { - AstExpression::TupleInit(self.reduce_tuple_init(ast, asg)?) - } - (AstExpression::TupleAccess(ast), AsgExpression::TupleAccess(asg)) => { - AstExpression::TupleAccess(self.reduce_tuple_access(ast, asg)?) - } - - (AstExpression::CircuitInit(ast), AsgExpression::CircuitInit(asg)) => { - AstExpression::CircuitInit(self.reduce_circuit_init(ast, asg)?) - } - (AstExpression::CircuitMemberAccess(ast), AsgExpression::CircuitAccess(asg)) => { - AstExpression::CircuitMemberAccess(self.reduce_circuit_member_access(ast, asg)?) - } - (AstExpression::CircuitStaticFunctionAccess(ast), AsgExpression::CircuitAccess(asg)) => { - AstExpression::CircuitStaticFunctionAccess(self.reduce_circuit_static_fn_access(ast, asg)?) - } - - (AstExpression::Call(ast), AsgExpression::Call(asg)) => AstExpression::Call(self.reduce_call(ast, asg)?), - _ => ast.clone(), - }; - - self.ast_reducer.reduce_expression(ast, new) - } - - pub fn reduce_array_access( - &mut self, - ast: &AstArrayAccessExpression, - asg: &AsgArrayAccessExpression, - ) -> Result { - let array = self.reduce_expression(&ast.array, asg.array.get())?; - let index = self.reduce_expression(&ast.index, asg.index.get())?; - - self.ast_reducer.reduce_array_access(ast, array, index) - } - - pub fn reduce_array_init( - &mut self, - ast: &AstArrayInitExpression, - asg: &AsgArrayInitExpression, - ) -> Result { - let element = self.reduce_expression(&ast.element, asg.element.get())?; - - self.ast_reducer.reduce_array_init(ast, element) - } - - pub fn reduce_array_inline( - &mut self, - ast: &AstArrayInlineExpression, - asg: &AsgArrayInlineExpression, - ) -> Result { - let mut elements = vec![]; - for (ast_element, asg_element) in ast.elements.iter().zip(asg.elements.iter()) { - let reduced_element = match ast_element { - SpreadOrExpression::Expression(ast_expression) => { - SpreadOrExpression::Expression(self.reduce_expression(ast_expression, asg_element.0.get())?) - } - SpreadOrExpression::Spread(ast_expression) => { - SpreadOrExpression::Spread(self.reduce_expression(ast_expression, asg_element.0.get())?) - } - }; - - elements.push(reduced_element); - } - - self.ast_reducer.reduce_array_inline(ast, elements) - } - - pub fn reduce_array_range_access( - &mut self, - ast: &AstArrayRangeAccessExpression, - asg: &AsgArrayRangeAccessExpression, - ) -> Result { - let array = self.reduce_expression(&ast.array, asg.array.get())?; - let left = match (ast.left.as_ref(), asg.left.get()) { - (Some(ast_left), Some(asg_left)) => Some(self.reduce_expression(ast_left, asg_left)?), - _ => None, - }; - let right = match (ast.right.as_ref(), asg.right.get()) { - (Some(ast_right), Some(asg_right)) => Some(self.reduce_expression(ast_right, asg_right)?), - _ => None, - }; - - self.ast_reducer.reduce_array_range_access(ast, array, left, right) - } - - pub fn reduce_binary( - &mut self, - ast: &AstBinaryExpression, - asg: &AsgBinaryExpression, - ) -> Result { - let left = self.reduce_expression(&ast.left, asg.left.get())?; - let right = self.reduce_expression(&ast.right, asg.right.get())?; - - self.ast_reducer.reduce_binary(ast, left, right, ast.op.clone()) - } - - pub fn reduce_call(&mut self, ast: &AstCallExpression, asg: &AsgCallExpression) -> Result { - let mut function = *ast.function.clone(); - - if self.options.type_inference_enabled() { - let function_type: Option = asg - .target - .get() - .map(|target| { - (target as &dyn leo_asg::ExpressionNode) - .get_type() - .as_ref() - .map(|t| t.into()) - }) - .flatten(); - if let AstExpression::CircuitMemberAccess(mut access) = function { - access.type_ = function_type; - function = AstExpression::CircuitMemberAccess(access); - } - } - - let mut arguments = vec![]; - for (ast_arg, asg_arg) in ast.arguments.iter().zip(asg.arguments.iter()) { - arguments.push(self.reduce_expression(ast_arg, asg_arg.get())?); - } - - self.ast_reducer.reduce_call(ast, function, arguments) - } - - pub fn reduce_cast(&mut self, ast: &AstCastExpression, asg: &AsgCastExpression) -> Result { - let inner = self.reduce_expression(&ast.inner, asg.inner.get())?; - let target_type = self.reduce_type(&ast.target_type, &asg.target_type, &ast.span)?; - - self.ast_reducer.reduce_cast(ast, inner, target_type) - } - - pub fn reduce_circuit_member_access( - &mut self, - ast: &CircuitMemberAccessExpression, - asg: &AsgCircuitAccessExpression, - ) -> Result { - let type_ = if self.options.type_inference_enabled() { - Some(leo_ast::Type::Identifier(asg.circuit.get().name.borrow().clone())) - } else { - None - }; - - self.ast_reducer - .reduce_circuit_member_access(ast, *ast.circuit.clone(), ast.name.clone(), type_) - } - - pub fn reduce_circuit_static_fn_access( - &mut self, - ast: &CircuitStaticFunctionAccessExpression, - _asg: &AsgCircuitAccessExpression, - ) -> Result { - self.ast_reducer - .reduce_circuit_static_fn_access(ast, *ast.circuit.clone(), ast.name.clone()) - } - - pub fn reduce_circuit_implied_variable_definition( - &mut self, - ast: &CircuitImpliedVariableDefinition, - asg: &AsgExpression, - ) -> Result { - let expression = ast - .expression - .as_ref() - .map(|ast_expr| self.reduce_expression(ast_expr, asg)) - .transpose()?; - - self.ast_reducer - .reduce_circuit_implied_variable_definition(ast, ast.identifier.clone(), expression) - } - - pub fn reduce_circuit_init( - &mut self, - ast: &AstCircuitInitExpression, - asg: &AsgCircuitInitExpression, - ) -> Result { - let mut members = vec![]; - for (ast_member, asg_member) in ast.members.iter().zip(asg.values.iter()) { - members.push(self.reduce_circuit_implied_variable_definition(ast_member, asg_member.1.get())?); - } - - self.ast_reducer.reduce_circuit_init(ast, ast.name.clone(), members) - } - - pub fn reduce_ternary( - &mut self, - ast: &AstTernaryExpression, - asg: &AsgTernaryExpression, - ) -> Result { - let condition = self.reduce_expression(&ast.condition, asg.condition.get())?; - let if_true = self.reduce_expression(&ast.if_true, asg.if_true.get())?; - let if_false = self.reduce_expression(&ast.if_false, asg.if_false.get())?; - - self.ast_reducer.reduce_ternary(ast, condition, if_true, if_false) - } - - pub fn reduce_tuple_access( - &mut self, - ast: &AstTupleAccessExpression, - asg: &AsgTupleAccessExpression, - ) -> Result { - let tuple = self.reduce_expression(&ast.tuple, asg.tuple_ref.get())?; - - self.ast_reducer.reduce_tuple_access(ast, tuple) - } - - pub fn reduce_tuple_init( - &mut self, - ast: &AstTupleInitExpression, - asg: &AsgTupleInitExpression, - ) -> Result { - let mut elements = vec![]; - for (ast_element, asg_element) in ast.elements.iter().zip(asg.elements.iter()) { - let element = self.reduce_expression(ast_element, asg_element.get())?; - elements.push(element); - } - - self.ast_reducer.reduce_tuple_init(ast, elements) - } - - pub fn reduce_unary(&mut self, ast: &AstUnaryExpression, asg: &AsgUnaryExpression) -> Result { - let inner = self.reduce_expression(&ast.inner, asg.inner.get())?; - - self.ast_reducer.reduce_unary(ast, inner, ast.op.clone()) - } - - pub fn reduce_value(&mut self, ast: &ValueExpression, asg: &AsgConstant) -> Result { - let mut new = ast.clone(); - - if self.options.type_inference_enabled() { - if let ValueExpression::Implicit(tendril, span) = ast { - match &asg.value { - ConstValue::Int(int) => { - new = ValueExpression::Integer(int.get_int_type(), tendril.clone(), span.clone()); - } - ConstValue::Group(group) => { - let group_value = match group { - AsgGroupValue::Single(_) => AstGroupValue::Single(tendril.clone(), span.clone()), - AsgGroupValue::Tuple(x, y) => AstGroupValue::Tuple(GroupTuple { - x: x.into(), - y: y.into(), - span: span.clone(), - }), - }; - new = ValueExpression::Group(Box::new(group_value)); - } - ConstValue::Field(_) => { - new = ValueExpression::Field(tendril.clone(), span.clone()); - } - ConstValue::Address(_) => { - new = ValueExpression::Address(tendril.clone(), span.clone()); - } - ConstValue::Boolean(_) => { - new = ValueExpression::Boolean(tendril.clone(), span.clone()); - } - ConstValue::Char(asg_char) => { - new = match asg_char { - AsgCharValue::Scalar(scalar) => ValueExpression::Char(AstCharValue { - character: Char::Scalar(*scalar), - span: span.clone(), - }), - AsgCharValue::NonScalar(non_scalar) => ValueExpression::Char(AstCharValue { - character: Char::NonScalar(*non_scalar), - span: span.clone(), - }), - } - } - _ => unimplemented!(), // impossible? - } - } - } - - self.ast_reducer.reduce_value(ast, AstExpression::Value(new)) - } - - pub fn reduce_variable_ref(&mut self, ast: &ValueExpression, _asg: &AsgVariableRef) -> Result { - // TODO FIGURE IT OUT - let new = match ast { - // ValueExpression::Group(group_value) => { - // ValueExpression::Group(Box::new(self.reduce_group_value(&group_value)?)) - // } - _ => ast.clone(), - }; - - Ok(new) - // self.ast_reducer.reduce_value(value, new) - } - - pub fn reduce_statement( - &mut self, - ast_statement: &AstStatement, - asg_statement: &AsgStatement, - ) -> Result { - let new = match (ast_statement, asg_statement) { - (AstStatement::Assign(ast), AsgStatement::Assign(asg)) => { - AstStatement::Assign(Box::new(self.reduce_assign(ast, asg)?)) - } - (AstStatement::Block(ast), AsgStatement::Block(asg)) => AstStatement::Block(self.reduce_block(ast, asg)?), - (AstStatement::Conditional(ast), AsgStatement::Conditional(asg)) => { - AstStatement::Conditional(self.reduce_conditional(ast, asg)?) - } - (AstStatement::Console(ast), AsgStatement::Console(asg)) => { - AstStatement::Console(self.reduce_console(ast, asg)?) - } - (AstStatement::Definition(ast), AsgStatement::Definition(asg)) => { - AstStatement::Definition(self.reduce_definition(ast, asg)?) - } - (AstStatement::Expression(ast), AsgStatement::Expression(asg)) => { - AstStatement::Expression(self.reduce_expression_statement(ast, asg)?) - } - (AstStatement::Iteration(ast), AsgStatement::Iteration(asg)) => { - AstStatement::Iteration(Box::new(self.reduce_iteration(ast, asg)?)) - } - (AstStatement::Return(ast), AsgStatement::Return(asg)) => { - AstStatement::Return(self.reduce_return(ast, asg)?) - } - _ => ast_statement.clone(), - }; - - self.ast_reducer.reduce_statement(ast_statement, new) - } - - pub fn reduce_assign_access(&mut self, ast: &AstAssignAccess, asg: &AsgAssignAccess) -> Result { - let new = match (ast, asg) { - (AstAssignAccess::ArrayRange(ast_left, ast_right), AsgAssignAccess::ArrayRange(asg_left, asg_right)) => { - let left = match (ast_left.as_ref(), asg_left.get()) { - (Some(ast_left), Some(asg_left)) => Some(self.reduce_expression(ast_left, asg_left)?), - _ => None, - }; - let right = match (ast_right.as_ref(), asg_right.get()) { - (Some(ast_right), Some(asg_right)) => Some(self.reduce_expression(ast_right, asg_right)?), - _ => None, - }; - - AstAssignAccess::ArrayRange(left, right) - } - (AstAssignAccess::ArrayIndex(ast_index), AsgAssignAccess::ArrayIndex(asg_index)) => { - let index = self.reduce_expression(ast_index, asg_index.get())?; - AstAssignAccess::ArrayIndex(index) - } - _ => ast.clone(), - }; - - self.ast_reducer.reduce_assignee_access(ast, new) - } - - pub fn reduce_assignee(&mut self, ast: &Assignee, asg: &[AsgAssignAccess]) -> Result { - let mut accesses = vec![]; - for (ast_access, asg_access) in ast.accesses.iter().zip(asg) { - accesses.push(self.reduce_assign_access(ast_access, asg_access)?); - } - - self.ast_reducer.reduce_assignee(ast, ast.identifier.clone(), accesses) - } - - pub fn reduce_assign(&mut self, ast: &AstAssignStatement, asg: &AsgAssignStatement) -> Result { - let assignee = self.reduce_assignee(&ast.assignee, &asg.target_accesses)?; - let value = self.reduce_expression(&ast.value, asg.value.get())?; - - self.ast_reducer.reduce_assign(ast, assignee, value) - } - - pub fn reduce_block(&mut self, ast: &AstBlockStatement, asg: &AsgBlockStatement) -> Result { - let mut statements = vec![]; - for (ast_statement, asg_statement) in ast.statements.iter().zip(asg.statements.iter()) { - statements.push(self.reduce_statement(ast_statement, asg_statement.get())?); - } - - self.ast_reducer.reduce_block(ast, statements) - } - - pub fn reduce_conditional( - &mut self, - ast: &AstConditionalStatement, - asg: &AsgConditionalStatement, - ) -> Result { - let condition = self.reduce_expression(&ast.condition, asg.condition.get())?; - let block; - if let AsgStatement::Block(asg_block) = asg.result.get() { - block = self.reduce_block(&ast.block, asg_block)?; - } else { - return Err(AstError::ast_statement_not_block(asg.span.as_ref().unwrap()).into()); - } - let next = match (ast.next.as_ref(), asg.next.get()) { - (Some(ast_next), Some(asg_next)) => Some(self.reduce_statement(ast_next, asg_next)?), - _ => None, - }; - - self.ast_reducer.reduce_conditional(ast, condition, block, next) - } - - pub fn reduce_console( - &mut self, - ast: &AstConsoleStatement, - asg: &AsgConsoleStatement, - ) -> Result { - let function = match (&ast.function, &asg.function) { - (AstConsoleFunction::Assert(ast_expression), AsgConsoleFunction::Assert(asg_expression)) => { - AstConsoleFunction::Assert(self.reduce_expression(ast_expression, asg_expression.get())?) - } - (AstConsoleFunction::Error(ast_console_args), AsgConsoleFunction::Error(asg_format)) - | (AstConsoleFunction::Log(ast_console_args), AsgConsoleFunction::Log(asg_format)) => { - let mut parameters = vec![]; - for (ast_parameter, asg_parameter) in - ast_console_args.parameters.iter().zip(asg_format.parameters.iter()) - { - parameters.push(self.reduce_expression(ast_parameter, asg_parameter.get())?); - } - - let args = AstConsoleArgs { - string: ast_console_args.string.clone(), - parameters, - span: ast_console_args.span.clone(), - }; - - match &ast.function { - AstConsoleFunction::Error(_) => AstConsoleFunction::Error(args), - AstConsoleFunction::Log(_) => AstConsoleFunction::Log(args), - _ => { - return Err(AstError::impossible_console_assert_call(&ast_console_args.span).into()); - } - } - } - _ => ast.function.clone(), - }; - - self.ast_reducer.reduce_console(ast, function) - } - - pub fn reduce_definition( - &mut self, - ast: &AstDefinitionStatement, - asg: &AsgDefinitionStatement, - ) -> Result { - let type_; - - if asg.variables.len() > 1 { - let mut types = vec![]; - for variable in asg.variables.iter() { - types.push(variable.borrow().type_.clone()); - } - - let asg_type = AsgType::Tuple(types); - - type_ = match &ast.type_ { - Some(ast_type) => Some(self.reduce_type(ast_type, &asg_type, &ast.span)?), - None if self.options.type_inference_enabled() => Some((&asg_type).into()), - _ => None, - }; - } else { - type_ = match &ast.type_ { - Some(ast_type) => { - Some(self.reduce_type(ast_type, &asg.variables.first().unwrap().borrow().type_, &ast.span)?) - } - None if self.options.type_inference_enabled() => { - Some((&asg.variables.first().unwrap().borrow().type_).into()) - } - _ => None, - }; - } - - let value = self.reduce_expression(&ast.value, asg.value.get())?; - - self.ast_reducer - .reduce_definition(ast, ast.variable_names.clone(), type_, value) - } - - pub fn reduce_expression_statement( - &mut self, - ast: &AstExpressionStatement, - asg: &AsgExpressionStatement, - ) -> Result { - let inner_expression = self.reduce_expression(&ast.expression, asg.expression.get())?; - self.ast_reducer.reduce_expression_statement(ast, inner_expression) - } - - pub fn reduce_iteration( - &mut self, - ast: &AstIterationStatement, - asg: &AsgIterationStatement, - ) -> Result { - let start = self.reduce_expression(&ast.start, asg.start.get())?; - let stop = self.reduce_expression(&ast.stop, asg.stop.get())?; - let block; - if let AsgStatement::Block(asg_block) = asg.body.get() { - block = self.reduce_block(&ast.block, asg_block)?; - } else { - return Err(AstError::ast_statement_not_block(asg.span.as_ref().unwrap()).into()); - } - - self.ast_reducer - .reduce_iteration(ast, ast.variable.clone(), start, stop, block) - } - - pub fn reduce_return(&mut self, ast: &AstReturnStatement, asg: &AsgReturnStatement) -> Result { - let expression = self.reduce_expression(&ast.expression, asg.expression.get())?; - - self.ast_reducer.reduce_return(ast, expression) - } - - pub fn reduce_program(&mut self, ast: &leo_ast::Program, asg: &leo_asg::Program) -> Result { - let mut imports = IndexMap::new(); - for ((ast_ident, ast_program), (_asg_ident, asg_program)) in ast.imports.iter().zip(&asg.imported_modules) { - imports.insert(ast_ident.clone(), self.reduce_program(ast_program, asg_program)?); - } - - self.ast_reducer.swap_in_circuit(); - let mut circuits = IndexMap::new(); - for ((ast_ident, ast_circuit), (_asg_ident, asg_circuit)) in ast.circuits.iter().zip(&asg.circuits) { - circuits.insert(ast_ident.clone(), self.reduce_circuit(ast_circuit, asg_circuit)?); - } - self.ast_reducer.swap_in_circuit(); - - let mut functions = IndexMap::new(); - for ((ast_ident, ast_function), (_asg_ident, asg_function)) in ast.functions.iter().zip(&asg.functions) { - functions.insert(ast_ident.clone(), self.reduce_function(ast_function, asg_function)?); - } - - let mut global_consts = IndexMap::new(); - for ((ast_str, ast_definition), (_asg_str, asg_definition)) in ast.global_consts.iter().zip(&asg.global_consts) - { - global_consts.insert(ast_str.clone(), self.reduce_definition(ast_definition, asg_definition)?); - } - - self.ast_reducer.reduce_program( - ast, - ast.expected_input.clone(), - ast.import_statements.clone(), - imports, - ast.aliases.clone(), - circuits, - functions, - global_consts, - ) - } - - pub fn reduce_function(&mut self, ast: &AstFunction, asg: &AsgFunction) -> Result { - let output = ast - .output - .as_ref() - .map(|type_| self.reduce_type(type_, &asg.output, &ast.span)) - .transpose()?; - - let mut statements = vec![]; - if let Some(AsgStatement::Block(asg_block)) = asg.body.get() { - for (ast_statement, asg_statement) in ast.block.statements.iter().zip(asg_block.statements.iter()) { - statements.push(self.reduce_statement(ast_statement, asg_statement.get())?); - } - } - - let block = AstBlockStatement { - statements, - span: ast.block.span.clone(), - }; - - self.ast_reducer.reduce_function( - ast, - ast.identifier.clone(), - ast.annotations.clone(), - ast.input.clone(), - output, - block, - ) - } - - pub fn reduce_circuit_member( - &mut self, - ast: &AstCircuitMember, - asg: &AsgCircuitMember, - ) -> Result { - let new = match (ast, asg) { - (AstCircuitMember::CircuitVariable(identifier, ast_type), AsgCircuitMember::Variable(asg_type)) => { - AstCircuitMember::CircuitVariable( - identifier.clone(), - self.reduce_type(ast_type, asg_type, &identifier.span)?, - ) - } - (AstCircuitMember::CircuitFunction(ast_function), AsgCircuitMember::Function(asg_function)) => { - AstCircuitMember::CircuitFunction(self.reduce_function(ast_function, asg_function)?) - } - _ => ast.clone(), - }; - - self.ast_reducer.reduce_circuit_member(ast, new) - } - - pub fn reduce_circuit(&mut self, ast: &AstCircuit, asg: &AsgCircuit) -> Result { - let mut members = vec![]; - for (ast_member, asg_member) in ast.members.iter().zip(asg.members.borrow().iter()) { - members.push(self.reduce_circuit_member(ast_member, asg_member.1)?); - } - - self.ast_reducer.reduce_circuit(ast, ast.circuit_name.clone(), members) - } -} diff --git a/compiler/src/unused/prelude/mod.rs b/compiler/src/unused/prelude/mod.rs deleted file mode 100644 index 810fa1d788..0000000000 --- a/compiler/src/unused/prelude/mod.rs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ConstrainedValue, GroupType}; -use leo_asg::Function; -use leo_errors::{Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -pub trait CoreCircuit<'a, F: PrimeField, G: GroupType>: Send + Sync { - fn call_function>( - &self, - cs: &mut CS, - function: &'a Function<'a>, - span: &Span, - target: Option>, - arguments: Vec>, - ) -> Result>; -} - -// pub fn resolve_core_circuit<'a, F: PrimeField, G: GroupType>(name: &str) -> impl CoreCircuit<'a, F, G> { -// match name { -// "blake2s" => Blake2s, -// _ => unimplemented!("invalid core circuit: {}", name), -// } -// } diff --git a/compiler/src/unused/program/mod.rs b/compiler/src/unused/program/mod.rs deleted file mode 100644 index 38258e4a0f..0000000000 --- a/compiler/src/unused/program/mod.rs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub mod program; -pub use self::program::*; diff --git a/compiler/src/unused/program/program.rs b/compiler/src/unused/program/program.rs deleted file mode 100644 index 1110e9a7c0..0000000000 --- a/compiler/src/unused/program/program.rs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! An in memory store to keep track of defined names when constraining a Leo program. - -use crate::{value::ConstrainedValue, GroupType}; - -use leo_asg::Program; -use snarkvm_fields::PrimeField; - -use indexmap::IndexMap; - -pub struct ConstrainedProgram<'a, F: PrimeField, G: GroupType> { - pub asg: Program<'a>, - identifiers: IndexMap>, -} - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub fn new(asg: Program<'a>) -> Self { - Self { - asg, - identifiers: IndexMap::new(), - } - } - - pub(crate) fn store(&mut self, id: u32, value: ConstrainedValue<'a, F, G>) { - self.identifiers.insert(id, value); - } - - pub(crate) fn get(&self, id: u32) -> Option<&ConstrainedValue<'a, F, G>> { - self.identifiers.get(&id) - } - - pub(crate) fn get_mut(&mut self, id: u32) -> Option<&mut ConstrainedValue<'a, F, G>> { - self.identifiers.get_mut(&id) - } -} diff --git a/compiler/src/unused/statement/assign/assign.rs b/compiler/src/unused/statement/assign/assign.rs deleted file mode 100644 index 8fbf0af1e8..0000000000 --- a/compiler/src/unused/statement/assign/assign.rs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces an assign statement in a compiled Leo program. - -use crate::{arithmetic::*, program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::{AssignOperation, AssignStatement}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::{boolean::Boolean, traits::select::CondSelectGadget}; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - #[allow(clippy::too_many_arguments)] - pub fn enforce_assign_statement>( - &mut self, - cs: &mut CS, - indicator: &Boolean, - statement: &AssignStatement<'a>, - ) -> Result<()> { - // Get the name of the variable we are assigning to - let new_value = self.enforce_expression(cs, statement.value.get())?; - - self.resolve_assign(cs, statement, new_value, indicator)?; - - Ok(()) - } - - pub(super) fn enforce_assign_operation>( - cs: &mut CS, - condition: &Boolean, - scope: String, - operation: &AssignOperation, - target: &mut ConstrainedValue<'a, F, G>, - new_value: ConstrainedValue<'a, F, G>, - span: &Span, - ) -> Result<()> { - let new_value = match operation { - AssignOperation::Assign => new_value, - AssignOperation::Add => enforce_add(cs, target.clone(), new_value, span)?, - AssignOperation::Sub => enforce_sub(cs, target.clone(), new_value, span)?, - AssignOperation::Mul => enforce_mul(cs, target.clone(), new_value, span)?, - AssignOperation::Div => enforce_div(cs, target.clone(), new_value, span)?, - AssignOperation::Pow => enforce_pow(cs, target.clone(), new_value, span)?, - _ => unimplemented!("unimplemented assign operator"), - }; - let selected_value = ConstrainedValue::conditionally_select(cs.ns(|| scope), condition, &new_value, target) - .map_err(|_| CompilerError::statement_select_fail(new_value, target.clone(), span))?; - - *target = selected_value; - Ok(()) - } -} diff --git a/compiler/src/unused/statement/assign/assignee/array_index.rs b/compiler/src/unused/statement/assign/assignee/array_index.rs deleted file mode 100644 index a08064e7d3..0000000000 --- a/compiler/src/unused/statement/assign/assignee/array_index.rs +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Resolves assignees in a compiled Leo program. - -use std::convert::TryInto; - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType, Integer}; -use leo_asg::{ConstInt, Expression, Node}; -use leo_errors::{CompilerError, Result}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::traits::{eq::EvaluateEqGadget, select::CondSelectGadget}; -use snarkvm_r1cs::ConstraintSystem; - -use super::ResolverContext; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub(super) fn resolve_target_access_array_index<'b, CS: ConstraintSystem>( - &mut self, - cs: &mut CS, - mut context: ResolverContext<'a, 'b, F, G>, - index: &'a Expression<'a>, - ) -> Result<()> { - let input_len = context.input.len(); - - let index_resolved = self.enforce_index(cs, index, &context.span)?; - if !context.from_range && input_len == 1 { - match context.input.remove(0) { - ConstrainedValue::Array(input) => { - if let Some(index) = index_resolved.to_usize() { - if index >= input.len() { - Err( - CompilerError::statement_array_assign_index_bounds(index, input.len(), &context.span) - .into(), - ) - } else { - let target = input.get_mut(index).unwrap(); - if context.remaining_accesses.is_empty() { - self.enforce_assign_context(cs, &context, target) - } else { - context.input = vec![target]; - self.resolve_target_access(cs, context) - } - } - } else { - let span = index.span().cloned().unwrap_or_default(); - { - let array_len: u32 = input - .len() - .try_into() - .map_err(|_| CompilerError::array_length_out_of_bounds(&span))?; - self.array_bounds_check(cs, &index_resolved, array_len, &span)?; - } - - for (i, item) in input.iter_mut().enumerate() { - let namespace_string = format!( - "evaluate dyn array assignment eq {} {}:{}", - i, span.line_start, span.col_start - ); - let eq_namespace = cs.ns(|| namespace_string); - - let index_bounded = i - .try_into() - .map_err(|_| CompilerError::array_index_out_of_legal_bounds(&span))?; - let const_index = ConstInt::U32(index_bounded).cast_to(&index_resolved.get_type()); - let index_comparison = index_resolved - .evaluate_equal(eq_namespace, &Integer::new(&const_index)) - .map_err(|_| CompilerError::cannot_evaluate_expression("==", &span))?; - - let mut unique_namespace = cs.ns(|| { - format!( - "select array dyn assignment {} {}:{}", - i, span.line_start, span.col_start - ) - }); - let temp_item = { - let mut item = item.clone(); - let mut new_context = ResolverContext { - input: vec![&mut item], - span: context.span.clone(), - target_value: context.target_value.clone(), - remaining_accesses: context.remaining_accesses, - indicator: context.indicator, - operation: context.operation, - from_range: false, - }; - if context.remaining_accesses.is_empty() { - let item = new_context.input.remove(0); - self.enforce_assign_context(&mut unique_namespace, &new_context, item)?; - } else { - self.resolve_target_access(&mut unique_namespace, new_context)?; - } - item - }; - let value = ConstrainedValue::conditionally_select( - unique_namespace, - &index_comparison, - &temp_item, - item, - ) - .map_err(|e| CompilerError::cannot_enforce_expression("conditional select", e, &span))?; - *item = value; - } - Ok(()) - } - } - _ => Err(CompilerError::statement_array_assign_interior_index(&context.span).into()), - } - } else if context.from_range && input_len != 0 { - context.from_range = false; - if let Some(index) = index_resolved.to_usize() { - if index >= input_len { - return Err( - CompilerError::statement_array_assign_index_bounds(index, input_len, &context.span).into(), - ); - } - let target = context.input.remove(index); - - if context.remaining_accesses.is_empty() { - self.enforce_assign_context(cs, &context, target) - } else { - context.input = vec![target]; - self.resolve_target_access(cs, context) - } - } else { - // index is input variable - let span = index.span().cloned().unwrap_or_default(); - { - let array_len: u32 = context - .input - .len() - .try_into() - .map_err(|_| CompilerError::array_length_out_of_bounds(&span))?; - self.array_bounds_check(cs, &index_resolved, array_len, &span)?; - } - - for (i, item) in context.input.iter_mut().enumerate() { - let namespace_string = format!( - "evaluate dyn array assignment eq {} {}:{}", - i, span.line_start, span.col_start - ); - let eq_namespace = cs.ns(|| namespace_string); - - let index_bounded = i - .try_into() - .map_err(|_| CompilerError::array_index_out_of_legal_bounds(&span))?; - let const_index = ConstInt::U32(index_bounded).cast_to(&index_resolved.get_type()); - let index_comparison = index_resolved - .evaluate_equal(eq_namespace, &Integer::new(&const_index)) - .map_err(|_| CompilerError::cannot_evaluate_expression("==", &span))?; - - let mut unique_namespace = cs.ns(|| { - format!( - "select array dyn assignment {} {}:{}", - i, span.line_start, span.col_start - ) - }); - let temp_item = { - let mut item = item.clone(); - let mut new_context = ResolverContext { - input: vec![&mut item], - span: context.span.clone(), - target_value: context.target_value.clone(), - remaining_accesses: context.remaining_accesses, - indicator: context.indicator, - operation: context.operation, - from_range: false, - }; - if context.remaining_accesses.is_empty() { - let item = new_context.input.remove(0); - self.enforce_assign_context(&mut unique_namespace, &new_context, item)?; - } else { - self.resolve_target_access(&mut unique_namespace, new_context)?; - } - item - }; - let value = - ConstrainedValue::conditionally_select(unique_namespace, &index_comparison, &temp_item, item) - .map_err(|e| CompilerError::cannot_enforce_expression("conditional select", e, &span))?; - **item = value; - } - Ok(()) - } - } else { - Err(CompilerError::statement_array_assign_interior_index(&context.span).into()) - } - } -} diff --git a/compiler/src/unused/statement/assign/assignee/array_range_index.rs b/compiler/src/unused/statement/assign/assignee/array_range_index.rs deleted file mode 100644 index aa5234d707..0000000000 --- a/compiler/src/unused/statement/assign/assignee/array_range_index.rs +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Resolves assignees in a compiled Leo program. - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::Expression; -use leo_errors::{CompilerError, Result}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -use super::ResolverContext; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub(super) fn resolve_target_access_array_range<'b, CS: ConstraintSystem>( - &mut self, - cs: &mut CS, - mut context: ResolverContext<'a, 'b, F, G>, - start: Option<&'a Expression<'a>>, - stop: Option<&'a Expression<'a>>, - ) -> Result<()> { - let start_index = start - .map(|start| self.enforce_index(cs, start, &context.span)) - .transpose()? - .map(|x| { - x.to_usize() - .ok_or_else(|| CompilerError::statement_array_assign_index_const(&context.span)) - }) - .transpose()?; - let stop_index = stop - .map(|stop| self.enforce_index(cs, stop, &context.span)) - .transpose()? - .map(|x| { - x.to_usize() - .ok_or_else(|| CompilerError::statement_array_assign_index_const(&context.span)) - }) - .transpose()?; - let start_index = start_index.unwrap_or(0); - - if !context.from_range { - // not a range of a range - context.from_range = true; - match context.input.remove(0) { - ConstrainedValue::Array(old) => { - let stop_index = stop_index.unwrap_or(old.len()); - Self::check_range_index(start_index, stop_index, old.len(), &context.span)?; - - if context.remaining_accesses.is_empty() { - let target_values = match context.target_value { - ConstrainedValue::Array(x) => x, - _ => unimplemented!(), - }; - - for (target, target_value) in old[start_index..stop_index].iter_mut().zip(target_values) { - context.target_value = target_value; - self.enforce_assign_context(cs, &context, target)?; - } - } else { - context.input = old[start_index..stop_index].iter_mut().collect(); - self.resolve_target_access(cs, context)?; - } - Ok(()) - } - _ => Err(CompilerError::statement_array_assign_index(&context.span).into()), - } - } else { - // range of a range - let stop_index = stop_index.unwrap_or(context.input.len()); - Self::check_range_index(start_index, stop_index, context.input.len(), &context.span)?; - - context.input = context - .input - .into_iter() - .skip(start_index) - .take(stop_index - start_index) - .collect(); - if context.remaining_accesses.is_empty() { - let target_values = match context.target_value { - ConstrainedValue::Array(x) => x, - _ => unimplemented!(), - }; - - let iter = context.input.into_iter().zip(target_values.into_iter()); - context.input = vec![]; - for (target, target_value) in iter { - context.target_value = target_value; - self.enforce_assign_context(cs, &context, target)?; - } - Ok(()) - } else { - self.resolve_target_access(cs, context) - } - } - } -} diff --git a/compiler/src/unused/statement/assign/assignee/member.rs b/compiler/src/unused/statement/assign/assignee/member.rs deleted file mode 100644 index e1c2e76728..0000000000 --- a/compiler/src/unused/statement/assign/assignee/member.rs +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::Identifier; -use leo_errors::{CompilerError, Result}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -use super::ResolverContext; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub(super) fn resolve_target_access_member<'b, CS: ConstraintSystem>( - &mut self, - cs: &mut CS, - mut context: ResolverContext<'a, 'b, F, G>, - name: &Identifier, - ) -> Result<()> { - if context.input.len() != 1 { - return Err(CompilerError::statement_array_assign_interior_index(&context.span).into()); - } - match context.input.remove(0) { - ConstrainedValue::CircuitExpression(_variable, members) => { - // Modify the circuit variable in place - let matched_variable = members.iter_mut().find(|member| member.0.matches(name)); - - match matched_variable { - Some(member) => { - context.input = vec![&mut member.1]; - self.resolve_target_access(cs, context) - } - None => { - // Throw an error if the circuit variable does not exist in the circuit - Err(CompilerError::statement_undefined_circuit_variable(name, &context.span).into()) - } - } - } - // Throw an error if the circuit definition does not exist in the file - x => Err(CompilerError::undefined_circuit(x, &context.span).into()), - } - } -} diff --git a/compiler/src/unused/statement/assign/assignee/mod.rs b/compiler/src/unused/statement/assign/assignee/mod.rs deleted file mode 100644 index 5c9cbd5927..0000000000 --- a/compiler/src/unused/statement/assign/assignee/mod.rs +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Resolves assignees in a compiled Leo program. - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::{AssignAccess, AssignOperation, AssignStatement}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::boolean::Boolean; -use snarkvm_r1cs::ConstraintSystem; - -mod array_index; -mod array_range_index; -mod member; -mod tuple; - -struct ResolverContext<'a, 'b, F: PrimeField, G: GroupType> { - input: Vec<&'b mut ConstrainedValue<'a, F, G>>, - span: Span, - target_value: ConstrainedValue<'a, F, G>, - remaining_accesses: &'b [&'b AssignAccess<'a>], - indicator: &'b Boolean, - operation: AssignOperation, - from_range: bool, -} - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - fn enforce_assign_context<'b, CS: ConstraintSystem>( - &mut self, - cs: &mut CS, - context: &ResolverContext<'a, 'b, F, G>, - target: &mut ConstrainedValue<'a, F, G>, - ) -> Result<()> { - Self::enforce_assign_operation( - cs, - context.indicator, - format!("select_assign {}:{}", &context.span.line_start, &context.span.col_start), - &context.operation, - target, - context.target_value.clone(), - &context.span, - ) - } - - fn resolve_target_access<'b, CS: ConstraintSystem>( - &mut self, - cs: &mut CS, - mut context: ResolverContext<'a, 'b, F, G>, - ) -> Result<()> { - if context.remaining_accesses.is_empty() { - if context.input.len() != 1 { - panic!("invalid non-array-context multi-value assignment"); - } - let input = context.input.remove(0); - self.enforce_assign_context(cs, &context, input)?; - return Ok(()); - } - - let access = context.remaining_accesses[context.remaining_accesses.len() - 1]; - context.remaining_accesses = &context.remaining_accesses[..context.remaining_accesses.len() - 1]; - - match access { - AssignAccess::ArrayRange(start, stop) => { - self.resolve_target_access_array_range(cs, context, start.get(), stop.get()) - } - AssignAccess::ArrayIndex(index) => self.resolve_target_access_array_index(cs, context, index.get()), - AssignAccess::Tuple(index) => self.resolve_target_access_tuple(cs, context, *index), - AssignAccess::Member(identifier) => self.resolve_target_access_member(cs, context, identifier), - } - } - - pub fn resolve_assign>( - &mut self, - cs: &mut CS, - assignee: &AssignStatement<'a>, - target_value: ConstrainedValue<'a, F, G>, - indicator: &Boolean, - ) -> Result<()> { - let span = assignee.span.clone().unwrap_or_default(); - let variable = assignee.target_variable.get().borrow(); - - let mut target = self.get(variable.id).unwrap().clone(); - let accesses: Vec<_> = assignee.target_accesses.iter().rev().collect(); - self.resolve_target_access( - cs, - ResolverContext { - input: vec![&mut target], - span, - target_value, - remaining_accesses: &accesses[..], - indicator, - operation: assignee.operation, - from_range: false, - }, - )?; - *self.get_mut(variable.id).unwrap() = target; - Ok(()) - } - - pub(crate) fn check_range_index(start_index: usize, stop_index: usize, len: usize, span: &Span) -> Result<()> { - if stop_index < start_index { - Err(CompilerError::statement_array_assign_range_order(start_index, stop_index, len, span).into()) - } else if start_index > len { - Err(CompilerError::statement_array_assign_index_bounds(start_index, len, span).into()) - } else if stop_index > len { - Err(CompilerError::statement_array_assign_index_bounds(stop_index, len, span).into()) - } else { - Ok(()) - } - } -} diff --git a/compiler/src/unused/statement/assign/assignee/tuple.rs b/compiler/src/unused/statement/assign/assignee/tuple.rs deleted file mode 100644 index 7cf32c1edd..0000000000 --- a/compiler/src/unused/statement/assign/assignee/tuple.rs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_errors::{CompilerError, Result}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -use super::ResolverContext; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub(super) fn resolve_target_access_tuple<'b, CS: ConstraintSystem>( - &mut self, - cs: &mut CS, - mut context: ResolverContext<'a, 'b, F, G>, - index: usize, - ) -> Result<()> { - if context.input.len() != 1 { - return Err(CompilerError::statement_array_assign_interior_index(&context.span).into()); - } - match context.input.remove(0) { - ConstrainedValue::Tuple(old) => { - if index > old.len() { - Err(CompilerError::statement_tuple_assign_index_bounds(index, old.len(), &context.span).into()) - } else { - context.input = vec![&mut old[index]]; - self.resolve_target_access(cs, context) - } - } - _ => Err(CompilerError::statement_tuple_assign_index(&context.span).into()), - } - } -} diff --git a/compiler/src/unused/statement/assign/mod.rs b/compiler/src/unused/statement/assign/mod.rs deleted file mode 100644 index ece4dab456..0000000000 --- a/compiler/src/unused/statement/assign/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce constraints on assign statements in a compiled Leo program. - -pub mod assign; -pub use self::assign::*; - -mod assignee; diff --git a/compiler/src/unused/statement/block/block.rs b/compiler/src/unused/statement/block/block.rs deleted file mode 100644 index 63440ab1d1..0000000000 --- a/compiler/src/unused/statement/block/block.rs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a branch of a conditional or iteration statement in a compiled Leo program. - -use crate::{program::ConstrainedProgram, GroupType, IndicatorAndConstrainedValue, StatementResult}; -use leo_asg::BlockStatement; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::boolean::Boolean; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - /// Evaluates a branch of one or more statements and returns a result in - /// the given scope. - #[allow(clippy::too_many_arguments)] - pub fn evaluate_block>( - &mut self, - cs: &mut CS, - indicator: &Boolean, - block: &BlockStatement<'a>, - ) -> StatementResult>> { - let mut results = Vec::with_capacity(block.statements.len()); - // Evaluate statements. Only allow a single return argument to be returned. - for statement in block.statements.iter() { - let value = self.enforce_statement(cs, indicator, statement.get())?; - - results.extend(value); - } - - Ok(results) - } -} diff --git a/compiler/src/unused/statement/block/mod.rs b/compiler/src/unused/statement/block/mod.rs deleted file mode 100644 index 1f53722716..0000000000 --- a/compiler/src/unused/statement/block/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce constraints on a branch of a conditional or iteration statement -//! in a compiled Leo program. - -pub mod block; -pub use self::block::*; diff --git a/compiler/src/unused/statement/conditional/conditional.rs b/compiler/src/unused/statement/conditional/conditional.rs deleted file mode 100644 index c8ba369309..0000000000 --- a/compiler/src/unused/statement/conditional/conditional.rs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce constraints on statements in a compiled Leo program. - -use crate::{ - program::ConstrainedProgram, value::ConstrainedValue, GroupType, IndicatorAndConstrainedValue, StatementResult, -}; -use leo_asg::ConditionalStatement; -use leo_errors::CompilerError; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::boolean::Boolean; -use snarkvm_r1cs::ConstraintSystem; - -fn indicator_to_string(indicator: &Boolean) -> String { - indicator - .get_value() - .map(|b| b.to_string()) - .unwrap_or_else(|| "[input]".to_string()) -} - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - /// Enforces a conditional statement with one or more branches. - /// Due to R1CS constraints, we must evaluate every branch to properly construct the circuit. - /// At program execution, we will pass an `indicator` bit down to all child statements within each branch. - /// The `indicator` bit will select that branch while keeping the constraint system satisfied. - #[allow(clippy::too_many_arguments)] - pub fn enforce_conditional_statement>( - &mut self, - cs: &mut CS, - indicator: &Boolean, - statement: &ConditionalStatement<'a>, - ) -> StatementResult>> { - let span = statement.span.clone().unwrap_or_default(); - // Inherit an indicator from a previous statement. - let outer_indicator = indicator; - - // Evaluate the conditional boolean as the inner indicator - let inner_indicator = match self.enforce_expression(cs, statement.condition.get())? { - ConstrainedValue::Boolean(resolved) => resolved, - value => { - return Err(CompilerError::conditional_boolean_expression_fails_to_resolve_to_bool( - value.to_string(), - &span, - ) - .into()); - } - }; - - // If outer_indicator && inner_indicator, then select branch 1 - let outer_indicator_string = indicator_to_string(outer_indicator); - let inner_indicator_string = indicator_to_string(&inner_indicator); - let branch_1_name = format!( - "branch indicator 1 {} && {}", - outer_indicator_string, inner_indicator_string - ); - let branch_1_indicator = Boolean::and( - &mut cs.ns(|| format!("branch 1 {}:{}", &span.line_start, &span.col_start)), - outer_indicator, - &inner_indicator, - ) - .map_err(|_| CompilerError::statement_indicator_calculation(branch_1_name, &span))?; - - let mut results = vec![]; - - // Evaluate branch 1 - let mut branch_1_result = self.enforce_statement(cs, &branch_1_indicator, statement.result.get())?; - - results.append(&mut branch_1_result); - - // If outer_indicator && !inner_indicator, then select branch 2 - let inner_indicator = inner_indicator.not(); - let inner_indicator_string = indicator_to_string(&inner_indicator); - let branch_2_name = format!( - "branch indicator 2 {} && {}", - outer_indicator_string, inner_indicator_string - ); - let branch_2_indicator = Boolean::and( - &mut cs.ns(|| format!("branch 2 {}:{}", &span.line_start, &span.col_start)), - outer_indicator, - &inner_indicator, - ) - .map_err(|_| CompilerError::statement_indicator_calculation(branch_2_name, &span))?; - - // Evaluate branch 2 - let mut branch_2_result = match statement.next.get() { - Some(next) => self.enforce_statement(cs, &branch_2_indicator, next)?, - None => vec![], - }; - - results.append(&mut branch_2_result); - - // We return the results of both branches and leave it up to the caller to select the appropriate return - Ok(results) - } -} diff --git a/compiler/src/unused/statement/conditional/mod.rs b/compiler/src/unused/statement/conditional/mod.rs deleted file mode 100644 index 68fdf0b5c8..0000000000 --- a/compiler/src/unused/statement/conditional/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce constraints on conditional statements in a compiled Leo program. - -pub mod conditional; -pub use self::conditional::*; diff --git a/compiler/src/unused/statement/definition/definition.rs b/compiler/src/unused/statement/definition/definition.rs deleted file mode 100644 index 586ff67e42..0000000000 --- a/compiler/src/unused/statement/definition/definition.rs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a definition statement in a compiled Leo program. - -use crate::{program::ConstrainedProgram, ConstrainedValue, GroupType}; -use leo_asg::{DefinitionStatement, Variable}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - fn enforce_multiple_definition( - &mut self, - variable_names: &[&'a Variable<'a>], - values: Vec>, - span: &Span, - ) -> Result<()> { - if values.len() != variable_names.len() { - return Err(CompilerError::statement_invalid_number_of_definitions( - values.len(), - variable_names.len(), - span, - ) - .into()); - } - - for (variable, value) in variable_names.iter().zip(values.into_iter()) { - self.store_definition(variable, value); - } - - Ok(()) - } - - #[allow(clippy::too_many_arguments)] - pub fn enforce_definition_statement>( - &mut self, - cs: &mut CS, - statement: &DefinitionStatement<'a>, - ) -> Result<()> { - let num_variables = statement.variables.len(); - let expression = self.enforce_expression(cs, statement.value.get())?; - - let span = statement.span.clone().unwrap_or_default(); - if num_variables == 1 { - // Define a single variable with a single value - self.store_definition(statement.variables.get(0).unwrap(), expression); - Ok(()) - } else { - // Define multiple variables for an expression that returns multiple results (multiple definition) - let values = match expression { - // ConstrainedValue::Return(values) => values, - ConstrainedValue::Tuple(values) => values, - value => { - return Err(CompilerError::statement_multiple_definition(value, &span).into()); - } - }; - - self.enforce_multiple_definition(&statement.variables[..], values, &span) - } - } -} diff --git a/compiler/src/unused/statement/definition/mod.rs b/compiler/src/unused/statement/definition/mod.rs deleted file mode 100644 index 9753fa9954..0000000000 --- a/compiler/src/unused/statement/definition/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce constraints on definition statements in a compiled Leo program. - -pub mod definition; -pub use self::definition::*; diff --git a/compiler/src/unused/statement/iteration/iteration.rs b/compiler/src/unused/statement/iteration/iteration.rs deleted file mode 100644 index 1efd9e4319..0000000000 --- a/compiler/src/unused/statement/iteration/iteration.rs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces an iteration statement in a compiled Leo program. - -use crate::{ - program::ConstrainedProgram, value::ConstrainedValue, GroupType, IndicatorAndConstrainedValue, Integer, - IntegerTrait, StatementResult, -}; -use leo_asg::IterationStatement; -use leo_errors::CompilerError; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::{boolean::Boolean, integers::uint::UInt32}; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - #[allow(clippy::too_many_arguments)] - pub fn enforce_iteration_statement>( - &mut self, - cs: &mut CS, - indicator: &Boolean, - statement: &IterationStatement<'a>, - ) -> StatementResult>> { - let mut results = vec![]; - - let span = statement.span.clone().unwrap_or_default(); - - let from = self - .enforce_index(cs, statement.start.get(), &span)? - .to_usize() - .ok_or_else(|| CompilerError::statement_loop_index_const(&span))?; - let to = self - .enforce_index(cs, statement.stop.get(), &span)? - .to_usize() - .ok_or_else(|| CompilerError::statement_loop_index_const(&span))?; - - let iter: Box> = match (from < to, statement.inclusive) { - (true, true) => Box::new(from..=to), - (true, false) => Box::new(from..to), - (false, true) => Box::new((to..=from).rev()), - // add the range to the values to get correct bound - (false, false) => Box::new(((to + 1)..(from + 1)).rev()), - }; - - for i in iter { - // Store index in current function scope. - // For loop scope is not implemented. - let variable = statement.variable.borrow(); - - // todo: replace definition with var typed - self.store( - variable.id, - ConstrainedValue::Integer(Integer::U32(UInt32::constant(i as u32))), - ); - - // Evaluate statements and possibly return early - let result = self.enforce_statement( - &mut cs.ns(|| format!("for loop iteration {} {}:{}", i, &span.line_start, &span.col_start)), - indicator, - statement.body.get(), - )?; - - results.extend(result); - } - - Ok(results) - } -} diff --git a/compiler/src/unused/statement/iteration/mod.rs b/compiler/src/unused/statement/iteration/mod.rs deleted file mode 100644 index 38d8c9d7d5..0000000000 --- a/compiler/src/unused/statement/iteration/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce constraints on iteration statements in a compiled Leo program. - -pub mod iteration; -pub use self::iteration::*; diff --git a/compiler/src/unused/statement/mod.rs b/compiler/src/unused/statement/mod.rs deleted file mode 100644 index 5b98524826..0000000000 --- a/compiler/src/unused/statement/mod.rs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce constraints on statements in a Leo program. - -pub mod assign; -pub use self::assign::*; - -pub mod block; -pub use self::block::*; - -pub mod conditional; -pub use self::conditional::*; - -pub mod definition; -pub use self::definition::*; - -pub mod iteration; -pub use self::iteration::*; - -pub mod return_; -pub use self::return_::*; - -pub mod statement; -pub use self::statement::*; diff --git a/compiler/src/unused/statement/return_/mod.rs b/compiler/src/unused/statement/return_/mod.rs deleted file mode 100644 index ca74473a62..0000000000 --- a/compiler/src/unused/statement/return_/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce constraints on return statements in a compiled Leo program. - -pub mod return_; -pub use self::return_::*; diff --git a/compiler/src/unused/statement/return_/return_.rs b/compiler/src/unused/statement/return_/return_.rs deleted file mode 100644 index a539592b4e..0000000000 --- a/compiler/src/unused/statement/return_/return_.rs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a return statement in a compiled Leo program. - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::ReturnStatement; -use leo_errors::Result; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::ConstraintSystem; - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - pub fn enforce_return_statement>( - &mut self, - cs: &mut CS, - statement: &ReturnStatement<'a>, - ) -> Result> { - let result = self.enforce_expression(cs, statement.expression.get())?; - Ok(result) - } -} diff --git a/compiler/src/unused/statement/statement.rs b/compiler/src/unused/statement/statement.rs deleted file mode 100644 index 81bc267226..0000000000 --- a/compiler/src/unused/statement/statement.rs +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Enforces a statement in a compiled Leo program. - -use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType}; -use leo_asg::{Node, Statement}; -use leo_errors::{CompilerError, Result}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::boolean::Boolean; -use snarkvm_r1cs::ConstraintSystem; - -pub type StatementResult = Result; -pub type IndicatorAndConstrainedValue<'a, T, U> = (Boolean, ConstrainedValue<'a, T, U>); - -impl<'a, F: PrimeField, G: GroupType> ConstrainedProgram<'a, F, G> { - /// - /// Enforce a program statement. - /// Returns a Vector of (indicator, value) tuples. - /// Each evaluated statement may execute of one or more statements that may return early. - /// To indicate which of these return values to take we conditionally select the value according - /// to the `indicator` bit that evaluates to true. - /// - #[allow(clippy::too_many_arguments)] - pub fn enforce_statement>( - &mut self, - cs: &mut CS, - indicator: &Boolean, - statement: &'a Statement<'a>, - ) -> StatementResult>> { - let mut results = vec![]; - let span = statement.span().cloned().unwrap_or_default(); - let mut cs = cs.ns(|| format!("statement {}:{}", span.line_start, span.col_start)); - let cs = &mut cs; - - match statement { - Statement::Return(statement) => { - let return_value = (*indicator, self.enforce_return_statement(cs, statement)?); - - results.push(return_value); - } - Statement::Definition(statement) => { - self.enforce_definition_statement(cs, statement)?; - } - Statement::Assign(statement) => { - self.enforce_assign_statement(cs, indicator, statement)?; - } - Statement::Conditional(statement) => { - let result = self.enforce_conditional_statement(cs, indicator, statement)?; - - results.extend(result); - } - Statement::Iteration(statement) => { - let result = self.enforce_iteration_statement(cs, indicator, statement)?; - - results.extend(result); - } - Statement::Console(statement) => { - self.evaluate_console_function_call(cs, indicator, statement)?; - } - Statement::Expression(statement) => { - let value = self.enforce_expression(cs, statement.expression.get())?; - // handle empty return value cases - match &value { - ConstrainedValue::Tuple(values) => { - if !values.is_empty() { - results.push((*indicator, value)); - } - } - _ => { - return Err( - CompilerError::statement_unassigned(&statement.span.clone().unwrap_or_default()).into(), - ); - } - } - } - Statement::Block(statement) => { - let span = statement.span.clone().unwrap_or_default(); - let result = self.evaluate_block( - &mut cs.ns(|| format!("block {}:{}", &span.line_start, &span.col_start)), - indicator, - statement, - )?; - - results.extend(result); - } - Statement::Empty(_) => (), - }; - - Ok(results) - } -} - -/// Unwraps the indicator boolean gadget value or `false` if `None`. -/// This method is used by logging methods only. -/// We can directly get the boolean value of the indicator since we are not enforcing any -/// constraints. -pub fn get_indicator_value(indicator: &Boolean) -> bool { - indicator.get_value().unwrap_or(false) -} diff --git a/compiler/src/unused/test.rs b/compiler/src/unused/test.rs deleted file mode 100644 index 88a63b6690..0000000000 --- a/compiler/src/unused/test.rs +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use std::{ - fs, - path::{Path, PathBuf}, -}; - -use leo_asg::*; -use leo_errors::Result; - -use leo_synthesizer::{CircuitSynthesizer, SerializedCircuit, SummarizedCircuit}; -use leo_test_framework::{ - runner::{Namespace, ParseType, Runner}, - Test, -}; -use serde_yaml::Value; -use snarkvm_curves::{bls12_377::Bls12_377, edwards_bls12::Fq}; - -use crate::{compiler::Compiler, targets::edwards_bls12::EdwardsGroupType, AstSnapshotOptions, Output}; -use indexmap::IndexMap; - -pub type EdwardsTestCompiler = Compiler<'static, Fq, EdwardsGroupType>; -// pub type EdwardsConstrainedValue = ConstrainedValue<'static, Fq, EdwardsGroupType>; - -//convenience function for tests, leaks memory -pub(crate) fn make_test_context() -> AsgContext<'static> { - let allocator = Box::leak(Box::new(new_alloc_context())); - new_context(allocator) -} - -fn new_compiler(path: PathBuf, theorem_options: Option) -> EdwardsTestCompiler { - let program_name = "test".to_string(); - let output_dir = PathBuf::from("/tmp/output/"); - fs::create_dir_all(output_dir.clone()).unwrap(); - - EdwardsTestCompiler::new( - program_name, - path, - output_dir, - make_test_context(), - None, - IndexMap::new(), - theorem_options, - ) -} - -fn hash_file(path: &str) -> String { - use sha2::{Digest, Sha256}; - let mut file = fs::File::open(&Path::new(path)).unwrap(); - let mut hasher = Sha256::new(); - std::io::copy(&mut file, &mut hasher).unwrap(); - let hash = hasher.finalize(); - - format!("{:x}", hash) -} - -pub(crate) fn parse_program( - program_string: &str, - theorem_options: Option, - cwd: Option, -) -> Result { - let mut compiler = new_compiler(cwd.unwrap_or_else(|| "compiler-test".into()), theorem_options); - - compiler.parse_program_from_string(program_string)?; - - Ok(compiler) -} - -struct CompileNamespace; - -#[derive(serde::Deserialize, serde::Serialize)] -struct OutputItem { - pub input_file: String, - pub output: Output, -} - -#[derive(serde::Deserialize, serde::Serialize)] -struct CompileOutput { - pub circuit: SummarizedCircuit, - pub output: Vec, - pub initial_ast: String, - pub imports_resolved_ast: String, - pub canonicalized_ast: String, - pub type_inferenced_ast: String, -} - -impl Namespace for CompileNamespace { - fn parse_type(&self) -> ParseType { - ParseType::Whole - } - - fn run_test(&self, test: Test) -> Result { - // Check for CWD option: - // ``` cwd: import ``` - // When set, uses different working directory for current file. - // If not, uses file path as current working directory. - let cwd = test.config.get("cwd").map(|val| { - let mut cwd = test.path.clone(); - cwd.pop(); - cwd.join(&val.as_str().unwrap()) - }); - // .unwrap_or(test.path.clone()); - - let parsed = parse_program( - &test.content, - Some(AstSnapshotOptions { - spans_enabled: false, - initial: true, - imports_resolved: true, - canonicalized: true, - type_inferenced: true, - }), - cwd, - ) - .map_err(|x| x.to_string())?; - - // (name, content) - let mut inputs = vec![]; - - if let Some(Value::Sequence(field)) = test.config.get("inputs") { - for map in field { - for (name, value) in map.as_mapping().unwrap().iter() { - // Try to parse string from 'inputs' map, else fail - let value = if let serde_yaml::Value::String(value) = value { - value - } else { - return Err("Expected string in 'inputs' map".to_string()); - }; - - inputs.push((name.as_str().unwrap().to_string(), value.clone())); - } - } - } - - if let Some(input) = test.config.get("input_file") { - let input_file: PathBuf = test.path.parent().expect("no test parent dir").into(); - if let Some(name) = input.as_str() { - let mut input_file = input_file; - input_file.push(input.as_str().expect("input_file was not a string or array")); - inputs.push(( - name.to_string(), - fs::read_to_string(&input_file).expect("failed to read test input file"), - )); - } else if let Some(seq) = input.as_sequence() { - for name in seq { - let mut input_file = input_file.clone(); - input_file.push(name.as_str().expect("input_file was not a string")); - inputs.push(( - name.as_str().expect("input_file item was not a string").to_string(), - fs::read_to_string(&input_file).expect("failed to read test input file"), - )); - } - } - } - if inputs.is_empty() { - inputs.push(("empty".to_string(), "".to_string())); - } - - let state = if let Some(input) = test.config.get("state_file") { - let mut input_file: PathBuf = test.path.parent().expect("no test parent dir").into(); - input_file.push(input.as_str().expect("state_file was not a string")); - fs::read_to_string(&input_file).expect("failed to read test state file") - } else { - "".to_string() - }; - - let mut output_items = vec![]; - - let mut last_circuit = None; - for input in inputs { - let mut parsed = parsed.clone(); - parsed - .parse_input(&input.1, Path::new("input"), &state, Path::new("state")) - .map_err(|x| x.to_string())?; - let mut cs: CircuitSynthesizer = Default::default(); - let output = parsed.compile_constraints(&mut cs).map_err(|x| x.to_string())?; - let circuit: SummarizedCircuit = SerializedCircuit::from(cs).into(); - - if circuit.num_constraints == 0 { - return Err( - "- Circuit has no constraints, use inputs and registers in program to produce them".to_string(), - ); - } - - if let Some(last_circuit) = last_circuit.as_ref() { - if last_circuit != &circuit { - eprintln!( - "{}\n{}", - serde_yaml::to_string(last_circuit).unwrap(), - serde_yaml::to_string(&circuit).unwrap() - ); - return Err("- Circuit changed on different input files".to_string()); - } - } else { - last_circuit = Some(circuit); - } - - output_items.push(OutputItem { - input_file: input.0, - output, - }); - } - - let initial_ast = hash_file("/tmp/output/initial_ast.json"); - let imports_resolved_ast = hash_file("/tmp/output/imports_resolved_ast.json"); - let canonicalized_ast = hash_file("/tmp/output/canonicalization_ast.json"); - let type_inferenced_ast = hash_file("/tmp/output/type_inferenced_ast.json"); - - if fs::read_dir("/tmp/output").is_ok() { - fs::remove_dir_all(Path::new("/tmp/output")).expect("Error failed to clean up output dir."); - } - - let final_output = CompileOutput { - circuit: last_circuit.unwrap(), - output: output_items, - initial_ast, - imports_resolved_ast, - canonicalized_ast, - type_inferenced_ast, - }; - Ok(serde_yaml::to_value(&final_output).expect("serialization failed")) - } -} - -struct TestRunner; - -impl Runner for TestRunner { - fn resolve_namespace(&self, name: &str) -> Option> { - Some(match name { - "Compile" => Box::new(CompileNamespace), - _ => return None, - }) - } -} - -#[test] -pub fn compiler_tests() { - leo_test_framework::run_tests(&TestRunner, "compiler"); -} diff --git a/compiler/src/unused/value/address/address.rs b/compiler/src/unused/value/address/address.rs deleted file mode 100644 index 19a0ad9a3e..0000000000 --- a/compiler/src/unused/value/address/address.rs +++ /dev/null @@ -1,275 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ConstrainedValue, GroupType, IntegerTrait}; -use leo_ast::InputValue; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_dpc::{account::Address as AleoAddress, network::testnet2::Testnet2}; -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::{ - boolean::Boolean, - integers::uint::UInt8, - traits::{ - alloc::AllocGadget, - eq::{ConditionalEqGadget, EqGadget, EvaluateEqGadget}, - select::CondSelectGadget, - }, -}; -use snarkvm_r1cs::{Assignment, ConstraintSystem, SynthesisError}; -use snarkvm_utilities::ToBytes; -use std::{borrow::Borrow, str::FromStr}; - -/// A public address -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Address { - pub address: Option>, - pub bytes: Vec, -} - -impl Address { - pub(crate) fn constant(address: String, span: &Span) -> Result { - let address = AleoAddress::::from_str(&address) - .map_err(|e| CompilerError::address_value_account_error(e, span))?; - - let address_bytes = address.to_bytes_le().unwrap(); - - let bytes = UInt8::constant_vec(&address_bytes[..]); - - Ok(Address { - address: Some(address), - bytes, - }) - } - - pub(crate) fn is_constant(&self) -> bool { - self.bytes.iter().all(|byte| byte.is_constant()) - } - - pub(crate) fn from_input<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - name: &str, - input_value: Option, - span: &Span, - ) -> Result> { - // Check that the input value is the correct type - let address_value = match input_value { - Some(input) => { - if let InputValue::Address(string) = input { - Some(string) - } else { - return Err(CompilerError::address_value_invalid_address(name, span).into()); - } - } - None => None, - }; - - let address = Address::alloc( - cs.ns(|| format!("`{}: address` {}:{}", name, span.line_start, span.col_start)), - || address_value.ok_or(SynthesisError::AssignmentMissing), - ) - .map_err(|_| CompilerError::address_value_missing_address(span))?; - - Ok(ConstrainedValue::Address(address)) - } - - pub(crate) fn alloc_helper< - F: PrimeField, - CS: ConstraintSystem, - Fn: FnOnce() -> Result, - T: Borrow, - >( - cs: CS, - value_gen: Fn, - ) -> Result, SynthesisError> { - if cs.is_in_setup_mode() { - Ok(AleoAddress::::default()) - } else { - let address_string = value_gen()?.borrow().clone(); - AleoAddress::from_str(&address_string).map_err(|_| SynthesisError::AssignmentMissing) - } - } -} - -impl AllocGadget for Address { - fn alloc_constant Result, T: Borrow, CS: ConstraintSystem>( - _cs: CS, - value_gen: Fn, - ) -> Result { - let address: AleoAddress = { - let address_string = value_gen()?.borrow().clone(); - AleoAddress::from_str(&address_string).map_err(|_| SynthesisError::AssignmentMissing)? - }; - let address_bytes = address.to_bytes_le().map_err(|_| SynthesisError::AssignmentMissing)?; - - let bytes = UInt8::constant_vec(&address_bytes[..]); - - Ok(Address { - address: Some(address), - bytes, - }) - } - - fn alloc Result, T: Borrow, CS: ConstraintSystem>( - mut cs: CS, - value_gen: Fn, - ) -> Result { - let address: AleoAddress = Self::alloc_helper(cs.ns(|| "allocate the address"), value_gen)?; - let address_bytes = address.to_bytes_le().map_err(|_| SynthesisError::AssignmentMissing)?; - - let bytes = UInt8::alloc_vec(cs.ns(|| "allocate the address bytes"), &address_bytes[..])?; - - Ok(Address { - address: Some(address), - bytes, - }) - } - - fn alloc_input Result, T: Borrow, CS: ConstraintSystem>( - mut cs: CS, - value_gen: Fn, - ) -> Result { - let address = Self::alloc_helper(cs.ns(|| "allocate the address"), value_gen)?; - let address_bytes = address.to_bytes_le().map_err(|_| SynthesisError::AssignmentMissing)?; - - let bytes = UInt8::alloc_input_vec_le(cs.ns(|| "allocate the address bytes"), &address_bytes[..])?; - - Ok(Address { - address: Some(address), - bytes, - }) - } -} - -impl EvaluateEqGadget for Address { - fn evaluate_equal>(&self, mut cs: CS, other: &Self) -> Result { - if self.is_constant() && other.is_constant() { - Ok(Boolean::Constant(self.eq(other))) - } else { - let mut result = Boolean::constant(true); - - for (i, (a, b)) in self.bytes.iter().zip(&other.bytes).enumerate() { - let equal = - a.evaluate_equal(&mut cs.ns(|| format!("address evaluate equality for {}-th byte", i)), b)?; - - result = Boolean::and( - &mut cs.ns(|| format!("address and result for {}-th byte", i)), - &equal, - &result, - )?; - } - - Ok(result) - } - } -} - -fn cond_equal_helper(first: &Address, second: &Address, cond: bool) -> Result<(), SynthesisError> { - if cond && first.address.is_some() && second.address.is_some() { - if first.eq(second) { - Ok(()) - } else { - Err(SynthesisError::Unsatisfiable) - } - } else { - Ok(()) - } -} - -impl ConditionalEqGadget for Address { - fn conditional_enforce_equal>( - &self, - mut cs: CS, - other: &Self, - condition: &Boolean, - ) -> Result<(), SynthesisError> { - if let Boolean::Constant(cond) = *condition { - cond_equal_helper(self, other, cond) - } else { - for (i, (a, b)) in self.bytes.iter().zip(&other.bytes).enumerate() { - a.conditional_enforce_equal( - &mut cs.ns(|| format!("address equality check for {}-th byte", i)), - b, - condition, - )?; - } - Ok(()) - } - } - - fn cost() -> usize { - >::cost() * 32 // address 32 bytes - } -} - -fn cond_select_helper(first: &Address, second: &Address, cond: bool) -> Address { - if cond { - first.clone() - } else { - second.clone() - } -} - -impl CondSelectGadget for Address { - fn conditionally_select>( - mut cs: CS, - cond: &Boolean, - first: &Self, - second: &Self, - ) -> Result { - if let Boolean::Constant(cond) = *cond { - Ok(cond_select_helper(first, second, cond)) - } else { - let result_val = cond - .get_value() - .and_then(|c| if c { first.address } else { second.address }); - - let result = Self::alloc(cs.ns(|| "cond_select_result"), || { - result_val.get().map(|v| v.to_string()) - })?; - - let expected_bytes = first - .bytes - .iter() - .zip(&second.bytes) - .enumerate() - .map(|(i, (a, b))| { - UInt8::conditionally_select(&mut cs.ns(|| format!("address_cond_select_{}", i)), cond, a, b) - .unwrap() - }) - .collect::>(); - - for (i, (actual, expected)) in result.bytes.iter().zip(expected_bytes.iter()).enumerate() { - actual.enforce_equal(&mut cs.ns(|| format!("selected_result_byte_{}", i)), expected)?; - } - - Ok(result) - } - } - - fn cost() -> usize { - >::cost() * 32 - } -} - -impl std::fmt::Display for Address { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self.address { - Some(ref address) => write!(f, "{}", address), - None => write!(f, "[input address]"), - } - } -} diff --git a/compiler/src/unused/value/address/mod.rs b/compiler/src/unused/value/address/mod.rs deleted file mode 100644 index 90df8a5e0c..0000000000 --- a/compiler/src/unused/value/address/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! An address value in a compiled Leo program. - -pub mod address; -pub use self::address::*; diff --git a/compiler/src/unused/value/boolean/input.rs b/compiler/src/unused/value/boolean/input.rs deleted file mode 100644 index bcba6e7616..0000000000 --- a/compiler/src/unused/value/boolean/input.rs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce constraints on input boolean values in a resolved Leo program. - -use crate::{value::ConstrainedValue, GroupType}; -use leo_ast::InputValue; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::{boolean::Boolean, traits::alloc::AllocGadget}; -use snarkvm_r1cs::{ConstraintSystem, SynthesisError}; - -pub(crate) fn allocate_bool>( - cs: &mut CS, - name: &str, - option: Option, - span: &Span, -) -> Result { - Ok(Boolean::alloc( - cs.ns(|| format!("`{}: bool` {}:{}", name, span.line_start, span.col_start)), - || option.ok_or(SynthesisError::AssignmentMissing), - ) - .map_err(|_| CompilerError::boolean_value_missing_boolean(format!("{}: bool", name), span))?) -} - -pub(crate) fn bool_from_input<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - name: &str, - input_value: Option, - span: &Span, -) -> Result> { - // Check that the input value is the correct type - let option = match input_value { - Some(input) => { - if let InputValue::Boolean(bool) = input { - Some(bool) - } else { - return Err(CompilerError::boolean_value_invalid_boolean(name, span).into()); - } - } - None => None, - }; - - let number = allocate_bool(cs, name, option, span)?; - - Ok(ConstrainedValue::Boolean(number)) -} diff --git a/compiler/src/unused/value/boolean/mod.rs b/compiler/src/unused/value/boolean/mod.rs deleted file mode 100644 index eb57444f83..0000000000 --- a/compiler/src/unused/value/boolean/mod.rs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! A boolean value in a compiled Leo program. - -pub mod input; diff --git a/compiler/src/unused/value/char/char.rs b/compiler/src/unused/value/char/char.rs deleted file mode 100644 index ed3a268cb8..0000000000 --- a/compiler/src/unused/value/char/char.rs +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{ - value::{field::input::allocate_field, ConstrainedValue}, - FieldType, GroupType, -}; - -use leo_ast::InputValue; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::{ - boolean::Boolean, - traits::{ - bits::comparator::{ComparatorGadget, EvaluateLtGadget}, - eq::{ConditionalEqGadget, EqGadget, EvaluateEqGadget, NEqGadget}, - select::CondSelectGadget, - }, -}; -use snarkvm_r1cs::{ConstraintSystem, SynthesisError}; - -#[derive(Clone, Debug)] -pub enum CharType { - Scalar(char), - NonScalar(u32), -} - -/// A char -#[derive(Clone, Debug)] -pub struct Char { - pub character: CharType, - pub field: FieldType, -} - -impl Char { - pub fn constant>(cs: CS, character: CharType, field: String, span: &Span) -> Result { - Ok(Self { - character, - field: FieldType::constant(cs, field, span)?, - }) - } -} - -impl PartialEq for Char { - fn eq(&self, other: &Self) -> bool { - self.field.eq(&other.field) - } -} - -impl Eq for Char {} - -impl PartialOrd for Char { - fn partial_cmp(&self, other: &Self) -> Option { - self.field.partial_cmp(&other.field) - } -} - -impl EvaluateLtGadget for Char { - fn less_than>(&self, cs: CS, other: &Self) -> Result { - self.field.less_than(cs, &other.field) - } -} - -impl ComparatorGadget for Char {} - -impl EvaluateEqGadget for Char { - fn evaluate_equal>(&self, cs: CS, other: &Self) -> Result { - self.field.evaluate_equal(cs, &other.field) - } -} - -impl EqGadget for Char {} - -impl ConditionalEqGadget for Char { - fn conditional_enforce_equal>( - &self, - cs: CS, - other: &Self, - condition: &Boolean, - ) -> Result<(), SynthesisError> { - self.field.conditional_enforce_equal(cs, &other.field, condition) - } - - fn cost() -> usize { - as ConditionalEqGadget>::cost() - } -} - -impl NEqGadget for Char { - fn enforce_not_equal>(&self, cs: CS, other: &Self) -> Result<(), SynthesisError> { - self.field.enforce_not_equal(cs, &other.field) - } - - fn cost() -> usize { - as NEqGadget>::cost() - } -} - -impl CondSelectGadget for Char { - fn conditionally_select>( - cs: CS, - cond: &Boolean, - first: &Self, - second: &Self, - ) -> Result { - let field = FieldType::::conditionally_select(cs, cond, &first.field, &second.field)?; - - if field == first.field { - return Ok(Char { - character: first.character.clone(), - field, - }); - } - - Ok(Char { - character: second.character.clone(), - field, - }) - } - - fn cost() -> usize { - as CondSelectGadget>::cost() - } -} - -pub(crate) fn char_from_input<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - name: &str, - input_value: Option, - span: &Span, -) -> Result> { - // Check that the parameter value is the correct type - let option = match input_value { - Some(input) => { - if let InputValue::Char(character) = input { - match character.character { - leo_ast::Char::Scalar(scalar) => (CharType::Scalar(scalar), Some((scalar as u32).to_string())), - leo_ast::Char::NonScalar(non_scalar) => { - (CharType::NonScalar(non_scalar), Some(non_scalar.to_string())) - } - } - } else { - return Err(CompilerError::char_value_invalid_char(input, span).into()); - } - } - None => (CharType::Scalar(0 as char), None), - }; - - let field = allocate_field(cs, name, option.1, span)?; - - Ok(ConstrainedValue::Char(Char { - character: option.0, - field, - })) -} - -impl std::fmt::Display for Char { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self.character { - CharType::Scalar(scalar) => write!(f, "{}", scalar), - CharType::NonScalar(non_scalar) => write!(f, "\\u{{{:X}}}", non_scalar), - } - } -} diff --git a/compiler/src/unused/value/char/mod.rs b/compiler/src/unused/value/char/mod.rs deleted file mode 100644 index 1e918d8e74..0000000000 --- a/compiler/src/unused/value/char/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! An char value in a compiled Leo program. - -pub mod char; -pub use self::char::*; diff --git a/compiler/src/unused/value/field/field_type.rs b/compiler/src/unused/value/field/field_type.rs deleted file mode 100644 index 0dbef30991..0000000000 --- a/compiler/src/unused/value/field/field_type.rs +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! A data type that represents a field value - -use crate::number_string_typing; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::{ - bits::{ToBitsBEGadget, ToBytesGadget}, - boolean::Boolean, - fields::FpGadget, - integers::uint::UInt8, - traits::{ - alloc::AllocGadget, - bits::comparator::{ComparatorGadget, EvaluateLtGadget}, - eq::{ConditionalEqGadget, EqGadget, EvaluateEqGadget, NEqGadget}, - fields::FieldGadget, - select::CondSelectGadget, - }, -}; -use snarkvm_r1cs::{ConstraintSystem, SynthesisError}; -use std::{borrow::Borrow, cmp::Ordering}; - -#[derive(Clone, Debug)] -pub struct FieldType(FpGadget); - -impl FieldType { - /// Returns the value of the field. - pub fn get_value(&self) -> Option { - self.0.get_value() - } - - /// Returns a new `FieldType` from the given `String` or returns a `FieldError`. - pub fn constant>(cs: CS, string: String, span: &Span) -> Result { - let number_info = number_string_typing(&string); - - let value = match number_info { - (number, neg) if neg => { - -F::from_str(&number).map_err(|_| CompilerError::field_value_invalid_field(string.clone(), span))? - } - (number, _) => { - F::from_str(&number).map_err(|_| CompilerError::field_value_invalid_field(string.clone(), span))? - } - }; - - let value = FpGadget::alloc_constant(cs, || Ok(value)) - .map_err(|_| CompilerError::field_value_invalid_field(string, span))?; - - Ok(FieldType(value)) - } - - /// Returns a new `FieldType` by calling the `FpGadget` `negate` function. - pub fn negate>(&self, cs: CS, span: &Span) -> Result { - let result = self - .0 - .negate(cs) - .map_err(|e| CompilerError::field_value_negate_operation(e, span))?; - - Ok(FieldType(result)) - } - - /// Returns a new `FieldType` by calling the `FpGadget` `add` function. - pub fn add>(&self, cs: CS, other: &Self, span: &Span) -> Result { - let value = self - .0 - .add(cs, &other.0) - .map_err(|e| CompilerError::field_value_binary_operation("+", e, span))?; - - Ok(FieldType(value)) - } - - /// Returns a new `FieldType` by calling the `FpGadget` `sub` function. - pub fn sub>(&self, cs: CS, other: &Self, span: &Span) -> Result { - let value = self - .0 - .sub(cs, &other.0) - .map_err(|e| CompilerError::field_value_binary_operation("-", e, span))?; - - Ok(FieldType(value)) - } - - /// Returns a new `FieldType` by calling the `FpGadget` `mul` function. - pub fn mul>(&self, cs: CS, other: &Self, span: &Span) -> Result { - let value = self - .0 - .mul(cs, &other.0) - .map_err(|e| CompilerError::field_value_binary_operation("*", e, span))?; - - Ok(FieldType(value)) - } - - /// Returns a new `FieldType` by calling the `FpGadget` `inverse` function. - pub fn inverse>(&self, cs: CS, span: &Span) -> Result { - let value = self - .0 - .inverse(cs) - .map_err(|e| CompilerError::field_value_binary_operation("inv", e, span))?; - - Ok(FieldType(value)) - } - - /// Returns a new `FieldType` by calling the `FpGadget` `div` function. - pub fn div>(&self, mut cs: CS, other: &Self, span: &Span) -> Result { - let inverse = other.inverse(cs.ns(|| "division inverse"), span)?; - - self.mul(cs, &inverse, span) - } - - pub fn alloc_helper Result, T: Borrow>( - value_gen: Fn, - ) -> Result { - let field_string = match value_gen() { - Ok(value) => { - let string_value = value.borrow().clone(); - Ok(string_value) - } - _ => Err(SynthesisError::AssignmentMissing), - }?; - - F::from_str(&field_string).map_err(|_| SynthesisError::AssignmentMissing) - } -} - -impl AllocGadget for FieldType { - fn alloc Result, T: Borrow, CS: ConstraintSystem>( - cs: CS, - value_gen: Fn, - ) -> Result { - let value = FpGadget::alloc(cs, || Self::alloc_helper(value_gen))?; - - Ok(FieldType(value)) - } - - fn alloc_input Result, T: Borrow, CS: ConstraintSystem>( - cs: CS, - value_gen: Fn, - ) -> Result { - let value = FpGadget::alloc_input(cs, || Self::alloc_helper(value_gen))?; - - Ok(FieldType(value)) - } -} - -impl PartialEq for FieldType { - fn eq(&self, other: &Self) -> bool { - self.0.eq(&other.0) - } -} - -impl Eq for FieldType {} - -impl PartialOrd for FieldType { - fn partial_cmp(&self, other: &Self) -> Option { - let self_value = self.get_value(); - let other_value = other.get_value(); - - Option::from(self_value.cmp(&other_value)) - } -} - -impl EvaluateLtGadget for FieldType { - fn less_than>(&self, _cs: CS, _other: &Self) -> Result { - unimplemented!() - } -} - -impl ComparatorGadget for FieldType {} - -impl EvaluateEqGadget for FieldType { - fn evaluate_equal>(&self, cs: CS, other: &Self) -> Result { - self.0.is_eq(cs, &other.0) - } -} - -impl EqGadget for FieldType {} - -impl ConditionalEqGadget for FieldType { - fn conditional_enforce_equal>( - &self, - cs: CS, - other: &Self, - condition: &Boolean, - ) -> Result<(), SynthesisError> { - self.0.conditional_enforce_equal(cs, &other.0, condition) - } - - fn cost() -> usize { - 2 * as ConditionalEqGadget>::cost() - } -} - -impl NEqGadget for FieldType { - fn enforce_not_equal>(&self, cs: CS, other: &Self) -> Result<(), SynthesisError> { - self.0.enforce_not_equal(cs, &other.0) - } - - fn cost() -> usize { - as NEqGadget>::cost() - } -} - -impl CondSelectGadget for FieldType { - fn conditionally_select>( - cs: CS, - cond: &Boolean, - first: &Self, - second: &Self, - ) -> Result { - let value = FpGadget::conditionally_select(cs, cond, &first.0, &second.0)?; - - Ok(FieldType(value)) - } - - fn cost() -> usize { - 2 * as CondSelectGadget>::cost() - } -} - -impl ToBitsBEGadget for FieldType { - fn to_bits_be>(&self, cs: CS) -> Result, SynthesisError> { - self.0.to_bits_be(cs) - } - - fn to_bits_be_strict>(&self, cs: CS) -> Result, SynthesisError> { - self.0.to_bits_be(cs) - } -} - -impl ToBytesGadget for FieldType { - fn to_bytes>(&self, cs: CS) -> Result, SynthesisError> { - self.0.to_bytes(cs) - } - - fn to_bytes_strict>(&self, cs: CS) -> Result, SynthesisError> { - self.0.to_bytes_strict(cs) - } -} - -impl std::fmt::Display for FieldType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self.get_value().ok_or(std::fmt::Error) { - Ok(value) => write!(f, "{}", value), - value => write!(f, "{:?}", value), - } - } -} diff --git a/compiler/src/unused/value/field/input.rs b/compiler/src/unused/value/field/input.rs deleted file mode 100644 index 350b659f71..0000000000 --- a/compiler/src/unused/value/field/input.rs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce constraints on input field values in a compiled Leo program. - -use crate::{number_string_typing, value::ConstrainedValue, FieldType, GroupType}; -use leo_ast::InputValue; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::traits::alloc::AllocGadget; -use snarkvm_r1cs::{ConstraintSystem, SynthesisError}; - -pub(crate) fn allocate_field>( - cs: &mut CS, - name: &str, - option: Option, - span: &Span, -) -> Result> { - match option { - Some(string) => { - let number_info = number_string_typing(&string); - - match number_info { - (number, neg) if neg => FieldType::alloc( - cs.ns(|| format!("`{}: field` {}:{}", name, span.line_start, span.col_start)), - || Some(number).ok_or(SynthesisError::AssignmentMissing), - ) - .map(|value| value.negate(cs, span)) - .map_err(|_| CompilerError::field_value_missing_field(format!("{}: field", name), span))?, - (number, _) => Ok(FieldType::alloc( - cs.ns(|| format!("`{}: field` {}:{}", name, span.line_start, span.col_start)), - || Some(number).ok_or(SynthesisError::AssignmentMissing), - ) - .map_err(|_| CompilerError::field_value_missing_field(format!("{}: field", name), span))?), - } - } - None => { - return Err(CompilerError::field_value_missing_field(format!("{}: field", name), span).into()); - } - } -} - -pub(crate) fn field_from_input<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - name: &str, - input_value: Option, - span: &Span, -) -> Result> { - // Check that the parameter value is the correct type - let option = match input_value { - Some(input) => { - if let InputValue::Field(string) = input { - Some(string) - } else { - return Err(CompilerError::field_value_invalid_field(input, span).into()); - } - } - None => None, - }; - - let field = allocate_field(cs, name, option, span)?; - - Ok(ConstrainedValue::Field(field)) -} diff --git a/compiler/src/unused/value/field/mod.rs b/compiler/src/unused/value/field/mod.rs deleted file mode 100644 index fab23912b2..0000000000 --- a/compiler/src/unused/value/field/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! A field value in a compiled Leo program. - -pub mod input; - -pub mod field_type; -pub use self::field_type::*; diff --git a/compiler/src/unused/value/group/group_type.rs b/compiler/src/unused/value/group/group_type.rs deleted file mode 100644 index 8ce9ffff7a..0000000000 --- a/compiler/src/unused/value/group/group_type.rs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! A data type that represents members in the group formed by the set of affine points on a curve. - -use leo_asg::GroupValue; -use leo_errors::{Result, Span}; - -use snarkvm_fields::{Field, One}; -use snarkvm_gadgets::{ - bits::{ToBitsBEGadget, ToBytesGadget}, - traits::{ - alloc::AllocGadget, - eq::{ConditionalEqGadget, EqGadget, EvaluateEqGadget}, - select::CondSelectGadget, - }, -}; -use snarkvm_r1cs::ConstraintSystem; -use std::fmt::{Debug, Display}; - -pub trait GroupType: - Sized - + Clone - + Debug - + Display - + One - + EvaluateEqGadget - + EqGadget - + ConditionalEqGadget - + AllocGadget - + CondSelectGadget - + ToBitsBEGadget - + ToBytesGadget -{ - fn constant(value: &GroupValue, span: &Span) -> Result; - - fn to_allocated>(&self, cs: CS, span: &Span) -> Result; - - fn negate>(&self, cs: CS, span: &Span) -> Result; - - fn add>(&self, cs: CS, other: &Self, span: &Span) -> Result; - - fn sub>(&self, cs: CS, other: &Self, span: &Span) -> Result; -} diff --git a/compiler/src/unused/value/group/input.rs b/compiler/src/unused/value/group/input.rs deleted file mode 100644 index 60d5eaa917..0000000000 --- a/compiler/src/unused/value/group/input.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce constraints on input group values in a Leo program. - -use crate::{ConstrainedValue, GroupType}; -use leo_asg::GroupValue; -use leo_ast::InputValue; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_r1cs::{ConstraintSystem, SynthesisError}; - -pub(crate) fn allocate_group, CS: ConstraintSystem>( - cs: &mut CS, - name: &str, - option: Option, - span: &Span, -) -> Result { - Ok(G::alloc( - cs.ns(|| format!("`{}: group` {}:{}", name, span.line_start, span.col_start)), - || option.ok_or(SynthesisError::AssignmentMissing), - ) - .map_err(|_| CompilerError::group_value_missing_group(format!("{}: group", name), span))?) -} - -pub(crate) fn group_from_input<'a, F: PrimeField, G: GroupType, CS: ConstraintSystem>( - cs: &mut CS, - name: &str, - input_value: Option, - span: &Span, -) -> Result> { - // Check that the parameter value is the correct type - let option = match input_value { - Some(input) => { - if let InputValue::Group(string) = input { - Some(string) - } else { - return Err(CompilerError::group_value_missing_group(input, span).into()); - } - } - None => None, - }; - - let group = allocate_group( - cs, - name, - option.map(|x| match x { - leo_ast::GroupValue::Single(s, _) => GroupValue::Single(s), - leo_ast::GroupValue::Tuple(leo_ast::GroupTuple { x, y, .. }) => GroupValue::Tuple((&x).into(), (&y).into()), - }), - span, - )?; - - Ok(ConstrainedValue::Group(group)) -} diff --git a/compiler/src/unused/value/group/mod.rs b/compiler/src/unused/value/group/mod.rs deleted file mode 100644 index efc778b6cf..0000000000 --- a/compiler/src/unused/value/group/mod.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! A group value in a compiled Leo program. - -pub mod input; - -pub mod group_type; -pub use self::group_type::*; - -pub mod targets; diff --git a/compiler/src/unused/value/group/targets/edwards_bls12.rs b/compiler/src/unused/value/group/targets/edwards_bls12.rs deleted file mode 100644 index 43c84a7ed4..0000000000 --- a/compiler/src/unused/value/group/targets/edwards_bls12.rs +++ /dev/null @@ -1,558 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{number_string_typing, GroupType}; -use leo_asg::{GroupCoordinate, GroupValue}; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_curves::{ - edwards_bls12::{EdwardsAffine, EdwardsParameters, Fq}, - templates::twisted_edwards_extended::Affine, - AffineCurve, TwistedEdwardsParameters, -}; -use snarkvm_fields::{Fp256, One, Zero}; -use snarkvm_gadgets::{ - bits::{ToBitsBEGadget, ToBytesGadget}, - boolean::Boolean, - curves::edwards_bls12::EdwardsBls12Gadget, - fields::{AllocatedFp, FpGadget}, - integers::uint::UInt8, - traits::{ - alloc::AllocGadget, - curves::GroupGadget, - eq::{ConditionalEqGadget, EqGadget, EvaluateEqGadget}, - fields::FieldGadget, - }, - CondSelectGadget, -}; -use snarkvm_r1cs::{ConstraintSystem, SynthesisError}; -use std::{ - borrow::Borrow, - ops::{Add, Mul, Neg, Sub}, - str::FromStr, -}; - -#[derive(Clone, Debug)] -pub enum EdwardsGroupType { - Constant(EdwardsAffine), - Allocated(Box), -} - -impl GroupType for EdwardsGroupType { - fn constant(group: &GroupValue, span: &Span) -> Result { - let value = Self::edwards_affine_from_value(group, span)?; - - Ok(EdwardsGroupType::Constant(value)) - } - - fn to_allocated>(&self, mut cs: CS, span: &Span) -> Result { - Ok(self - .allocated(cs.ns(|| format!("allocate affine point {}:{}", span.line_start, span.col_start))) - .map(|ebg| EdwardsGroupType::Allocated(Box::new(ebg))) - .map_err(|e| CompilerError::group_value_synthesis_error(e, span))?) - } - - fn negate>(&self, cs: CS, span: &Span) -> Result { - match self { - EdwardsGroupType::Constant(group) => Ok(EdwardsGroupType::Constant(group.neg())), - EdwardsGroupType::Allocated(group) => { - let result = , Fq>>::negate(group, cs) - .map_err(|e| CompilerError::group_value_negate_operation(e, span))?; - - Ok(EdwardsGroupType::Allocated(Box::new(result))) - } - } - } - - fn add>(&self, cs: CS, other: &Self, span: &Span) -> Result { - match (self, other) { - (EdwardsGroupType::Constant(self_value), EdwardsGroupType::Constant(other_value)) => { - Ok(EdwardsGroupType::Constant(self_value.add(other_value))) - } - - (EdwardsGroupType::Allocated(self_value), EdwardsGroupType::Allocated(other_value)) => { - let result = , Fq>>::add( - self_value, - cs, - other_value, - ) - .map_err(|e| CompilerError::group_value_binary_operation("+", e, span))?; - - Ok(EdwardsGroupType::Allocated(Box::new(result))) - } - - (EdwardsGroupType::Constant(constant_value), EdwardsGroupType::Allocated(allocated_value)) - | (EdwardsGroupType::Allocated(allocated_value), EdwardsGroupType::Constant(constant_value)) => { - Ok(EdwardsGroupType::Allocated(Box::new( - allocated_value - .add_constant(cs, constant_value) - .map_err(|e| CompilerError::group_value_binary_operation("+", e, span))?, - ))) - } - } - } - - fn sub>(&self, cs: CS, other: &Self, span: &Span) -> Result { - match (self, other) { - (EdwardsGroupType::Constant(self_value), EdwardsGroupType::Constant(other_value)) => { - Ok(EdwardsGroupType::Constant(self_value.sub(other_value))) - } - - (EdwardsGroupType::Allocated(self_value), EdwardsGroupType::Allocated(other_value)) => { - let result = , Fq>>::sub( - self_value, - cs, - other_value, - ) - .map_err(|e| CompilerError::group_value_binary_operation("-", e, span))?; - - Ok(EdwardsGroupType::Allocated(Box::new(result))) - } - - (EdwardsGroupType::Constant(constant_value), EdwardsGroupType::Allocated(allocated_value)) - | (EdwardsGroupType::Allocated(allocated_value), EdwardsGroupType::Constant(constant_value)) => { - Ok(EdwardsGroupType::Allocated(Box::new( - allocated_value - .sub_constant(cs, constant_value) - .map_err(|e| CompilerError::group_value_binary_operation("-", e, span))?, - ))) - } - } - } -} - -impl EdwardsGroupType { - pub fn edwards_affine_from_value(value: &GroupValue, span: &Span) -> Result { - match value { - GroupValue::Single(number, ..) => Self::edwards_affine_from_single(number, span), - GroupValue::Tuple(x, y) => Self::edwards_affine_from_tuple(x, y, span), - } - } - - pub fn edwards_affine_from_single(number: &str, span: &Span) -> Result { - let number_info = number_string_typing(number); - - if number_info.0.eq("0") { - Ok(EdwardsAffine::zero()) - } else { - let one = edwards_affine_one(); - let number_value = match number_info { - (number, neg) if neg => { - -Fp256::from_str(&number).map_err(|_| CompilerError::group_value_n_group(number, span))? - } - (number, _) => { - Fp256::from_str(&number).map_err(|_| CompilerError::group_value_n_group(number, span))? - } - }; - - let result: EdwardsAffine = one.mul(number_value); - - Ok(result) - } - } - - pub fn edwards_affine_from_tuple(x: &GroupCoordinate, y: &GroupCoordinate, span: &Span) -> Result { - let x = x.clone(); - let y = y.clone(); - - match (x, y) { - // (x, y) - (GroupCoordinate::Number(x_string), GroupCoordinate::Number(y_string)) => Self::edwards_affine_from_pair( - number_string_typing(&x_string), - number_string_typing(&y_string), - span, - span, - span, - ), - // (x, +) - (GroupCoordinate::Number(x_string), GroupCoordinate::SignHigh) => { - Self::edwards_affine_from_x_str(number_string_typing(&x_string), span, Some(true), span) - } - // (x, -) - (GroupCoordinate::Number(x_string), GroupCoordinate::SignLow) => { - Self::edwards_affine_from_x_str(number_string_typing(&x_string), span, Some(false), span) - } - // (x, _) - (GroupCoordinate::Number(x_string), GroupCoordinate::Inferred) => { - Self::edwards_affine_from_x_str(number_string_typing(&x_string), span, None, span) - } - // (+, y) - (GroupCoordinate::SignHigh, GroupCoordinate::Number(y_string)) => { - Self::edwards_affine_from_y_str(number_string_typing(&y_string), span, Some(true), span) - } - // (-, y) - (GroupCoordinate::SignLow, GroupCoordinate::Number(y_string)) => { - Self::edwards_affine_from_y_str(number_string_typing(&y_string), span, Some(false), span) - } - // (_, y) - (GroupCoordinate::Inferred, GroupCoordinate::Number(y_string)) => { - Self::edwards_affine_from_y_str(number_string_typing(&y_string), span, None, span) - } - // Invalid - (x, y) => { - return Err(CompilerError::group_value_invalid_group(format!("({}, {})", x, y), span).into()); - } - } - } - - pub fn edwards_affine_from_x_str( - x_info: (String, bool), - x_span: &Span, - greatest: Option, - element_span: &Span, - ) -> Result { - let x = match x_info { - (x_str, neg) if neg => { - -Fq::from_str(&x_str).map_err(|_| CompilerError::group_value_x_invalid(x_str, x_span))? - } - (x_str, _) => Fq::from_str(&x_str).map_err(|_| CompilerError::group_value_x_invalid(x_str, x_span))?, - }; - - match greatest { - // Sign provided - Some(greatest) => Ok(EdwardsAffine::from_x_coordinate(x, greatest) - .ok_or_else(|| CompilerError::group_value_x_recover(element_span))?), - // Sign inferred - None => { - // Attempt to recover with a sign_low bit. - if let Some(element) = EdwardsAffine::from_x_coordinate(x, false) { - return Ok(element); - } - - // Attempt to recover with a sign_high bit. - if let Some(element) = EdwardsAffine::from_x_coordinate(x, true) { - return Ok(element); - } - - // Otherwise return error. - Err(CompilerError::group_value_x_recover(element_span).into()) - } - } - } - - pub fn edwards_affine_from_y_str( - y_info: (String, bool), - y_span: &Span, - greatest: Option, - element_span: &Span, - ) -> Result { - let y = match y_info { - (y_str, neg) if neg => { - -Fq::from_str(&y_str).map_err(|_| CompilerError::group_value_y_invalid(y_str, y_span))? - } - (y_str, _) => Fq::from_str(&y_str).map_err(|_| CompilerError::group_value_y_invalid(y_str, y_span))?, - }; - - match greatest { - // Sign provided - Some(greatest) => Ok(EdwardsAffine::from_y_coordinate(y, greatest) - .ok_or_else(|| CompilerError::group_value_y_recover(element_span))?), - // Sign inferred - None => { - // Attempt to recover with a sign_low bit. - if let Some(element) = EdwardsAffine::from_y_coordinate(y, false) { - return Ok(element); - } - - // Attempt to recover with a sign_high bit. - if let Some(element) = EdwardsAffine::from_y_coordinate(y, true) { - return Ok(element); - } - - // Otherwise return error. - Err(CompilerError::group_value_y_recover(element_span).into()) - } - } - } - - pub fn edwards_affine_from_pair( - x_info: (String, bool), - y_info: (String, bool), - x_span: &Span, - y_span: &Span, - element_span: &Span, - ) -> Result { - let x = match x_info { - (x_str, neg) if neg => { - -Fq::from_str(&x_str).map_err(|_| CompilerError::group_value_x_invalid(x_str, x_span))? - } - (x_str, _) => Fq::from_str(&x_str).map_err(|_| CompilerError::group_value_x_invalid(x_str, x_span))?, - }; - - let y = match y_info { - (y_str, neg) if neg => { - -Fq::from_str(&y_str).map_err(|_| CompilerError::group_value_y_invalid(y_str, y_span))? - } - (y_str, _) => Fq::from_str(&y_str).map_err(|_| CompilerError::group_value_y_invalid(y_str, y_span))?, - }; - - let element = EdwardsAffine::new(x, y); - - if element.is_on_curve() { - Ok(element) - } else { - Err(CompilerError::group_value_not_on_curve(element, element_span).into()) - } - } - - pub fn alloc_helper Result, T: Borrow>( - value_gen: Fn, - ) -> Result { - let group_value = match value_gen() { - Ok(value) => { - let group_value = value.borrow().clone(); - Ok(group_value) - } - _ => Err(SynthesisError::AssignmentMissing), - }?; - - Self::edwards_affine_from_value(&group_value, &Span::default()).map_err(|_| SynthesisError::AssignmentMissing) - } - - pub fn allocated>(&self, mut cs: CS) -> Result { - match self { - EdwardsGroupType::Constant(constant) => { - , Fq>>::alloc( - &mut cs.ns(|| format!("{:?}", constant)), - || Ok(constant), - ) - } - EdwardsGroupType::Allocated(allocated) => { - let x_value = allocated.x.get_value(); - let y_value = allocated.y.get_value(); - - let x_allocated = FpGadget::alloc(cs.ns(|| "x"), || x_value.ok_or(SynthesisError::AssignmentMissing))?; - let y_allocated = FpGadget::alloc(cs.ns(|| "y"), || y_value.ok_or(SynthesisError::AssignmentMissing))?; - - Ok(EdwardsBls12Gadget::new(x_allocated, y_allocated)) - } - } - } -} - -impl AllocGadget for EdwardsGroupType { - fn alloc Result, T: Borrow, CS: ConstraintSystem>( - cs: CS, - value_gen: Fn, - ) -> Result { - let value = , Fq>>::alloc(cs, || { - Self::alloc_helper(value_gen) - })?; - - Ok(EdwardsGroupType::Allocated(Box::new(value))) - } - - fn alloc_input Result, T: Borrow, CS: ConstraintSystem>( - cs: CS, - value_gen: Fn, - ) -> Result { - let value = , Fq>>::alloc_input(cs, || { - Self::alloc_helper(value_gen) - })?; - - Ok(EdwardsGroupType::Allocated(Box::new(value))) - } -} - -impl PartialEq for EdwardsGroupType { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (EdwardsGroupType::Constant(self_value), EdwardsGroupType::Constant(other_value)) => { - self_value == other_value - } - - (EdwardsGroupType::Allocated(self_value), EdwardsGroupType::Allocated(other_value)) => { - self_value.eq(other_value) - } - - (EdwardsGroupType::Constant(constant_value), EdwardsGroupType::Allocated(allocated_value)) - | (EdwardsGroupType::Allocated(allocated_value), EdwardsGroupType::Constant(constant_value)) => { - , Fq>>::get_value(allocated_value) - .map(|allocated_value| allocated_value == *constant_value) - .unwrap_or(false) - } - } - } -} - -impl Eq for EdwardsGroupType {} - -// fn compare_allocated_edwards_bls_gadgets>( -// mut cs: CS, -// first: &EdwardsBls12Gadget, -// second: &EdwardsBls12Gadget, -// ) -> Result { -// // compare x coordinates -// let x_first = &first.x; -// let x_second = &second.x; -// -// let compare_x = x_first.evaluate_equal(&mut cs.ns(|| format!("compare x")), x_second)?; -// -// // compare y coordinates -// let y_first = &first.y; -// let y_second = &second.y; -// -// let compare_y = y_first.evaluate_equal(&mut cs.ns(|| format!("compare y")), y_second)?; -// -// Boolean::and( -// &mut cs.ns(|| format!("compare x and y results")), -// &compare_x, -// &compare_y, -// ) -// } - -impl EvaluateEqGadget for EdwardsGroupType { - fn evaluate_equal>(&self, mut _cs: CS, other: &Self) -> Result { - match (self, other) { - (EdwardsGroupType::Constant(self_value), EdwardsGroupType::Constant(other_value)) => { - Ok(Boolean::constant(self_value.eq(other_value))) - } - _ => unimplemented!(), - // (EdwardsGroupType::Allocated(first), EdwardsGroupType::Allocated(second)) => { - // compare_allocated_edwards_bls_gadgets(cs, first, second) - // } - // (EdwardsGroupType::Constant(constant_value), EdwardsGroupType::Allocated(allocated_value)) - // | (EdwardsGroupType::Allocated(allocated_value), EdwardsGroupType::Constant(constant_value)) => { - // let allocated_constant_value = - // , Fq>>::alloc( - // &mut cs.ns(|| format!("alloc constant for eq")), - // || Ok(constant_value), - // )?; - // compare_allocated_edwards_bls_gadgets(cs, allocated_value, &allocated_constant_value) - // } - } - } -} - -impl EqGadget for EdwardsGroupType {} - -impl ConditionalEqGadget for EdwardsGroupType { - #[inline] - fn conditional_enforce_equal>( - &self, - mut cs: CS, - other: &Self, - condition: &Boolean, - ) -> Result<(), SynthesisError> { - match (self, other) { - // c - c - (EdwardsGroupType::Constant(self_value), EdwardsGroupType::Constant(other_value)) => { - if self_value == other_value { - return Ok(()); - } - Err(SynthesisError::AssignmentMissing) - } - // a - a - (EdwardsGroupType::Allocated(self_value), EdwardsGroupType::Allocated(other_value)) => { - ::conditional_enforce_equal(self_value, cs, other_value, condition) - } - // c - a = a - c - (EdwardsGroupType::Constant(constant_value), EdwardsGroupType::Allocated(allocated_value)) - | (EdwardsGroupType::Allocated(allocated_value), EdwardsGroupType::Constant(constant_value)) => { - let x = FpGadget::from(AllocatedFp::from(&mut cs, &constant_value.x)); - let y = FpGadget::from(AllocatedFp::from(&mut cs, &constant_value.y)); - let constant_gadget = EdwardsBls12Gadget::new(x, y); - - constant_gadget.conditional_enforce_equal(cs, allocated_value, condition) - } - } - } - - fn cost() -> usize { - 2 * >::cost() //upper bound - } -} - -impl CondSelectGadget for EdwardsGroupType { - fn conditionally_select>( - mut cs: CS, - cond: &Boolean, - first: &Self, - second: &Self, - ) -> Result { - if let Boolean::Constant(cond) = *cond { - if cond { - Ok(first.clone()) - } else { - Ok(second.clone()) - } - } else { - let first_gadget = first.allocated(cs.ns(|| "first"))?; - let second_gadget = second.allocated(cs.ns(|| "second"))?; - let result = EdwardsBls12Gadget::conditionally_select(cs, cond, &first_gadget, &second_gadget)?; - - Ok(EdwardsGroupType::Allocated(Box::new(result))) - } - } - - fn cost() -> usize { - 2 * >::cost() - } -} - -impl ToBitsBEGadget for EdwardsGroupType { - fn to_bits_be>(&self, mut cs: CS) -> Result, SynthesisError> { - let self_gadget = self.allocated(&mut cs)?; - self_gadget.to_bits_be(cs) - } - - fn to_bits_be_strict>(&self, mut cs: CS) -> Result, SynthesisError> { - let self_gadget = self.allocated(&mut cs)?; - self_gadget.to_bits_be_strict(cs) - } -} - -impl ToBytesGadget for EdwardsGroupType { - fn to_bytes>(&self, mut cs: CS) -> Result, SynthesisError> { - let self_gadget = self.allocated(&mut cs)?; - self_gadget.to_bytes(cs) - } - - fn to_bytes_strict>(&self, mut cs: CS) -> Result, SynthesisError> { - let self_gadget = self.allocated(&mut cs)?; - self_gadget.to_bytes_strict(cs) - } -} - -fn edwards_affine_one() -> Affine { - let (x, y) = EdwardsParameters::AFFINE_GENERATOR_COEFFS; - - EdwardsAffine::new(x, y) -} - -impl One for EdwardsGroupType { - fn one() -> Self { - let one = edwards_affine_one(); - - Self::Constant(one) - } - - fn is_one(&self) -> bool { - self.eq(&Self::one()) - } -} - -impl std::fmt::Display for EdwardsGroupType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self { - EdwardsGroupType::Constant(constant) => write!(f, "({}, {})group", constant.x, constant.y), - EdwardsGroupType::Allocated(allocated) => match (allocated.x.get_value(), allocated.y.get_value()) { - (Some(x), Some(y)) => write!(f, "({}, {})group", x, y), - allocated => write!(f, "{:?}", allocated), - }, - } - } -} diff --git a/compiler/src/unused/value/group/targets/mod.rs b/compiler/src/unused/value/group/targets/mod.rs deleted file mode 100644 index 5efd8393fb..0000000000 --- a/compiler/src/unused/value/group/targets/mod.rs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! implemented group targets - -pub mod edwards_bls12; diff --git a/compiler/src/unused/value/integer/integer.rs b/compiler/src/unused/value/integer/integer.rs deleted file mode 100644 index e379213e21..0000000000 --- a/compiler/src/unused/value/integer/integer.rs +++ /dev/null @@ -1,316 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Conversion of integer declarations to constraints in Leo. -use crate::IntegerTrait; -use leo_asg::{ConstInt, IntegerType}; -use leo_ast::InputValue; -use leo_errors::{CompilerError, Result, Span}; - -use snarkvm_fields::{Field, PrimeField}; -use snarkvm_gadgets::{ - boolean::Boolean, - integers::{ - int::{Int128, Int16, Int32, Int64, Int8}, - uint::{Sub as UIntSub, *}, - }, - traits::{ - alloc::AllocGadget, - bits::comparator::{ComparatorGadget, EvaluateLtGadget}, - eq::{ConditionalEqGadget, EqGadget, EvaluateEqGadget}, - integers::{Add, Div, Mul, Neg, Pow, Sub}, - select::CondSelectGadget, - }, -}; -use snarkvm_r1cs::{ConstraintSystem, SynthesisError}; -use std::{convert::TryInto, fmt}; - -/// An integer type enum wrapping the integer value. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd)] -pub enum Integer { - U8(UInt8), - U16(UInt16), - U32(UInt32), - U64(UInt64), - U128(UInt128), - - I8(Int8), - I16(Int16), - I32(Int32), - I64(Int64), - I128(Int128), -} - -impl fmt::Display for Integer { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let integer = self; - let option = match_integer!(integer => integer.get_value()); - match option { - Some(number) => write!(f, "{}", number), - None => write!(f, "[input]{}", self.get_type()), - } - } -} - -impl Integer { - /// - /// Returns a new integer from an expression. - /// - /// Checks that the expression is equal to the expected type if given. - /// - pub fn new(value: &ConstInt) -> Self { - match value { - ConstInt::U8(i) => Integer::U8(UInt8::constant(*i)), - ConstInt::U16(i) => Integer::U16(UInt16::constant(*i)), - ConstInt::U32(i) => Integer::U32(UInt32::constant(*i)), - ConstInt::U64(i) => Integer::U64(UInt64::constant(*i)), - ConstInt::U128(i) => Integer::U128(UInt128::constant(*i)), - ConstInt::I8(i) => Integer::I8(Int8::constant(*i)), - ConstInt::I16(i) => Integer::I16(Int16::constant(*i)), - ConstInt::I32(i) => Integer::I32(Int32::constant(*i)), - ConstInt::I64(i) => Integer::I64(Int64::constant(*i)), - ConstInt::I128(i) => Integer::I128(Int128::constant(*i)), - } - } - - pub fn get_bits(&self) -> Vec { - let integer = self; - match_integer!(integer => integer.to_bits_le()) - } - - pub fn is_allocated(&self) -> bool { - self.get_bits() - .into_iter() - .any(|b| matches!(b, Boolean::Is(_) | Boolean::Not(_))) - } - - pub fn get_value(&self) -> Option { - let integer = self; - match_integer!(integer => integer.get_value()) - } - - pub fn to_usize(&self) -> Option { - if self.is_allocated() { - return None; - } - let unsigned_integer = self; - match_unsigned_integer!(unsigned_integer => unsigned_integer.value.map(|num| num.try_into().ok()).flatten()) - } - - pub fn get_type(&self) -> IntegerType { - match self { - Integer::U8(_u8) => IntegerType::U8, - Integer::U16(_u16) => IntegerType::U16, - Integer::U32(_u32) => IntegerType::U32, - Integer::U64(_u64) => IntegerType::U64, - Integer::U128(_u128) => IntegerType::U128, - - Integer::I8(_u8) => IntegerType::I8, - Integer::I16(_u16) => IntegerType::I16, - Integer::I32(_u32) => IntegerType::I32, - Integer::I64(_u64) => IntegerType::I64, - Integer::I128(_u128) => IntegerType::I128, - } - } - - pub fn allocate_type>( - cs: &mut CS, - integer_type: &IntegerType, - name: &str, - option: Option, - span: &Span, - ) -> Result { - Ok(match integer_type { - IntegerType::U8 => allocate_type!(u8, UInt8, Integer::U8, cs, name, option, span), - IntegerType::U16 => allocate_type!(u16, UInt16, Integer::U16, cs, name, option, span), - IntegerType::U32 => allocate_type!(u32, UInt32, Integer::U32, cs, name, option, span), - IntegerType::U64 => allocate_type!(u64, UInt64, Integer::U64, cs, name, option, span), - IntegerType::U128 => allocate_type!(u128, UInt128, Integer::U128, cs, name, option, span), - - IntegerType::I8 => allocate_type!(i8, Int8, Integer::I8, cs, name, option, span), - IntegerType::I16 => allocate_type!(i16, Int16, Integer::I16, cs, name, option, span), - IntegerType::I32 => allocate_type!(i32, Int32, Integer::I32, cs, name, option, span), - IntegerType::I64 => allocate_type!(i64, Int64, Integer::I64, cs, name, option, span), - IntegerType::I128 => allocate_type!(i128, Int128, Integer::I128, cs, name, option, span), - }) - } - - pub fn from_input>( - cs: &mut CS, - integer_type: &IntegerType, - name: &str, - integer_value: Option, - span: &Span, - ) -> Result { - // Check that the input value is the correct type - let option = match integer_value { - Some(input) => { - if let InputValue::Integer(type_, number) = input { - let asg_type = IntegerType::from(type_); - if std::mem::discriminant(&asg_type) != std::mem::discriminant(integer_type) { - return Err( - CompilerError::integer_value_integer_type_mismatch(integer_type, asg_type, span).into(), - ); - } - Some(number) - } else { - return Err(CompilerError::integer_value_invalid_integer(input, span).into()); - } - } - None => None, - }; - - Self::allocate_type(cs, integer_type, name, option, span) - } - - pub fn negate>(self, cs: &mut CS, span: &Span) -> Result { - let unique_namespace = format!("enforce -{} {}:{}", self, span.line_start, span.col_start); - - let a = self; - - let result = match_signed_integer!(a, span => a.neg(cs.ns(|| unique_namespace))); - - Ok(result.ok_or_else(|| CompilerError::integer_value_negate_operation(span))?) - } - - pub fn add>(self, cs: &mut CS, other: Self, span: &Span) -> Result { - let unique_namespace = format!("enforce {} + {} {}:{}", self, other, span.line_start, span.col_start); - - let a = self; - let b = other; - - let result = match_integers_span!((a, b), span => a.add(cs.ns(|| unique_namespace), &b)); - - Ok(result.ok_or_else(|| CompilerError::integer_value_binary_operation("+", span))?) - } - - pub fn sub>(self, cs: &mut CS, other: Self, span: &Span) -> Result { - let unique_namespace = format!("enforce {} - {} {}:{}", self, other, span.line_start, span.col_start); - - let a = self; - let b = other; - - let result = match_integers_span!((a, b), span => a.sub(cs.ns(|| unique_namespace), &b)); - - Ok(result.ok_or_else(|| CompilerError::integer_value_binary_operation("-", span))?) - } - - pub fn mul>(self, cs: &mut CS, other: Self, span: &Span) -> Result { - let unique_namespace = format!("enforce {} * {} {}:{}", self, other, span.line_start, span.col_start); - - let a = self; - let b = other; - - let result = match_integers_span!((a, b), span => a.mul(cs.ns(|| unique_namespace), &b)); - - Ok(result.ok_or_else(|| CompilerError::integer_value_binary_operation("*", span))?) - } - - pub fn div>(self, cs: &mut CS, other: Self, span: &Span) -> Result { - let unique_namespace = format!("enforce {} ÷ {} {}:{}", self, other, span.line_start, span.col_start); - - let a = self; - let b = other; - - let result = match_integers_span!((a, b), span => a.div(cs.ns(|| unique_namespace), &b)); - - Ok(result.ok_or_else(|| CompilerError::integer_value_binary_operation("÷", span))?) - } - - pub fn pow>(self, cs: &mut CS, other: Self, span: &Span) -> Result { - let unique_namespace = format!("enforce {} ** {} {}:{}", self, other, span.line_start, span.col_start); - - let a = self; - let b = other; - - let result = match_integers_span!((a, b), span => a.pow(cs.ns(|| unique_namespace), &b)); - - Ok(result.ok_or_else(|| CompilerError::integer_value_binary_operation("**", span))?) - } -} - -impl EvaluateEqGadget for Integer { - fn evaluate_equal>(&self, cs: CS, other: &Self) -> Result { - let a = self; - let b = other; - - let result = match_integers!((a, b) => a.evaluate_equal(cs, b)); - - result.ok_or(SynthesisError::Unsatisfiable) - } -} - -impl EvaluateLtGadget for Integer { - fn less_than>(&self, cs: CS, other: &Self) -> Result { - let a = self; - let b = other; - let result = match_integers!((a, b) => a.less_than(cs, b)); - - result.ok_or(SynthesisError::Unsatisfiable) - } -} - -impl ComparatorGadget for Integer {} - -impl EqGadget for Integer {} - -impl ConditionalEqGadget for Integer { - fn conditional_enforce_equal>( - &self, - cs: CS, - other: &Self, - condition: &Boolean, - ) -> Result<(), SynthesisError> { - let a = self; - let b = other; - - let result = match_integers!((a, b) => a.conditional_enforce_equal(cs, b, condition)); - - result.ok_or(SynthesisError::Unsatisfiable) - } - - fn cost() -> usize { - unimplemented!() // cannot determine which integer we are enforcing - } -} - -impl CondSelectGadget for Integer { - fn conditionally_select>( - cs: CS, - cond: &Boolean, - first: &Self, - second: &Self, - ) -> Result { - match (first, second) { - (Integer::U8(a), Integer::U8(b)) => Ok(Integer::U8(UInt8::conditionally_select(cs, cond, a, b)?)), - (Integer::U16(a), Integer::U16(b)) => Ok(Integer::U16(UInt16::conditionally_select(cs, cond, a, b)?)), - (Integer::U32(a), Integer::U32(b)) => Ok(Integer::U32(UInt32::conditionally_select(cs, cond, a, b)?)), - (Integer::U64(a), Integer::U64(b)) => Ok(Integer::U64(UInt64::conditionally_select(cs, cond, a, b)?)), - (Integer::U128(a), Integer::U128(b)) => Ok(Integer::U128(UInt128::conditionally_select(cs, cond, a, b)?)), - (Integer::I8(a), Integer::I8(b)) => Ok(Integer::I8(Int8::conditionally_select(cs, cond, a, b)?)), - (Integer::I16(a), Integer::I16(b)) => Ok(Integer::I16(Int16::conditionally_select(cs, cond, a, b)?)), - (Integer::I32(a), Integer::I32(b)) => Ok(Integer::I32(Int32::conditionally_select(cs, cond, a, b)?)), - (Integer::I64(a), Integer::I64(b)) => Ok(Integer::I64(Int64::conditionally_select(cs, cond, a, b)?)), - (Integer::I128(a), Integer::I128(b)) => Ok(Integer::I128(Int128::conditionally_select(cs, cond, a, b)?)), - - (_, _) => Err(SynthesisError::Unsatisfiable), // types do not match - } - } - - fn cost() -> usize { - unimplemented!() // cannot determine which integer we are enforcing - } -} diff --git a/compiler/src/unused/value/integer/macros.rs b/compiler/src/unused/value/integer/macros.rs deleted file mode 100644 index 67ae416946..0000000000 --- a/compiler/src/unused/value/integer/macros.rs +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub use snarkvm_gadgets::integer::Integer as IntegerTrait; - -/// Useful macros to avoid duplicating `match` constructions. -#[macro_export] -macro_rules! match_integer { - ($integer: ident => $expression: expr) => { - match $integer { - Integer::U8($integer) => $expression, - Integer::U16($integer) => $expression, - Integer::U32($integer) => $expression, - Integer::U64($integer) => $expression, - Integer::U128($integer) => $expression, - - Integer::I8($integer) => $expression, - Integer::I16($integer) => $expression, - Integer::I32($integer) => $expression, - Integer::I64($integer) => $expression, - Integer::I128($integer) => $expression, - } - }; -} - -#[macro_export] -macro_rules! match_unsigned_integer { - ($integer: ident => $expression: expr) => { - match $integer { - Integer::U8($integer) => $expression, - Integer::U16($integer) => $expression, - Integer::U32($integer) => $expression, - Integer::U64($integer) => $expression, - Integer::U128($integer) => $expression, - - _ => None, - } - }; -} - -#[macro_export] -macro_rules! match_signed_integer { - ($integer: ident, $span: ident => $expression: expr) => { - match $integer { - Integer::I8($integer) => Some(Integer::I8( - $expression.map_err(|e| CompilerError::integer_value_signed(e, $span))?, - )), - Integer::I16($integer) => Some(Integer::I16( - $expression.map_err(|e| CompilerError::integer_value_signed(e, $span))?, - )), - Integer::I32($integer) => Some(Integer::I32( - $expression.map_err(|e| CompilerError::integer_value_signed(e, $span))?, - )), - Integer::I64($integer) => Some(Integer::I64( - $expression.map_err(|e| CompilerError::integer_value_signed(e, $span))?, - )), - Integer::I128($integer) => Some(Integer::I128( - $expression.map_err(|e| CompilerError::integer_value_signed(e, $span))?, - )), - - _ => None, - } - }; -} - -#[macro_export] -macro_rules! match_integers { - (($a: ident, $b: ident) => $expression:expr) => { - match ($a, $b) { - (Integer::U8($a), Integer::U8($b)) => Some($expression?), - (Integer::U16($a), Integer::U16($b)) => Some($expression?), - (Integer::U32($a), Integer::U32($b)) => Some($expression?), - (Integer::U64($a), Integer::U64($b)) => Some($expression?), - (Integer::U128($a), Integer::U128($b)) => Some($expression?), - - (Integer::I8($a), Integer::I8($b)) => Some($expression?), - (Integer::I16($a), Integer::I16($b)) => Some($expression?), - (Integer::I32($a), Integer::I32($b)) => Some($expression?), - (Integer::I64($a), Integer::I64($b)) => Some($expression?), - (Integer::I128($a), Integer::I128($b)) => Some($expression?), - (_, _) => None, - } - }; -} - -#[macro_export] -macro_rules! match_integers_span { - (($a: ident, $b: ident), $span: ident => $expression:expr) => { - match ($a, $b) { - (Integer::U8($a), Integer::U8($b)) => Some(Integer::U8( - $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?, - )), - (Integer::U16($a), Integer::U16($b)) => Some(Integer::U16( - $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?, - )), - (Integer::U32($a), Integer::U32($b)) => Some(Integer::U32( - $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?, - )), - (Integer::U64($a), Integer::U64($b)) => Some(Integer::U64( - $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?, - )), - (Integer::U128($a), Integer::U128($b)) => Some(Integer::U128( - $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?, - )), - - (Integer::I8($a), Integer::I8($b)) => Some(Integer::I8( - $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?, - )), - (Integer::I16($a), Integer::I16($b)) => Some(Integer::I16( - $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?, - )), - (Integer::I32($a), Integer::I32($b)) => Some(Integer::I32( - $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?, - )), - (Integer::I64($a), Integer::I64($b)) => Some(Integer::I64( - $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?, - )), - (Integer::I128($a), Integer::I128($b)) => Some(Integer::I128( - $expression.map_err(|e| CompilerError::integer_value_unsigned(e, $span))?, - )), - (_, _) => None, - } - }; -} - -macro_rules! allocate_type { - ($rust_ty:ty, $gadget_ty:ty, $leo_ty:path, $cs:expr, $name:expr, $option:expr, $span:expr) => {{ - let option = $option - .map(|s| { - s.parse::<$rust_ty>() - .map_err(|_| CompilerError::integer_value_invalid_integer(s, $span)) - }) - .transpose()?; - - let result = <$gadget_ty>::alloc( - $cs.ns(|| { - format!( - "`{}: {}` {}:{}", - $name.to_string(), - stringify!($rust_ty), - $span.line_start, - $span.col_start - ) - }), - || option.ok_or(SynthesisError::AssignmentMissing), - ) - .map_err(|_| { - CompilerError::integer_value_missing_integer( - format!("{}: {}", $name.to_string(), stringify!($rust_ty)), - $span, - ) - })?; - - $leo_ty(result) - }}; -} diff --git a/compiler/src/unused/value/integer/mod.rs b/compiler/src/unused/value/integer/mod.rs deleted file mode 100644 index 2dd7a93129..0000000000 --- a/compiler/src/unused/value/integer/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -#[macro_use] -pub mod macros; -pub use self::macros::*; - -pub mod integer; -pub use self::integer::*; diff --git a/compiler/src/unused/value/mod.rs b/compiler/src/unused/value/mod.rs deleted file mode 100644 index e292e7b117..0000000000 --- a/compiler/src/unused/value/mod.rs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! Methods to enforce constraints on values in a Leo program. - -pub mod address; -pub use self::address::*; - -pub mod boolean; - -pub mod char; -pub use self::char::*; - -pub mod field; -pub use self::field::*; - -pub mod group; -pub use self::group::*; - -pub mod integer; -pub use self::integer::*; - -pub mod value; -pub use self::value::*; - -pub(crate) fn number_string_typing(number: &str) -> (String, bool) { - let first_char = number.chars().next().unwrap(); - - // Check if first symbol is a negative. - // If so strip it, parse rest of string and then negate it. - if first_char == '-' { - let uint = number.chars().next().map(|c| &number[c.len_utf8()..]).unwrap_or(""); - (uint.to_string(), true) - } else { - (number.to_string(), false) - } -} diff --git a/compiler/src/unused/value/value.rs b/compiler/src/unused/value/value.rs deleted file mode 100644 index 2a227ba845..0000000000 --- a/compiler/src/unused/value/value.rs +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -//! The in memory stored value for a defined name in a compiled Leo program. - -use crate::{Address, Char, FieldType, GroupType, Integer}; -use leo_asg::{Circuit, Identifier, Type}; -use leo_errors::{Result, Span}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::{ - bits::Boolean, - traits::{eq::ConditionalEqGadget, select::CondSelectGadget}, -}; -use snarkvm_r1cs::{ConstraintSystem, SynthesisError}; -use std::fmt; - -#[derive(Clone, PartialEq, Eq)] -pub struct ConstrainedCircuitMember<'a, F: PrimeField, G: GroupType>(pub Identifier, pub ConstrainedValue<'a, F, G>); - -#[derive(Clone, PartialEq, Eq)] -pub enum ConstrainedValue<'a, F: PrimeField, G: GroupType> { - // Data types - Address(Address), - Boolean(Boolean), - Char(Char), - Field(FieldType), - Group(G), - Integer(Integer), - - // Arrays - Array(Vec>), - - // Tuples - Tuple(Vec>), - - // Circuits - CircuitExpression(&'a Circuit<'a>, Vec>), -} - -impl<'a, F: PrimeField, G: GroupType> ConstrainedValue<'a, F, G> { - pub(crate) fn to_type(&self, span: &Span) -> Result> { - Ok(match self { - // Data types - ConstrainedValue::Address(_address) => Type::Address, - ConstrainedValue::Boolean(_bool) => Type::Boolean, - ConstrainedValue::Char(_char) => Type::Char, - ConstrainedValue::Field(_field) => Type::Field, - ConstrainedValue::Group(_group) => Type::Group, - ConstrainedValue::Integer(integer) => Type::Integer(integer.get_type()), - - // Data type wrappers - ConstrainedValue::Array(array) => { - let array_type = array[0].to_type(span)?; - - Type::Array(Box::new(array_type), array.len()) - } - ConstrainedValue::Tuple(tuple) => { - let mut types = Vec::with_capacity(tuple.len()); - - for value in tuple { - let type_ = value.to_type(span)?; - types.push(type_) - } - - Type::Tuple(types) - } - ConstrainedValue::CircuitExpression(id, _members) => Type::Circuit(*id), - }) - } -} - -impl<'a, F: PrimeField, G: GroupType> fmt::Display for ConstrainedValue<'a, F, G> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - // Data types - ConstrainedValue::Address(ref value) => write!(f, "{}", value), - ConstrainedValue::Boolean(ref value) => write!( - f, - "{}", - value - .get_value() - .map(|v| v.to_string()) - .unwrap_or_else(|| "[allocated]".to_string()) - ), - ConstrainedValue::Char(ref value) => write!(f, "{}", value), - ConstrainedValue::Field(ref value) => write!(f, "{}", value), - ConstrainedValue::Group(ref value) => write!(f, "{}", value), - ConstrainedValue::Integer(ref value) => write!(f, "{}", value), - - // Data type wrappers - ConstrainedValue::Array(ref array) => { - if matches!(array[0], ConstrainedValue::Char(_)) { - for character in array { - write!(f, "{}", character)?; - } - - Ok(()) - } else { - write!(f, "[")?; - for (i, e) in array.iter().enumerate() { - write!(f, "{}", e)?; - if i < array.len() - 1 { - write!(f, ", ")?; - } - } - write!(f, "]") - } - } - ConstrainedValue::Tuple(ref tuple) => { - let values = tuple.iter().map(|x| x.to_string()).collect::>().join(", "); - - write!(f, "({})", values) - } - ConstrainedValue::CircuitExpression(circuit, ref members) => { - write!(f, "{} {{", circuit.name.borrow())?; - for (i, member) in members.iter().enumerate() { - write!(f, "{}: {}", member.0, member.1)?; - if i < members.len() - 1 { - write!(f, ", ")?; - } - } - write!(f, "}}") - } - } - } -} - -impl<'a, F: PrimeField, G: GroupType> fmt::Debug for ConstrainedValue<'a, F, G> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self) - } -} - -impl<'a, F: PrimeField, G: GroupType> ConditionalEqGadget for ConstrainedValue<'a, F, G> { - fn conditional_enforce_equal>( - &self, - mut cs: CS, - other: &Self, - condition: &Boolean, - ) -> Result<(), SynthesisError> { - match (self, other) { - (ConstrainedValue::Address(address_1), ConstrainedValue::Address(address_2)) => { - address_1.conditional_enforce_equal(cs, address_2, condition) - } - (ConstrainedValue::Boolean(bool_1), ConstrainedValue::Boolean(bool_2)) => { - bool_1.conditional_enforce_equal(cs, bool_2, condition) - } - (ConstrainedValue::Char(char_1), ConstrainedValue::Char(char_2)) => { - char_1.conditional_enforce_equal(cs, char_2, condition) - } - (ConstrainedValue::Field(field_1), ConstrainedValue::Field(field_2)) => { - field_1.conditional_enforce_equal(cs, field_2, condition) - } - (ConstrainedValue::Group(group_1), ConstrainedValue::Group(group_2)) => { - group_1.conditional_enforce_equal(cs, group_2, condition) - } - (ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => { - num_1.conditional_enforce_equal(cs, num_2, condition) - } - (ConstrainedValue::Array(arr_1), ConstrainedValue::Array(arr_2)) => { - for (i, (left, right)) in arr_1.iter().zip(arr_2.iter()).enumerate() { - left.conditional_enforce_equal(cs.ns(|| format!("array[{}]", i)), right, condition)?; - } - Ok(()) - } - (ConstrainedValue::Tuple(tuple_1), ConstrainedValue::Tuple(tuple_2)) => { - for (i, (left, right)) in tuple_1.iter().zip(tuple_2.iter()).enumerate() { - left.conditional_enforce_equal(cs.ns(|| format!("tuple index {}", i)), right, condition)?; - } - Ok(()) - } - (_, _) => Err(SynthesisError::Unsatisfiable), - } - } - - fn cost() -> usize { - unimplemented!() - } -} - -impl<'a, F: PrimeField, G: GroupType> CondSelectGadget for ConstrainedValue<'a, F, G> { - fn conditionally_select>( - mut cs: CS, - cond: &Boolean, - first: &Self, - second: &Self, - ) -> Result { - Ok(match (first, second) { - (ConstrainedValue::Address(address_1), ConstrainedValue::Address(address_2)) => { - ConstrainedValue::Address(Address::conditionally_select(cs, cond, address_1, address_2)?) - } - (ConstrainedValue::Boolean(bool_1), ConstrainedValue::Boolean(bool_2)) => { - ConstrainedValue::Boolean(Boolean::conditionally_select(cs, cond, bool_1, bool_2)?) - } - (ConstrainedValue::Char(char_1), ConstrainedValue::Char(char_2)) => { - ConstrainedValue::Char(Char::conditionally_select(cs, cond, char_1, char_2)?) - } - (ConstrainedValue::Field(field_1), ConstrainedValue::Field(field_2)) => { - ConstrainedValue::Field(FieldType::conditionally_select(cs, cond, field_1, field_2)?) - } - (ConstrainedValue::Group(group_1), ConstrainedValue::Group(group_2)) => { - ConstrainedValue::Group(G::conditionally_select(cs, cond, group_1, group_2)?) - } - (ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => { - ConstrainedValue::Integer(Integer::conditionally_select(cs, cond, num_1, num_2)?) - } - (ConstrainedValue::Array(arr_1), ConstrainedValue::Array(arr_2)) => { - let mut array = Vec::with_capacity(arr_1.len()); - - for (i, (first, second)) in arr_1.iter().zip(arr_2.iter()).enumerate() { - array.push(Self::conditionally_select( - cs.ns(|| format!("array[{}]", i)), - cond, - first, - second, - )?); - } - - ConstrainedValue::Array(array) - } - (ConstrainedValue::Tuple(tuple_1), ConstrainedValue::Tuple(tuple_2)) => { - let mut array = Vec::with_capacity(tuple_1.len()); - - for (i, (first, second)) in tuple_1.iter().zip(tuple_2.iter()).enumerate() { - array.push(Self::conditionally_select( - cs.ns(|| format!("tuple index {}", i)), - cond, - first, - second, - )?); - } - - ConstrainedValue::Tuple(array) - } - ( - ConstrainedValue::CircuitExpression(identifier, members_1), - ConstrainedValue::CircuitExpression(_identifier, members_2), - ) => { - let mut members = Vec::with_capacity(members_1.len()); - - for (i, (first, second)) in members_1.iter().zip(members_2.iter()).enumerate() { - members.push(ConstrainedCircuitMember::conditionally_select( - cs.ns(|| format!("circuit member[{}]", i)), - cond, - first, - second, - )?); - } - - ConstrainedValue::CircuitExpression(*identifier, members) - } - (_, _) => return Err(SynthesisError::Unsatisfiable), - }) - } - - fn cost() -> usize { - unimplemented!() //lower bound 1, upper bound 128 or length of static array - } -} - -impl<'a, F: PrimeField, G: GroupType> CondSelectGadget for ConstrainedCircuitMember<'a, F, G> { - fn conditionally_select>( - cs: CS, - cond: &Boolean, - first: &Self, - second: &Self, - ) -> Result { - // identifiers will be the same - let value = ConstrainedValue::conditionally_select(cs, cond, &first.1, &second.1)?; - - Ok(ConstrainedCircuitMember(first.0.clone(), value)) - } - - fn cost() -> usize { - unimplemented!() - } -} diff --git a/stdlib/Cargo.toml b/compiler/stdlib/Cargo.toml similarity index 96% rename from stdlib/Cargo.toml rename to compiler/stdlib/Cargo.toml index 921f45658c..e54cd1f9d7 100644 --- a/stdlib/Cargo.toml +++ b/compiler/stdlib/Cargo.toml @@ -25,7 +25,7 @@ path = "../ast" version = "1.5.3" [dependencies.leo-errors] -path = "../errors" +path = "../../leo/errors" version = "1.5.3" [dependencies.leo-parser] diff --git a/imports/LICENSE.md b/compiler/stdlib/LICENSE.md similarity index 100% rename from imports/LICENSE.md rename to compiler/stdlib/LICENSE.md diff --git a/stdlib/README.md b/compiler/stdlib/README.md similarity index 100% rename from stdlib/README.md rename to compiler/stdlib/README.md diff --git a/stdlib/prelude/string.leo b/compiler/stdlib/prelude/string.leo similarity index 100% rename from stdlib/prelude/string.leo rename to compiler/stdlib/prelude/string.leo diff --git a/stdlib/src/lib.rs b/compiler/stdlib/src/lib.rs similarity index 100% rename from stdlib/src/lib.rs rename to compiler/stdlib/src/lib.rs diff --git a/stdlib/unstable/blake2s.leo b/compiler/stdlib/unstable/blake2s.leo similarity index 100% rename from stdlib/unstable/blake2s.leo rename to compiler/stdlib/unstable/blake2s.leo diff --git a/wasm/.gitignore b/compiler/wasm/.gitignore similarity index 100% rename from wasm/.gitignore rename to compiler/wasm/.gitignore diff --git a/wasm/Cargo.toml b/compiler/wasm/Cargo.toml similarity index 92% rename from wasm/Cargo.toml rename to compiler/wasm/Cargo.toml index 86a6a3f786..ca2fc176ef 100644 --- a/wasm/Cargo.toml +++ b/compiler/wasm/Cargo.toml @@ -21,25 +21,21 @@ license = "GPL-3.0" [lib] crate-type = ["cdylib", "rlib"] -[dependencies.leo-asg] -version = "1.5.3" -path = "../asg" - [dependencies.leo-ast] -version = "1.5.3" path = "../ast" +version = "1.5.3" [dependencies.leo-ast-passes] -version = "1.5.3" path = "../ast-passes" +version = "1.5.3" [dependencies.leo-errors] +path = "../../leo/errors" version = "1.5.3" -path = "../errors" [dependencies.leo-parser] -version = "1.5.3" path = "../parser" +version = "1.5.3" [dependencies.serde] version = "1.0" diff --git a/wasm/README.md b/compiler/wasm/README.md similarity index 100% rename from wasm/README.md rename to compiler/wasm/README.md diff --git a/wasm/src/lib.rs b/compiler/wasm/src/lib.rs similarity index 100% rename from wasm/src/lib.rs rename to compiler/wasm/src/lib.rs diff --git a/wasm/tests/.gitignore b/compiler/wasm/tests/.gitignore similarity index 100% rename from wasm/tests/.gitignore rename to compiler/wasm/tests/.gitignore diff --git a/wasm/tests/package-lock.json b/compiler/wasm/tests/package-lock.json similarity index 100% rename from wasm/tests/package-lock.json rename to compiler/wasm/tests/package-lock.json diff --git a/wasm/tests/package.json b/compiler/wasm/tests/package.json similarity index 100% rename from wasm/tests/package.json rename to compiler/wasm/tests/package.json diff --git a/wasm/tests/src/index.ts b/compiler/wasm/tests/src/index.ts similarity index 100% rename from wasm/tests/src/index.ts rename to compiler/wasm/tests/src/index.ts diff --git a/wasm/tests/tsconfig.json b/compiler/wasm/tests/tsconfig.json similarity index 100% rename from wasm/tests/tsconfig.json rename to compiler/wasm/tests/tsconfig.json diff --git a/grammar/.gitattributes b/docs/grammar/.gitattributes similarity index 100% rename from grammar/.gitattributes rename to docs/grammar/.gitattributes diff --git a/grammar/Cargo.toml b/docs/grammar/Cargo.toml similarity index 100% rename from grammar/Cargo.toml rename to docs/grammar/Cargo.toml diff --git a/grammar/FORMAT_ABNF_GRAMMAR.md b/docs/grammar/FORMAT_ABNF_GRAMMAR.md similarity index 100% rename from grammar/FORMAT_ABNF_GRAMMAR.md rename to docs/grammar/FORMAT_ABNF_GRAMMAR.md diff --git a/grammar/README.md b/docs/grammar/README.md similarity index 100% rename from grammar/README.md rename to docs/grammar/README.md diff --git a/grammar/abnf-grammar.txt b/docs/grammar/abnf-grammar.txt similarity index 100% rename from grammar/abnf-grammar.txt rename to docs/grammar/abnf-grammar.txt diff --git a/grammar/format-abnf-grammar.txt b/docs/grammar/format-abnf-grammar.txt similarity index 100% rename from grammar/format-abnf-grammar.txt rename to docs/grammar/format-abnf-grammar.txt diff --git a/grammar/src/main.rs b/docs/grammar/src/main.rs similarity index 100% rename from grammar/src/main.rs rename to docs/grammar/src/main.rs diff --git a/leo/README.md b/leo/README.md new file mode 100644 index 0000000000..ee5fca0446 --- /dev/null +++ b/leo/README.md @@ -0,0 +1,7 @@ +# Overview + +This directory contains the source code for the Leo command line interface. +For a comprehensive list of commands and usage see the [developer documentation](https://developer.aleo.org/developer/cli/overview). + +The `leo-errors` and `leo-package` modules are also included in this directory for convenience. +However, they are also used throughout the `compiler/` directory and `leo-compiler` module. \ No newline at end of file diff --git a/leo/commands/build.rs b/leo/commands/build.rs index 47d84c3c88..b8d0d1fb7b 100644 --- a/leo/commands/build.rs +++ b/leo/commands/build.rs @@ -15,7 +15,7 @@ // along with the Leo library. If not, see . use crate::{commands::Command, context::Context}; -use leo_compiler::Compiler; +use leo_compiler::{Ast, Compiler}; use leo_errors::{CliError, Result}; use leo_package::{ // inputs::*, @@ -24,7 +24,6 @@ use leo_package::{ source::{MainFile, MAIN_FILENAME, SOURCE_DIRECTORY_NAME}, }; -use leo_ast::Ast; use structopt::StructOpt; use tracing::span::Span; diff --git a/errors/Cargo.toml b/leo/errors/Cargo.toml similarity index 97% rename from errors/Cargo.toml rename to leo/errors/Cargo.toml index a2e51114d4..e18615f1eb 100644 --- a/errors/Cargo.toml +++ b/leo/errors/Cargo.toml @@ -26,7 +26,7 @@ path = "../span" version = "1.5.3" [dependencies.leo-input] -path = "../input" +path = "../../compiler/input" version = "1.5.3" [dependencies.colored] diff --git a/errors/ERROR_INDEX.md b/leo/errors/ERROR_INDEX.md similarity index 100% rename from errors/ERROR_INDEX.md rename to leo/errors/ERROR_INDEX.md diff --git a/input/LICENSE.md b/leo/errors/LICENSE.md similarity index 100% rename from input/LICENSE.md rename to leo/errors/LICENSE.md diff --git a/errors/README.md b/leo/errors/README.md similarity index 100% rename from errors/README.md rename to leo/errors/README.md diff --git a/errors/src/asg/asg_errors.rs b/leo/errors/src/asg/asg_errors.rs similarity index 100% rename from errors/src/asg/asg_errors.rs rename to leo/errors/src/asg/asg_errors.rs diff --git a/errors/src/asg/mod.rs b/leo/errors/src/asg/mod.rs similarity index 100% rename from errors/src/asg/mod.rs rename to leo/errors/src/asg/mod.rs diff --git a/errors/src/ast/ast_errors.rs b/leo/errors/src/ast/ast_errors.rs similarity index 100% rename from errors/src/ast/ast_errors.rs rename to leo/errors/src/ast/ast_errors.rs diff --git a/errors/src/ast/mod.rs b/leo/errors/src/ast/mod.rs similarity index 100% rename from errors/src/ast/mod.rs rename to leo/errors/src/ast/mod.rs diff --git a/errors/src/cli/cli_errors.rs b/leo/errors/src/cli/cli_errors.rs similarity index 100% rename from errors/src/cli/cli_errors.rs rename to leo/errors/src/cli/cli_errors.rs diff --git a/errors/src/cli/mod.rs b/leo/errors/src/cli/mod.rs similarity index 100% rename from errors/src/cli/mod.rs rename to leo/errors/src/cli/mod.rs diff --git a/errors/src/common/backtraced.rs b/leo/errors/src/common/backtraced.rs similarity index 100% rename from errors/src/common/backtraced.rs rename to leo/errors/src/common/backtraced.rs diff --git a/errors/src/common/formatted.rs b/leo/errors/src/common/formatted.rs similarity index 100% rename from errors/src/common/formatted.rs rename to leo/errors/src/common/formatted.rs diff --git a/errors/src/common/macros.rs b/leo/errors/src/common/macros.rs similarity index 100% rename from errors/src/common/macros.rs rename to leo/errors/src/common/macros.rs diff --git a/errors/src/common/mod.rs b/leo/errors/src/common/mod.rs similarity index 100% rename from errors/src/common/mod.rs rename to leo/errors/src/common/mod.rs diff --git a/errors/src/common/traits.rs b/leo/errors/src/common/traits.rs similarity index 100% rename from errors/src/common/traits.rs rename to leo/errors/src/common/traits.rs diff --git a/errors/src/compiler/compiler_errors.rs b/leo/errors/src/compiler/compiler_errors.rs similarity index 100% rename from errors/src/compiler/compiler_errors.rs rename to leo/errors/src/compiler/compiler_errors.rs diff --git a/errors/src/compiler/mod.rs b/leo/errors/src/compiler/mod.rs similarity index 100% rename from errors/src/compiler/mod.rs rename to leo/errors/src/compiler/mod.rs diff --git a/errors/src/emitter/mod.rs b/leo/errors/src/emitter/mod.rs similarity index 100% rename from errors/src/emitter/mod.rs rename to leo/errors/src/emitter/mod.rs diff --git a/errors/src/import/import_errors.rs b/leo/errors/src/import/import_errors.rs similarity index 100% rename from errors/src/import/import_errors.rs rename to leo/errors/src/import/import_errors.rs diff --git a/errors/src/import/mod.rs b/leo/errors/src/import/mod.rs similarity index 100% rename from errors/src/import/mod.rs rename to leo/errors/src/import/mod.rs diff --git a/errors/src/lib.rs b/leo/errors/src/lib.rs similarity index 100% rename from errors/src/lib.rs rename to leo/errors/src/lib.rs diff --git a/errors/src/package/mod.rs b/leo/errors/src/package/mod.rs similarity index 100% rename from errors/src/package/mod.rs rename to leo/errors/src/package/mod.rs diff --git a/errors/src/package/package_errors.rs b/leo/errors/src/package/package_errors.rs similarity index 100% rename from errors/src/package/package_errors.rs rename to leo/errors/src/package/package_errors.rs diff --git a/errors/src/parser/mod.rs b/leo/errors/src/parser/mod.rs similarity index 100% rename from errors/src/parser/mod.rs rename to leo/errors/src/parser/mod.rs diff --git a/errors/src/parser/parser_errors.rs b/leo/errors/src/parser/parser_errors.rs similarity index 100% rename from errors/src/parser/parser_errors.rs rename to leo/errors/src/parser/parser_errors.rs diff --git a/errors/src/snarkvm/mod.rs b/leo/errors/src/snarkvm/mod.rs similarity index 100% rename from errors/src/snarkvm/mod.rs rename to leo/errors/src/snarkvm/mod.rs diff --git a/errors/src/snarkvm/snarkvm_errors.rs b/leo/errors/src/snarkvm/snarkvm_errors.rs similarity index 100% rename from errors/src/snarkvm/snarkvm_errors.rs rename to leo/errors/src/snarkvm/snarkvm_errors.rs diff --git a/errors/src/state/mod.rs b/leo/errors/src/state/mod.rs similarity index 100% rename from errors/src/state/mod.rs rename to leo/errors/src/state/mod.rs diff --git a/errors/src/state/state_errors.rs b/leo/errors/src/state/state_errors.rs similarity index 100% rename from errors/src/state/state_errors.rs rename to leo/errors/src/state/state_errors.rs diff --git a/package/Cargo.toml b/leo/package/Cargo.toml similarity index 100% rename from package/Cargo.toml rename to leo/package/Cargo.toml diff --git a/linter/LICENSE.md b/leo/package/LICENSE.md similarity index 100% rename from linter/LICENSE.md rename to leo/package/LICENSE.md diff --git a/package/README.md b/leo/package/README.md similarity index 100% rename from package/README.md rename to leo/package/README.md diff --git a/package/src/imports/directory.rs b/leo/package/src/imports/directory.rs similarity index 100% rename from package/src/imports/directory.rs rename to leo/package/src/imports/directory.rs diff --git a/package/src/imports/mod.rs b/leo/package/src/imports/mod.rs similarity index 100% rename from package/src/imports/mod.rs rename to leo/package/src/imports/mod.rs diff --git a/package/src/inputs/directory.rs b/leo/package/src/inputs/directory.rs similarity index 100% rename from package/src/inputs/directory.rs rename to leo/package/src/inputs/directory.rs diff --git a/package/src/inputs/input.rs b/leo/package/src/inputs/input.rs similarity index 100% rename from package/src/inputs/input.rs rename to leo/package/src/inputs/input.rs diff --git a/package/src/inputs/mod.rs b/leo/package/src/inputs/mod.rs similarity index 100% rename from package/src/inputs/mod.rs rename to leo/package/src/inputs/mod.rs diff --git a/package/src/inputs/pairs.rs b/leo/package/src/inputs/pairs.rs similarity index 100% rename from package/src/inputs/pairs.rs rename to leo/package/src/inputs/pairs.rs diff --git a/package/src/inputs/state.rs b/leo/package/src/inputs/state.rs similarity index 100% rename from package/src/inputs/state.rs rename to leo/package/src/inputs/state.rs diff --git a/package/src/lib.rs b/leo/package/src/lib.rs similarity index 100% rename from package/src/lib.rs rename to leo/package/src/lib.rs diff --git a/package/src/outputs/ast_snapshot.rs b/leo/package/src/outputs/ast_snapshot.rs similarity index 100% rename from package/src/outputs/ast_snapshot.rs rename to leo/package/src/outputs/ast_snapshot.rs diff --git a/package/src/outputs/checksum.rs b/leo/package/src/outputs/checksum.rs similarity index 100% rename from package/src/outputs/checksum.rs rename to leo/package/src/outputs/checksum.rs diff --git a/package/src/outputs/circuit.rs b/leo/package/src/outputs/circuit.rs similarity index 100% rename from package/src/outputs/circuit.rs rename to leo/package/src/outputs/circuit.rs diff --git a/package/src/outputs/directory.rs b/leo/package/src/outputs/directory.rs similarity index 100% rename from package/src/outputs/directory.rs rename to leo/package/src/outputs/directory.rs diff --git a/package/src/outputs/mod.rs b/leo/package/src/outputs/mod.rs similarity index 100% rename from package/src/outputs/mod.rs rename to leo/package/src/outputs/mod.rs diff --git a/package/src/outputs/proof.rs b/leo/package/src/outputs/proof.rs similarity index 100% rename from package/src/outputs/proof.rs rename to leo/package/src/outputs/proof.rs diff --git a/package/src/outputs/proving_key.rs b/leo/package/src/outputs/proving_key.rs similarity index 100% rename from package/src/outputs/proving_key.rs rename to leo/package/src/outputs/proving_key.rs diff --git a/package/src/outputs/verification_key.rs b/leo/package/src/outputs/verification_key.rs similarity index 100% rename from package/src/outputs/verification_key.rs rename to leo/package/src/outputs/verification_key.rs diff --git a/package/src/package.rs b/leo/package/src/package.rs similarity index 100% rename from package/src/package.rs rename to leo/package/src/package.rs diff --git a/package/src/root/gitignore.rs b/leo/package/src/root/gitignore.rs similarity index 100% rename from package/src/root/gitignore.rs rename to leo/package/src/root/gitignore.rs diff --git a/package/src/root/lock_file.rs b/leo/package/src/root/lock_file.rs similarity index 100% rename from package/src/root/lock_file.rs rename to leo/package/src/root/lock_file.rs diff --git a/package/src/root/manifest.rs b/leo/package/src/root/manifest.rs similarity index 100% rename from package/src/root/manifest.rs rename to leo/package/src/root/manifest.rs diff --git a/package/src/root/mod.rs b/leo/package/src/root/mod.rs similarity index 100% rename from package/src/root/mod.rs rename to leo/package/src/root/mod.rs diff --git a/package/src/root/readme.rs b/leo/package/src/root/readme.rs similarity index 100% rename from package/src/root/readme.rs rename to leo/package/src/root/readme.rs diff --git a/package/src/root/zip.rs b/leo/package/src/root/zip.rs similarity index 100% rename from package/src/root/zip.rs rename to leo/package/src/root/zip.rs diff --git a/package/src/source/directory.rs b/leo/package/src/source/directory.rs similarity index 100% rename from package/src/source/directory.rs rename to leo/package/src/source/directory.rs diff --git a/package/src/source/main.rs b/leo/package/src/source/main.rs similarity index 100% rename from package/src/source/main.rs rename to leo/package/src/source/main.rs diff --git a/package/src/source/mod.rs b/leo/package/src/source/mod.rs similarity index 100% rename from package/src/source/mod.rs rename to leo/package/src/source/mod.rs diff --git a/package/tests/initialize/initialize.rs b/leo/package/tests/initialize/initialize.rs similarity index 100% rename from package/tests/initialize/initialize.rs rename to leo/package/tests/initialize/initialize.rs diff --git a/package/tests/initialize/mod.rs b/leo/package/tests/initialize/mod.rs similarity index 100% rename from package/tests/initialize/mod.rs rename to leo/package/tests/initialize/mod.rs diff --git a/package/tests/manifest/manifest.rs b/leo/package/tests/manifest/manifest.rs similarity index 100% rename from package/tests/manifest/manifest.rs rename to leo/package/tests/manifest/manifest.rs diff --git a/package/tests/manifest/mod.rs b/leo/package/tests/manifest/mod.rs similarity index 100% rename from package/tests/manifest/mod.rs rename to leo/package/tests/manifest/mod.rs diff --git a/package/tests/mod.rs b/leo/package/tests/mod.rs similarity index 100% rename from package/tests/mod.rs rename to leo/package/tests/mod.rs diff --git a/span/Cargo.toml b/leo/span/Cargo.toml similarity index 100% rename from span/Cargo.toml rename to leo/span/Cargo.toml diff --git a/span/src/dropless.rs b/leo/span/src/dropless.rs similarity index 100% rename from span/src/dropless.rs rename to leo/span/src/dropless.rs diff --git a/span/src/lib.rs b/leo/span/src/lib.rs similarity index 100% rename from span/src/lib.rs rename to leo/span/src/lib.rs diff --git a/span/src/span.rs b/leo/span/src/span.rs similarity index 100% rename from span/src/span.rs rename to leo/span/src/span.rs diff --git a/span/src/span_json.rs b/leo/span/src/span_json.rs similarity index 100% rename from span/src/span_json.rs rename to leo/span/src/span_json.rs diff --git a/span/src/symbol.rs b/leo/span/src/symbol.rs similarity index 100% rename from span/src/symbol.rs rename to leo/span/src/symbol.rs diff --git a/span/src/tendril_json.rs b/leo/span/src/tendril_json.rs similarity index 100% rename from span/src/tendril_json.rs rename to leo/span/src/tendril_json.rs diff --git a/stdlib/LICENSE.md b/stdlib/LICENSE.md deleted file mode 100644 index b95c626e2a..0000000000 --- a/stdlib/LICENSE.md +++ /dev/null @@ -1,596 +0,0 @@ -GNU General Public License -========================== - -Version 3, 29 June 2007 - -Copyright © 2007 Free Software Foundation, Inc. <> - -Everyone is permitted to copy and distribute verbatim copies of this license -document, but changing it is not allowed. - -## Preamble - -The GNU General Public License is a free, copyleft license for software and other -kinds of works. - -The licenses for most software and other practical works are designed to take away -your freedom to share and change the works. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change all versions of a -program--to make sure it remains free software for all its users. We, the Free -Software Foundation, use the GNU General Public License for most of our software; it -applies also to any other work released this way by its authors. You can apply it to -your programs, too. - -When we speak of free software, we are referring to freedom, not price. Our General -Public Licenses are designed to make sure that you have the freedom to distribute -copies of free software (and charge for them if you wish), that you receive source -code or can get it if you want it, that you can change the software or use pieces of -it in new free programs, and that you know you can do these things. - -To protect your rights, we need to prevent others from denying you these rights or -asking you to surrender the rights. Therefore, you have certain responsibilities if -you distribute copies of the software, or if you modify it: responsibilities to -respect the freedom of others. - -For example, if you distribute copies of such a program, whether gratis or for a fee, -you must pass on to the recipients the same freedoms that you received. You must make -sure that they, too, receive or can get the source code. And you must show them these -terms so they know their rights. - -Developers that use the GNU GPL protect your rights with two steps: **(1)** assert -copyright on the software, and **(2)** offer you this License giving you legal permission -to copy, distribute and/or modify it. - -For the developers' and authors' protection, the GPL clearly explains that there is -no warranty for this free software. For both users' and authors' sake, the GPL -requires that modified versions be marked as changed, so that their problems will not -be attributed erroneously to authors of previous versions. - -Some devices are designed to deny users access to install or run modified versions of -the software inside them, although the manufacturer can do so. This is fundamentally -incompatible with the aim of protecting users' freedom to change the software. The -systematic pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we have designed -this version of the GPL to prohibit the practice for those products. If such problems -arise substantially in other domains, we stand ready to extend this provision to -those domains in future versions of the GPL, as needed to protect the freedom of -users. - -Finally, every program is threatened constantly by software patents. States should -not allow patents to restrict development and use of software on general-purpose -computers, but in those that do, we wish to avoid the special danger that patents -applied to a free program could make it effectively proprietary. To prevent this, the -GPL assures that patents cannot be used to render the program non-free. - -The precise terms and conditions for copying, distribution and modification follow. - -## TERMS AND CONDITIONS - -### 0. Definitions - -“This License” refers to version 3 of the GNU General Public License. - -“Copyright” also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - -“The Program” refers to any copyrightable work licensed under this -License. Each licensee is addressed as “you”. “Licensees” and -“recipients” may be individuals or organizations. - -To “modify” a work means to copy from or adapt all or part of the work in -a fashion requiring copyright permission, other than the making of an exact copy. The -resulting work is called a “modified version” of the earlier work or a -work “based on” the earlier work. - -A “covered work” means either the unmodified Program or a work based on -the Program. - -To “propagate” a work means to do anything with it that, without -permission, would make you directly or secondarily liable for infringement under -applicable copyright law, except executing it on a computer or modifying a private -copy. Propagation includes copying, distribution (with or without modification), -making available to the public, and in some countries other activities as well. - -To “convey” a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through a computer -network, with no transfer of a copy, is not conveying. - -An interactive user interface displays “Appropriate Legal Notices” to the -extent that it includes a convenient and prominently visible feature that **(1)** -displays an appropriate copyright notice, and **(2)** tells the user that there is no -warranty for the work (except to the extent that warranties are provided), that -licensees may convey the work under this License, and how to view a copy of this -License. If the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - -### 1. Source Code - -The “source code” for a work means the preferred form of the work for -making modifications to it. “Object code” means any non-source form of a -work. - -A “Standard Interface” means an interface that either is an official -standard defined by a recognized standards body, or, in the case of interfaces -specified for a particular programming language, one that is widely used among -developers working in that language. - -The “System Libraries” of an executable work include anything, other than -the work as a whole, that **(a)** is included in the normal form of packaging a Major -Component, but which is not part of that Major Component, and **(b)** serves only to -enable use of the work with that Major Component, or to implement a Standard -Interface for which an implementation is available to the public in source code form. -A “Major Component”, in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system (if any) on which -the executable work runs, or a compiler used to produce the work, or an object code -interpreter used to run it. - -The “Corresponding Source” for a work in object code form means all the -source code needed to generate, install, and (for an executable work) run the object -code and to modify the work, including scripts to control those activities. However, -it does not include the work's System Libraries, or general-purpose tools or -generally available free programs which are used unmodified in performing those -activities but which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for the work, and -the source code for shared libraries and dynamically linked subprograms that the work -is specifically designed to require, such as by intimate data communication or -control flow between those subprograms and other parts of the work. - -The Corresponding Source need not include anything that users can regenerate -automatically from other parts of the Corresponding Source. - -The Corresponding Source for a work in source code form is that same work. - -### 2. Basic Permissions - -All rights granted under this License are granted for the term of copyright on the -Program, and are irrevocable provided the stated conditions are met. This License -explicitly affirms your unlimited permission to run the unmodified Program. The -output from running a covered work is covered by this License only if the output, -given its content, constitutes a covered work. This License acknowledges your rights -of fair use or other equivalent, as provided by copyright law. - -You may make, run and propagate covered works that you do not convey, without -conditions so long as your license otherwise remains in force. You may convey covered -works to others for the sole purpose of having them make modifications exclusively -for you, or provide you with facilities for running those works, provided that you -comply with the terms of this License in conveying all material for which you do not -control copyright. Those thus making or running the covered works for you must do so -exclusively on your behalf, under your direction and control, on terms that prohibit -them from making any copies of your copyrighted material outside their relationship -with you. - -Conveying under any other circumstances is permitted solely under the conditions -stated below. Sublicensing is not allowed; section 10 makes it unnecessary. - -### 3. Protecting Users' Legal Rights From Anti-Circumvention Law - -No covered work shall be deemed part of an effective technological measure under any -applicable law fulfilling obligations under article 11 of the WIPO copyright treaty -adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention -of such measures. - -When you convey a covered work, you waive any legal power to forbid circumvention of -technological measures to the extent such circumvention is effected by exercising -rights under this License with respect to the covered work, and you disclaim any -intention to limit operation or modification of the work as a means of enforcing, -against the work's users, your or third parties' legal rights to forbid circumvention -of technological measures. - -### 4. Conveying Verbatim Copies - -You may convey verbatim copies of the Program's source code as you receive it, in any -medium, provided that you conspicuously and appropriately publish on each copy an -appropriate copyright notice; keep intact all notices stating that this License and -any non-permissive terms added in accord with section 7 apply to the code; keep -intact all notices of the absence of any warranty; and give all recipients a copy of -this License along with the Program. - -You may charge any price or no price for each copy that you convey, and you may offer -support or warranty protection for a fee. - -### 5. Conveying Modified Source Versions - -You may convey a work based on the Program, or the modifications to produce it from -the Program, in the form of source code under the terms of section 4, provided that -you also meet all of these conditions: - -* **a)** The work must carry prominent notices stating that you modified it, and giving a -relevant date. -* **b)** The work must carry prominent notices stating that it is released under this -License and any conditions added under section 7. This requirement modifies the -requirement in section 4 to “keep intact all notices”. -* **c)** You must license the entire work, as a whole, under this License to anyone who -comes into possession of a copy. This License will therefore apply, along with any -applicable section 7 additional terms, to the whole of the work, and all its parts, -regardless of how they are packaged. This License gives no permission to license the -work in any other way, but it does not invalidate such permission if you have -separately received it. -* **d)** If the work has interactive user interfaces, each must display Appropriate Legal -Notices; however, if the Program has interactive interfaces that do not display -Appropriate Legal Notices, your work need not make them do so. - -A compilation of a covered work with other separate and independent works, which are -not by their nature extensions of the covered work, and which are not combined with -it such as to form a larger program, in or on a volume of a storage or distribution -medium, is called an “aggregate” if the compilation and its resulting -copyright are not used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work in an aggregate -does not cause this License to apply to the other parts of the aggregate. - -### 6. Conveying Non-Source Forms - -You may convey a covered work in object code form under the terms of sections 4 and -5, provided that you also convey the machine-readable Corresponding Source under the -terms of this License, in one of these ways: - -* **a)** Convey the object code in, or embodied in, a physical product (including a -physical distribution medium), accompanied by the Corresponding Source fixed on a -durable physical medium customarily used for software interchange. -* **b)** Convey the object code in, or embodied in, a physical product (including a -physical distribution medium), accompanied by a written offer, valid for at least -three years and valid for as long as you offer spare parts or customer support for -that product model, to give anyone who possesses the object code either **(1)** a copy of -the Corresponding Source for all the software in the product that is covered by this -License, on a durable physical medium customarily used for software interchange, for -a price no more than your reasonable cost of physically performing this conveying of -source, or **(2)** access to copy the Corresponding Source from a network server at no -charge. -* **c)** Convey individual copies of the object code with a copy of the written offer to -provide the Corresponding Source. This alternative is allowed only occasionally and -noncommercially, and only if you received the object code with such an offer, in -accord with subsection 6b. -* **d)** Convey the object code by offering access from a designated place (gratis or for -a charge), and offer equivalent access to the Corresponding Source in the same way -through the same place at no further charge. You need not require recipients to copy -the Corresponding Source along with the object code. If the place to copy the object -code is a network server, the Corresponding Source may be on a different server -(operated by you or a third party) that supports equivalent copying facilities, -provided you maintain clear directions next to the object code saying where to find -the Corresponding Source. Regardless of what server hosts the Corresponding Source, -you remain obligated to ensure that it is available for as long as needed to satisfy -these requirements. -* **e)** Convey the object code using peer-to-peer transmission, provided you inform -other peers where the object code and Corresponding Source of the work are being -offered to the general public at no charge under subsection 6d. - -A separable portion of the object code, whose source code is excluded from the -Corresponding Source as a System Library, need not be included in conveying the -object code work. - -A “User Product” is either **(1)** a “consumer product”, which -means any tangible personal property which is normally used for personal, family, or -household purposes, or **(2)** anything designed or sold for incorporation into a -dwelling. In determining whether a product is a consumer product, doubtful cases -shall be resolved in favor of coverage. For a particular product received by a -particular user, “normally used” refers to a typical or common use of -that class of product, regardless of the status of the particular user or of the way -in which the particular user actually uses, or expects or is expected to use, the -product. A product is a consumer product regardless of whether the product has -substantial commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - -“Installation Information” for a User Product means any methods, -procedures, authorization keys, or other information required to install and execute -modified versions of a covered work in that User Product from a modified version of -its Corresponding Source. The information must suffice to ensure that the continued -functioning of the modified object code is in no case prevented or interfered with -solely because modification has been made. - -If you convey an object code work under this section in, or with, or specifically for -use in, a User Product, and the conveying occurs as part of a transaction in which -the right of possession and use of the User Product is transferred to the recipient -in perpetuity or for a fixed term (regardless of how the transaction is -characterized), the Corresponding Source conveyed under this section must be -accompanied by the Installation Information. But this requirement does not apply if -neither you nor any third party retains the ability to install modified object code -on the User Product (for example, the work has been installed in ROM). - -The requirement to provide Installation Information does not include a requirement to -continue to provide support service, warranty, or updates for a work that has been -modified or installed by the recipient, or for the User Product in which it has been -modified or installed. Access to a network may be denied when the modification itself -materially and adversely affects the operation of the network or violates the rules -and protocols for communication across the network. - -Corresponding Source conveyed, and Installation Information provided, in accord with -this section must be in a format that is publicly documented (and with an -implementation available to the public in source code form), and must require no -special password or key for unpacking, reading or copying. - -### 7. Additional Terms - -“Additional permissions” are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. Additional -permissions that are applicable to the entire Program shall be treated as though they -were included in this License, to the extent that they are valid under applicable -law. If additional permissions apply only to part of the Program, that part may be -used separately under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - -When you convey a copy of a covered work, you may at your option remove any -additional permissions from that copy, or from any part of it. (Additional -permissions may be written to require their own removal in certain cases when you -modify the work.) You may place additional permissions on material, added by you to a -covered work, for which you have or can give appropriate copyright permission. - -Notwithstanding any other provision of this License, for material you add to a -covered work, you may (if authorized by the copyright holders of that material) -supplement the terms of this License with terms: - -* **a)** Disclaiming warranty or limiting liability differently from the terms of -sections 15 and 16 of this License; or -* **b)** Requiring preservation of specified reasonable legal notices or author -attributions in that material or in the Appropriate Legal Notices displayed by works -containing it; or -* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that -modified versions of such material be marked in reasonable ways as different from the -original version; or -* **d)** Limiting the use for publicity purposes of names of licensors or authors of the -material; or -* **e)** Declining to grant rights under trademark law for use of some trade names, -trademarks, or service marks; or -* **f)** Requiring indemnification of licensors and authors of that material by anyone -who conveys the material (or modified versions of it) with contractual assumptions of -liability to the recipient, for any liability that these contractual assumptions -directly impose on those licensors and authors. - -All other non-permissive additional terms are considered “further -restrictions” within the meaning of section 10. If the Program as you received -it, or any part of it, contains a notice stating that it is governed by this License -along with a term that is a further restriction, you may remove that term. If a -license document contains a further restriction but permits relicensing or conveying -under this License, you may add to a covered work material governed by the terms of -that license document, provided that the further restriction does not survive such -relicensing or conveying. - -If you add terms to a covered work in accord with this section, you must place, in -the relevant source files, a statement of the additional terms that apply to those -files, or a notice indicating where to find the applicable terms. - -Additional terms, permissive or non-permissive, may be stated in the form of a -separately written license, or stated as exceptions; the above requirements apply -either way. - -### 8. Termination - -You may not propagate or modify a covered work except as expressly provided under -this License. Any attempt otherwise to propagate or modify it is void, and will -automatically terminate your rights under this License (including any patent licenses -granted under the third paragraph of section 11). - -However, if you cease all violation of this License, then your license from a -particular copyright holder is reinstated **(a)** provisionally, unless and until the -copyright holder explicitly and finally terminates your license, and **(b)** permanently, -if the copyright holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - -Moreover, your license from a particular copyright holder is reinstated permanently -if the copyright holder notifies you of the violation by some reasonable means, this -is the first time you have received notice of violation of this License (for any -work) from that copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - -Termination of your rights under this section does not terminate the licenses of -parties who have received copies or rights from you under this License. If your -rights have been terminated and not permanently reinstated, you do not qualify to -receive new licenses for the same material under section 10. - -### 9. Acceptance Not Required for Having Copies - -You are not required to accept this License in order to receive or run a copy of the -Program. Ancillary propagation of a covered work occurring solely as a consequence of -using peer-to-peer transmission to receive a copy likewise does not require -acceptance. However, nothing other than this License grants you permission to -propagate or modify any covered work. These actions infringe copyright if you do not -accept this License. Therefore, by modifying or propagating a covered work, you -indicate your acceptance of this License to do so. - -### 10. Automatic Licensing of Downstream Recipients - -Each time you convey a covered work, the recipient automatically receives a license -from the original licensors, to run, modify and propagate that work, subject to this -License. You are not responsible for enforcing compliance by third parties with this -License. - -An “entity transaction” is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an organization, or -merging organizations. If propagation of a covered work results from an entity -transaction, each party to that transaction who receives a copy of the work also -receives whatever licenses to the work the party's predecessor in interest had or -could give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if the predecessor -has it or can get it with reasonable efforts. - -You may not impose any further restrictions on the exercise of the rights granted or -affirmed under this License. For example, you may not impose a license fee, royalty, -or other charge for exercise of rights granted under this License, and you may not -initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging -that any patent claim is infringed by making, using, selling, offering for sale, or -importing the Program or any portion of it. - -### 11. Patents - -A “contributor” is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The work thus -licensed is called the contributor's “contributor version”. - -A contributor's “essential patent claims” are all patent claims owned or -controlled by the contributor, whether already acquired or hereafter acquired, that -would be infringed by some manner, permitted by this License, of making, using, or -selling its contributor version, but do not include claims that would be infringed -only as a consequence of further modification of the contributor version. For -purposes of this definition, “control” includes the right to grant patent -sublicenses in a manner consistent with the requirements of this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free patent license -under the contributor's essential patent claims, to make, use, sell, offer for sale, -import and otherwise run, modify and propagate the contents of its contributor -version. - -In the following three paragraphs, a “patent license” is any express -agreement or commitment, however denominated, not to enforce a patent (such as an -express permission to practice a patent or covenant not to sue for patent -infringement). To “grant” such a patent license to a party means to make -such an agreement or commitment not to enforce a patent against the party. - -If you convey a covered work, knowingly relying on a patent license, and the -Corresponding Source of the work is not available for anyone to copy, free of charge -and under the terms of this License, through a publicly available network server or -other readily accessible means, then you must either **(1)** cause the Corresponding -Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the -patent license for this particular work, or **(3)** arrange, in a manner consistent with -the requirements of this License, to extend the patent license to downstream -recipients. “Knowingly relying” means you have actual knowledge that, but -for the patent license, your conveying the covered work in a country, or your -recipient's use of the covered work in a country, would infringe one or more -identifiable patents in that country that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or arrangement, you -convey, or propagate by procuring conveyance of, a covered work, and grant a patent -license to some of the parties receiving the covered work authorizing them to use, -propagate, modify or convey a specific copy of the covered work, then the patent -license you grant is automatically extended to all recipients of the covered work and -works based on it. - -A patent license is “discriminatory” if it does not include within the -scope of its coverage, prohibits the exercise of, or is conditioned on the -non-exercise of one or more of the rights that are specifically granted under this -License. You may not convey a covered work if you are a party to an arrangement with -a third party that is in the business of distributing software, under which you make -payment to the third party based on the extent of your activity of conveying the -work, and under which the third party grants, to any of the parties who would receive -the covered work from you, a discriminatory patent license **(a)** in connection with -copies of the covered work conveyed by you (or copies made from those copies), or **(b)** -primarily for and in connection with specific products or compilations that contain -the covered work, unless you entered into that arrangement, or that patent license -was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting any implied -license or other defenses to infringement that may otherwise be available to you -under applicable patent law. - -### 12. No Surrender of Others' Freedom - -If conditions are imposed on you (whether by court order, agreement or otherwise) -that contradict the conditions of this License, they do not excuse you from the -conditions of this License. If you cannot convey a covered work so as to satisfy -simultaneously your obligations under this License and any other pertinent -obligations, then as a consequence you may not convey it at all. For example, if you -agree to terms that obligate you to collect a royalty for further conveying from -those to whom you convey the Program, the only way you could satisfy both those terms -and this License would be to refrain entirely from conveying the Program. - -### 13. Use with the GNU Affero General Public License - -Notwithstanding any other provision of this License, you have permission to link or -combine any covered work with a work licensed under version 3 of the GNU Affero -General Public License into a single combined work, and to convey the resulting work. -The terms of this License will continue to apply to the part which is the covered -work, but the special requirements of the GNU Affero General Public License, section -13, concerning interaction through a network will apply to the combination as such. - -### 14. Revised Versions of this License - -The Free Software Foundation may publish revised and/or new versions of the GNU -General Public License from time to time. Such new versions will be similar in spirit -to the present version, but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Program specifies that -a certain numbered version of the GNU General Public License “or any later -version” applies to it, you have the option of following the terms and -conditions either of that numbered version or of any later version published by the -Free Software Foundation. If the Program does not specify a version number of the GNU -General Public License, you may choose any version ever published by the Free -Software Foundation. - -If the Program specifies that a proxy can decide which future versions of the GNU -General Public License can be used, that proxy's public statement of acceptance of a -version permanently authorizes you to choose that version for the Program. - -Later license versions may give you additional or different permissions. However, no -additional obligations are imposed on any author or copyright holder as a result of -your choosing to follow a later version. - -### 15. Disclaimer of Warranty - -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER -EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE -QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE -DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -### 16. Limitation of Liability - -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY -COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS -PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, -INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE -OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE -WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - -### 17. Interpretation of Sections 15 and 16 - -If the disclaimer of warranty and limitation of liability provided above cannot be -given local legal effect according to their terms, reviewing courts shall apply local -law that most closely approximates an absolute waiver of all civil liability in -connection with the Program, unless a warranty or assumption of liability accompanies -a copy of the Program in return for a fee. - -_END OF TERMS AND CONDITIONS_ - -## How to Apply These Terms to Your New Programs - -If you develop a new program, and you want it to be of the greatest possible use to -the public, the best way to achieve this is to make it free software which everyone -can redistribute and change under these terms. - -To do so, attach the following notices to the program. It is safest to attach them -to the start of each source file to most effectively state the exclusion of warranty; -and each file should have at least the “copyright” line and a pointer to -where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - -If the program does terminal interaction, make it output a short notice like this -when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type 'show c' for details. - -The hypothetical commands `show w` and `show c` should show the appropriate parts of -the General Public License. Of course, your program's commands might be different; -for a GUI interface, you would use an “about box”. - -You should also get your employer (if you work as a programmer) or school, if any, to -sign a “copyright disclaimer” for the program, if necessary. For more -information on this, and how to apply and follow the GNU GPL, see -<>. - -The GNU General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may consider it -more useful to permit linking proprietary applications with the library. If this is -what you want to do, use the GNU Lesser General Public License instead of this -License. But first, please read -<>. diff --git a/synthesizer/Cargo.toml b/synthesizer/Cargo.toml deleted file mode 100644 index 9bae9f1ef3..0000000000 --- a/synthesizer/Cargo.toml +++ /dev/null @@ -1,61 +0,0 @@ -[package] -name = "leo-synthesizer" -version = "1.5.3" -authors = [ "The Aleo Team " ] -description = "Circuit synthesizer of the Leo programming language" -homepage = "https://aleo.org" -repository = "https://github.com/AleoHQ/leo" -keywords = [ - "aleo", - "cryptography", - "leo", - "programming-language", - "zero-knowledge" -] -categories = [ "cryptography::cryptocurrencies", "web-programming" ] -include = [ "Cargo.toml", "src", "README.md", "LICENSE.md" ] -license = "GPL-3.0" -edition = "2018" - -[dependencies.leo-errors] -path = "../errors" -version = "1.5.3" - -[dependencies.snarkvm-curves] -git = "https://github.com/AleoHQ/snarkVM.git" -rev = "51633e2" -default-features = false - -[dependencies.snarkvm-fields] -git = "https://github.com/AleoHQ/snarkVM.git" -rev = "51633e2" -default-features = false - -[dependencies.snarkvm-gadgets] -git = "https://github.com/AleoHQ/snarkVM.git" -rev = "51633e2" - -[dependencies.snarkvm-r1cs] -git = "https://github.com/AleoHQ/snarkVM.git" -rev = "51633e2" -default-features = false - -[dependencies.eyre] -version = "0.6.6" -default-features = false - -[dependencies.hex] -version = "0.4" - -[dependencies.num-bigint] -version = "0.4" - -[dependencies.serde] -version = "1.0" -features = [ "derive" ] - -[dependencies.serde_json] -version = "1.0" - -[dependencies.sha2] -version = "0.10" diff --git a/synthesizer/LICENSE.md b/synthesizer/LICENSE.md deleted file mode 100644 index b95c626e2a..0000000000 --- a/synthesizer/LICENSE.md +++ /dev/null @@ -1,596 +0,0 @@ -GNU General Public License -========================== - -Version 3, 29 June 2007 - -Copyright © 2007 Free Software Foundation, Inc. <> - -Everyone is permitted to copy and distribute verbatim copies of this license -document, but changing it is not allowed. - -## Preamble - -The GNU General Public License is a free, copyleft license for software and other -kinds of works. - -The licenses for most software and other practical works are designed to take away -your freedom to share and change the works. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change all versions of a -program--to make sure it remains free software for all its users. We, the Free -Software Foundation, use the GNU General Public License for most of our software; it -applies also to any other work released this way by its authors. You can apply it to -your programs, too. - -When we speak of free software, we are referring to freedom, not price. Our General -Public Licenses are designed to make sure that you have the freedom to distribute -copies of free software (and charge for them if you wish), that you receive source -code or can get it if you want it, that you can change the software or use pieces of -it in new free programs, and that you know you can do these things. - -To protect your rights, we need to prevent others from denying you these rights or -asking you to surrender the rights. Therefore, you have certain responsibilities if -you distribute copies of the software, or if you modify it: responsibilities to -respect the freedom of others. - -For example, if you distribute copies of such a program, whether gratis or for a fee, -you must pass on to the recipients the same freedoms that you received. You must make -sure that they, too, receive or can get the source code. And you must show them these -terms so they know their rights. - -Developers that use the GNU GPL protect your rights with two steps: **(1)** assert -copyright on the software, and **(2)** offer you this License giving you legal permission -to copy, distribute and/or modify it. - -For the developers' and authors' protection, the GPL clearly explains that there is -no warranty for this free software. For both users' and authors' sake, the GPL -requires that modified versions be marked as changed, so that their problems will not -be attributed erroneously to authors of previous versions. - -Some devices are designed to deny users access to install or run modified versions of -the software inside them, although the manufacturer can do so. This is fundamentally -incompatible with the aim of protecting users' freedom to change the software. The -systematic pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we have designed -this version of the GPL to prohibit the practice for those products. If such problems -arise substantially in other domains, we stand ready to extend this provision to -those domains in future versions of the GPL, as needed to protect the freedom of -users. - -Finally, every program is threatened constantly by software patents. States should -not allow patents to restrict development and use of software on general-purpose -computers, but in those that do, we wish to avoid the special danger that patents -applied to a free program could make it effectively proprietary. To prevent this, the -GPL assures that patents cannot be used to render the program non-free. - -The precise terms and conditions for copying, distribution and modification follow. - -## TERMS AND CONDITIONS - -### 0. Definitions - -“This License” refers to version 3 of the GNU General Public License. - -“Copyright” also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - -“The Program” refers to any copyrightable work licensed under this -License. Each licensee is addressed as “you”. “Licensees” and -“recipients” may be individuals or organizations. - -To “modify” a work means to copy from or adapt all or part of the work in -a fashion requiring copyright permission, other than the making of an exact copy. The -resulting work is called a “modified version” of the earlier work or a -work “based on” the earlier work. - -A “covered work” means either the unmodified Program or a work based on -the Program. - -To “propagate” a work means to do anything with it that, without -permission, would make you directly or secondarily liable for infringement under -applicable copyright law, except executing it on a computer or modifying a private -copy. Propagation includes copying, distribution (with or without modification), -making available to the public, and in some countries other activities as well. - -To “convey” a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through a computer -network, with no transfer of a copy, is not conveying. - -An interactive user interface displays “Appropriate Legal Notices” to the -extent that it includes a convenient and prominently visible feature that **(1)** -displays an appropriate copyright notice, and **(2)** tells the user that there is no -warranty for the work (except to the extent that warranties are provided), that -licensees may convey the work under this License, and how to view a copy of this -License. If the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - -### 1. Source Code - -The “source code” for a work means the preferred form of the work for -making modifications to it. “Object code” means any non-source form of a -work. - -A “Standard Interface” means an interface that either is an official -standard defined by a recognized standards body, or, in the case of interfaces -specified for a particular programming language, one that is widely used among -developers working in that language. - -The “System Libraries” of an executable work include anything, other than -the work as a whole, that **(a)** is included in the normal form of packaging a Major -Component, but which is not part of that Major Component, and **(b)** serves only to -enable use of the work with that Major Component, or to implement a Standard -Interface for which an implementation is available to the public in source code form. -A “Major Component”, in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system (if any) on which -the executable work runs, or a compiler used to produce the work, or an object code -interpreter used to run it. - -The “Corresponding Source” for a work in object code form means all the -source code needed to generate, install, and (for an executable work) run the object -code and to modify the work, including scripts to control those activities. However, -it does not include the work's System Libraries, or general-purpose tools or -generally available free programs which are used unmodified in performing those -activities but which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for the work, and -the source code for shared libraries and dynamically linked subprograms that the work -is specifically designed to require, such as by intimate data communication or -control flow between those subprograms and other parts of the work. - -The Corresponding Source need not include anything that users can regenerate -automatically from other parts of the Corresponding Source. - -The Corresponding Source for a work in source code form is that same work. - -### 2. Basic Permissions - -All rights granted under this License are granted for the term of copyright on the -Program, and are irrevocable provided the stated conditions are met. This License -explicitly affirms your unlimited permission to run the unmodified Program. The -output from running a covered work is covered by this License only if the output, -given its content, constitutes a covered work. This License acknowledges your rights -of fair use or other equivalent, as provided by copyright law. - -You may make, run and propagate covered works that you do not convey, without -conditions so long as your license otherwise remains in force. You may convey covered -works to others for the sole purpose of having them make modifications exclusively -for you, or provide you with facilities for running those works, provided that you -comply with the terms of this License in conveying all material for which you do not -control copyright. Those thus making or running the covered works for you must do so -exclusively on your behalf, under your direction and control, on terms that prohibit -them from making any copies of your copyrighted material outside their relationship -with you. - -Conveying under any other circumstances is permitted solely under the conditions -stated below. Sublicensing is not allowed; section 10 makes it unnecessary. - -### 3. Protecting Users' Legal Rights From Anti-Circumvention Law - -No covered work shall be deemed part of an effective technological measure under any -applicable law fulfilling obligations under article 11 of the WIPO copyright treaty -adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention -of such measures. - -When you convey a covered work, you waive any legal power to forbid circumvention of -technological measures to the extent such circumvention is effected by exercising -rights under this License with respect to the covered work, and you disclaim any -intention to limit operation or modification of the work as a means of enforcing, -against the work's users, your or third parties' legal rights to forbid circumvention -of technological measures. - -### 4. Conveying Verbatim Copies - -You may convey verbatim copies of the Program's source code as you receive it, in any -medium, provided that you conspicuously and appropriately publish on each copy an -appropriate copyright notice; keep intact all notices stating that this License and -any non-permissive terms added in accord with section 7 apply to the code; keep -intact all notices of the absence of any warranty; and give all recipients a copy of -this License along with the Program. - -You may charge any price or no price for each copy that you convey, and you may offer -support or warranty protection for a fee. - -### 5. Conveying Modified Source Versions - -You may convey a work based on the Program, or the modifications to produce it from -the Program, in the form of source code under the terms of section 4, provided that -you also meet all of these conditions: - -* **a)** The work must carry prominent notices stating that you modified it, and giving a -relevant date. -* **b)** The work must carry prominent notices stating that it is released under this -License and any conditions added under section 7. This requirement modifies the -requirement in section 4 to “keep intact all notices”. -* **c)** You must license the entire work, as a whole, under this License to anyone who -comes into possession of a copy. This License will therefore apply, along with any -applicable section 7 additional terms, to the whole of the work, and all its parts, -regardless of how they are packaged. This License gives no permission to license the -work in any other way, but it does not invalidate such permission if you have -separately received it. -* **d)** If the work has interactive user interfaces, each must display Appropriate Legal -Notices; however, if the Program has interactive interfaces that do not display -Appropriate Legal Notices, your work need not make them do so. - -A compilation of a covered work with other separate and independent works, which are -not by their nature extensions of the covered work, and which are not combined with -it such as to form a larger program, in or on a volume of a storage or distribution -medium, is called an “aggregate” if the compilation and its resulting -copyright are not used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work in an aggregate -does not cause this License to apply to the other parts of the aggregate. - -### 6. Conveying Non-Source Forms - -You may convey a covered work in object code form under the terms of sections 4 and -5, provided that you also convey the machine-readable Corresponding Source under the -terms of this License, in one of these ways: - -* **a)** Convey the object code in, or embodied in, a physical product (including a -physical distribution medium), accompanied by the Corresponding Source fixed on a -durable physical medium customarily used for software interchange. -* **b)** Convey the object code in, or embodied in, a physical product (including a -physical distribution medium), accompanied by a written offer, valid for at least -three years and valid for as long as you offer spare parts or customer support for -that product model, to give anyone who possesses the object code either **(1)** a copy of -the Corresponding Source for all the software in the product that is covered by this -License, on a durable physical medium customarily used for software interchange, for -a price no more than your reasonable cost of physically performing this conveying of -source, or **(2)** access to copy the Corresponding Source from a network server at no -charge. -* **c)** Convey individual copies of the object code with a copy of the written offer to -provide the Corresponding Source. This alternative is allowed only occasionally and -noncommercially, and only if you received the object code with such an offer, in -accord with subsection 6b. -* **d)** Convey the object code by offering access from a designated place (gratis or for -a charge), and offer equivalent access to the Corresponding Source in the same way -through the same place at no further charge. You need not require recipients to copy -the Corresponding Source along with the object code. If the place to copy the object -code is a network server, the Corresponding Source may be on a different server -(operated by you or a third party) that supports equivalent copying facilities, -provided you maintain clear directions next to the object code saying where to find -the Corresponding Source. Regardless of what server hosts the Corresponding Source, -you remain obligated to ensure that it is available for as long as needed to satisfy -these requirements. -* **e)** Convey the object code using peer-to-peer transmission, provided you inform -other peers where the object code and Corresponding Source of the work are being -offered to the general public at no charge under subsection 6d. - -A separable portion of the object code, whose source code is excluded from the -Corresponding Source as a System Library, need not be included in conveying the -object code work. - -A “User Product” is either **(1)** a “consumer product”, which -means any tangible personal property which is normally used for personal, family, or -household purposes, or **(2)** anything designed or sold for incorporation into a -dwelling. In determining whether a product is a consumer product, doubtful cases -shall be resolved in favor of coverage. For a particular product received by a -particular user, “normally used” refers to a typical or common use of -that class of product, regardless of the status of the particular user or of the way -in which the particular user actually uses, or expects or is expected to use, the -product. A product is a consumer product regardless of whether the product has -substantial commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - -“Installation Information” for a User Product means any methods, -procedures, authorization keys, or other information required to install and execute -modified versions of a covered work in that User Product from a modified version of -its Corresponding Source. The information must suffice to ensure that the continued -functioning of the modified object code is in no case prevented or interfered with -solely because modification has been made. - -If you convey an object code work under this section in, or with, or specifically for -use in, a User Product, and the conveying occurs as part of a transaction in which -the right of possession and use of the User Product is transferred to the recipient -in perpetuity or for a fixed term (regardless of how the transaction is -characterized), the Corresponding Source conveyed under this section must be -accompanied by the Installation Information. But this requirement does not apply if -neither you nor any third party retains the ability to install modified object code -on the User Product (for example, the work has been installed in ROM). - -The requirement to provide Installation Information does not include a requirement to -continue to provide support service, warranty, or updates for a work that has been -modified or installed by the recipient, or for the User Product in which it has been -modified or installed. Access to a network may be denied when the modification itself -materially and adversely affects the operation of the network or violates the rules -and protocols for communication across the network. - -Corresponding Source conveyed, and Installation Information provided, in accord with -this section must be in a format that is publicly documented (and with an -implementation available to the public in source code form), and must require no -special password or key for unpacking, reading or copying. - -### 7. Additional Terms - -“Additional permissions” are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. Additional -permissions that are applicable to the entire Program shall be treated as though they -were included in this License, to the extent that they are valid under applicable -law. If additional permissions apply only to part of the Program, that part may be -used separately under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - -When you convey a copy of a covered work, you may at your option remove any -additional permissions from that copy, or from any part of it. (Additional -permissions may be written to require their own removal in certain cases when you -modify the work.) You may place additional permissions on material, added by you to a -covered work, for which you have or can give appropriate copyright permission. - -Notwithstanding any other provision of this License, for material you add to a -covered work, you may (if authorized by the copyright holders of that material) -supplement the terms of this License with terms: - -* **a)** Disclaiming warranty or limiting liability differently from the terms of -sections 15 and 16 of this License; or -* **b)** Requiring preservation of specified reasonable legal notices or author -attributions in that material or in the Appropriate Legal Notices displayed by works -containing it; or -* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that -modified versions of such material be marked in reasonable ways as different from the -original version; or -* **d)** Limiting the use for publicity purposes of names of licensors or authors of the -material; or -* **e)** Declining to grant rights under trademark law for use of some trade names, -trademarks, or service marks; or -* **f)** Requiring indemnification of licensors and authors of that material by anyone -who conveys the material (or modified versions of it) with contractual assumptions of -liability to the recipient, for any liability that these contractual assumptions -directly impose on those licensors and authors. - -All other non-permissive additional terms are considered “further -restrictions” within the meaning of section 10. If the Program as you received -it, or any part of it, contains a notice stating that it is governed by this License -along with a term that is a further restriction, you may remove that term. If a -license document contains a further restriction but permits relicensing or conveying -under this License, you may add to a covered work material governed by the terms of -that license document, provided that the further restriction does not survive such -relicensing or conveying. - -If you add terms to a covered work in accord with this section, you must place, in -the relevant source files, a statement of the additional terms that apply to those -files, or a notice indicating where to find the applicable terms. - -Additional terms, permissive or non-permissive, may be stated in the form of a -separately written license, or stated as exceptions; the above requirements apply -either way. - -### 8. Termination - -You may not propagate or modify a covered work except as expressly provided under -this License. Any attempt otherwise to propagate or modify it is void, and will -automatically terminate your rights under this License (including any patent licenses -granted under the third paragraph of section 11). - -However, if you cease all violation of this License, then your license from a -particular copyright holder is reinstated **(a)** provisionally, unless and until the -copyright holder explicitly and finally terminates your license, and **(b)** permanently, -if the copyright holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - -Moreover, your license from a particular copyright holder is reinstated permanently -if the copyright holder notifies you of the violation by some reasonable means, this -is the first time you have received notice of violation of this License (for any -work) from that copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - -Termination of your rights under this section does not terminate the licenses of -parties who have received copies or rights from you under this License. If your -rights have been terminated and not permanently reinstated, you do not qualify to -receive new licenses for the same material under section 10. - -### 9. Acceptance Not Required for Having Copies - -You are not required to accept this License in order to receive or run a copy of the -Program. Ancillary propagation of a covered work occurring solely as a consequence of -using peer-to-peer transmission to receive a copy likewise does not require -acceptance. However, nothing other than this License grants you permission to -propagate or modify any covered work. These actions infringe copyright if you do not -accept this License. Therefore, by modifying or propagating a covered work, you -indicate your acceptance of this License to do so. - -### 10. Automatic Licensing of Downstream Recipients - -Each time you convey a covered work, the recipient automatically receives a license -from the original licensors, to run, modify and propagate that work, subject to this -License. You are not responsible for enforcing compliance by third parties with this -License. - -An “entity transaction” is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an organization, or -merging organizations. If propagation of a covered work results from an entity -transaction, each party to that transaction who receives a copy of the work also -receives whatever licenses to the work the party's predecessor in interest had or -could give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if the predecessor -has it or can get it with reasonable efforts. - -You may not impose any further restrictions on the exercise of the rights granted or -affirmed under this License. For example, you may not impose a license fee, royalty, -or other charge for exercise of rights granted under this License, and you may not -initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging -that any patent claim is infringed by making, using, selling, offering for sale, or -importing the Program or any portion of it. - -### 11. Patents - -A “contributor” is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The work thus -licensed is called the contributor's “contributor version”. - -A contributor's “essential patent claims” are all patent claims owned or -controlled by the contributor, whether already acquired or hereafter acquired, that -would be infringed by some manner, permitted by this License, of making, using, or -selling its contributor version, but do not include claims that would be infringed -only as a consequence of further modification of the contributor version. For -purposes of this definition, “control” includes the right to grant patent -sublicenses in a manner consistent with the requirements of this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free patent license -under the contributor's essential patent claims, to make, use, sell, offer for sale, -import and otherwise run, modify and propagate the contents of its contributor -version. - -In the following three paragraphs, a “patent license” is any express -agreement or commitment, however denominated, not to enforce a patent (such as an -express permission to practice a patent or covenant not to sue for patent -infringement). To “grant” such a patent license to a party means to make -such an agreement or commitment not to enforce a patent against the party. - -If you convey a covered work, knowingly relying on a patent license, and the -Corresponding Source of the work is not available for anyone to copy, free of charge -and under the terms of this License, through a publicly available network server or -other readily accessible means, then you must either **(1)** cause the Corresponding -Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the -patent license for this particular work, or **(3)** arrange, in a manner consistent with -the requirements of this License, to extend the patent license to downstream -recipients. “Knowingly relying” means you have actual knowledge that, but -for the patent license, your conveying the covered work in a country, or your -recipient's use of the covered work in a country, would infringe one or more -identifiable patents in that country that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or arrangement, you -convey, or propagate by procuring conveyance of, a covered work, and grant a patent -license to some of the parties receiving the covered work authorizing them to use, -propagate, modify or convey a specific copy of the covered work, then the patent -license you grant is automatically extended to all recipients of the covered work and -works based on it. - -A patent license is “discriminatory” if it does not include within the -scope of its coverage, prohibits the exercise of, or is conditioned on the -non-exercise of one or more of the rights that are specifically granted under this -License. You may not convey a covered work if you are a party to an arrangement with -a third party that is in the business of distributing software, under which you make -payment to the third party based on the extent of your activity of conveying the -work, and under which the third party grants, to any of the parties who would receive -the covered work from you, a discriminatory patent license **(a)** in connection with -copies of the covered work conveyed by you (or copies made from those copies), or **(b)** -primarily for and in connection with specific products or compilations that contain -the covered work, unless you entered into that arrangement, or that patent license -was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting any implied -license or other defenses to infringement that may otherwise be available to you -under applicable patent law. - -### 12. No Surrender of Others' Freedom - -If conditions are imposed on you (whether by court order, agreement or otherwise) -that contradict the conditions of this License, they do not excuse you from the -conditions of this License. If you cannot convey a covered work so as to satisfy -simultaneously your obligations under this License and any other pertinent -obligations, then as a consequence you may not convey it at all. For example, if you -agree to terms that obligate you to collect a royalty for further conveying from -those to whom you convey the Program, the only way you could satisfy both those terms -and this License would be to refrain entirely from conveying the Program. - -### 13. Use with the GNU Affero General Public License - -Notwithstanding any other provision of this License, you have permission to link or -combine any covered work with a work licensed under version 3 of the GNU Affero -General Public License into a single combined work, and to convey the resulting work. -The terms of this License will continue to apply to the part which is the covered -work, but the special requirements of the GNU Affero General Public License, section -13, concerning interaction through a network will apply to the combination as such. - -### 14. Revised Versions of this License - -The Free Software Foundation may publish revised and/or new versions of the GNU -General Public License from time to time. Such new versions will be similar in spirit -to the present version, but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Program specifies that -a certain numbered version of the GNU General Public License “or any later -version” applies to it, you have the option of following the terms and -conditions either of that numbered version or of any later version published by the -Free Software Foundation. If the Program does not specify a version number of the GNU -General Public License, you may choose any version ever published by the Free -Software Foundation. - -If the Program specifies that a proxy can decide which future versions of the GNU -General Public License can be used, that proxy's public statement of acceptance of a -version permanently authorizes you to choose that version for the Program. - -Later license versions may give you additional or different permissions. However, no -additional obligations are imposed on any author or copyright holder as a result of -your choosing to follow a later version. - -### 15. Disclaimer of Warranty - -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER -EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE -QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE -DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -### 16. Limitation of Liability - -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY -COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS -PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, -INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE -OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE -WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - -### 17. Interpretation of Sections 15 and 16 - -If the disclaimer of warranty and limitation of liability provided above cannot be -given local legal effect according to their terms, reviewing courts shall apply local -law that most closely approximates an absolute waiver of all civil liability in -connection with the Program, unless a warranty or assumption of liability accompanies -a copy of the Program in return for a fee. - -_END OF TERMS AND CONDITIONS_ - -## How to Apply These Terms to Your New Programs - -If you develop a new program, and you want it to be of the greatest possible use to -the public, the best way to achieve this is to make it free software which everyone -can redistribute and change under these terms. - -To do so, attach the following notices to the program. It is safest to attach them -to the start of each source file to most effectively state the exclusion of warranty; -and each file should have at least the “copyright” line and a pointer to -where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - -If the program does terminal interaction, make it output a short notice like this -when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type 'show c' for details. - -The hypothetical commands `show w` and `show c` should show the appropriate parts of -the General Public License. Of course, your program's commands might be different; -for a GUI interface, you would use an “about box”. - -You should also get your employer (if you work as a programmer) or school, if any, to -sign a “copyright disclaimer” for the program, if necessary. For more -information on this, and how to apply and follow the GNU GPL, see -<>. - -The GNU General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may consider it -more useful to permit linking proprietary applications with the library. If this is -what you want to do, use the GNU Lesser General Public License instead of this -License. But first, please read -<>. diff --git a/synthesizer/README.md b/synthesizer/README.md deleted file mode 100644 index 4e4671a2ec..0000000000 --- a/synthesizer/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# leo-synthesizer - -[![Crates.io](https://img.shields.io/crates/v/leo-synthesizer.svg?color=neon)](https://crates.io/crates/leo-synthesizer) -[![Authors](https://img.shields.io/badge/authors-Aleo-orange.svg)](../AUTHORS) -[![License](https://img.shields.io/badge/License-GPLv3-blue.svg)](./LICENSE.md) diff --git a/synthesizer/src/circuit_synthesizer.rs b/synthesizer/src/circuit_synthesizer.rs deleted file mode 100644 index 480a7284c4..0000000000 --- a/synthesizer/src/circuit_synthesizer.rs +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use snarkvm_curves::traits::PairingEngine; -use snarkvm_fields::Field; -use snarkvm_r1cs::{ConstraintSystem, Index, LinearCombination, OptionalVec, SynthesisError, Variable}; - -#[derive(Default)] -pub struct Namespace { - pub constraint_indices: Vec, - pub public_var_indices: Vec, - pub private_var_indices: Vec, -} - -pub struct ConstraintSet { - pub at: Vec<(E::Fr, Index)>, - pub bt: Vec<(E::Fr, Index)>, - pub ct: Vec<(E::Fr, Index)>, -} - -impl Default for ConstraintSet { - fn default() -> Self { - ConstraintSet { - at: Default::default(), - bt: Default::default(), - ct: Default::default(), - } - } -} - -pub struct CircuitSynthesizer { - // Constraints - pub constraints: OptionalVec>, - - // Assignments of variables - pub public_variables: OptionalVec, - pub private_variables: OptionalVec, - - // Technical namespaces used to remove of out-of-scope objects. - pub namespaces: Vec, -} - -impl Default for CircuitSynthesizer { - fn default() -> Self { - Self { - constraints: Default::default(), - public_variables: Default::default(), - private_variables: Default::default(), - namespaces: Default::default(), - } - } -} - -impl ConstraintSystem for CircuitSynthesizer { - type Root = Self; - - #[inline] - fn alloc(&mut self, _: A, f: F) -> Result - where - F: FnOnce() -> Result, - A: FnOnce() -> AR, - AR: AsRef, - { - let index = self.private_variables.insert(f()?); - if let Some(ref mut ns) = self.namespaces.last_mut() { - ns.private_var_indices.push(index); - } - Ok(Variable::new_unchecked(Index::Private(index))) - } - - #[inline] - fn alloc_input(&mut self, _: A, f: F) -> Result - where - F: FnOnce() -> Result, - A: FnOnce() -> AR, - AR: AsRef, - { - let index = self.public_variables.insert(f()?); - if let Some(ref mut ns) = self.namespaces.last_mut() { - ns.public_var_indices.push(index); - } - Ok(Variable::new_unchecked(Index::Public(index))) - } - - #[inline] - fn enforce(&mut self, _: A, a: LA, b: LB, c: LC) - where - A: FnOnce() -> AR, - AR: AsRef, - LA: FnOnce(LinearCombination) -> LinearCombination, - LB: FnOnce(LinearCombination) -> LinearCombination, - LC: FnOnce(LinearCombination) -> LinearCombination, - { - let index = self.constraints.insert(Default::default()); - - push_constraints(a(LinearCombination::zero()), &mut self.constraints[index].at); - push_constraints(b(LinearCombination::zero()), &mut self.constraints[index].bt); - push_constraints(c(LinearCombination::zero()), &mut self.constraints[index].ct); - - if let Some(ref mut ns) = self.namespaces.last_mut() { - ns.constraint_indices.push(index); - } - } - - fn push_namespace(&mut self, _: N) - where - NR: AsRef, - N: FnOnce() -> NR, - { - self.namespaces.push(Namespace::default()); - } - - fn pop_namespace(&mut self) { - // Todo @ljedrz: Fix constraint system optimizations. - // if let Some(ns) = self.namespaces.pop() { - // for idx in ns.constraint_indices { - // self.constraints.remove(idx); - // } - // - // for idx in ns.private_var_indices { - // self.private_variables.remove(idx); - // } - // - // for idx in ns.public_var_indices { - // self.public_variables.remove(idx); - // } - // } - } - - fn get_root(&mut self) -> &mut Self::Root { - self - } - - fn num_constraints(&self) -> usize { - self.constraints.len() - } - - fn num_public_variables(&self) -> usize { - self.public_variables.len() - } - - fn num_private_variables(&self) -> usize { - self.private_variables.len() - } - - fn is_in_setup_mode(&self) -> bool { - false - } -} - -fn push_constraints(l: LinearCombination, constraint: &mut Vec<(F, Index)>) { - for (var, coeff) in l.as_ref() { - match var.get_unchecked() { - Index::Public(i) => constraint.push((*coeff, Index::Public(i))), - Index::Private(i) => constraint.push((*coeff, Index::Private(i))), - } - } -} diff --git a/synthesizer/src/lib.rs b/synthesizer/src/lib.rs deleted file mode 100644 index 36396dd78e..0000000000 --- a/synthesizer/src/lib.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -#![doc = include_str!("../README.md")] - -pub mod circuit_synthesizer; -pub use self::circuit_synthesizer::*; - -pub mod serialized_circuit; -pub use self::serialized_circuit::*; - -pub mod summarized_circuit; -pub use self::summarized_circuit::*; - -pub mod serialized_field; -pub use self::serialized_field::*; - -pub mod serialized_index; -pub use self::serialized_index::*; diff --git a/synthesizer/src/serialized_circuit.rs b/synthesizer/src/serialized_circuit.rs deleted file mode 100644 index a70ba5e3ec..0000000000 --- a/synthesizer/src/serialized_circuit.rs +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use std::convert::TryFrom; - -use eyre::eyre; -use serde::{Deserialize, Serialize}; -use snarkvm_curves::{bls12_377::Bls12_377, traits::PairingEngine}; -use snarkvm_r1cs::{ConstraintSystem, Index, OptionalVec}; - -use crate::{CircuitSynthesizer, ConstraintSet, SerializedField, SerializedIndex}; -use leo_errors::{LeoError, SnarkVMError}; - -#[derive(Serialize, Deserialize)] -pub struct SerializedCircuit { - pub num_public_variables: usize, - pub num_private_variables: usize, - pub num_constraints: usize, - - pub public_variables: Vec, - pub private_variables: Vec, - - pub at: Vec>, - pub bt: Vec>, - pub ct: Vec>, -} - -impl SerializedCircuit { - pub fn to_json_string(&self) -> Result { - serde_json::to_string_pretty(&self).map_err(|e| LeoError::from(SnarkVMError::from(eyre!(e)))) - } - - pub fn from_json_string(json: &str) -> Result { - serde_json::from_str(json).map_err(|e| LeoError::from(SnarkVMError::from(eyre!(e)))) - } -} - -impl From> for SerializedCircuit { - fn from(synthesizer: CircuitSynthesizer) -> Self { - let num_public_variables = synthesizer.num_public_variables(); - let num_private_variables = synthesizer.num_private_variables(); - let num_constraints = synthesizer.num_constraints(); - - // Serialize assignments - fn get_serialized_assignments<'a, E: PairingEngine, I: Iterator>( - assignments: I, - ) -> Vec { - assignments.map(SerializedField::from).collect() - } - - let public_variables = get_serialized_assignments::(synthesizer.public_variables.iter()); - let private_variables = get_serialized_assignments::(synthesizer.private_variables.iter()); - - // Serialize constraints - fn get_serialized_constraints( - constraints: &[(E::Fr, Index)], - ) -> Vec<(SerializedField, SerializedIndex)> { - let mut serialized = Vec::with_capacity(constraints.len()); - - for &(ref coeff, index) in constraints { - let field = SerializedField::from(coeff); - let index = SerializedIndex::from(index); - - serialized.push((field, index)) - } - - serialized - } - - let mut at = Vec::with_capacity(num_constraints); - let mut bt = Vec::with_capacity(num_constraints); - let mut ct = Vec::with_capacity(num_constraints); - - for i in 0..num_constraints { - // Serialize at[i] - - let a_constraints = get_serialized_constraints::(&synthesizer.constraints[i].at); - at.push(a_constraints); - - // Serialize bt[i] - - let b_constraints = get_serialized_constraints::(&synthesizer.constraints[i].bt); - bt.push(b_constraints); - - // Serialize ct[i] - - let c_constraints = get_serialized_constraints::(&synthesizer.constraints[i].ct); - ct.push(c_constraints); - } - - Self { - num_public_variables, - num_private_variables, - num_constraints, - public_variables, - private_variables, - at, - bt, - ct, - } - } -} - -impl TryFrom for CircuitSynthesizer { - type Error = LeoError; - - fn try_from(serialized: SerializedCircuit) -> Result, Self::Error> { - // Deserialize assignments - fn get_deserialized_assignments( - assignments: &[SerializedField], - ) -> Result::Fr>, LeoError> { - let mut deserialized = OptionalVec::with_capacity(assignments.len()); - - for serialized_assignment in assignments { - let field = ::Fr::try_from(serialized_assignment) - .map_err(|e| LeoError::from(SnarkVMError::from(eyre!(e))))?; - - deserialized.insert(field); - } - - Ok(deserialized) - } - - let public_variables = get_deserialized_assignments(&serialized.public_variables)?; - let private_variables = get_deserialized_assignments(&serialized.private_variables)?; - - // Deserialize constraints - fn get_deserialized_constraints( - constraints: &[(SerializedField, SerializedIndex)], - ) -> Result::Fr, Index)>, LeoError> { - let mut deserialized = Vec::with_capacity(constraints.len()); - - for &(ref serialized_coeff, ref serialized_index) in constraints { - let field = ::Fr::try_from(serialized_coeff) - .map_err(|e| LeoError::from(SnarkVMError::from(eyre!(e))))?; - let index = Index::from(serialized_index); - - deserialized.push((field, index)); - } - - Ok(deserialized) - } - - let mut constraints = OptionalVec::with_capacity(serialized.num_constraints); - - for i in 0..serialized.num_constraints { - // Deserialize at[i] - let a_constraints = get_deserialized_constraints(&serialized.at[i])?; - - // Deserialize bt[i] - let b_constraints = get_deserialized_constraints(&serialized.bt[i])?; - - // Deserialize ct[i] - let c_constraints = get_deserialized_constraints(&serialized.ct[i])?; - - constraints.insert(ConstraintSet { - at: a_constraints, - bt: b_constraints, - ct: c_constraints, - }); - } - - Ok(CircuitSynthesizer:: { - constraints, - public_variables, - private_variables, - namespaces: Default::default(), - }) - } -} diff --git a/synthesizer/src/serialized_field.rs b/synthesizer/src/serialized_field.rs deleted file mode 100644 index 78d0f13d13..0000000000 --- a/synthesizer/src/serialized_field.rs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use std::{convert::TryFrom, str::FromStr}; - -use num_bigint::BigUint; -use serde::{Deserialize, Serialize}; -use snarkvm_fields::{Field, FieldError, Fp256, Fp256Parameters}; - -#[derive(Serialize, Deserialize)] -pub struct SerializedField(pub String); - -impl From<&F> for SerializedField { - fn from(field: &F) -> Self { - // write field to buffer - - let mut buf = Vec::new(); - - field.write_le(&mut buf).unwrap(); - - // convert to base 10 integer - - let f_bigint = BigUint::from_bytes_le(&buf); - - let f_string = f_bigint.to_str_radix(10); - - Self(f_string) - } -} - -impl TryFrom<&SerializedField> for Fp256

{ - type Error = FieldError; - - fn try_from(serialized: &SerializedField) -> Result { - Fp256::

::from_str(&serialized.0) - } -} diff --git a/synthesizer/src/serialized_index.rs b/synthesizer/src/serialized_index.rs deleted file mode 100644 index 2d7c879881..0000000000 --- a/synthesizer/src/serialized_index.rs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use serde::{Deserialize, Serialize}; -use snarkvm_r1cs::Index; - -#[derive(Serialize, Deserialize)] -pub enum SerializedIndex { - Public(usize), - Private(usize), -} - -impl From for SerializedIndex { - fn from(index: Index) -> Self { - match index { - Index::Public(idx) => Self::Public(idx), - Index::Private(idx) => Self::Private(idx), - } - } -} - -impl From<&SerializedIndex> for Index { - fn from(serialized_index: &SerializedIndex) -> Self { - match serialized_index { - SerializedIndex::Public(idx) => Index::Public(*idx), - SerializedIndex::Private(idx) => Index::Private(*idx), - } - } -} diff --git a/synthesizer/src/summarized_circuit.rs b/synthesizer/src/summarized_circuit.rs deleted file mode 100644 index 0d083585fc..0000000000 --- a/synthesizer/src/summarized_circuit.rs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; - -use crate::SerializedCircuit; - -#[derive(Serialize, Deserialize, PartialEq)] -pub struct SummarizedCircuit { - pub num_public_variables: usize, - pub num_private_variables: usize, - pub num_constraints: usize, - - // pub public_variables: String, - // pub private_variables: String, - pub at: String, - pub bt: String, - pub ct: String, -} - -fn hash_field(input: &str) -> String { - let mut hasher = Sha256::new(); - hasher.update(input.as_bytes()); - let output = hasher.finalize(); - hex::encode(&output[..]) -} - -impl From for SummarizedCircuit { - fn from(other: SerializedCircuit) -> Self { - Self { - num_public_variables: other.num_public_variables, - num_private_variables: other.num_private_variables, - num_constraints: other.num_constraints, - // public_variables: hash_field(&serde_json::to_string(&other.public_variables) - // .expect("failed to serialize public_variables")), - // private_variables: hash_field(&serde_json::to_string(&other.private_variables) - // .expect("failed to serialize private_variables")), - at: hash_field(&serde_json::to_string(&other.at).expect("failed to serialize at")), - bt: hash_field(&serde_json::to_string(&other.bt).expect("failed to serialize bt")), - ct: hash_field(&serde_json::to_string(&other.ct).expect("failed to serialize ct")), - } - } -} diff --git a/test-framework/README.md b/test-framework/README.md deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/linter/Cargo.toml b/tools/linter/Cargo.toml similarity index 100% rename from linter/Cargo.toml rename to tools/linter/Cargo.toml diff --git a/package/LICENSE.md b/tools/linter/LICENSE.md similarity index 100% rename from package/LICENSE.md rename to tools/linter/LICENSE.md diff --git a/linter/README.md b/tools/linter/README.md similarity index 100% rename from linter/README.md rename to tools/linter/README.md diff --git a/linter/src/main.rs b/tools/linter/src/main.rs similarity index 100% rename from linter/src/main.rs rename to tools/linter/src/main.rs diff --git a/test-framework/.gitignore b/tools/test-framework/.gitignore similarity index 100% rename from test-framework/.gitignore rename to tools/test-framework/.gitignore diff --git a/test-framework/Cargo.toml b/tools/test-framework/Cargo.toml similarity index 98% rename from test-framework/Cargo.toml rename to tools/test-framework/Cargo.toml index 567c2db3c7..fa4a97beb6 100644 --- a/test-framework/Cargo.toml +++ b/tools/test-framework/Cargo.toml @@ -60,7 +60,7 @@ version = "0.3" # List of dependencies for errcov [dependencies.leo-errors] -path = "../errors" +path = "../../leo/errors" version = "1.5.3" [dependencies.regex] diff --git a/asg-passes/README.md b/tools/test-framework/README.md similarity index 100% rename from asg-passes/README.md rename to tools/test-framework/README.md diff --git a/test-framework/src/bin/errcov.rs b/tools/test-framework/src/bin/errcov.rs similarity index 100% rename from test-framework/src/bin/errcov.rs rename to tools/test-framework/src/bin/errcov.rs diff --git a/test-framework/src/error.rs b/tools/test-framework/src/error.rs similarity index 100% rename from test-framework/src/error.rs rename to tools/test-framework/src/error.rs diff --git a/test-framework/src/fetch.rs b/tools/test-framework/src/fetch.rs similarity index 100% rename from test-framework/src/fetch.rs rename to tools/test-framework/src/fetch.rs diff --git a/test-framework/src/lib.rs b/tools/test-framework/src/lib.rs similarity index 100% rename from test-framework/src/lib.rs rename to tools/test-framework/src/lib.rs diff --git a/test-framework/src/output.rs b/tools/test-framework/src/output.rs similarity index 100% rename from test-framework/src/output.rs rename to tools/test-framework/src/output.rs diff --git a/test-framework/src/runner.rs b/tools/test-framework/src/runner.rs similarity index 99% rename from test-framework/src/runner.rs rename to tools/test-framework/src/runner.rs index 402e268aae..b2d49394c3 100644 --- a/test-framework/src/runner.rs +++ b/tools/test-framework/src/runner.rs @@ -56,7 +56,7 @@ pub fn run_tests(runner: &T, expectation_category: &str) { let mut tests = Vec::new(); let mut test_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - test_dir.push("../tests/"); + test_dir.push("../../tests/"); let mut expectation_dir = test_dir.clone(); expectation_dir.push("expectations"); diff --git a/test-framework/src/test.rs b/tools/test-framework/src/test.rs similarity index 100% rename from test-framework/src/test.rs rename to tools/test-framework/src/test.rs diff --git a/test-framework/src/unused/tgc.rs b/tools/test-framework/src/unused/tgc.rs similarity index 100% rename from test-framework/src/unused/tgc.rs rename to tools/test-framework/src/unused/tgc.rs diff --git a/unused/state/Cargo.toml b/unused/state/Cargo.toml deleted file mode 100644 index 1628b317b4..0000000000 --- a/unused/state/Cargo.toml +++ /dev/null @@ -1,61 +0,0 @@ -[package] -name = "leo-state" -version = "1.5.3" -authors = [ "The Aleo Team " ] -description = "State parser of the Leo programming language" -homepage = "https://aleo.org" -repository = "https://github.com/AleoHQ/leo" -keywords = [ - "aleo", - "cryptography", - "leo", - "programming-language", - "zero-knowledge" -] -categories = [ "cryptography::cryptocurrencies", "web-programming" ] -include = [ "Cargo.toml", "src", "README.md", "LICENSE.md" ] -license = "GPL-3.0" -edition = "2018" - -[dependencies.leo-ast] -path = "../ast" -version = "1.5.3" - -[dependencies.leo-errors] -path = "../errors" -version = "1.5.3" - -[dependencies.leo-input] -path = "../input" -version = "1.5.3" - -[dependencies.snarkvm-algorithms] -git = "https://github.com/AleoHQ/snarkVM.git" -rev = "51633e2" - -[dependencies.snarkvm-curves] -git = "https://github.com/AleoHQ/snarkVM.git" -rev = "51633e2" -default-features = false - -[dependencies.snarkvm-dpc] -git = "https://github.com/AleoHQ/snarkVM.git" -rev = "51633e2" -features = [ "testnet2" ] - -[dependencies.snarkvm-utilities] -git = "https://github.com/AleoHQ/snarkVM.git" -rev = "51633e2" - -[dependencies.indexmap] -version = "1.7.0" -features = [ "serde-1" ] - -[dependencies.rand] -version = "0.8" - -[dependencies.rand_xorshift] -version = "0.3" - -[dev-dependencies.rand_core] -version = "0.6.3" diff --git a/unused/state/LICENSE.md b/unused/state/LICENSE.md deleted file mode 100644 index b95c626e2a..0000000000 --- a/unused/state/LICENSE.md +++ /dev/null @@ -1,596 +0,0 @@ -GNU General Public License -========================== - -Version 3, 29 June 2007 - -Copyright © 2007 Free Software Foundation, Inc. <> - -Everyone is permitted to copy and distribute verbatim copies of this license -document, but changing it is not allowed. - -## Preamble - -The GNU General Public License is a free, copyleft license for software and other -kinds of works. - -The licenses for most software and other practical works are designed to take away -your freedom to share and change the works. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change all versions of a -program--to make sure it remains free software for all its users. We, the Free -Software Foundation, use the GNU General Public License for most of our software; it -applies also to any other work released this way by its authors. You can apply it to -your programs, too. - -When we speak of free software, we are referring to freedom, not price. Our General -Public Licenses are designed to make sure that you have the freedom to distribute -copies of free software (and charge for them if you wish), that you receive source -code or can get it if you want it, that you can change the software or use pieces of -it in new free programs, and that you know you can do these things. - -To protect your rights, we need to prevent others from denying you these rights or -asking you to surrender the rights. Therefore, you have certain responsibilities if -you distribute copies of the software, or if you modify it: responsibilities to -respect the freedom of others. - -For example, if you distribute copies of such a program, whether gratis or for a fee, -you must pass on to the recipients the same freedoms that you received. You must make -sure that they, too, receive or can get the source code. And you must show them these -terms so they know their rights. - -Developers that use the GNU GPL protect your rights with two steps: **(1)** assert -copyright on the software, and **(2)** offer you this License giving you legal permission -to copy, distribute and/or modify it. - -For the developers' and authors' protection, the GPL clearly explains that there is -no warranty for this free software. For both users' and authors' sake, the GPL -requires that modified versions be marked as changed, so that their problems will not -be attributed erroneously to authors of previous versions. - -Some devices are designed to deny users access to install or run modified versions of -the software inside them, although the manufacturer can do so. This is fundamentally -incompatible with the aim of protecting users' freedom to change the software. The -systematic pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we have designed -this version of the GPL to prohibit the practice for those products. If such problems -arise substantially in other domains, we stand ready to extend this provision to -those domains in future versions of the GPL, as needed to protect the freedom of -users. - -Finally, every program is threatened constantly by software patents. States should -not allow patents to restrict development and use of software on general-purpose -computers, but in those that do, we wish to avoid the special danger that patents -applied to a free program could make it effectively proprietary. To prevent this, the -GPL assures that patents cannot be used to render the program non-free. - -The precise terms and conditions for copying, distribution and modification follow. - -## TERMS AND CONDITIONS - -### 0. Definitions - -“This License” refers to version 3 of the GNU General Public License. - -“Copyright” also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - -“The Program” refers to any copyrightable work licensed under this -License. Each licensee is addressed as “you”. “Licensees” and -“recipients” may be individuals or organizations. - -To “modify” a work means to copy from or adapt all or part of the work in -a fashion requiring copyright permission, other than the making of an exact copy. The -resulting work is called a “modified version” of the earlier work or a -work “based on” the earlier work. - -A “covered work” means either the unmodified Program or a work based on -the Program. - -To “propagate” a work means to do anything with it that, without -permission, would make you directly or secondarily liable for infringement under -applicable copyright law, except executing it on a computer or modifying a private -copy. Propagation includes copying, distribution (with or without modification), -making available to the public, and in some countries other activities as well. - -To “convey” a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through a computer -network, with no transfer of a copy, is not conveying. - -An interactive user interface displays “Appropriate Legal Notices” to the -extent that it includes a convenient and prominently visible feature that **(1)** -displays an appropriate copyright notice, and **(2)** tells the user that there is no -warranty for the work (except to the extent that warranties are provided), that -licensees may convey the work under this License, and how to view a copy of this -License. If the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - -### 1. Source Code - -The “source code” for a work means the preferred form of the work for -making modifications to it. “Object code” means any non-source form of a -work. - -A “Standard Interface” means an interface that either is an official -standard defined by a recognized standards body, or, in the case of interfaces -specified for a particular programming language, one that is widely used among -developers working in that language. - -The “System Libraries” of an executable work include anything, other than -the work as a whole, that **(a)** is included in the normal form of packaging a Major -Component, but which is not part of that Major Component, and **(b)** serves only to -enable use of the work with that Major Component, or to implement a Standard -Interface for which an implementation is available to the public in source code form. -A “Major Component”, in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system (if any) on which -the executable work runs, or a compiler used to produce the work, or an object code -interpreter used to run it. - -The “Corresponding Source” for a work in object code form means all the -source code needed to generate, install, and (for an executable work) run the object -code and to modify the work, including scripts to control those activities. However, -it does not include the work's System Libraries, or general-purpose tools or -generally available free programs which are used unmodified in performing those -activities but which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for the work, and -the source code for shared libraries and dynamically linked subprograms that the work -is specifically designed to require, such as by intimate data communication or -control flow between those subprograms and other parts of the work. - -The Corresponding Source need not include anything that users can regenerate -automatically from other parts of the Corresponding Source. - -The Corresponding Source for a work in source code form is that same work. - -### 2. Basic Permissions - -All rights granted under this License are granted for the term of copyright on the -Program, and are irrevocable provided the stated conditions are met. This License -explicitly affirms your unlimited permission to run the unmodified Program. The -output from running a covered work is covered by this License only if the output, -given its content, constitutes a covered work. This License acknowledges your rights -of fair use or other equivalent, as provided by copyright law. - -You may make, run and propagate covered works that you do not convey, without -conditions so long as your license otherwise remains in force. You may convey covered -works to others for the sole purpose of having them make modifications exclusively -for you, or provide you with facilities for running those works, provided that you -comply with the terms of this License in conveying all material for which you do not -control copyright. Those thus making or running the covered works for you must do so -exclusively on your behalf, under your direction and control, on terms that prohibit -them from making any copies of your copyrighted material outside their relationship -with you. - -Conveying under any other circumstances is permitted solely under the conditions -stated below. Sublicensing is not allowed; section 10 makes it unnecessary. - -### 3. Protecting Users' Legal Rights From Anti-Circumvention Law - -No covered work shall be deemed part of an effective technological measure under any -applicable law fulfilling obligations under article 11 of the WIPO copyright treaty -adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention -of such measures. - -When you convey a covered work, you waive any legal power to forbid circumvention of -technological measures to the extent such circumvention is effected by exercising -rights under this License with respect to the covered work, and you disclaim any -intention to limit operation or modification of the work as a means of enforcing, -against the work's users, your or third parties' legal rights to forbid circumvention -of technological measures. - -### 4. Conveying Verbatim Copies - -You may convey verbatim copies of the Program's source code as you receive it, in any -medium, provided that you conspicuously and appropriately publish on each copy an -appropriate copyright notice; keep intact all notices stating that this License and -any non-permissive terms added in accord with section 7 apply to the code; keep -intact all notices of the absence of any warranty; and give all recipients a copy of -this License along with the Program. - -You may charge any price or no price for each copy that you convey, and you may offer -support or warranty protection for a fee. - -### 5. Conveying Modified Source Versions - -You may convey a work based on the Program, or the modifications to produce it from -the Program, in the form of source code under the terms of section 4, provided that -you also meet all of these conditions: - -* **a)** The work must carry prominent notices stating that you modified it, and giving a -relevant date. -* **b)** The work must carry prominent notices stating that it is released under this -License and any conditions added under section 7. This requirement modifies the -requirement in section 4 to “keep intact all notices”. -* **c)** You must license the entire work, as a whole, under this License to anyone who -comes into possession of a copy. This License will therefore apply, along with any -applicable section 7 additional terms, to the whole of the work, and all its parts, -regardless of how they are packaged. This License gives no permission to license the -work in any other way, but it does not invalidate such permission if you have -separately received it. -* **d)** If the work has interactive user interfaces, each must display Appropriate Legal -Notices; however, if the Program has interactive interfaces that do not display -Appropriate Legal Notices, your work need not make them do so. - -A compilation of a covered work with other separate and independent works, which are -not by their nature extensions of the covered work, and which are not combined with -it such as to form a larger program, in or on a volume of a storage or distribution -medium, is called an “aggregate” if the compilation and its resulting -copyright are not used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work in an aggregate -does not cause this License to apply to the other parts of the aggregate. - -### 6. Conveying Non-Source Forms - -You may convey a covered work in object code form under the terms of sections 4 and -5, provided that you also convey the machine-readable Corresponding Source under the -terms of this License, in one of these ways: - -* **a)** Convey the object code in, or embodied in, a physical product (including a -physical distribution medium), accompanied by the Corresponding Source fixed on a -durable physical medium customarily used for software interchange. -* **b)** Convey the object code in, or embodied in, a physical product (including a -physical distribution medium), accompanied by a written offer, valid for at least -three years and valid for as long as you offer spare parts or customer support for -that product model, to give anyone who possesses the object code either **(1)** a copy of -the Corresponding Source for all the software in the product that is covered by this -License, on a durable physical medium customarily used for software interchange, for -a price no more than your reasonable cost of physically performing this conveying of -source, or **(2)** access to copy the Corresponding Source from a network server at no -charge. -* **c)** Convey individual copies of the object code with a copy of the written offer to -provide the Corresponding Source. This alternative is allowed only occasionally and -noncommercially, and only if you received the object code with such an offer, in -accord with subsection 6b. -* **d)** Convey the object code by offering access from a designated place (gratis or for -a charge), and offer equivalent access to the Corresponding Source in the same way -through the same place at no further charge. You need not require recipients to copy -the Corresponding Source along with the object code. If the place to copy the object -code is a network server, the Corresponding Source may be on a different server -(operated by you or a third party) that supports equivalent copying facilities, -provided you maintain clear directions next to the object code saying where to find -the Corresponding Source. Regardless of what server hosts the Corresponding Source, -you remain obligated to ensure that it is available for as long as needed to satisfy -these requirements. -* **e)** Convey the object code using peer-to-peer transmission, provided you inform -other peers where the object code and Corresponding Source of the work are being -offered to the general public at no charge under subsection 6d. - -A separable portion of the object code, whose source code is excluded from the -Corresponding Source as a System Library, need not be included in conveying the -object code work. - -A “User Product” is either **(1)** a “consumer product”, which -means any tangible personal property which is normally used for personal, family, or -household purposes, or **(2)** anything designed or sold for incorporation into a -dwelling. In determining whether a product is a consumer product, doubtful cases -shall be resolved in favor of coverage. For a particular product received by a -particular user, “normally used” refers to a typical or common use of -that class of product, regardless of the status of the particular user or of the way -in which the particular user actually uses, or expects or is expected to use, the -product. A product is a consumer product regardless of whether the product has -substantial commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - -“Installation Information” for a User Product means any methods, -procedures, authorization keys, or other information required to install and execute -modified versions of a covered work in that User Product from a modified version of -its Corresponding Source. The information must suffice to ensure that the continued -functioning of the modified object code is in no case prevented or interfered with -solely because modification has been made. - -If you convey an object code work under this section in, or with, or specifically for -use in, a User Product, and the conveying occurs as part of a transaction in which -the right of possession and use of the User Product is transferred to the recipient -in perpetuity or for a fixed term (regardless of how the transaction is -characterized), the Corresponding Source conveyed under this section must be -accompanied by the Installation Information. But this requirement does not apply if -neither you nor any third party retains the ability to install modified object code -on the User Product (for example, the work has been installed in ROM). - -The requirement to provide Installation Information does not include a requirement to -continue to provide support service, warranty, or updates for a work that has been -modified or installed by the recipient, or for the User Product in which it has been -modified or installed. Access to a network may be denied when the modification itself -materially and adversely affects the operation of the network or violates the rules -and protocols for communication across the network. - -Corresponding Source conveyed, and Installation Information provided, in accord with -this section must be in a format that is publicly documented (and with an -implementation available to the public in source code form), and must require no -special password or key for unpacking, reading or copying. - -### 7. Additional Terms - -“Additional permissions” are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. Additional -permissions that are applicable to the entire Program shall be treated as though they -were included in this License, to the extent that they are valid under applicable -law. If additional permissions apply only to part of the Program, that part may be -used separately under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - -When you convey a copy of a covered work, you may at your option remove any -additional permissions from that copy, or from any part of it. (Additional -permissions may be written to require their own removal in certain cases when you -modify the work.) You may place additional permissions on material, added by you to a -covered work, for which you have or can give appropriate copyright permission. - -Notwithstanding any other provision of this License, for material you add to a -covered work, you may (if authorized by the copyright holders of that material) -supplement the terms of this License with terms: - -* **a)** Disclaiming warranty or limiting liability differently from the terms of -sections 15 and 16 of this License; or -* **b)** Requiring preservation of specified reasonable legal notices or author -attributions in that material or in the Appropriate Legal Notices displayed by works -containing it; or -* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that -modified versions of such material be marked in reasonable ways as different from the -original version; or -* **d)** Limiting the use for publicity purposes of names of licensors or authors of the -material; or -* **e)** Declining to grant rights under trademark law for use of some trade names, -trademarks, or service marks; or -* **f)** Requiring indemnification of licensors and authors of that material by anyone -who conveys the material (or modified versions of it) with contractual assumptions of -liability to the recipient, for any liability that these contractual assumptions -directly impose on those licensors and authors. - -All other non-permissive additional terms are considered “further -restrictions” within the meaning of section 10. If the Program as you received -it, or any part of it, contains a notice stating that it is governed by this License -along with a term that is a further restriction, you may remove that term. If a -license document contains a further restriction but permits relicensing or conveying -under this License, you may add to a covered work material governed by the terms of -that license document, provided that the further restriction does not survive such -relicensing or conveying. - -If you add terms to a covered work in accord with this section, you must place, in -the relevant source files, a statement of the additional terms that apply to those -files, or a notice indicating where to find the applicable terms. - -Additional terms, permissive or non-permissive, may be stated in the form of a -separately written license, or stated as exceptions; the above requirements apply -either way. - -### 8. Termination - -You may not propagate or modify a covered work except as expressly provided under -this License. Any attempt otherwise to propagate or modify it is void, and will -automatically terminate your rights under this License (including any patent licenses -granted under the third paragraph of section 11). - -However, if you cease all violation of this License, then your license from a -particular copyright holder is reinstated **(a)** provisionally, unless and until the -copyright holder explicitly and finally terminates your license, and **(b)** permanently, -if the copyright holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - -Moreover, your license from a particular copyright holder is reinstated permanently -if the copyright holder notifies you of the violation by some reasonable means, this -is the first time you have received notice of violation of this License (for any -work) from that copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - -Termination of your rights under this section does not terminate the licenses of -parties who have received copies or rights from you under this License. If your -rights have been terminated and not permanently reinstated, you do not qualify to -receive new licenses for the same material under section 10. - -### 9. Acceptance Not Required for Having Copies - -You are not required to accept this License in order to receive or run a copy of the -Program. Ancillary propagation of a covered work occurring solely as a consequence of -using peer-to-peer transmission to receive a copy likewise does not require -acceptance. However, nothing other than this License grants you permission to -propagate or modify any covered work. These actions infringe copyright if you do not -accept this License. Therefore, by modifying or propagating a covered work, you -indicate your acceptance of this License to do so. - -### 10. Automatic Licensing of Downstream Recipients - -Each time you convey a covered work, the recipient automatically receives a license -from the original licensors, to run, modify and propagate that work, subject to this -License. You are not responsible for enforcing compliance by third parties with this -License. - -An “entity transaction” is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an organization, or -merging organizations. If propagation of a covered work results from an entity -transaction, each party to that transaction who receives a copy of the work also -receives whatever licenses to the work the party's predecessor in interest had or -could give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if the predecessor -has it or can get it with reasonable efforts. - -You may not impose any further restrictions on the exercise of the rights granted or -affirmed under this License. For example, you may not impose a license fee, royalty, -or other charge for exercise of rights granted under this License, and you may not -initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging -that any patent claim is infringed by making, using, selling, offering for sale, or -importing the Program or any portion of it. - -### 11. Patents - -A “contributor” is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The work thus -licensed is called the contributor's “contributor version”. - -A contributor's “essential patent claims” are all patent claims owned or -controlled by the contributor, whether already acquired or hereafter acquired, that -would be infringed by some manner, permitted by this License, of making, using, or -selling its contributor version, but do not include claims that would be infringed -only as a consequence of further modification of the contributor version. For -purposes of this definition, “control” includes the right to grant patent -sublicenses in a manner consistent with the requirements of this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free patent license -under the contributor's essential patent claims, to make, use, sell, offer for sale, -import and otherwise run, modify and propagate the contents of its contributor -version. - -In the following three paragraphs, a “patent license” is any express -agreement or commitment, however denominated, not to enforce a patent (such as an -express permission to practice a patent or covenant not to sue for patent -infringement). To “grant” such a patent license to a party means to make -such an agreement or commitment not to enforce a patent against the party. - -If you convey a covered work, knowingly relying on a patent license, and the -Corresponding Source of the work is not available for anyone to copy, free of charge -and under the terms of this License, through a publicly available network server or -other readily accessible means, then you must either **(1)** cause the Corresponding -Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the -patent license for this particular work, or **(3)** arrange, in a manner consistent with -the requirements of this License, to extend the patent license to downstream -recipients. “Knowingly relying” means you have actual knowledge that, but -for the patent license, your conveying the covered work in a country, or your -recipient's use of the covered work in a country, would infringe one or more -identifiable patents in that country that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or arrangement, you -convey, or propagate by procuring conveyance of, a covered work, and grant a patent -license to some of the parties receiving the covered work authorizing them to use, -propagate, modify or convey a specific copy of the covered work, then the patent -license you grant is automatically extended to all recipients of the covered work and -works based on it. - -A patent license is “discriminatory” if it does not include within the -scope of its coverage, prohibits the exercise of, or is conditioned on the -non-exercise of one or more of the rights that are specifically granted under this -License. You may not convey a covered work if you are a party to an arrangement with -a third party that is in the business of distributing software, under which you make -payment to the third party based on the extent of your activity of conveying the -work, and under which the third party grants, to any of the parties who would receive -the covered work from you, a discriminatory patent license **(a)** in connection with -copies of the covered work conveyed by you (or copies made from those copies), or **(b)** -primarily for and in connection with specific products or compilations that contain -the covered work, unless you entered into that arrangement, or that patent license -was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting any implied -license or other defenses to infringement that may otherwise be available to you -under applicable patent law. - -### 12. No Surrender of Others' Freedom - -If conditions are imposed on you (whether by court order, agreement or otherwise) -that contradict the conditions of this License, they do not excuse you from the -conditions of this License. If you cannot convey a covered work so as to satisfy -simultaneously your obligations under this License and any other pertinent -obligations, then as a consequence you may not convey it at all. For example, if you -agree to terms that obligate you to collect a royalty for further conveying from -those to whom you convey the Program, the only way you could satisfy both those terms -and this License would be to refrain entirely from conveying the Program. - -### 13. Use with the GNU Affero General Public License - -Notwithstanding any other provision of this License, you have permission to link or -combine any covered work with a work licensed under version 3 of the GNU Affero -General Public License into a single combined work, and to convey the resulting work. -The terms of this License will continue to apply to the part which is the covered -work, but the special requirements of the GNU Affero General Public License, section -13, concerning interaction through a network will apply to the combination as such. - -### 14. Revised Versions of this License - -The Free Software Foundation may publish revised and/or new versions of the GNU -General Public License from time to time. Such new versions will be similar in spirit -to the present version, but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Program specifies that -a certain numbered version of the GNU General Public License “or any later -version” applies to it, you have the option of following the terms and -conditions either of that numbered version or of any later version published by the -Free Software Foundation. If the Program does not specify a version number of the GNU -General Public License, you may choose any version ever published by the Free -Software Foundation. - -If the Program specifies that a proxy can decide which future versions of the GNU -General Public License can be used, that proxy's public statement of acceptance of a -version permanently authorizes you to choose that version for the Program. - -Later license versions may give you additional or different permissions. However, no -additional obligations are imposed on any author or copyright holder as a result of -your choosing to follow a later version. - -### 15. Disclaimer of Warranty - -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER -EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE -QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE -DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -### 16. Limitation of Liability - -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY -COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS -PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, -INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE -OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE -WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - -### 17. Interpretation of Sections 15 and 16 - -If the disclaimer of warranty and limitation of liability provided above cannot be -given local legal effect according to their terms, reviewing courts shall apply local -law that most closely approximates an absolute waiver of all civil liability in -connection with the Program, unless a warranty or assumption of liability accompanies -a copy of the Program in return for a fee. - -_END OF TERMS AND CONDITIONS_ - -## How to Apply These Terms to Your New Programs - -If you develop a new program, and you want it to be of the greatest possible use to -the public, the best way to achieve this is to make it free software which everyone -can redistribute and change under these terms. - -To do so, attach the following notices to the program. It is safest to attach them -to the start of each source file to most effectively state the exclusion of warranty; -and each file should have at least the “copyright” line and a pointer to -where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - -If the program does terminal interaction, make it output a short notice like this -when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type 'show c' for details. - -The hypothetical commands `show w` and `show c` should show the appropriate parts of -the General Public License. Of course, your program's commands might be different; -for a GUI interface, you would use an “about box”. - -You should also get your employer (if you work as a programmer) or school, if any, to -sign a “copyright disclaimer” for the program, if necessary. For more -information on this, and how to apply and follow the GNU GPL, see -<>. - -The GNU General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may consider it -more useful to permit linking proprietary applications with the library. If this is -what you want to do, use the GNU Lesser General Public License instead of this -License. But first, please read -<>. diff --git a/unused/state/README.md b/unused/state/README.md deleted file mode 100644 index 43f2f3e00c..0000000000 --- a/unused/state/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# leo-state - -[![Crates.io](https://img.shields.io/crates/v/leo-state.svg?color=neon)](https://crates.io/crates/leo-state) -[![Authors](https://img.shields.io/badge/authors-Aleo-orange.svg)](../AUTHORS) -[![License](https://img.shields.io/badge/License-GPLv3-blue.svg)](./LICENSE.md) diff --git a/unused/state/src/lib.rs b/unused/state/src/lib.rs deleted file mode 100644 index 88531a4873..0000000000 --- a/unused/state/src/lib.rs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -#![allow(clippy::module_inception)] -#![allow(clippy::upper_case_acronyms)] -#![doc = include_str!("../README.md")] - -pub mod local_data_commitment; -pub use self::local_data_commitment::*; - -pub mod record_commitment; -pub use self::record_commitment::*; - -pub mod utilities; -pub use self::utilities::*; diff --git a/unused/state/src/local_data_commitment/local_data_commitment.rs b/unused/state/src/local_data_commitment/local_data_commitment.rs deleted file mode 100644 index 3cf8144ead..0000000000 --- a/unused/state/src/local_data_commitment/local_data_commitment.rs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{verify_record_commitment, StateLeafValues, StateValues}; -use leo_ast::Input as AstInput; -use leo_errors::{Result, SnarkVMError, StateError}; - -use snarkvm_algorithms::{ - commitment_tree::CommitmentMerklePath, - traits::{CommitmentScheme, CRH}, -}; -use snarkvm_dpc::{ - testnet1::{instantiated::Components, parameters::SystemParameters}, - DPCComponents, -}; -use snarkvm_utilities::{bytes::ToBytes, to_bytes_le, FromBytes}; - -use std::convert::TryFrom; - -/// Returns `true` if the path to the local data commitment leaf is a valid path in the record -/// commitment Merkle tree. -pub fn verify_local_data_commitment(dpc: &SystemParameters, ast_input: &AstInput) -> Result { - // Verify record commitment. - let typed_record = ast_input.get_record(); - let dpc_record_values = verify_record_commitment(dpc, typed_record)?; - let record_commitment: Vec = dpc_record_values.commitment; - let record_serial_number: Vec = dpc_record_values.serial_number; - - // Parse typed state values. - let typed_state = ast_input.get_state(); - let state_values = StateValues::try_from(typed_state)?; - let leaf_index: u32 = state_values.leaf_index; - let root: Vec = state_values.root; - - // parse typed state leaf values. - let typed_state_leaf = ast_input.get_state_leaf(); - let state_leaf_values = StateLeafValues::try_from(typed_state_leaf)?; - let path: Vec = state_leaf_values.path; - let memo: Vec = state_leaf_values.memo; - let network_id: u8 = state_leaf_values.network_id; - let leaf_randomness: Vec = state_leaf_values.leaf_randomness; - - // Select local data commitment input bytes. - let is_death = leaf_index < (Components::NUM_INPUT_RECORDS as u32); - let input_bytes = if is_death { - to_bytes_le![record_serial_number, record_commitment, memo, network_id].map_err(StateError::state_io_error)? - } else { - to_bytes_le![record_commitment, memo, network_id].map_err(StateError::state_io_error)? - }; - - // Construct local data commitment leaf. - let local_data_leaf_randomness = - <::LocalDataCommitment as CommitmentScheme>::Randomness::read_le( - &leaf_randomness[..], - ) - .map_err(StateError::state_io_error)?; - let local_data_commitment_leaf = ::LocalDataCommitment::commit( - &dpc.local_data_commitment, - &input_bytes, - &local_data_leaf_randomness, - ) - .map_err(|_| SnarkVMError::default())?; - - // Construct record commitment merkle path. - let local_data_merkle_path = CommitmentMerklePath::< - ::LocalDataCommitment, - ::LocalDataCRH, - >::read_le(&path[..]) - .map_err(StateError::state_io_error)?; - - // Check record commitment merkle path is valid for the given local data commitment root. - let local_data_commitment_root = <::LocalDataCRH as CRH>::Output::read_le(&root[..]) - .map_err(StateError::state_io_error)?; - let result = local_data_merkle_path - .verify( - &dpc.local_data_crh, - &local_data_commitment_root, - &local_data_commitment_leaf, - ) - .map_err(|_| SnarkVMError::default())?; - - Ok(result) -} diff --git a/unused/state/src/local_data_commitment/mod.rs b/unused/state/src/local_data_commitment/mod.rs deleted file mode 100644 index 65b44b4c1c..0000000000 --- a/unused/state/src/local_data_commitment/mod.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub mod state_values; -pub use self::state_values::*; - -pub mod state_leaf_values; -pub use self::state_leaf_values::*; - -pub mod local_data_commitment; -pub use self::local_data_commitment::*; diff --git a/unused/state/src/local_data_commitment/state_leaf_values.rs b/unused/state/src/local_data_commitment/state_leaf_values.rs deleted file mode 100644 index b0f60390cd..0000000000 --- a/unused/state/src/local_data_commitment/state_leaf_values.rs +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{find_input, input_to_bytes, input_to_integer_string}; -use leo_ast::StateLeaf as AstStateLeaf; -use leo_errors::{LeoError, Result, StateError}; - -use std::convert::TryFrom; - -static PATH_PARAMETER_STRING: &str = "path"; -static MEMO_PARAMETER_STRING: &str = "memo"; -static NETWORK_ID_PARAMETER_STRING: &str = "network_id"; -static LEAF_RANDOMNESS_PARAMETER_STRING: &str = "leaf_randomness"; - -/// The serialized values included in the state leaf. -/// A new [`StateLeafValues`] type can be constructed from an [`AstStateLeaf`] type. -pub struct StateLeafValues { - pub path: Vec, - pub memo: Vec, - pub network_id: u8, - pub leaf_randomness: Vec, -} - -impl TryFrom<&AstStateLeaf> for StateLeafValues { - type Error = LeoError; - - fn try_from(ast_state_leaf: &AstStateLeaf) -> Result { - let parameters = ast_state_leaf.values(); - - // Lookup path - let path_value = find_input(PATH_PARAMETER_STRING.to_owned(), ¶meters)?; - let path = input_to_bytes(path_value)?; - - // Lookup memo - let memo_value = find_input(MEMO_PARAMETER_STRING.to_owned(), ¶meters)?; - let memo = input_to_bytes(memo_value)?; - - // Lookup network id - let network_id_value = find_input(NETWORK_ID_PARAMETER_STRING.to_owned(), ¶meters)?; - let network_id = input_to_integer_string(network_id_value)? - .parse::() - .map_err(StateError::parse_int_error)?; - - // Lookup leaf randomness - let leaf_randomness_value = find_input(LEAF_RANDOMNESS_PARAMETER_STRING.to_owned(), ¶meters)?; - let leaf_randomness = input_to_bytes(leaf_randomness_value)?; - - Ok(Self { - path, - memo, - network_id, - leaf_randomness, - }) - } -} diff --git a/unused/state/src/local_data_commitment/state_values.rs b/unused/state/src/local_data_commitment/state_values.rs deleted file mode 100644 index 323d4ccf46..0000000000 --- a/unused/state/src/local_data_commitment/state_values.rs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{find_input, input_to_bytes, input_to_integer_string}; -use leo_ast::State as AstState; -use leo_errors::{LeoError, Result, StateError}; - -use std::convert::TryFrom; - -static LEAF_INDEX_PARAMETER_STRING: &str = "leaf_index"; -static ROOT_PARAMETER_STRING: &str = "root"; - -/// The serialized values included in the state. -/// A new [`StateValues`] type can be constructed from an [`AstState`] type. -pub struct StateValues { - pub leaf_index: u32, - pub root: Vec, -} - -impl TryFrom<&AstState> for StateValues { - type Error = LeoError; - - fn try_from(ast_state: &AstState) -> Result { - let parameters = ast_state.values(); - - // Lookup leaf index - let leaf_index_value = find_input(LEAF_INDEX_PARAMETER_STRING.to_owned(), ¶meters)?; - let leaf_index = input_to_integer_string(leaf_index_value)? - .parse::() - .map_err(StateError::parse_int_error)?; - - // Lookup root - let root_value = find_input(ROOT_PARAMETER_STRING.to_owned(), ¶meters)?; - let root = input_to_bytes(root_value)?; - - Ok(Self { leaf_index, root }) - } -} diff --git a/unused/state/src/record_commitment/dpc_record_values.rs b/unused/state/src/record_commitment/dpc_record_values.rs deleted file mode 100644 index 945b541001..0000000000 --- a/unused/state/src/record_commitment/dpc_record_values.rs +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::utilities::*; -use leo_ast::Record as AstRecord; -use leo_errors::{LeoError, Result, SnarkVMError, StateError}; - -use snarkvm_dpc::{testnet1::instantiated::Components, Address}; - -use std::{convert::TryFrom, str::FromStr}; - -static SERIAL_NUMBER_PARAMETER_STRING: &str = "serial_number"; -static OWNER_PARAMETER_STRING: &str = "owner"; -static IS_DUMMY_PARAMETER_STRING: &str = "is_dummy"; -static VALUE_PARAMETER_STRING: &str = "value"; -static PAYLOAD_PARAMETER_STRING: &str = "payload"; -static BIRTH_PROGRAM_ID_PARAMETER_STRING: &str = "birth_program_id"; -static DEATH_PROGRAM_ID_PARAMETER_STRING: &str = "death_program_id"; -static SERIAL_NUMBER_NONCE_PARAMETER_STRING: &str = "serial_number_nonce"; -static COMMITMENT_PARAMETER_STRING: &str = "commitment"; -static COMMITMENT_RANDOMNESS_PARAMETER_STRING: &str = "commitment_randomness"; - -/// The serialized values included in the dpc record. -/// A new [`DPCRecordValues`] type can be constructed from an [`AstRecord`] type. -pub struct DPCRecordValues { - pub serial_number: Vec, - pub owner: Address, - pub is_dummy: bool, - pub value: u64, - pub payload: Vec, - pub birth_program_id: Vec, - pub death_program_id: Vec, - pub serial_number_nonce: Vec, - pub commitment: Vec, - pub commitment_randomness: Vec, -} - -impl TryFrom<&AstRecord> for DPCRecordValues { - type Error = LeoError; - - fn try_from(ast_record: &AstRecord) -> Result { - let parameters = ast_record.values(); - - // Lookup serial number - let serial_number_value = find_input(SERIAL_NUMBER_PARAMETER_STRING.to_owned(), ¶meters)?; - let serial_number = input_to_bytes(serial_number_value)?; - - // Lookup record owner - let owner_value = find_input(OWNER_PARAMETER_STRING.to_owned(), ¶meters)?; - let owner = Address::::from_str(&owner_value.to_string()).map_err(|_| SnarkVMError::default())?; - - // Lookup record is_dummy - let is_dummy_value = find_input(IS_DUMMY_PARAMETER_STRING.to_owned(), ¶meters)?; - let is_dummy = is_dummy_value - .to_string() - .parse::() - .map_err(StateError::parse_bool_error)?; - - // Lookup record value - let value_value = find_input(VALUE_PARAMETER_STRING.to_owned(), ¶meters)?; - let value = input_to_integer_string(value_value)? - .parse::() - .map_err(StateError::parse_int_error)?; - - // Lookup record payload - let payload_value = find_input(PAYLOAD_PARAMETER_STRING.to_owned(), ¶meters)?; - let payload = input_to_bytes(payload_value)?; - - // Lookup record birth program id - let birth_program_id_value = find_input(BIRTH_PROGRAM_ID_PARAMETER_STRING.to_owned(), ¶meters)?; - let birth_program_id = input_to_bytes(birth_program_id_value)?; - - // Lookup record death program id - let death_program_id_value = find_input(DEATH_PROGRAM_ID_PARAMETER_STRING.to_owned(), ¶meters)?; - let death_program_id = input_to_bytes(death_program_id_value)?; - - // Lookup record serial number nonce - let serial_number_nonce_value = find_input(SERIAL_NUMBER_NONCE_PARAMETER_STRING.to_owned(), ¶meters)?; - let serial_number_nonce = input_to_bytes(serial_number_nonce_value)?; - - // Lookup record commitment - let commitment_value = find_input(COMMITMENT_PARAMETER_STRING.to_owned(), ¶meters)?; - let commitment = input_to_bytes(commitment_value)?; - - // Lookup record commitment randomness - let commitment_randomness_value = find_input(COMMITMENT_RANDOMNESS_PARAMETER_STRING.to_owned(), ¶meters)?; - let commitment_randomness = input_to_bytes(commitment_randomness_value)?; - - Ok(Self { - serial_number, - owner, - is_dummy, - value, - payload, - birth_program_id, - death_program_id, - serial_number_nonce, - commitment, - commitment_randomness, - }) - } -} diff --git a/unused/state/src/record_commitment/mod.rs b/unused/state/src/record_commitment/mod.rs deleted file mode 100644 index e019ee0585..0000000000 --- a/unused/state/src/record_commitment/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub mod dpc_record_values; -pub use self::dpc_record_values::*; - -pub mod record_commitment; -pub use self::record_commitment::*; diff --git a/unused/state/src/record_commitment/record_commitment.rs b/unused/state/src/record_commitment/record_commitment.rs deleted file mode 100644 index fad0ed8241..0000000000 --- a/unused/state/src/record_commitment/record_commitment.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::DPCRecordValues; -use leo_ast::Record as AstRecord; -use leo_errors::{Result, SnarkVMError, StateError}; - -use snarkvm_algorithms::traits::CommitmentScheme; -use snarkvm_dpc::{ - testnet1::{instantiated::Components, parameters::SystemParameters}, - DPCComponents, -}; -use snarkvm_utilities::{bytes::ToBytes, to_bytes_le, FromBytes}; - -use std::convert::TryFrom; - -/// Returns a serialized [`DPCRecordValues`] type if the record commitment is valid given the -/// system parameters. -pub fn verify_record_commitment(dpc: &SystemParameters, ast_record: &AstRecord) -> Result { - // generate a dpc record from the typed record - let record: DPCRecordValues = DPCRecordValues::try_from(ast_record)?; - - // verify record commitment - let record_commitment_input = to_bytes_le![ - record.owner, - record.is_dummy, - record.value, - record.payload, - record.birth_program_id, - record.death_program_id, - record.serial_number_nonce - ] - .map_err(StateError::state_io_error)?; - - let commitment = - <::RecordCommitment as CommitmentScheme>::Output::read_le(&record.commitment[..]) - .map_err(StateError::state_io_error)?; - let commitment_randomness = - <::RecordCommitment as CommitmentScheme>::Randomness::read_le( - &record.commitment_randomness[..], - ) - .map_err(StateError::state_io_error)?; - - let record_commitment = ::RecordCommitment::commit( - &dpc.record_commitment, - &record_commitment_input, - &commitment_randomness, - ) - .map_err(|_| SnarkVMError::default())?; - - if record_commitment == commitment { - Ok(record) - } else { - Err(SnarkVMError::default().into()) - } -} diff --git a/unused/state/src/utilities/input_value.rs b/unused/state/src/utilities/input_value.rs deleted file mode 100644 index 3d7ca2b92a..0000000000 --- a/unused/state/src/utilities/input_value.rs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use leo_ast::{InputValue, Parameter}; -use leo_errors::{Result, StateError}; - -use indexmap::IndexMap; - -/// Returns the input parameter with the given name. -/// If a parameter with the given name does not exist, then an error is returned. -pub fn find_input(name: String, parameters: &IndexMap>) -> Result { - let matched_parameter = parameters - .iter() - .find(|(parameter, _value)| parameter.variable.name.as_ref() == name); - - match matched_parameter { - Some((_, Some(value))) => Ok(value.clone()), - _ => Err(StateError::missing_parameter(name).into()), - } -} - -/// Returns the string of the integer input value. -/// If the input value is not an integer, then an error is returned. -pub fn input_to_integer_string(input: InputValue) -> Result { - match input { - InputValue::Integer(_type, string) => Ok(string), - value => Err(StateError::expected_int(value).into()), - } -} - -/// Returns the given input value as u8 bytes. -/// If the given input value cannot be serialized into bytes then an error is returned. -pub fn input_to_bytes(input: InputValue) -> Result> { - let input_array = match input { - InputValue::Array(values) => values, - value => return Err(StateError::expected_bytes(value).into()), - }; - - let mut result_vec = Vec::with_capacity(input_array.len()); - - for input in input_array { - let integer_string = input_to_integer_string(input)?; - let byte = integer_string.parse::().map_err(StateError::parse_int_error)?; - - result_vec.push(byte); - } - - Ok(result_vec) -} - -/// Returns the given input value as an array of u8 bytes. -/// If the given input value cannot be serialized into an array of bytes then an error is returned. -pub fn input_to_nested_bytes(input: InputValue) -> Result>> { - let inner_arrays = match input { - InputValue::Array(arrays) => arrays, - value => return Err(StateError::expected_bytes(value).into()), - }; - - let mut result_vec = Vec::with_capacity(inner_arrays.len()); - - for input_array in inner_arrays { - let array = input_to_bytes(input_array)?; - - result_vec.push(array); - } - - Ok(result_vec) -} diff --git a/unused/state/src/utilities/mod.rs b/unused/state/src/utilities/mod.rs deleted file mode 100644 index 2bffeb586a..0000000000 --- a/unused/state/src/utilities/mod.rs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub mod input_value; -pub use self::input_value::*; diff --git a/unused/state/tests/inputs/test_record.state b/unused/state/tests/inputs/test_record.state deleted file mode 100644 index dcc712d3de..0000000000 --- a/unused/state/tests/inputs/test_record.state +++ /dev/null @@ -1,23 +0,0 @@ -[[public]] -[state] -leaf_index: u32 = 0; -root: u8[32] = [0u8; 32]; - -[[private]] -[record] -serial_number: u8[32] = [0u8; 32]; -commitment: u8[32] = [24, 156, 6, 189, 180, 191, 65, 243, 196, 227, 127, 239, 207, 46, 119, 151, 6, 98, 159, 197, 6, 239, 1, 149, 94, 119, 37, 190, 168, 146, 198, 6]; -owner: address = aleo1daxej63vwrmn2zhl4dymygagh89k5d2vaw6rjauueme7le6k2q8sjn0ng9; -is_dummy: bool = false; -value: u64 = 13895627391323573723; -payload: u8[32] = [235, 120, 28, 41, 42, 46, 237, 32, 50, 70, 185, 70, 180, 174, 198, 169, 149, 118, 227, 124, 192, 36, 43, 2, 239, 2, 207, 166, 142, 240, 246, 39]; -birth_program_id: u8[48] = [89, 70, 116, 103, 190, 86, 194, 133, 37, 77, 113, 166, 160, 156, 98, 252, 16, 219, 94, 12, 214, 12, 151, 139, 239, 1, 79, 79, 86, 235, 209, 168, 240, 156, 224, 86, 35, 63, 185, 196, 0, 10, 148, 56, 92, 199, 45, 0]; -death_program_id: u8[48] = [89, 70, 116, 103, 190, 86, 194, 133, 37, 77, 113, 166, 160, 156, 98, 252, 16, 219, 94, 12, 214, 12, 151, 139, 239, 1, 79, 79, 86, 235, 209, 168, 240, 156, 224, 86, 35, 63, 185, 196, 0, 10, 148, 56, 92, 199, 45, 0]; -serial_number_nonce: u8[32] = [13, 163, 44, 146, 30, 254, 39, 255, 41, 20, 154, 181, 69, 34, 205, 82, 37, 173, 21, 57, 100, 180, 40, 7, 57, 209, 107, 89, 142, 91, 122, 16]; -commitment_randomness: u8[32] = [55, 189, 0, 182, 148, 137, 120, 223, 121, 7, 140, 240, 100, 202, 196, 41, 236, 128, 38, 189, 60, 59, 23, 210, 25, 102, 65, 117, 38, 140, 136, 1]; - -[state_leaf] -path: u8[128] = [0u8; 128]; -memo: u8[32] = [0u8; 32]; -network_id: u8 = 0; -leaf_randomness: u8[32] = [0u8; 32]; \ No newline at end of file diff --git a/unused/state/tests/inputs/test_state.state b/unused/state/tests/inputs/test_state.state deleted file mode 100644 index 4336865638..0000000000 --- a/unused/state/tests/inputs/test_state.state +++ /dev/null @@ -1,23 +0,0 @@ -[[public]] -[state] -leaf_index: u32 = 0; -root: u8[32] = [70, 27, 231, 101, 102, 20, 37, 118, 77, 38, 56, 106, 49, 17, 135, 81, 134, 61, 255, 147, 230, 94, 218, 157, 98, 31, 132, 10, 116, 201, 78, 15]; - -[[private]] -[record] -serial_number: u8[64] = [98, 228, 41, 139, 42, 245, 63, 73, 45, 255, 134, 169, 18, 86, 90, 209, 31, 207, 161, 83, 183, 126, 53, 86, 142, 64, 59, 29, 185, 204, 179, 8, 43, 199, 156, 127, 124, 7, 91, 56, 27, 101, 57, 52, 166, 145, 153, 137, 17, 1, 140, 42, 205, 91, 32, 99, 22, 119, 141, 253, 235, 213, 112, 14]; -commitment: u8[32] = [233, 180, 207, 91, 31, 4, 177, 7, 21, 177, 170, 63, 134, 227, 249, 217, 193, 113, 220, 188, 97, 228, 70, 43, 160, 112, 228, 151, 110, 58, 85, 7]; -owner: address = aleo1daxej63vwrmn2zhl4dymygagh89k5d2vaw6rjauueme7le6k2q8sjn0ng9; -is_dummy: bool = false; -value: u64 = 18186969098991041491; -payload: u8[32] = [192, 118, 4, 191, 56, 79, 165, 142, 20, 92, 140, 207, 81, 125, 226, 247, 184, 40, 101, 235, 205, 174, 175, 180, 18, 104, 251, 132, 117, 163, 219, 125]; -birth_program_id: u8[48] = [89, 70, 116, 103, 190, 86, 194, 133, 37, 77, 113, 166, 160, 156, 98, 252, 16, 219, 94, 12, 214, 12, 151, 139, 239, 1, 79, 79, 86, 235, 209, 168, 240, 156, 224, 86, 35, 63, 185, 196, 0, 10, 148, 56, 92, 199, 45, 0]; -death_program_id: u8[48] = [89, 70, 116, 103, 190, 86, 194, 133, 37, 77, 113, 166, 160, 156, 98, 252, 16, 219, 94, 12, 214, 12, 151, 139, 239, 1, 79, 79, 86, 235, 209, 168, 240, 156, 224, 86, 35, 63, 185, 196, 0, 10, 148, 56, 92, 199, 45, 0]; -serial_number_nonce: u8[32] = [74, 128, 103, 188, 105, 165, 185, 183, 83, 178, 164, 202, 65, 224, 154, 216, 132, 146, 103, 158, 153, 229, 73, 162, 0, 182, 176, 162, 17, 201, 27, 6]; -commitment_randomness: u8[32] = [129, 174, 175, 20, 1, 168, 248, 69, 51, 186, 30, 34, 82, 6, 148, 174, 128, 163, 156, 197, 94, 129, 117, 226, 240, 95, 203, 196, 65, 222, 96, 4]; - -[state_leaf] -path: u8[128] = [144, 36, 140, 16, 110, 109, 215, 172, 251, 234, 246, 145, 192, 60, 79, 255, 58, 199, 52, 107, 224, 235, 152, 27, 232, 42, 96, 225, 170, 62, 118, 12, 8, 205, 94, 96, 200, 133, 229, 122, 179, 198, 124, 104, 197, 86, 67, 1, 52, 61, 168, 92, 201, 240, 61, 116, 221, 76, 172, 83, 174, 194, 118, 5, 221, 106, 153, 186, 50, 200, 155, 245, 255, 253, 169, 40, 236, 88, 58, 147, 46, 160, 55, 132, 157, 0, 134, 15, 40, 223, 53, 175, 220, 13, 222, 15, 143, 179, 79, 184, 75, 238, 87, 199, 102, 168, 167, 60, 232, 62, 64, 107, 12, 182, 200, 155, 107, 138, 224, 193, 233, 221, 54, 96, 206, 191, 83, 9]; -memo: u8[32] = [0u8; 32]; -network_id: u8 = 0; -leaf_randomness: u8[32] = [102, 202, 135, 202, 235, 133, 143, 160, 137, 212, 216, 158, 17, 44, 104, 126, 157, 109, 93, 213, 174, 57, 194, 113, 75, 184, 26, 204, 143, 131, 95, 1]; \ No newline at end of file diff --git a/unused/state/tests/mod.rs b/unused/state/tests/mod.rs deleted file mode 100644 index 94f0a47fd9..0000000000 --- a/unused/state/tests/mod.rs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -// mod test_verify_local_data_commitment; - -// mod test_verify_record_commitment; diff --git a/unused/state/tests/test_verify_local_data_commitment.rs b/unused/state/tests/test_verify_local_data_commitment.rs deleted file mode 100644 index d722de562a..0000000000 --- a/unused/state/tests/test_verify_local_data_commitment.rs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -// use leo_ast::Input; -// use leo_input::LeoInputParser; -// use leo_state::verify_local_data_commitment; -// -// use snarkos_storage::{mem::MemDb, Ledger}; -// use snarkvm_algorithms::traits::{CommitmentScheme, CRH}; -// use snarkvm_dpc::{ -// base_dpc::{instantiated::*, record_payload::RecordPayload, DPC}, -// traits::DPCScheme, -// Account, -// AccountScheme, -// Record, -// }; -// use snarkvm_utilities::{bytes::ToBytes, to_bytes}; -// -// use rand::Rng; -// use rand_core::SeedableRng; -// use rand_xorshift::XorShiftRng; -// -// // TODO (Collin): Update input to reflect new parameter ordering. -// #[test] -// #[ignore] -// fn test_verify_local_data_commitment_from_file() { -// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); -// -// // Generate parameters for the record commitment scheme -// let system_parameters = InstantiatedDPC::generate_system_parameters(&mut rng).unwrap(); -// -// // Load test record state file from `inputs/test.state` -// let file_bytes = include_bytes!("inputs/test_state.state"); -// let file_string = String::from_utf8_lossy(file_bytes); -// let file = LeoInputParser::parse_file(&file_string).unwrap(); -// -// let mut program_input = Input::new(); -// program_input.parse_state(file).unwrap(); -// -// // check record state is correct by verifying commitment -// let result = verify_local_data_commitment(&system_parameters, &program_input).unwrap(); -// -// assert!(result); -// } -// -// #[test] -// #[ignore] -// fn test_generate_values_from_dpc() { -// type L = Ledger; -// -// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); -// -// // Specify network_id -// let network_id: u8 = 0; -// -// // Generate parameters for the ledger, commitment schemes, CRH, and the -// // "always-accept" program. -// let system_parameters = InstantiatedDPC::generate_system_parameters(&mut rng).unwrap(); -// let noop_program_snark_pp = -// InstantiatedDPC::generate_noop_program_snark_parameters(&system_parameters, &mut rng).unwrap(); -// -// let noop_program_id = to_bytes_le![ -// ProgramVerificationKeyCRH::hash( -// &system_parameters.program_verification_key_crh, -// &to_bytes_le![noop_program_snark_pp.verification_key].unwrap() -// ) -// .unwrap() -// ] -// .unwrap(); -// -// let signature_parameters = &system_parameters.account_signature; -// let commitment_parameters = &system_parameters.account_commitment; -// let encryption_parameters = &system_parameters.account_encryption; -// -// // Generate metadata and an account for a dummy initial record. -// let dummy_account = Account::new( -// signature_parameters, -// commitment_parameters, -// encryption_parameters, -// &mut rng, -// ) -// .unwrap(); -// -// let sn_nonce = SerialNumberNonce::hash(&system_parameters.serial_number_nonce, &[0u8; 1]).unwrap(); -// let value = rng.gen(); -// let payload: [u8; 32] = rng.gen(); -// -// let old_record = DPC::generate_record( -// &system_parameters, -// sn_nonce, -// dummy_account.address, -// false, -// value, -// RecordPayload::from_bytes(&payload), -// noop_program_id.clone(), -// noop_program_id.clone(), -// &mut rng, -// ) -// .unwrap(); -// -// // Set the input records for our transaction to be the initial dummy records. -// let old_records = vec![old_record; NUM_INPUT_RECORDS]; -// let old_account_private_keys = vec![dummy_account.private_key; NUM_INPUT_RECORDS]; -// -// // Construct new records. -// -// // Create an account for an actual new record. -// -// let new_account = Account::new( -// signature_parameters, -// commitment_parameters, -// encryption_parameters, -// &mut rng, -// ) -// .unwrap(); -// -// // Set the new record's program to be the "always-accept" program. -// -// let new_record_owners = vec![new_account.address; NUM_OUTPUT_RECORDS]; -// let new_is_dummy_flags = vec![false; NUM_OUTPUT_RECORDS]; -// let new_values = vec![10; NUM_OUTPUT_RECORDS]; -// let new_payloads = vec![RecordPayload::default(); NUM_OUTPUT_RECORDS]; -// let new_birth_program_ids = vec![noop_program_id.clone(); NUM_OUTPUT_RECORDS]; -// let new_death_program_ids = vec![noop_program_id; NUM_OUTPUT_RECORDS]; -// let memo = [0u8; 32]; -// -// let context = >::execute_offline( -// system_parameters.clone(), -// old_records, -// old_account_private_keys, -// new_record_owners, -// &new_is_dummy_flags, -// &new_values, -// new_payloads, -// new_birth_program_ids, -// new_death_program_ids, -// memo, -// network_id, -// &mut rng, -// ) -// .unwrap(); -// -// let local_data = context.into_local_data(); -// let leaf_index = 0; -// let record = &local_data.old_records[leaf_index]; -// -// let root = local_data.local_data_merkle_tree.root(); -// -// let serial_number = local_data.old_serial_numbers[0]; -// let serial_number_bytes = to_bytes_le![serial_number].unwrap(); -// -// let memorandum = local_data.memorandum; -// let network_id = local_data.network_id; -// let input_bytes = to_bytes_le![serial_number, record.commitment(), memorandum, network_id].unwrap(); -// let leaf_randomness = local_data.local_data_commitment_randomizers[0]; -// -// let old_record_leaf = ::commit( -// &system_parameters.local_data_commitment, -// &input_bytes, -// &leaf_randomness, -// ) -// .unwrap(); -// -// // generate the path -// -// let path = local_data -// .local_data_merkle_tree -// .generate_proof(&old_record_leaf) -// .unwrap(); -// -// println!("////////////////////////////////////////////////////"); -// println!(); -// println!("[state]"); -// println!("leaf index {}", leaf_index); -// println!("root {:?}", to_bytes_le![root].unwrap()); -// println!(); -// println!("[record]"); -// println!( -// "serial number {:?} len {}", -// serial_number_bytes, -// serial_number_bytes.len() -// ); -// println!("commitment {:?}", to_bytes_le![record.commitment()].unwrap()); -// println!("owner {}", record.owner()); -// println!("is_dummy {:?}", record.is_dummy()); -// println!("value {:?}", record.value()); -// println!("payload {:?}", record.payload()); -// println!("birth_program_id {:?}", record.birth_program_id()); -// println!("death_program_id {:?}", record.death_program_id()); -// println!( -// "serial number nonce {:?}", -// to_bytes_le![record.serial_number_nonce()].unwrap() -// ); -// println!( -// "commitment randomness {:?}", -// to_bytes_le![record.commitment_randomness()].unwrap() -// ); -// println!(); -// println!("[state_leaf]"); -// println!("path {:?}", to_bytes_le![path].unwrap()); -// println!("memo {:?}", memorandum); -// println!("network id {:?}", network_id); -// println!("leaf randomness {:?}", to_bytes_le![leaf_randomness].unwrap()); -// println!(); -// println!("////////////////////////////////////////////////////"); -// } diff --git a/unused/state/tests/test_verify_record_commitment.rs b/unused/state/tests/test_verify_record_commitment.rs deleted file mode 100644 index 52d97781e6..0000000000 --- a/unused/state/tests/test_verify_record_commitment.rs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -// use leo_ast::Input; -// use leo_input::LeoInputParser; -// use leo_state::verify_record_commitment; -// -// use snarkvm_dpc::base_dpc::instantiated::*; -// -// use rand_core::SeedableRng; -// use rand_xorshift::XorShiftRng; -// -// // TODO (Collin): Update input to reflect new parameter ordering. -// #[test] -// #[ignore] -// fn test_verify_record_from_file() { -// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); -// -// // Generate parameters for the record commitment scheme -// let system_parameters = InstantiatedDPC::generate_system_parameters(&mut rng).unwrap(); -// -// // Load test record state file from `inputs/test.state` -// let file_bytes = include_bytes!("inputs/test_record.state"); -// let file_string = String::from_utf8_lossy(file_bytes); -// let file = LeoInputParser::parse_file(&file_string).unwrap(); -// -// let mut program_input = Input::new(); -// program_input.parse_state(file).unwrap(); -// -// let typed_record = program_input.get_record(); -// -// // check record state is correct by verifying commitment -// let _values = verify_record_commitment(&system_parameters, typed_record).unwrap(); -// } diff --git a/unused/tests/parser/serialize/silly_sudoku.leo b/unused/tests/parser/serialize/silly_sudoku.leo deleted file mode 100644 index 1b940e2689..0000000000 --- a/unused/tests/parser/serialize/silly_sudoku.leo +++ /dev/null @@ -1,76 +0,0 @@ -/* -namespace: Serialize -expectation: Pass -*/ - -import lib.SillySudoku; - -// The `silly-sudoku` main function -function main(puzzle: [u8; (3, 3)], answer: [u8; (3, 3)]) -> bool { - console.log("Starting Sudoku solver..."); - console.log("{}", puzzle); - - // Instantiate the Sudoku puzzle. - let sudoku = SillySudoku { puzzle_grid: puzzle }; - - console.log("Checking Sudoku answer..."); - console.log("{}", answer); - - // Evaluate the Sudoku puzzle with the given answer. - let result = sudoku.solve(answer); - - console.log("The answer is {}.", result); - - return result; -} - -// Tests that the `silly-sudoku` circuit outputs true on a correct answer. -@test -function test_solve_pass() { - let puzzle: [u8; (3, 3)] = [[0, 2, 0], - [0, 0, 6], - [0, 8, 9]]; - - let answer: [u8; (3, 3)] = [[1, 2, 3], - [4, 5, 6], - [7, 8, 9]]; - - // Runs the Sudoku checker. - let result = main(puzzle, answer); - - // Expects the result to be true. - console.assert(true == result); -} - -// Tests that the `silly-sudoku` circuit outputs false on an incorrect answer. -@test -function test_solve_fail() { - let puzzle: [u8; (3, 3)] = [[0, 2, 0], - [0, 0, 6], - [0, 8, 0]]; - - let answer: [u8; (3, 3)] = [[1, 2, 3], - [4, 5, 6], - [7, 8, 8]]; // We have an extra `8` in this column! - - // Runs the Sudoku checker. - let result = main(puzzle, answer); - - // Expects the result to be false. - console.assert(false == result); -} - -// Test that the `silly-sudoku` circuit outputs the expected value on a custom test input. -@test(test_input) -function test_solve_with_input( - puzzle: [u8; (3, 3)], - answer: [u8; (3, 3)], - expected: bool -) { - // Runs the Sudoku checker. - let result = main(puzzle, answer); - - console.log("expected {}, got {}", expected, result); - - console.assert(expected == result); -} diff --git a/unused/tests/parser/serialize/silly_sudoku.leo.out b/unused/tests/parser/serialize/silly_sudoku.leo.out deleted file mode 100644 index f0c7db8212..0000000000 --- a/unused/tests/parser/serialize/silly_sudoku.leo.out +++ /dev/null @@ -1,528 +0,0 @@ ---- -namespace: Serialize -expectation: Pass -outputs: - - name: "" - expected_input: [] - import_statements: - - package_or_packages: - Package: - name: "{\"name\":\"lib\",\"span\":\"{\\\"line_start\\\":3,\\\"line_stop\\\":3,\\\"col_start\\\":8,\\\"col_stop\\\":11,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"import lib.SillySudoku;\\\"}\"}" - access: - Symbol: - symbol: "{\"name\":\"SillySudoku\",\"span\":\"{\\\"line_start\\\":3,\\\"line_stop\\\":3,\\\"col_start\\\":12,\\\"col_stop\\\":23,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"import lib.SillySudoku;\\\"}\"}" - alias: ~ - imports: {} - aliases: {} - circuits: {} - global_consts: {} - functions: - "{\"name\":\"main\",\"span\":\"{\\\"line_start\\\":6,\\\"line_stop\\\":6,\\\"col_start\\\":10,\\\"col_stop\\\":14,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"function main(puzzle: [u8; (3, 3)], answer: [u8; (3, 3)]) -> bool {\\\"}\"}": - annotations: {} - identifier: "{\"name\":\"main\",\"span\":\"{\\\"line_start\\\":6,\\\"line_stop\\\":6,\\\"col_start\\\":10,\\\"col_stop\\\":14,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"function main(puzzle: [u8; (3, 3)], answer: [u8; (3, 3)]) -> bool {\\\"}\"}" - input: - - Variable: - identifier: "{\"name\":\"puzzle\",\"span\":\"{\\\"line_start\\\":6,\\\"line_stop\\\":6,\\\"col_start\\\":15,\\\"col_stop\\\":21,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"function main(puzzle: [u8; (3, 3)], answer: [u8; (3, 3)]) -> bool {\\\"}\"}" - const_: false - mutable: true - type_: - Array: - - IntegerType: U8 - - - value: "3" - - value: "3" - - Variable: - identifier: "{\"name\":\"answer\",\"span\":\"{\\\"line_start\\\":6,\\\"line_stop\\\":6,\\\"col_start\\\":37,\\\"col_stop\\\":43,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"function main(puzzle: [u8; (3, 3)], answer: [u8; (3, 3)]) -> bool {\\\"}\"}" - const_: false - mutable: true - type_: - Array: - - IntegerType: U8 - - - value: "3" - - value: "3" - const_: false - output: Boolean - core_mapping: ~ - block: - statements: - - Console: - function: - Log: - string: - - Scalar: 83 - - Scalar: 116 - - Scalar: 97 - - Scalar: 114 - - Scalar: 116 - - Scalar: 105 - - Scalar: 110 - - Scalar: 103 - - Scalar: 32 - - Scalar: 83 - - Scalar: 117 - - Scalar: 100 - - Scalar: 111 - - Scalar: 107 - - Scalar: 117 - - Scalar: 32 - - Scalar: 115 - - Scalar: 111 - - Scalar: 108 - - Scalar: 118 - - Scalar: 101 - - Scalar: 114 - - Scalar: 46 - - Scalar: 46 - - Scalar: 46 - parameters: [] - - Console: - function: - Log: - string: - - Scalar: 123 - - Scalar: 125 - parameters: - - Identifier: "{\"name\":\"puzzle\",\"span\":\"{\\\"line_start\\\":8,\\\"line_stop\\\":8,\\\"col_start\\\":23,\\\"col_stop\\\":29,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" console.log(\\\\\\\"{}\\\\\\\", puzzle);\\\"}\"}" - - Definition: - declaration_type: Let - variable_names: - - mutable: true - identifier: "{\"name\":\"sudoku\",\"span\":\"{\\\"line_start\\\":11,\\\"line_stop\\\":11,\\\"col_start\\\":9,\\\"col_stop\\\":15,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let sudoku = SillySudoku { puzzle_grid: puzzle };\\\"}\"}" - type_: ~ - value: - CircuitInit: - name: "{\"name\":\"SillySudoku\",\"span\":\"{\\\"line_start\\\":11,\\\"line_stop\\\":11,\\\"col_start\\\":18,\\\"col_stop\\\":29,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let sudoku = SillySudoku { puzzle_grid: puzzle };\\\"}\"}" - members: - - identifier: "{\"name\":\"puzzle_grid\",\"span\":\"{\\\"line_start\\\":11,\\\"line_stop\\\":11,\\\"col_start\\\":32,\\\"col_stop\\\":43,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let sudoku = SillySudoku { puzzle_grid: puzzle };\\\"}\"}" - expression: - Identifier: "{\"name\":\"puzzle\",\"span\":\"{\\\"line_start\\\":11,\\\"line_stop\\\":11,\\\"col_start\\\":45,\\\"col_stop\\\":51,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let sudoku = SillySudoku { puzzle_grid: puzzle };\\\"}\"}" - - Console: - function: - Log: - string: - - Scalar: 67 - - Scalar: 104 - - Scalar: 101 - - Scalar: 99 - - Scalar: 107 - - Scalar: 105 - - Scalar: 110 - - Scalar: 103 - - Scalar: 32 - - Scalar: 83 - - Scalar: 117 - - Scalar: 100 - - Scalar: 111 - - Scalar: 107 - - Scalar: 117 - - Scalar: 32 - - Scalar: 97 - - Scalar: 110 - - Scalar: 115 - - Scalar: 119 - - Scalar: 101 - - Scalar: 114 - - Scalar: 46 - - Scalar: 46 - - Scalar: 46 - parameters: [] - - Console: - function: - Log: - string: - - Scalar: 123 - - Scalar: 125 - parameters: - - Identifier: "{\"name\":\"answer\",\"span\":\"{\\\"line_start\\\":14,\\\"line_stop\\\":14,\\\"col_start\\\":23,\\\"col_stop\\\":29,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" console.log(\\\\\\\"{}\\\\\\\", answer);\\\"}\"}" - - Definition: - declaration_type: Let - variable_names: - - mutable: true - identifier: "{\"name\":\"result\",\"span\":\"{\\\"line_start\\\":17,\\\"line_stop\\\":17,\\\"col_start\\\":9,\\\"col_stop\\\":15,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let result = sudoku.solve(answer);\\\"}\"}" - type_: ~ - value: - Call: - function: - Access: - Member: - inner: - Identifier: "{\"name\":\"sudoku\",\"span\":\"{\\\"line_start\\\":17,\\\"line_stop\\\":17,\\\"col_start\\\":18,\\\"col_stop\\\":24,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let result = sudoku.solve(answer);\\\"}\"}" - name: "{\"name\":\"solve\",\"span\":\"{\\\"line_start\\\":17,\\\"line_stop\\\":17,\\\"col_start\\\":25,\\\"col_stop\\\":30,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let result = sudoku.solve(answer);\\\"}\"}" - type_: ~ - arguments: - - Identifier: "{\"name\":\"answer\",\"span\":\"{\\\"line_start\\\":17,\\\"line_stop\\\":17,\\\"col_start\\\":31,\\\"col_stop\\\":37,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let result = sudoku.solve(answer);\\\"}\"}" - - Console: - function: - Log: - string: - - Scalar: 84 - - Scalar: 104 - - Scalar: 101 - - Scalar: 32 - - Scalar: 97 - - Scalar: 110 - - Scalar: 115 - - Scalar: 119 - - Scalar: 101 - - Scalar: 114 - - Scalar: 32 - - Scalar: 105 - - Scalar: 115 - - Scalar: 32 - - Scalar: 123 - - Scalar: 125 - - Scalar: 46 - parameters: - - Identifier: "{\"name\":\"result\",\"span\":\"{\\\"line_start\\\":19,\\\"line_stop\\\":19,\\\"col_start\\\":38,\\\"col_stop\\\":44,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" console.log(\\\\\\\"The answer is {}.\\\\\\\", result);\\\"}\"}" - - Return: - expression: - Identifier: "{\"name\":\"result\",\"span\":\"{\\\"line_start\\\":21,\\\"line_stop\\\":21,\\\"col_start\\\":12,\\\"col_stop\\\":18,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" return result;\\\"}\"}" - "{\"name\":\"test_solve_pass\",\"span\":\"{\\\"line_start\\\":26,\\\"line_stop\\\":26,\\\"col_start\\\":10,\\\"col_stop\\\":25,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"function test_solve_pass() {\\\"}\"}": - annotations: - test: - arguments: [] - name: "{\"name\":\"test\",\"span\":\"{\\\"line_start\\\":25,\\\"line_stop\\\":25,\\\"col_start\\\":2,\\\"col_stop\\\":6,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"@test\\\"}\"}" - identifier: "{\"name\":\"test_solve_pass\",\"span\":\"{\\\"line_start\\\":26,\\\"line_stop\\\":26,\\\"col_start\\\":10,\\\"col_stop\\\":25,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"function test_solve_pass() {\\\"}\"}" - input: [] - const_: false - output: ~ - core_mapping: ~ - block: - statements: - - Definition: - declaration_type: Let - variable_names: - - mutable: true - identifier: "{\"name\":\"puzzle\",\"span\":\"{\\\"line_start\\\":27,\\\"line_stop\\\":27,\\\"col_start\\\":9,\\\"col_stop\\\":15,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let puzzle: [u8; (3, 3)] = [[0, 2, 0],\\\"}\"}" - type_: - Array: - - IntegerType: U8 - - - value: "3" - - value: "3" - value: - ArrayInline: - elements: - - Expression: - ArrayInline: - elements: - - Expression: - Value: - Implicit: "0" - - Expression: - Value: - Implicit: "2" - - Expression: - Value: - Implicit: "0" - - Expression: - ArrayInline: - elements: - - Expression: - Value: - Implicit: "0" - - Expression: - Value: - Implicit: "0" - - Expression: - Value: - Implicit: "6" - - Expression: - ArrayInline: - elements: - - Expression: - Value: - Implicit: "0" - - Expression: - Value: - Implicit: "8" - - Expression: - Value: - Implicit: "9" - - Definition: - declaration_type: Let - variable_names: - - mutable: true - identifier: "{\"name\":\"answer\",\"span\":\"{\\\"line_start\\\":31,\\\"line_stop\\\":31,\\\"col_start\\\":9,\\\"col_stop\\\":15,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let answer: [u8; (3, 3)] = [[1, 2, 3],\\\"}\"}" - type_: - Array: - - IntegerType: U8 - - - value: "3" - - value: "3" - value: - ArrayInline: - elements: - - Expression: - ArrayInline: - elements: - - Expression: - Value: - Implicit: "1" - - Expression: - Value: - Implicit: "2" - - Expression: - Value: - Implicit: "3" - - Expression: - ArrayInline: - elements: - - Expression: - Value: - Implicit: "4" - - Expression: - Value: - Implicit: "5" - - Expression: - Value: - Implicit: "6" - - Expression: - ArrayInline: - elements: - - Expression: - Value: - Implicit: "7" - - Expression: - Value: - Implicit: "8" - - Expression: - Value: - Implicit: "9" - - Definition: - declaration_type: Let - variable_names: - - mutable: true - identifier: "{\"name\":\"result\",\"span\":\"{\\\"line_start\\\":36,\\\"line_stop\\\":36,\\\"col_start\\\":9,\\\"col_stop\\\":15,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let result = main(puzzle, answer);\\\"}\"}" - type_: ~ - value: - Call: - function: - Identifier: "{\"name\":\"main\",\"span\":\"{\\\"line_start\\\":36,\\\"line_stop\\\":36,\\\"col_start\\\":18,\\\"col_stop\\\":22,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let result = main(puzzle, answer);\\\"}\"}" - arguments: - - Identifier: "{\"name\":\"puzzle\",\"span\":\"{\\\"line_start\\\":36,\\\"line_stop\\\":36,\\\"col_start\\\":23,\\\"col_stop\\\":29,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let result = main(puzzle, answer);\\\"}\"}" - - Identifier: "{\"name\":\"answer\",\"span\":\"{\\\"line_start\\\":36,\\\"line_stop\\\":36,\\\"col_start\\\":31,\\\"col_stop\\\":37,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let result = main(puzzle, answer);\\\"}\"}" - - Console: - function: - Assert: - Binary: - left: - Value: - Boolean: "true" - right: - Identifier: "{\"name\":\"result\",\"span\":\"{\\\"line_start\\\":39,\\\"line_stop\\\":39,\\\"col_start\\\":28,\\\"col_stop\\\":34,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" console.assert(true == result);\\\"}\"}" - op: Eq - "{\"name\":\"test_solve_fail\",\"span\":\"{\\\"line_start\\\":44,\\\"line_stop\\\":44,\\\"col_start\\\":10,\\\"col_stop\\\":25,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"function test_solve_fail() {\\\"}\"}": - annotations: - test: - arguments: [] - name: "{\"name\":\"test\",\"span\":\"{\\\"line_start\\\":43,\\\"line_stop\\\":43,\\\"col_start\\\":2,\\\"col_stop\\\":6,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"@test\\\"}\"}" - identifier: "{\"name\":\"test_solve_fail\",\"span\":\"{\\\"line_start\\\":44,\\\"line_stop\\\":44,\\\"col_start\\\":10,\\\"col_stop\\\":25,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"function test_solve_fail() {\\\"}\"}" - input: [] - const_: false - output: ~ - core_mapping: ~ - block: - statements: - - Definition: - declaration_type: Let - variable_names: - - mutable: true - identifier: "{\"name\":\"puzzle\",\"span\":\"{\\\"line_start\\\":45,\\\"line_stop\\\":45,\\\"col_start\\\":9,\\\"col_stop\\\":15,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let puzzle: [u8; (3, 3)] = [[0, 2, 0],\\\"}\"}" - type_: - Array: - - IntegerType: U8 - - - value: "3" - - value: "3" - value: - ArrayInline: - elements: - - Expression: - ArrayInline: - elements: - - Expression: - Value: - Implicit: "0" - - Expression: - Value: - Implicit: "2" - - Expression: - Value: - Implicit: "0" - - Expression: - ArrayInline: - elements: - - Expression: - Value: - Implicit: "0" - - Expression: - Value: - Implicit: "0" - - Expression: - Value: - Implicit: "6" - - Expression: - ArrayInline: - elements: - - Expression: - Value: - Implicit: "0" - - Expression: - Value: - Implicit: "8" - - Expression: - Value: - Implicit: "0" - - Definition: - declaration_type: Let - variable_names: - - mutable: true - identifier: "{\"name\":\"answer\",\"span\":\"{\\\"line_start\\\":49,\\\"line_stop\\\":49,\\\"col_start\\\":9,\\\"col_stop\\\":15,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let answer: [u8; (3, 3)] = [[1, 2, 3],\\\"}\"}" - type_: - Array: - - IntegerType: U8 - - - value: "3" - - value: "3" - value: - ArrayInline: - elements: - - Expression: - ArrayInline: - elements: - - Expression: - Value: - Implicit: "1" - - Expression: - Value: - Implicit: "2" - - Expression: - Value: - Implicit: "3" - - Expression: - ArrayInline: - elements: - - Expression: - Value: - Implicit: "4" - - Expression: - Value: - Implicit: "5" - - Expression: - Value: - Implicit: "6" - - Expression: - ArrayInline: - elements: - - Expression: - Value: - Implicit: "7" - - Expression: - Value: - Implicit: "8" - - Expression: - Value: - Implicit: "8" - - Definition: - declaration_type: Let - variable_names: - - mutable: true - identifier: "{\"name\":\"result\",\"span\":\"{\\\"line_start\\\":54,\\\"line_stop\\\":54,\\\"col_start\\\":9,\\\"col_stop\\\":15,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let result = main(puzzle, answer);\\\"}\"}" - type_: ~ - value: - Call: - function: - Identifier: "{\"name\":\"main\",\"span\":\"{\\\"line_start\\\":54,\\\"line_stop\\\":54,\\\"col_start\\\":18,\\\"col_stop\\\":22,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let result = main(puzzle, answer);\\\"}\"}" - arguments: - - Identifier: "{\"name\":\"puzzle\",\"span\":\"{\\\"line_start\\\":54,\\\"line_stop\\\":54,\\\"col_start\\\":23,\\\"col_stop\\\":29,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let result = main(puzzle, answer);\\\"}\"}" - - Identifier: "{\"name\":\"answer\",\"span\":\"{\\\"line_start\\\":54,\\\"line_stop\\\":54,\\\"col_start\\\":31,\\\"col_stop\\\":37,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let result = main(puzzle, answer);\\\"}\"}" - - Console: - function: - Assert: - Binary: - left: - Value: - Boolean: "false" - right: - Identifier: "{\"name\":\"result\",\"span\":\"{\\\"line_start\\\":57,\\\"line_stop\\\":57,\\\"col_start\\\":29,\\\"col_stop\\\":35,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" console.assert(false == result);\\\"}\"}" - op: Eq - "{\"name\":\"test_solve_with_input\",\"span\":\"{\\\"line_start\\\":62,\\\"line_stop\\\":62,\\\"col_start\\\":10,\\\"col_stop\\\":31,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"function test_solve_with_input(\\\"}\"}": - annotations: - test: - arguments: - - test_input - name: "{\"name\":\"test\",\"span\":\"{\\\"line_start\\\":61,\\\"line_stop\\\":61,\\\"col_start\\\":2,\\\"col_stop\\\":6,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"@test(test_input)\\\"}\"}" - identifier: "{\"name\":\"test_solve_with_input\",\"span\":\"{\\\"line_start\\\":62,\\\"line_stop\\\":62,\\\"col_start\\\":10,\\\"col_stop\\\":31,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\"function test_solve_with_input(\\\"}\"}" - input: - - Variable: - identifier: "{\"name\":\"puzzle\",\"span\":\"{\\\"line_start\\\":63,\\\"line_stop\\\":63,\\\"col_start\\\":5,\\\"col_stop\\\":11,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" puzzle: [u8; (3, 3)],\\\"}\"}" - const_: false - mutable: true - type_: - Array: - - IntegerType: U8 - - - value: "3" - - value: "3" - - Variable: - identifier: "{\"name\":\"answer\",\"span\":\"{\\\"line_start\\\":64,\\\"line_stop\\\":64,\\\"col_start\\\":5,\\\"col_stop\\\":11,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" answer: [u8; (3, 3)],\\\"}\"}" - const_: false - mutable: true - type_: - Array: - - IntegerType: U8 - - - value: "3" - - value: "3" - - Variable: - identifier: "{\"name\":\"expected\",\"span\":\"{\\\"line_start\\\":65,\\\"line_stop\\\":65,\\\"col_start\\\":5,\\\"col_stop\\\":13,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" expected: bool\\\"}\"}" - const_: false - mutable: true - type_: Boolean - const_: false - output: ~ - core_mapping: ~ - block: - statements: - - Definition: - declaration_type: Let - variable_names: - - mutable: true - identifier: "{\"name\":\"result\",\"span\":\"{\\\"line_start\\\":68,\\\"line_stop\\\":68,\\\"col_start\\\":9,\\\"col_stop\\\":15,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let result = main(puzzle, answer);\\\"}\"}" - type_: ~ - value: - Call: - function: - Identifier: "{\"name\":\"main\",\"span\":\"{\\\"line_start\\\":68,\\\"line_stop\\\":68,\\\"col_start\\\":18,\\\"col_stop\\\":22,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let result = main(puzzle, answer);\\\"}\"}" - arguments: - - Identifier: "{\"name\":\"puzzle\",\"span\":\"{\\\"line_start\\\":68,\\\"line_stop\\\":68,\\\"col_start\\\":23,\\\"col_stop\\\":29,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let result = main(puzzle, answer);\\\"}\"}" - - Identifier: "{\"name\":\"answer\",\"span\":\"{\\\"line_start\\\":68,\\\"line_stop\\\":68,\\\"col_start\\\":31,\\\"col_stop\\\":37,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" let result = main(puzzle, answer);\\\"}\"}" - - Console: - function: - Log: - string: - - Scalar: 101 - - Scalar: 120 - - Scalar: 112 - - Scalar: 101 - - Scalar: 99 - - Scalar: 116 - - Scalar: 101 - - Scalar: 100 - - Scalar: 32 - - Scalar: 123 - - Scalar: 125 - - Scalar: 44 - - Scalar: 32 - - Scalar: 103 - - Scalar: 111 - - Scalar: 116 - - Scalar: 32 - - Scalar: 123 - - Scalar: 125 - parameters: - - Identifier: "{\"name\":\"expected\",\"span\":\"{\\\"line_start\\\":70,\\\"line_stop\\\":70,\\\"col_start\\\":40,\\\"col_stop\\\":48,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" console.log(\\\\\\\"expected {}, got {}\\\\\\\", expected, result);\\\"}\"}" - - Identifier: "{\"name\":\"result\",\"span\":\"{\\\"line_start\\\":70,\\\"line_stop\\\":70,\\\"col_start\\\":50,\\\"col_stop\\\":56,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" console.log(\\\\\\\"expected {}, got {}\\\\\\\", expected, result);\\\"}\"}" - - Console: - function: - Assert: - Binary: - left: - Identifier: "{\"name\":\"expected\",\"span\":\"{\\\"line_start\\\":72,\\\"line_stop\\\":72,\\\"col_start\\\":20,\\\"col_stop\\\":28,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" console.assert(expected == result);\\\"}\"}" - right: - Identifier: "{\"name\":\"result\",\"span\":\"{\\\"line_start\\\":72,\\\"line_stop\\\":72,\\\"col_start\\\":32,\\\"col_stop\\\":38,\\\"path\\\":\\\"\\\",\\\"content\\\":\\\" console.assert(expected == result);\\\"}\"}" - op: Eq