diff --git a/asg/src/checks/mod.rs b/asg/src/checks/mod.rs
index 0c345aefd2..98f973c3e5 100644
--- a/asg/src/checks/mod.rs
+++ b/asg/src/checks/mod.rs
@@ -1,3 +1,18 @@
+// Copyright (C) 2019-2020 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 return_path;
pub use return_path::*;
diff --git a/asg/src/checks/return_path.rs b/asg/src/checks/return_path.rs
index 23ef3be975..15dcacc3bf 100644
--- a/asg/src/checks/return_path.rs
+++ b/asg/src/checks/return_path.rs
@@ -1,4 +1,29 @@
-use crate::{ BoolAnd, MonoidalReducerExpression, MonoidalReducerStatement, Monoid, Expression, statement::*, Span, Node };
+// Copyright (C) 2019-2020 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,
+ Span,
+};
use std::sync::Arc;
pub struct ReturnPathReducer {
@@ -11,9 +36,7 @@ impl ReturnPathReducer {
}
pub fn new() -> ReturnPathReducer {
- ReturnPathReducer {
- errors: vec![],
- }
+ ReturnPathReducer { errors: vec![] }
}
}
@@ -38,16 +61,28 @@ impl MonoidalReducerStatement for ReturnPathReducer {
if statements.len() == 0 {
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].span(), "dead code due to unconditional early return".to_string());
+ self.record_error(
+ input.statements[index].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 {
+ 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());
+ self.record_error(
+ input.span(),
+ "cannot have asymmetrical return in if statement".to_string(),
+ );
}
if_true.append(if_false.unwrap_or_else(|| BoolAnd(false)))
}
@@ -68,7 +103,13 @@ impl MonoidalReducerStatement for ReturnPathReducer {
BoolAnd(false)
}
- fn reduce_iteration(&mut self, input: &IterationStatement, start: BoolAnd, stop: BoolAnd, body: BoolAnd) -> BoolAnd {
+ 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)
}
@@ -76,4 +117,4 @@ impl MonoidalReducerStatement for ReturnPathReducer {
fn reduce_return(&mut self, input: &ReturnStatement, value: BoolAnd) -> BoolAnd {
BoolAnd(true)
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/const_value.rs b/asg/src/const_value.rs
index 53178ab8c8..010f3930a4 100644
--- a/asg/src/const_value.rs
+++ b/asg/src/const_value.rs
@@ -1,7 +1,22 @@
-use crate::{ Type, IntegerType, AsgConvertError, Span };
-use std::convert::TryInto;
+// Copyright (C) 2019-2020 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::{AsgConvertError, IntegerType, Span, Type};
use num_bigint::BigInt;
-use std::fmt;
+use std::{convert::TryInto, fmt};
#[derive(Clone, Debug, PartialEq)]
pub enum ConstInt {
@@ -137,7 +152,6 @@ macro_rules! const_int_map {
};
}
-
macro_rules! const_int_bimap {
($name: ident, $x: ident, $y: ident, $transform: expr) => {
pub fn $name(&self, other: &ConstInt) -> Option {
@@ -159,6 +173,29 @@ macro_rules! const_int_bimap {
}
impl ConstInt {
+ const_int_op!(raw_value, String, x, format!("{}", x));
+
+ const_int_map!(value_negate, x, x.checked_neg()?);
+
+ 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)?);
+
+ const_int_bimap!(value_pow, x, y, x.checked_pow((*y).try_into().ok()?)?);
+
+ // TODO: limited to 32 bit exponents
+ 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,
@@ -178,18 +215,6 @@ impl ConstInt {
Type::Integer(self.get_int_type())
}
- const_int_op!(raw_value, String, x, format!("{}", x));
- const_int_map!(value_negate, x, x.checked_neg()?);
- 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)?);
- const_int_bimap!(value_pow, x, y, x.checked_pow((*y).try_into().ok()?)?); // TODO: limited to 32 bit exponents
- 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 parse(int_type: &IntegerType, value: &str, span: &Span) -> Result {
Ok(match int_type {
IntegerType::I8 => ConstInt::I8(value.parse().map_err(|_| AsgConvertError::invalid_int(&value, span))?),
@@ -214,7 +239,9 @@ impl ConstValue {
ConstValue::Field(_) => Type::Field,
ConstValue::Address(_) => Type::Address,
ConstValue::Boolean(_) => Type::Boolean,
- ConstValue::Tuple(sub_consts) => Type::Tuple(sub_consts.iter().map(|x| x.get_type()).collect::>>()?),
+ 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()),
})
}
diff --git a/asg/src/error/mod.rs b/asg/src/error/mod.rs
index 7870f0a1d5..df36ad13a3 100644
--- a/asg/src/error/mod.rs
+++ b/asg/src/error/mod.rs
@@ -1,3 +1,19 @@
+// Copyright (C) 2019-2020 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::Span;
use leo_ast::Error as FormattedError;
use leo_grammar::ParserError;
@@ -28,39 +44,84 @@ impl AsgConvertError {
}
pub fn unresolved_circuit_member(circuit_name: &str, name: &str, span: &Span) -> Self {
- Self::new_from_span(format!("illegal reference to non-existant member '{}' of circuit '{}'", name, circuit_name), span)
+ Self::new_from_span(
+ format!(
+ "illegal reference to non-existant member '{}' of circuit '{}'",
+ name, circuit_name
+ ),
+ span,
+ )
}
pub fn missing_circuit_member(circuit_name: &str, name: &str, span: &Span) -> Self {
- Self::new_from_span(format!("missing circuit member '{}' for initialization of circuit '{}'", name, circuit_name), span)
+ Self::new_from_span(
+ format!(
+ "missing circuit member '{}' for initialization of circuit '{}'",
+ name, circuit_name
+ ),
+ span,
+ )
}
pub fn extra_circuit_member(circuit_name: &str, name: &str, span: &Span) -> Self {
- Self::new_from_span(format!("extra circuit member '{}' for initialization of circuit '{}' is not allowed", name, circuit_name), span)
+ Self::new_from_span(
+ format!(
+ "extra circuit member '{}' for initialization of circuit '{}' is not allowed",
+ name, circuit_name
+ ),
+ span,
+ )
}
- pub fn illegal_function_assign( name: &str, span: &Span) -> Self {
+ pub fn illegal_function_assign(name: &str, span: &Span) -> Self {
Self::new_from_span(format!("attempt to assign to function '{}'", name), span)
}
pub fn circuit_variable_call(circuit_name: &str, name: &str, span: &Span) -> Self {
- Self::new_from_span(format!("cannot call variable member '{}' of circuit '{}'", name, circuit_name), span)
+ Self::new_from_span(
+ format!("cannot call variable member '{}' of circuit '{}'", name, circuit_name),
+ span,
+ )
}
pub fn circuit_static_call_invalid(circuit_name: &str, name: &str, span: &Span) -> Self {
- Self::new_from_span(format!("cannot call static function '{}' of circuit '{}' from target", name, circuit_name), span)
+ Self::new_from_span(
+ format!(
+ "cannot call static function '{}' of circuit '{}' from target",
+ name, circuit_name
+ ),
+ span,
+ )
}
pub fn circuit_member_mut_call_invalid(circuit_name: &str, name: &str, span: &Span) -> Self {
- Self::new_from_span(format!("cannot call mutable member function '{}' of circuit '{}' from immutable context", name, circuit_name), span)
+ Self::new_from_span(
+ format!(
+ "cannot call mutable member function '{}' of circuit '{}' from immutable context",
+ name, circuit_name
+ ),
+ span,
+ )
}
pub fn circuit_member_call_invalid(circuit_name: &str, name: &str, span: &Span) -> Self {
- Self::new_from_span(format!("cannot call member function '{}' of circuit '{}' from static context", name, circuit_name), span)
+ Self::new_from_span(
+ format!(
+ "cannot call member function '{}' of circuit '{}' from static context",
+ name, circuit_name
+ ),
+ span,
+ )
}
pub fn circuit_function_ref(circuit_name: &str, name: &str, span: &Span) -> Self {
- Self::new_from_span(format!("cannot reference function member '{}' of circuit '{}' as value", name, circuit_name), span)
+ Self::new_from_span(
+ format!(
+ "cannot reference function member '{}' of circuit '{}' as value",
+ name, circuit_name
+ ),
+ span,
+ )
}
pub fn index_into_non_array(name: &str, span: &Span) -> Self {
@@ -76,7 +137,10 @@ impl AsgConvertError {
}
pub fn unexpected_call_argument_count(expected: usize, got: usize, span: &Span) -> Self {
- Self::new_from_span(format!("function call expected {} arguments, got {}", expected, got), span)
+ Self::new_from_span(
+ format!("function call expected {} arguments, got {}", expected, got),
+ span,
+ )
}
pub fn unresolved_function(name: &str, span: &Span) -> Self {
@@ -84,12 +148,22 @@ impl AsgConvertError {
}
pub fn unresolved_type(name: &str, span: &Span) -> Self {
- Self::new_from_span(format!("failed to resolve type for variable definition '{}'", name), span)
+ Self::new_from_span(
+ format!("failed to resolve type for variable definition '{}'", name),
+ span,
+ )
}
pub fn unexpected_type(expected: &str, received: Option<&str>, span: &Span) -> Self {
// panic!(format!("unexpected type, expected: '{}', received: '{}'", expected, received.unwrap_or("unknown")));
- Self::new_from_span(format!("unexpected type, expected: '{}', received: '{}'", expected, received.unwrap_or("unknown")), span)
+ Self::new_from_span(
+ format!(
+ "unexpected type, expected: '{}', received: '{}'",
+ expected,
+ received.unwrap_or("unknown")
+ ),
+ span,
+ )
}
pub fn unresolved_reference(name: &str, span: &Span) -> Self {
@@ -113,15 +187,24 @@ impl AsgConvertError {
}
pub fn function_return_validation(name: &str, description: &str, span: &Span) -> Self {
- Self::new_from_span(format!("function '{}' failed to validate return path: '{}'", name, description), span)
+ Self::new_from_span(
+ format!("function '{}' failed to validate return path: '{}'", name, description),
+ span,
+ )
}
pub fn input_ref_needs_type(category: &str, name: &str, span: &Span) -> Self {
- Self::new_from_span(format!("could not infer type for input in '{}': '{}'", category, name), span)
+ Self::new_from_span(
+ format!("could not infer type for input in '{}': '{}'", category, name),
+ span,
+ )
}
pub fn invalid_self_in_global(span: &Span) -> Self {
- Self::new_from_span("cannot have `mut self` or `self` arguments in global functions".to_string(), span)
+ Self::new_from_span(
+ "cannot have `mut self` or `self` arguments in global functions".to_string(),
+ span,
+ )
}
pub fn parse_index_error() -> Self {
diff --git a/asg/src/expression/array_access.rs b/asg/src/expression/array_access.rs
index 7fe55213ea..71f7dccef3 100644
--- a/asg/src/expression/array_access.rs
+++ b/asg/src/expression/array_access.rs
@@ -1,7 +1,36 @@
-use crate::Span;
-use crate::{ Expression, Node, Type, ExpressionNode, AsgConvertError, FromAst, Scope, ConstValue, ConstInt, PartialType };
-use std::sync::{ Weak, Arc };
-use std::cell::RefCell;
+// Copyright (C) 2019-2020 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::{
+ AsgConvertError,
+ ConstInt,
+ ConstValue,
+ Expression,
+ ExpressionNode,
+ FromAst,
+ Node,
+ PartialType,
+ Scope,
+ Span,
+ Type,
+};
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
pub struct ArrayAccessExpression {
pub parent: RefCell >>,
@@ -58,18 +87,36 @@ impl ExpressionNode for ArrayAccessExpression {
}
impl FromAst for ArrayAccessExpression {
- fn from_ast(scope: &Scope, value: &leo_ast::ArrayAccessExpression, expected_type: Option) -> Result {
- let array = Arc::::from_ast(scope, &*value.array, Some(PartialType::Array(expected_type.clone().map(Box::new), None)))?;
+ fn from_ast(
+ scope: &Scope,
+ value: &leo_ast::ArrayAccessExpression,
+ expected_type: Option,
+ ) -> Result {
+ let array = Arc::::from_ast(
+ scope,
+ &*value.array,
+ Some(PartialType::Array(expected_type.clone().map(Box::new), None)),
+ )?;
match array.get_type() {
Some(Type::Array(..)) => (),
- type_ => return Err(AsgConvertError::unexpected_type("array", type_.map(|x| x.to_string()).as_deref(), &value.span)),
+ type_ => {
+ return Err(AsgConvertError::unexpected_type(
+ "array",
+ type_.map(|x| x.to_string()).as_deref(),
+ &value.span,
+ ));
+ }
}
Ok(ArrayAccessExpression {
parent: RefCell::new(None),
span: Some(value.span.clone()),
array,
- index: Arc::::from_ast(scope, &*value.index, Some(Type::Integer(leo_ast::IntegerType::U32).partial()))?,
+ index: Arc::::from_ast(
+ scope,
+ &*value.index,
+ Some(Type::Integer(leo_ast::IntegerType::U32).partial()),
+ )?,
})
}
}
@@ -82,4 +129,4 @@ impl Into for &ArrayAccessExpression {
span: self.span.clone().unwrap_or_default(),
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/expression/array_init.rs b/asg/src/expression/array_init.rs
index ccfbbc5426..ae7f12d483 100644
--- a/asg/src/expression/array_init.rs
+++ b/asg/src/expression/array_init.rs
@@ -1,7 +1,24 @@
-use crate::Span;
-use crate::{ Expression, Node, Type, ExpressionNode, FromAst, Scope, AsgConvertError, ConstValue, PartialType };
-use std::sync::{ Weak, Arc };
-use std::cell::RefCell;
+// Copyright (C) 2019-2020 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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
pub struct ArrayInitExpression {
pub parent: RefCell>>,
@@ -44,35 +61,69 @@ impl ExpressionNode for ArrayInitExpression {
}
impl FromAst for ArrayInitExpression {
- fn from_ast(scope: &Scope, value: &leo_ast::ArrayInitExpression, expected_type: Option) -> Result {
+ fn from_ast(
+ scope: &Scope,
+ 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(AsgConvertError::unexpected_type(&type_.to_string(), Some("array"), &value.span)),
+ Some(type_) => {
+ return Err(AsgConvertError::unexpected_type(
+ &type_.to_string(),
+ Some("array"),
+ &value.span,
+ ));
+ }
};
- let dimensions = value.dimensions.0.iter().map(|x| x.value.parse::().map_err(|_| AsgConvertError::parse_dimension_error())).collect::, AsgConvertError>>()?;
+ let dimensions = value
+ .dimensions
+ .0
+ .iter()
+ .map(|x| {
+ x.value
+ .parse::()
+ .map_err(|_| AsgConvertError::parse_dimension_error())
+ })
+ .collect::, AsgConvertError>>()?;
- let len = *dimensions.get(0).ok_or_else(|| AsgConvertError::parse_dimension_error())?;
+ let len = *dimensions
+ .get(0)
+ .ok_or_else(|| AsgConvertError::parse_dimension_error())?;
if let Some(expected_len) = expected_len {
if expected_len != len {
- return Err(AsgConvertError::unexpected_type(&*format!("array of length {}", expected_len), Some(&*format!("array of length {}", len)), &value.span));
+ return Err(AsgConvertError::unexpected_type(
+ &*format!("array of length {}", expected_len),
+ Some(&*format!("array of length {}", len)),
+ &value.span,
+ ));
}
}
-
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(AsgConvertError::unexpected_type(&*format!("array of length {}", dimension), Some(&*format!("array of length {}", len)), &value.span));
- }
+ return Err(AsgConvertError::unexpected_type(
+ &*format!("array of length {}", dimension),
+ Some(&*format!("array of length {}", len)),
+ &value.span,
+ ));
+ }
}
-
+
item.map(|x| *x)
- },
+ }
None => None,
- Some(type_) => return Err(AsgConvertError::unexpected_type("array", Some(&type_.to_string()), &value.span)),
+ Some(type_) => {
+ return Err(AsgConvertError::unexpected_type(
+ "array",
+ Some(&type_.to_string()),
+ &value.span,
+ ));
+ }
}
}
let mut element = Some(Arc::::from_ast(scope, &*value.element, expected_item)?);
@@ -82,7 +133,10 @@ impl FromAst for ArrayInitExpression {
output = Some(ArrayInitExpression {
parent: RefCell::new(None),
span: Some(value.span.clone()),
- element: output.map(Expression::ArrayInit).map(Arc::new).unwrap_or_else(|| element.take().unwrap()),
+ element: output
+ .map(Expression::ArrayInit)
+ .map(Arc::new)
+ .unwrap_or_else(|| element.take().unwrap()),
len: dimension,
});
}
@@ -94,8 +148,10 @@ impl Into for &ArrayInitExpression {
fn into(self) -> leo_ast::ArrayInitExpression {
leo_ast::ArrayInitExpression {
element: Box::new(self.element.as_ref().into()),
- dimensions: leo_ast::ArrayDimensions(vec![leo_ast::PositiveNumber { value: self.len.to_string() }]),
+ dimensions: leo_ast::ArrayDimensions(vec![leo_ast::PositiveNumber {
+ value: self.len.to_string(),
+ }]),
span: self.span.clone().unwrap_or_default(),
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/expression/array_inline.rs b/asg/src/expression/array_inline.rs
index b2a8102143..abbdeb72a5 100644
--- a/asg/src/expression/array_inline.rs
+++ b/asg/src/expression/array_inline.rs
@@ -1,8 +1,25 @@
-use crate::Span;
-use crate::{ Expression, Node, Type, ExpressionNode, FromAst, Scope, AsgConvertError, ConstValue, PartialType };
-use std::sync::{ Weak, Arc };
+// Copyright (C) 2019-2020 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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
use leo_ast::SpreadOrExpression;
-use std::cell::RefCell;
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
pub struct ArrayInlineExpression {
pub parent: RefCell>>,
@@ -12,14 +29,19 @@ pub struct ArrayInlineExpression {
impl ArrayInlineExpression {
pub fn len(&self) -> usize {
- self.elements.iter().map(|(expr, is_spread)| if *is_spread {
- match expr.get_type() {
- Some(Type::Array(_item, len)) => len,
- _ => 0,
- }
- } else {
- 1
- }).sum()
+ self.elements
+ .iter()
+ .map(|(expr, is_spread)| {
+ if *is_spread {
+ match expr.get_type() {
+ Some(Type::Array(_item, len)) => len,
+ _ => 0,
+ }
+ } else {
+ 1
+ }
+ })
+ .sum()
}
}
@@ -37,7 +59,7 @@ impl ExpressionNode for ArrayInlineExpression {
fn get_parent(&self) -> Option> {
self.parent.borrow().as_ref().map(Weak::upgrade).flatten()
}
-
+
fn enforce_parents(&self, expr: &Arc) {
self.elements.iter().for_each(|(element, _)| {
element.set_parent(Arc::downgrade(expr));
@@ -69,11 +91,21 @@ impl ExpressionNode for ArrayInlineExpression {
}
impl FromAst for ArrayInlineExpression {
- fn from_ast(scope: &Scope, value: &leo_ast::ArrayInlineExpression, expected_type: Option) -> Result {
+ fn from_ast(
+ scope: &Scope,
+ 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),
None => (None, None),
- Some(type_) => return Err(AsgConvertError::unexpected_type(&type_.to_string(), Some("array"), &value.span)),
+ Some(type_) => {
+ return Err(AsgConvertError::unexpected_type(
+ &type_.to_string(),
+ Some("array"),
+ &value.span,
+ ));
+ }
};
// todo: make sure to add some tests with spreading into multidimensional arrays
@@ -82,35 +114,57 @@ impl FromAst for ArrayInlineExpression {
let output = ArrayInlineExpression {
parent: RefCell::new(None),
span: Some(value.span.clone()),
- elements: value.elements.iter().map(|e| match e {
- SpreadOrExpression::Expression(e) => {
- let expr = Arc::::from_ast(scope, e, expected_item.clone())?;
- if expected_item.is_none() {
- expected_item = expr.get_type().map(Type::partial);
+ elements: value
+ .elements
+ .iter()
+ .map(|e| match e {
+ SpreadOrExpression::Expression(e) => {
+ let expr = Arc::::from_ast(scope, e, expected_item.clone())?;
+ if expected_item.is_none() {
+ expected_item = expr.get_type().map(Type::partial);
+ }
+ len += 1;
+ Ok((expr, false))
}
- len += 1;
- Ok((expr, false))
- },
- SpreadOrExpression::Spread(e) => {
- let expr = Arc::::from_ast(scope, e, Some(PartialType::Array(expected_item.clone().map(Box::new), None)))?;
+ SpreadOrExpression::Spread(e) => {
+ let expr = Arc::::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());
+ 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(AsgConvertError::unexpected_type(
+ expected_item
+ .as_ref()
+ .map(|x| x.to_string())
+ .as_deref()
+ .unwrap_or("unknown"),
+ type_.map(|x| x.to_string()).as_deref(),
+ &value.span,
+ ));
}
-
- len += spread_len;
- },
- type_ => return Err(AsgConvertError::unexpected_type(expected_item.as_ref().map(|x| x.to_string()).as_deref().unwrap_or("unknown"), type_.map(|x| x.to_string()).as_deref(), &value.span)),
+ }
+ Ok((expr, true))
}
- Ok((expr, true))
- },
- }).collect::, AsgConvertError>>()?,
+ })
+ .collect::, AsgConvertError>>()?,
};
if let Some(expected_len) = expected_len {
if len != expected_len {
- return Err(AsgConvertError::unexpected_type(&*format!("array of length {}", expected_len), Some(&*format!("array of length {}", len)), &value.span));
+ return Err(AsgConvertError::unexpected_type(
+ &*format!("array of length {}", expected_len),
+ Some(&*format!("array of length {}", len)),
+ &value.span,
+ ));
}
}
Ok(output)
@@ -120,15 +174,19 @@ impl FromAst for ArrayInlineExpression {
impl Into for &ArrayInlineExpression {
fn into(self) -> leo_ast::ArrayInlineExpression {
leo_ast::ArrayInlineExpression {
- elements: self.elements.iter().map(|(element, spread)| {
- let element = element.as_ref().into();
- if *spread {
- SpreadOrExpression::Spread(element)
- } else {
- SpreadOrExpression::Expression(element)
- }
- }).collect(),
+ elements: self
+ .elements
+ .iter()
+ .map(|(element, spread)| {
+ let element = element.as_ref().into();
+ if *spread {
+ SpreadOrExpression::Spread(element)
+ } else {
+ SpreadOrExpression::Expression(element)
+ }
+ })
+ .collect(),
span: self.span.clone().unwrap_or_default(),
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/expression/array_range_access.rs b/asg/src/expression/array_range_access.rs
index 9ae5ffe599..80716ecf8f 100644
--- a/asg/src/expression/array_range_access.rs
+++ b/asg/src/expression/array_range_access.rs
@@ -1,8 +1,37 @@
-use crate::Span;
-use crate::{ Expression, Node, Type, ExpressionNode, FromAst, Scope, AsgConvertError, ConstValue, ConstInt, PartialType };
-use std::sync::{ Weak, Arc };
-use std::cell::RefCell;
+// Copyright (C) 2019-2020 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::{
+ AsgConvertError,
+ ConstInt,
+ ConstValue,
+ Expression,
+ ExpressionNode,
+ FromAst,
+ Node,
+ PartialType,
+ Scope,
+ Span,
+ Type,
+};
use leo_ast::IntegerType;
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
pub struct ArrayRangeAccessExpression {
pub parent: RefCell>>,
@@ -83,32 +112,55 @@ impl ExpressionNode for ArrayRangeAccessExpression {
return None;
}
- Some(ConstValue::Array(array.drain(const_left as usize..const_right as usize).collect()))
+ Some(ConstValue::Array(
+ array.drain(const_left as usize..const_right as usize).collect(),
+ ))
}
}
impl FromAst for ArrayRangeAccessExpression {
- fn from_ast(scope: &Scope, value: &leo_ast::ArrayRangeAccessExpression, expected_type: Option) -> Result {
+ fn from_ast(
+ scope: &Scope,
+ value: &leo_ast::ArrayRangeAccessExpression,
+ expected_type: Option,
+ ) -> Result {
let expected_array = match expected_type {
- Some(PartialType::Array(element, _len)) => {
- Some(PartialType::Array(element, None))
- },
+ Some(PartialType::Array(element, _len)) => Some(PartialType::Array(element, None)),
None => None,
- Some(x) => return Err(AsgConvertError::unexpected_type(&x.to_string(), Some("array"), &value.span)),
+ Some(x) => {
+ return Err(AsgConvertError::unexpected_type(
+ &x.to_string(),
+ Some("array"),
+ &value.span,
+ ));
+ }
};
let array = Arc::::from_ast(scope, &*value.array, expected_array)?;
let array_type = array.get_type();
match array_type {
Some(Type::Array(_, _)) => (),
- type_ =>
- return Err(AsgConvertError::unexpected_type("array", type_.map(|x| x.to_string()).as_deref(), &value.span)),
+ type_ => {
+ return Err(AsgConvertError::unexpected_type(
+ "array",
+ type_.map(|x| x.to_string()).as_deref(),
+ &value.span,
+ ));
+ }
}
Ok(ArrayRangeAccessExpression {
parent: RefCell::new(None),
span: Some(value.span.clone()),
array,
- left: value.left.as_deref().map(|left| Arc::::from_ast(scope, left, Some(Type::Integer(IntegerType::U32).partial()))).transpose()?,
- right: value.right.as_deref().map(|right| Arc::::from_ast(scope, right, Some(Type::Integer(IntegerType::U32).partial()))).transpose()?,
+ left: value
+ .left
+ .as_deref()
+ .map(|left| Arc::::from_ast(scope, left, Some(Type::Integer(IntegerType::U32).partial())))
+ .transpose()?,
+ right: value
+ .right
+ .as_deref()
+ .map(|right| Arc::::from_ast(scope, right, Some(Type::Integer(IntegerType::U32).partial())))
+ .transpose()?,
})
}
}
@@ -122,4 +174,4 @@ impl Into for &ArrayRangeAccessExpression {
span: self.span.clone().unwrap_or_default(),
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/expression/binary.rs b/asg/src/expression/binary.rs
index 1832580845..cae726c8c5 100644
--- a/asg/src/expression/binary.rs
+++ b/asg/src/expression/binary.rs
@@ -1,8 +1,25 @@
-pub use leo_ast::{ BinaryOperation, BinaryOperationClass };
-use crate::Span;
-use crate::{ Expression, Node, Type, ExpressionNode, FromAst, Scope, AsgConvertError, ConstValue, PartialType };
-use std::sync::{ Weak, Arc };
-use std::cell::RefCell;
+// Copyright (C) 2019-2020 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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
+pub use leo_ast::{BinaryOperation, BinaryOperationClass};
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
pub struct BinaryExpression {
pub parent: RefCell>>,
@@ -49,22 +66,20 @@ impl ExpressionNode for BinaryExpression {
let right = self.right.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::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)?),
@@ -76,45 +91,54 @@ impl ExpressionNode for BinaryExpression {
// _ => 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,
- })
- },
+ (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,
- })
- },
+ (left, right) => Some(match self.operation {
+ Eq => ConstValue::Boolean(left == right),
+ Ne => ConstValue::Boolean(left != right),
+ _ => return None,
+ }),
}
}
}
impl FromAst for BinaryExpression {
- fn from_ast(scope: &Scope, value: &leo_ast::BinaryExpression, expected_type: Option) -> Result {
+ fn from_ast(
+ scope: &Scope,
+ 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(AsgConvertError::unexpected_type(&x.to_string(), Some(&*Type::Boolean.to_string()), &value.span)),
+ BinaryOperationClass::Boolean => match expected_type {
+ Some(PartialType::Type(Type::Boolean)) | None => None,
+ Some(x) => {
+ return Err(AsgConvertError::unexpected_type(
+ &x.to_string(),
+ Some(&*Type::Boolean.to_string()),
+ &value.span,
+ ));
}
},
- BinaryOperationClass::Numeric => {
- match expected_type {
- Some(PartialType::Type(x @ Type::Integer(_))) => Some(x),
- Some(x) => return Err(AsgConvertError::unexpected_type(&x.to_string(), Some("integer"), &value.span)),
- None => None,
+ BinaryOperationClass::Numeric => match expected_type {
+ Some(PartialType::Type(x @ Type::Integer(_))) => Some(x),
+ Some(x) => {
+ return Err(AsgConvertError::unexpected_type(
+ &x.to_string(),
+ Some("integer"),
+ &value.span,
+ ));
}
+ None => None,
},
- }.map(Type::partial);
+ }
+ .map(Type::partial);
// left
let (left, right) = match Arc::::from_ast(scope, &*value.left, expected_type.clone()) {
@@ -125,16 +149,22 @@ impl FromAst for BinaryExpression {
} else {
let right = Arc::::from_ast(scope, &*value.right, expected_type.clone())?;
if let Some(right_type) = right.get_type() {
- (Arc::::from_ast(scope, &*value.left, Some(right_type.partial()))?, right)
+ (
+ Arc::::from_ast(scope, &*value.left, Some(right_type.partial()))?,
+ right,
+ )
} else {
(left, right)
}
}
- },
+ }
Err(e) => {
let right = Arc::::from_ast(scope, &*value.right, expected_type.clone())?;
if let Some(right_type) = right.get_type() {
- (Arc::::from_ast(scope, &*value.left, Some(right_type.partial()))?, right)
+ (
+ Arc::::from_ast(scope, &*value.left, Some(right_type.partial()))?,
+ right,
+ )
} else {
return Err(e);
}
@@ -145,23 +175,43 @@ impl FromAst for BinaryExpression {
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::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(AsgConvertError::unexpected_type("integer", type_.map(|x| x.to_string()).as_deref(), &value.span)),
+ type_ => {
+ return Err(AsgConvertError::unexpected_type(
+ "integer",
+ type_.map(|x| x.to_string()).as_deref(),
+ &value.span,
+ ));
+ }
},
- BinaryOperationClass::Boolean =>
- match &value.op {
- BinaryOperation::And | BinaryOperation::Or =>
- match left_type {
- Some(Type::Boolean) | None => (),
- Some(x) => return Err(AsgConvertError::unexpected_type(&x.to_string(), Some(&*Type::Boolean.to_string()), &value.span)),
- },
- BinaryOperation::Eq | BinaryOperation::Ne => (), // all types allowed
- _ => match left_type {
- Some(Type::Integer(_)) | None => (),
- Some(x) => return Err(AsgConvertError::unexpected_type(&x.to_string(), Some("integer"), &value.span)),
+ BinaryOperationClass::Boolean => match &value.op {
+ BinaryOperation::And | BinaryOperation::Or => match left_type {
+ Some(Type::Boolean) | None => (),
+ Some(x) => {
+ return Err(AsgConvertError::unexpected_type(
+ &x.to_string(),
+ Some(&*Type::Boolean.to_string()),
+ &value.span,
+ ));
}
- }
+ },
+ BinaryOperation::Eq | BinaryOperation::Ne => (), // all types allowed
+ _ => match left_type {
+ Some(Type::Integer(_)) | None => (),
+ Some(x) => {
+ return Err(AsgConvertError::unexpected_type(
+ &x.to_string(),
+ Some("integer"),
+ &value.span,
+ ));
+ }
+ },
+ },
}
let right_type = right.get_type();
@@ -169,10 +219,20 @@ impl FromAst for BinaryExpression {
match (left_type, right_type) {
(Some(left_type), Some(right_type)) => {
if !left_type.is_assignable_from(&right_type) {
- return Err(AsgConvertError::unexpected_type(&left_type.to_string(), Some(&*right_type.to_string()), &value.span));
+ return Err(AsgConvertError::unexpected_type(
+ &left_type.to_string(),
+ Some(&*right_type.to_string()),
+ &value.span,
+ ));
}
- },
- (None, None) => return Err(AsgConvertError::unexpected_type("any type", Some("unknown type"), &value.span)),
+ }
+ (None, None) => {
+ return Err(AsgConvertError::unexpected_type(
+ "any type",
+ Some("unknown type"),
+ &value.span,
+ ));
+ }
(_, _) => (), //todo: improve this with type drilling
}
Ok(BinaryExpression {
@@ -194,4 +254,4 @@ impl Into for &BinaryExpression {
span: self.span.clone().unwrap_or_default(),
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/expression/call.rs b/asg/src/expression/call.rs
index 55db6d404c..685a328501 100644
--- a/asg/src/expression/call.rs
+++ b/asg/src/expression/call.rs
@@ -1,8 +1,39 @@
+// Copyright (C) 2019-2020 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::{
+ AsgConvertError,
+ CircuitMember,
+ ConstValue,
+ Expression,
+ ExpressionNode,
+ FromAst,
+ Function,
+ FunctionQualifier,
+ Node,
+ PartialType,
+ Scope,
+ Span,
+ Type,
+};
pub use leo_ast::BinaryOperation;
-use crate::Span;
-use crate::{ Expression, Function, Node, Type, ExpressionNode, FromAst, Scope, AsgConvertError, CircuitMember, ConstValue, PartialType, FunctionQualifier };
-use std::sync::{ Weak, Arc };
-use std::cell::RefCell;
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
pub struct CallExpression {
pub parent: RefCell>>,
@@ -51,73 +82,136 @@ impl ExpressionNode for CallExpression {
}
impl FromAst for CallExpression {
- fn from_ast(scope: &Scope, value: &leo_ast::CallExpression, expected_type: Option) -> Result {
-
+ fn from_ast(
+ scope: &Scope,
+ value: &leo_ast::CallExpression,
+ expected_type: Option,
+ ) -> Result {
let (target, function) = match &*value.function {
- leo_ast::Expression::Identifier(name) => (None, scope.borrow().resolve_function(&name.name).ok_or_else(|| AsgConvertError::unresolved_function(&name.name, &name.span))?),
- leo_ast::Expression::CircuitMemberAccess(leo_ast::CircuitMemberAccessExpression { circuit: ast_circuit, name, span }) => {
+ leo_ast::Expression::Identifier(name) => (
+ None,
+ scope
+ .borrow()
+ .resolve_function(&name.name)
+ .ok_or_else(|| AsgConvertError::unresolved_function(&name.name, &name.span))?,
+ ),
+ leo_ast::Expression::CircuitMemberAccess(leo_ast::CircuitMemberAccessExpression {
+ circuit: ast_circuit,
+ name,
+ span,
+ }) => {
let target = Arc::::from_ast(scope, &**ast_circuit, None)?;
let circuit = match target.get_type() {
Some(Type::Circuit(circuit)) => circuit,
- type_ => return Err(AsgConvertError::unexpected_type("circuit", type_.map(|x| x.to_string()).as_deref(), &span)),
+ type_ => {
+ return Err(AsgConvertError::unexpected_type(
+ "circuit",
+ type_.map(|x| x.to_string()).as_deref(),
+ &span,
+ ));
+ }
};
let circuit_name = circuit.name.borrow().name.clone();
let member = circuit.members.borrow();
- let member = member.get(&name.name).ok_or_else(|| AsgConvertError::unresolved_circuit_member(&circuit_name, &name.name, &span))?;
+ let member = member
+ .get(&name.name)
+ .ok_or_else(|| AsgConvertError::unresolved_circuit_member(&circuit_name, &name.name, &span))?;
match member {
CircuitMember::Function(body) => {
if body.qualifier == FunctionQualifier::Static {
- return Err(AsgConvertError::circuit_static_call_invalid(&circuit_name, &name.name, &span));
+ return Err(AsgConvertError::circuit_static_call_invalid(
+ &circuit_name,
+ &name.name,
+ &span,
+ ));
} else if body.qualifier == FunctionQualifier::MutSelfRef {
if !target.is_mut_ref() {
- return Err(AsgConvertError::circuit_member_mut_call_invalid(&circuit_name, &name.name, &span));
+ return Err(AsgConvertError::circuit_member_mut_call_invalid(
+ &circuit_name,
+ &name.name,
+ &span,
+ ));
}
}
(Some(target), body.clone())
- },
- CircuitMember::Variable(_) => return Err(AsgConvertError::circuit_variable_call(&circuit_name, &name.name, &span))?,
+ }
+ CircuitMember::Variable(_) => {
+ return Err(AsgConvertError::circuit_variable_call(&circuit_name, &name.name, &span))?;
+ }
}
- },
- leo_ast::Expression::CircuitStaticFunctionAccess(leo_ast::CircuitStaticFunctionAccessExpression { circuit: ast_circuit, name, span }) => {
+ }
+ 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.borrow().resolve_circuit(&circuit_name.name).ok_or_else(|| AsgConvertError::unresolved_circuit(&circuit_name.name, &circuit_name.span))?
+ scope
+ .borrow()
+ .resolve_circuit(&circuit_name.name)
+ .ok_or_else(|| AsgConvertError::unresolved_circuit(&circuit_name.name, &circuit_name.span))?
} else {
return Err(AsgConvertError::unexpected_type("circuit", None, &span));
};
let circuit_name = circuit.name.borrow().name.clone();
let member = circuit.members.borrow();
- let member = member.get(&name.name).ok_or_else(|| AsgConvertError::unresolved_circuit_member(&circuit_name, &name.name, &span))?;
+ let member = member
+ .get(&name.name)
+ .ok_or_else(|| AsgConvertError::unresolved_circuit_member(&circuit_name, &name.name, &span))?;
match member {
CircuitMember::Function(body) => {
if body.qualifier != FunctionQualifier::Static {
- return Err(AsgConvertError::circuit_member_call_invalid(&circuit_name, &name.name, &span));
+ return Err(AsgConvertError::circuit_member_call_invalid(
+ &circuit_name,
+ &name.name,
+ &span,
+ ));
}
(None, body.clone())
- },
- CircuitMember::Variable(_) => return Err(AsgConvertError::circuit_variable_call(&circuit_name, &name.name, &span))?,
+ }
+ CircuitMember::Variable(_) => {
+ return Err(AsgConvertError::circuit_variable_call(&circuit_name, &name.name, &span))?;
+ }
}
- },
- _ => return Err(AsgConvertError::illegal_ast_structure("non Identifier/CircuitMemberAccess/CircuitStaticFunctionAccess as call target")),
+ }
+ _ => {
+ return Err(AsgConvertError::illegal_ast_structure(
+ "non Identifier/CircuitMemberAccess/CircuitStaticFunctionAccess as call target",
+ ));
+ }
};
match expected_type {
Some(expected) => {
let output: Type = function.output.clone().into();
if !expected.matches(&output) {
- return Err(AsgConvertError::unexpected_type(&expected.to_string(), Some(&*output.to_string()), &value.span));
+ return Err(AsgConvertError::unexpected_type(
+ &expected.to_string(),
+ Some(&*output.to_string()),
+ &value.span,
+ ));
}
- },
+ }
_ => (),
}
if value.arguments.len() != function.argument_types.len() {
- return Err(AsgConvertError::unexpected_call_argument_count(function.argument_types.len(), value.arguments.len(), &value.span));
+ return Err(AsgConvertError::unexpected_call_argument_count(
+ function.argument_types.len(),
+ value.arguments.len(),
+ &value.span,
+ ));
}
Ok(CallExpression {
parent: RefCell::new(None),
span: Some(value.span.clone()),
- arguments: value.arguments.iter().zip(function.argument_types.iter())
- .map(|(expr, argument)| Arc::::from_ast(scope, expr, Some(argument.clone().strong().partial())))
+ arguments: value
+ .arguments
+ .iter()
+ .zip(function.argument_types.iter())
+ .map(|(expr, argument)| {
+ Arc::::from_ast(scope, expr, Some(argument.clone().strong().partial()))
+ })
.collect::, AsgConvertError>>()?,
function,
target,
@@ -147,4 +241,4 @@ impl Into for &CallExpression {
span: self.span.clone().unwrap_or_default(),
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/expression/circuit_access.rs b/asg/src/expression/circuit_access.rs
index d35068984a..5c71fc1f70 100644
--- a/asg/src/expression/circuit_access.rs
+++ b/asg/src/expression/circuit_access.rs
@@ -1,7 +1,55 @@
-use crate::Span;
-use crate::{ Expression, Identifier, Type, Node, ExpressionNode, FromAst, Scope, AsgConvertError, Circuit, CircuitMember, ConstValue, PartialType, CircuitMemberBody };
-use std::sync::{ Weak, Arc };
-use std::cell::RefCell;
+// Copyright (C) 2019-2020 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 .
+
+// Copyright (C) 2019-2020 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::{
+ AsgConvertError,
+ Circuit,
+ CircuitMember,
+ CircuitMemberBody,
+ ConstValue,
+ Expression,
+ ExpressionNode,
+ FromAst,
+ Identifier,
+ Node,
+ PartialType,
+ Scope,
+ Span,
+ Type,
+};
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
pub struct CircuitAccessExpression {
pub parent: RefCell>>,
@@ -59,14 +107,23 @@ impl ExpressionNode for CircuitAccessExpression {
}
impl FromAst for CircuitAccessExpression {
- fn from_ast(scope: &Scope, value: &leo_ast::CircuitMemberAccessExpression, expected_type: Option) -> Result {
+ fn from_ast(
+ scope: &Scope,
+ value: &leo_ast::CircuitMemberAccessExpression,
+ expected_type: Option,
+ ) -> Result {
let target = Arc::::from_ast(scope, &*value.circuit, None)?;
let circuit = match target.get_type() {
Some(Type::Circuit(circuit)) => circuit,
- x => return Err(AsgConvertError::unexpected_type("circuit", x.map(|x| x.to_string()).as_deref(), &value.span)),
+ x => {
+ return Err(AsgConvertError::unexpected_type(
+ "circuit",
+ x.map(|x| x.to_string()).as_deref(),
+ &value.span,
+ ));
+ }
};
-
// scoping refcell reference
let found_member = {
if let Some(member) = circuit.members.borrow().get(&value.name.name) {
@@ -74,7 +131,11 @@ impl FromAst for CircuitAccessExpression
if let CircuitMember::Variable(type_) = &member {
let type_: Type = type_.clone().into();
if !expected_type.matches(&type_) {
- return Err(AsgConvertError::unexpected_type(&expected_type.to_string(), Some(&type_.to_string()), &value.span));
+ return Err(AsgConvertError::unexpected_type(
+ &expected_type.to_string(),
+ Some(&type_.to_string()),
+ &value.span,
+ ));
}
} // used by call expression
}
@@ -86,27 +147,31 @@ impl FromAst for CircuitAccessExpression
if found_member {
// skip
- } else if circuit.is_input_psuedo_circuit() { // add new member to implicit input
+ } else if circuit.is_input_psuedo_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.clone(),
- CircuitMember::Variable(
- expected_type.clone().into()
- )
+ CircuitMember::Variable(expected_type.clone().into()),
);
let body = circuit.body.borrow().upgrade().expect("stale input circuit body");
- body.members.borrow_mut().insert(
- value.name.name.clone(),
- CircuitMemberBody::Variable(
- expected_type
- )
- );
+ body.members
+ .borrow_mut()
+ .insert(value.name.name.clone(), CircuitMemberBody::Variable(expected_type));
} else {
- return Err(AsgConvertError::input_ref_needs_type(&circuit.name.borrow().name, &value.name.name, &value.span));
+ return Err(AsgConvertError::input_ref_needs_type(
+ &circuit.name.borrow().name,
+ &value.name.name,
+ &value.span,
+ ));
}
} else {
- return Err(AsgConvertError::unresolved_circuit_member(&circuit.name.borrow().name, &value.name.name, &value.span));
+ return Err(AsgConvertError::unresolved_circuit_member(
+ &circuit.name.borrow().name,
+ &value.name.name,
+ &value.span,
+ ));
}
Ok(CircuitAccessExpression {
@@ -120,22 +185,41 @@ impl FromAst for CircuitAccessExpression
}
impl FromAst for CircuitAccessExpression {
- fn from_ast(scope: &Scope, value: &leo_ast::CircuitStaticFunctionAccessExpression, expected_type: Option) -> Result {
+ fn from_ast(
+ scope: &Scope,
+ value: &leo_ast::CircuitStaticFunctionAccessExpression,
+ expected_type: Option,
+ ) -> Result {
let circuit = match &*value.circuit {
- leo_ast::Expression::Identifier(name) => {
- scope.borrow().resolve_circuit(&name.name).ok_or_else(|| AsgConvertError::unresolved_circuit(&name.name, &name.span))?
- },
- _ => return Err(AsgConvertError::unexpected_type("circuit", Some("unknown"), &value.span)),
+ leo_ast::Expression::Identifier(name) => scope
+ .borrow()
+ .resolve_circuit(&name.name)
+ .ok_or_else(|| AsgConvertError::unresolved_circuit(&name.name, &name.span))?,
+ _ => {
+ return Err(AsgConvertError::unexpected_type(
+ "circuit",
+ Some("unknown"),
+ &value.span,
+ ));
+ }
};
if let Some(expected_type) = expected_type {
- return Err(AsgConvertError::unexpected_type(&expected_type.to_string(), Some("none"), &value.span));
+ return Err(AsgConvertError::unexpected_type(
+ &expected_type.to_string(),
+ Some("none"),
+ &value.span,
+ ));
}
-
+
if let Some(CircuitMember::Function(_)) = circuit.members.borrow().get(&value.name.name) {
// okay
} else {
- return Err(AsgConvertError::unresolved_circuit_member(&circuit.name.borrow().name, &value.name.name, &value.span));
+ return Err(AsgConvertError::unresolved_circuit_member(
+ &circuit.name.borrow().name,
+ &value.name.name,
+ &value.span,
+ ));
}
Ok(CircuitAccessExpression {
@@ -164,4 +248,4 @@ impl Into for &CircuitAccessExpression {
})
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/expression/circuit_init.rs b/asg/src/expression/circuit_init.rs
index 76c7bb9dbc..c9597eac62 100644
--- a/asg/src/expression/circuit_init.rs
+++ b/asg/src/expression/circuit_init.rs
@@ -1,8 +1,39 @@
-use crate::Span;
-use crate::{ Expression, Circuit, Identifier, Type, Node, ExpressionNode, FromAst, Scope, AsgConvertError, CircuitMember, ConstValue, PartialType };
-use std::sync::{ Weak, Arc };
-use std::cell::RefCell;
+// Copyright (C) 2019-2020 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::{
+ AsgConvertError,
+ Circuit,
+ CircuitMember,
+ ConstValue,
+ Expression,
+ ExpressionNode,
+ FromAst,
+ Identifier,
+ Node,
+ PartialType,
+ Scope,
+ Span,
+ Type,
+};
use indexmap::IndexMap;
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
pub struct CircuitInitExpression {
pub parent: RefCell>>,
@@ -46,14 +77,31 @@ impl ExpressionNode for CircuitInitExpression {
}
impl FromAst for CircuitInitExpression {
- fn from_ast(scope: &Scope, value: &leo_ast::CircuitInitExpression, expected_type: Option) -> Result {
- let circuit = scope.borrow().resolve_circuit(&value.name.name).ok_or_else(|| AsgConvertError::unresolved_circuit(&value.name.name, &value.name.span))?;
+ fn from_ast(
+ scope: &Scope,
+ value: &leo_ast::CircuitInitExpression,
+ expected_type: Option,
+ ) -> Result {
+ let circuit = scope
+ .borrow()
+ .resolve_circuit(&value.name.name)
+ .ok_or_else(|| AsgConvertError::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(AsgConvertError::unexpected_type(&x.to_string(), Some(&circuit.name.borrow().name), &value.span)),
+ Some(x) => {
+ return Err(AsgConvertError::unexpected_type(
+ &x.to_string(),
+ Some(&circuit.name.borrow().name),
+ &value.span,
+ ));
+ }
}
- let members: IndexMap<&String, (&Identifier, &leo_ast::Expression)> = value.members.iter().map(|x| (&x.identifier.name, (&x.identifier, &x.expression))).collect();
+ let members: IndexMap<&String, (&Identifier, &leo_ast::Expression)> = value
+ .members
+ .iter()
+ .map(|x| (&x.identifier.name, (&x.identifier, &x.expression)))
+ .collect();
let mut values: Vec<(Identifier, Arc)> = vec![];
@@ -69,13 +117,21 @@ impl FromAst for CircuitInitExpression {
let received = Arc::::from_ast(scope, *receiver, Some(type_.partial()))?;
values.push(((*identifier).clone(), received));
} else {
- return Err(AsgConvertError::missing_circuit_member(&circuit.name.borrow().name, name, &value.span));
+ return Err(AsgConvertError::missing_circuit_member(
+ &circuit.name.borrow().name,
+ name,
+ &value.span,
+ ));
}
}
for (name, (identifier, _expression)) in members.iter() {
if circuit_members.get(*name).is_none() {
- return Err(AsgConvertError::extra_circuit_member(&circuit.name.borrow().name, *name, &identifier.span));
+ return Err(AsgConvertError::extra_circuit_member(
+ &circuit.name.borrow().name,
+ *name,
+ &identifier.span,
+ ));
}
}
}
@@ -93,13 +149,15 @@ impl Into for &CircuitInitExpression {
fn into(self) -> leo_ast::CircuitInitExpression {
leo_ast::CircuitInitExpression {
name: self.circuit.name.borrow().clone(),
- members: self.values.iter().map(|(name, value)| {
- leo_ast::CircuitVariableDefinition {
+ members: self
+ .values
+ .iter()
+ .map(|(name, value)| leo_ast::CircuitVariableDefinition {
identifier: name.clone(),
expression: value.as_ref().into(),
- }
- }).collect(),
+ })
+ .collect(),
span: self.span.clone().unwrap_or_default(),
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/expression/conditional.rs b/asg/src/expression/conditional.rs
index 780d1ecebd..bba227b36a 100644
--- a/asg/src/expression/conditional.rs
+++ b/asg/src/expression/conditional.rs
@@ -1,7 +1,24 @@
-use crate::Span;
-use crate::{ Expression, Node, Type, ExpressionNode, FromAst, Scope, AsgConvertError, ConstValue, PartialType };
-use std::sync::{ Weak, Arc };
-use std::cell::RefCell;
+// Copyright (C) 2019-2020 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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
pub struct ConditionalExpression {
pub parent: RefCell>>,
@@ -54,7 +71,11 @@ impl ExpressionNode for ConditionalExpression {
}
impl FromAst for ConditionalExpression {
- fn from_ast(scope: &Scope, value: &leo_ast::ConditionalExpression, expected_type: Option) -> Result {
+ fn from_ast(
+ scope: &Scope,
+ value: &leo_ast::ConditionalExpression,
+ expected_type: Option,
+ ) -> Result {
Ok(ConditionalExpression {
parent: RefCell::new(None),
span: Some(value.span.clone()),
@@ -74,4 +95,4 @@ impl Into for &ConditionalExpression {
span: self.span.clone().unwrap_or_default(),
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/expression/constant.rs b/asg/src/expression/constant.rs
index 52c895d8b9..28336cd11c 100644
--- a/asg/src/expression/constant.rs
+++ b/asg/src/expression/constant.rs
@@ -1,6 +1,37 @@
-use crate::{ Node, Type, Span, Expression, ExpressionNode, FromAst, Scope, AsgConvertError, ConstValue, GroupValue, ConstInt, PartialType };
-use std::sync::{ Arc, Weak };
-use std::cell::RefCell;
+// Copyright (C) 2019-2020 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::{
+ AsgConvertError,
+ ConstInt,
+ ConstValue,
+ Expression,
+ ExpressionNode,
+ FromAst,
+ GroupValue,
+ Node,
+ PartialType,
+ Scope,
+ Span,
+ Type,
+};
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
pub struct Constant {
pub parent: RefCell>>,
@@ -23,8 +54,7 @@ impl ExpressionNode for Constant {
self.parent.borrow().as_ref().map(Weak::upgrade).flatten()
}
- fn enforce_parents(&self, _expr: &Arc) {
- }
+ fn enforce_parents(&self, _expr: &Arc) {}
fn get_type(&self) -> Option {
self.value.get_type()
@@ -40,98 +70,127 @@ impl ExpressionNode for Constant {
}
impl FromAst for Constant {
- fn from_ast(_scope: &Scope, value: &leo_ast::ValueExpression, expected_type: Option) -> Result {
+ fn from_ast(
+ _scope: &Scope,
+ 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(AsgConvertError::unexpected_type(&x.to_string(), Some(&*Type::Address.to_string()), span)),
+ Some(x) => {
+ return Err(AsgConvertError::unexpected_type(
+ &x.to_string(),
+ Some(&*Type::Address.to_string()),
+ span,
+ ));
+ }
}
Constant {
parent: RefCell::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(AsgConvertError::unexpected_type(&x.to_string(), Some(&*Type::Boolean.to_string()), span)),
+ Some(x) => {
+ return Err(AsgConvertError::unexpected_type(
+ &x.to_string(),
+ Some(&*Type::Boolean.to_string()),
+ span,
+ ));
+ }
}
Constant {
parent: RefCell::new(None),
span: Some(span.clone()),
- value: ConstValue::Boolean(value.parse::().map_err(|_| AsgConvertError::invalid_boolean(&value, span))?),
+ value: ConstValue::Boolean(
+ value
+ .parse::()
+ .map_err(|_| AsgConvertError::invalid_boolean(&value, span))?,
+ ),
}
- },
+ }
Field(value, span) => {
match expected_type.map(PartialType::full).flatten() {
Some(Type::Field) | None => (),
- Some(x) => return Err(AsgConvertError::unexpected_type(&x.to_string(), Some(&*Type::Field.to_string()), span)),
+ Some(x) => {
+ return Err(AsgConvertError::unexpected_type(
+ &x.to_string(),
+ Some(&*Type::Field.to_string()),
+ span,
+ ));
+ }
}
Constant {
parent: RefCell::new(None),
span: Some(span.clone()),
value: ConstValue::Field(value.parse().map_err(|_| AsgConvertError::invalid_int(&value, span))?),
}
- },
+ }
Group(value) => {
match expected_type.map(PartialType::full).flatten() {
Some(Type::Group) | None => (),
- Some(x) => return Err(AsgConvertError::unexpected_type(&x.to_string(), Some(&*Type::Group.to_string()), value.span())),
+ Some(x) => {
+ return Err(AsgConvertError::unexpected_type(
+ &x.to_string(),
+ Some(&*Type::Group.to_string()),
+ value.span(),
+ ));
+ }
}
Constant {
parent: RefCell::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.map(PartialType::full).flatten() {
- None => return Err(AsgConvertError::unresolved_type("unknown", span)),
- Some(Type::Integer(int_type)) => {
- Constant {
- parent: RefCell::new(None),
- span: Some(span.clone()),
- value: ConstValue::Int(ConstInt::parse(&int_type, value, span)?),
- }
- },
- Some(Type::Field) => {
- Constant {
- parent: RefCell::new(None),
- span: Some(span.clone()),
- value: ConstValue::Field(value.parse().map_err(|_| AsgConvertError::invalid_int(&value, span))?),
+ leo_ast::GroupValue::Tuple(leo_ast::GroupTuple { x, y, .. }) => {
+ GroupValue::Tuple(x.into(), y.into())
}
- },
- Some(Type::Address) => {
- Constant {
- parent: RefCell::new(None),
- span: Some(span.clone()),
- value: ConstValue::Address(value.to_string()),
- }
- },
- Some(x) => return Err(AsgConvertError::unexpected_type(&x.to_string(), Some("unknown"), span)),
+ }),
}
+ }
+ Implicit(value, span) => match expected_type.map(PartialType::full).flatten() {
+ None => return Err(AsgConvertError::unresolved_type("unknown", span)),
+ Some(Type::Integer(int_type)) => Constant {
+ parent: RefCell::new(None),
+ span: Some(span.clone()),
+ value: ConstValue::Int(ConstInt::parse(&int_type, value, span)?),
+ },
+ Some(Type::Field) => Constant {
+ parent: RefCell::new(None),
+ span: Some(span.clone()),
+ value: ConstValue::Field(value.parse().map_err(|_| AsgConvertError::invalid_int(&value, span))?),
+ },
+ Some(Type::Address) => Constant {
+ parent: RefCell::new(None),
+ span: Some(span.clone()),
+ value: ConstValue::Address(value.to_string()),
+ },
+ Some(x) => return Err(AsgConvertError::unexpected_type(&x.to_string(), Some("unknown"), span)),
},
Integer(int_type, value, span) => {
match expected_type.map(PartialType::full).flatten() {
Some(Type::Integer(sub_type)) if &sub_type == int_type => (),
None => (),
- Some(x) => return Err(AsgConvertError::unexpected_type(&x.to_string(), Some(&*int_type.to_string()), span)),
+ Some(x) => {
+ return Err(AsgConvertError::unexpected_type(
+ &x.to_string(),
+ Some(&*int_type.to_string()),
+ span,
+ ));
+ }
}
Constant {
parent: RefCell::new(None),
span: Some(span.clone()),
value: ConstValue::Int(ConstInt::parse(int_type, value, span)?),
}
- },
+ }
})
}
}
@@ -139,21 +198,32 @@ impl FromAst for Constant {
impl Into for &Constant {
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(), self.span.clone().unwrap_or_default()),
- ConstValue::Field(value) => leo_ast::ValueExpression::Field(value.to_string(), 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(), self.span.clone().unwrap_or_default()),
+ 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(), self.span.clone().unwrap_or_default())
+ }
+ ConstValue::Field(value) => {
+ leo_ast::ValueExpression::Field(value.to_string(), 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(),
+ self.span.clone().unwrap_or_default(),
+ ),
ConstValue::Tuple(_) => unimplemented!(),
ConstValue::Array(_) => unimplemented!(),
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/expression/mod.rs b/asg/src/expression/mod.rs
index 46f08250ea..12ad96e1f9 100644
--- a/asg/src/expression/mod.rs
+++ b/asg/src/expression/mod.rs
@@ -1,3 +1,18 @@
+// Copyright (C) 2019-2020 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 variable_ref;
pub use variable_ref::*;
@@ -28,8 +43,8 @@ pub use circuit_access::*;
mod call;
pub use call::*;
-use std::sync::{ Arc, Weak };
-use crate::{ Node, Type, PartialType, Span, FromAst, AsgConvertError, Scope, ConstValue };
+use crate::{AsgConvertError, ConstValue, FromAst, Node, PartialType, Scope, Span, Type};
+use std::sync::{Arc, Weak};
pub enum Expression {
VariableRef(VariableRef),
@@ -53,7 +68,6 @@ pub enum Expression {
}
impl Node for Expression {
-
fn span(&self) -> Option<&Span> {
use Expression::*;
match self {
@@ -208,27 +222,56 @@ impl ExpressionNode for Expression {
}
impl FromAst for Arc {
- fn from_ast(scope: &Scope, value: &leo_ast::Expression, expected_type: Option) -> Result {
+ fn from_ast(
+ scope: &Scope,
+ 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) => Arc::new(Constant::from_ast(scope, value, expected_type).map(Expression::Constant)?),
- Binary(binary) => Arc::new(BinaryExpression::from_ast(scope, binary, expected_type).map(Expression::Binary)?),
+ Binary(binary) => {
+ Arc::new(BinaryExpression::from_ast(scope, binary, expected_type).map(Expression::Binary)?)
+ }
Unary(unary) => Arc::new(UnaryExpression::from_ast(scope, unary, expected_type).map(Expression::Unary)?),
- Conditional(conditional) => Arc::new(ConditionalExpression::from_ast(scope, conditional, expected_type).map(Expression::Conditional)?),
-
- ArrayInline(array_inline) => Arc::new(ArrayInlineExpression::from_ast(scope, array_inline, expected_type).map(Expression::ArrayInline)?),
- ArrayInit(array_init) => Arc::new(ArrayInitExpression::from_ast(scope, array_init, expected_type).map(Expression::ArrayInit)?),
- ArrayAccess(array_access) => Arc::new(ArrayAccessExpression::from_ast(scope, array_access, expected_type).map(Expression::ArrayAccess)?),
- ArrayRangeAccess(array_range_access) => Arc::new(ArrayRangeAccessExpression::from_ast(scope, array_range_access, expected_type).map(Expression::ArrayRangeAccess)?),
-
- TupleInit(tuple_init) => Arc::new(TupleInitExpression::from_ast(scope, tuple_init, expected_type).map(Expression::TupleInit)?),
- TupleAccess(tuple_access) => Arc::new(TupleAccessExpression::from_ast(scope, tuple_access, expected_type).map(Expression::TupleAccess)?),
-
- CircuitInit(circuit_init) => Arc::new(CircuitInitExpression::from_ast(scope, circuit_init, expected_type).map(Expression::CircuitInit)?),
- CircuitMemberAccess(circuit_member) => Arc::new(CircuitAccessExpression::from_ast(scope, circuit_member, expected_type).map(Expression::CircuitAccess)?),
- CircuitStaticFunctionAccess(circuit_member) => Arc::new(CircuitAccessExpression::from_ast(scope, circuit_member, expected_type).map(Expression::CircuitAccess)?),
-
+ Conditional(conditional) => Arc::new(
+ ConditionalExpression::from_ast(scope, conditional, expected_type).map(Expression::Conditional)?,
+ ),
+
+ ArrayInline(array_inline) => Arc::new(
+ ArrayInlineExpression::from_ast(scope, array_inline, expected_type).map(Expression::ArrayInline)?,
+ ),
+ ArrayInit(array_init) => {
+ Arc::new(ArrayInitExpression::from_ast(scope, array_init, expected_type).map(Expression::ArrayInit)?)
+ }
+ ArrayAccess(array_access) => Arc::new(
+ ArrayAccessExpression::from_ast(scope, array_access, expected_type).map(Expression::ArrayAccess)?,
+ ),
+ ArrayRangeAccess(array_range_access) => Arc::new(
+ ArrayRangeAccessExpression::from_ast(scope, array_range_access, expected_type)
+ .map(Expression::ArrayRangeAccess)?,
+ ),
+
+ TupleInit(tuple_init) => {
+ Arc::new(TupleInitExpression::from_ast(scope, tuple_init, expected_type).map(Expression::TupleInit)?)
+ }
+ TupleAccess(tuple_access) => Arc::new(
+ TupleAccessExpression::from_ast(scope, tuple_access, expected_type).map(Expression::TupleAccess)?,
+ ),
+
+ CircuitInit(circuit_init) => Arc::new(
+ CircuitInitExpression::from_ast(scope, circuit_init, expected_type).map(Expression::CircuitInit)?,
+ ),
+ CircuitMemberAccess(circuit_member) => Arc::new(
+ CircuitAccessExpression::from_ast(scope, circuit_member, expected_type)
+ .map(Expression::CircuitAccess)?,
+ ),
+ CircuitStaticFunctionAccess(circuit_member) => Arc::new(
+ CircuitAccessExpression::from_ast(scope, circuit_member, expected_type)
+ .map(Expression::CircuitAccess)?,
+ ),
+
Call(call) => Arc::new(CallExpression::from_ast(scope, call, expected_type).map(Expression::Call)?),
};
expression.enforce_parents(&expression);
@@ -256,4 +299,4 @@ impl Into for &Expression {
Call(x) => leo_ast::Expression::Call(x.into()),
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/expression/tuple_access.rs b/asg/src/expression/tuple_access.rs
index c88a7b4bcf..5739f4a910 100644
--- a/asg/src/expression/tuple_access.rs
+++ b/asg/src/expression/tuple_access.rs
@@ -1,7 +1,24 @@
-use crate::Span;
-use crate::{ Expression, Node, Type, ExpressionNode, FromAst, Scope, AsgConvertError, ConstValue, PartialType };
-use std::sync::{ Weak, Arc };
-use std::cell::RefCell;
+// Copyright (C) 2019-2020 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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
pub struct TupleAccessExpression {
pub parent: RefCell>>,
@@ -11,7 +28,6 @@ pub struct TupleAccessExpression {
}
impl Node for TupleAccessExpression {
-
fn span(&self) -> Option<&Span> {
self.span.as_ref()
}
@@ -51,8 +67,16 @@ impl ExpressionNode for TupleAccessExpression {
}
impl FromAst for TupleAccessExpression {
- fn from_ast(scope: &Scope, value: &leo_ast::TupleAccessExpression, expected_type: Option) -> Result {
- let index = value.index.value.parse::().map_err(|_| AsgConvertError::parse_index_error())?;
+ fn from_ast(
+ scope: &Scope,
+ value: &leo_ast::TupleAccessExpression,
+ expected_type: Option,
+ ) -> Result {
+ let index = value
+ .index
+ .value
+ .parse::()
+ .map_err(|_| AsgConvertError::parse_index_error())?;
let mut expected_tuple = vec![None; index + 1];
expected_tuple[index] = expected_type.clone();
@@ -61,7 +85,11 @@ impl FromAst for TupleAccessExpression {
let tuple_type = tuple.get_type();
if let Some(Type::Tuple(_items)) = tuple_type {
} else {
- return Err(AsgConvertError::unexpected_type("a tuple", tuple_type.map(|x| x.to_string()).as_deref(), &value.span));
+ return Err(AsgConvertError::unexpected_type(
+ "a tuple",
+ tuple_type.map(|x| x.to_string()).as_deref(),
+ &value.span,
+ ));
}
Ok(TupleAccessExpression {
@@ -77,8 +105,10 @@ impl Into for &TupleAccessExpression {
fn into(self) -> leo_ast::TupleAccessExpression {
leo_ast::TupleAccessExpression {
tuple: Box::new(self.tuple_ref.as_ref().into()),
- index: leo_ast::PositiveNumber { value: self.index.to_string() },
+ index: leo_ast::PositiveNumber {
+ value: self.index.to_string(),
+ },
span: self.span.clone().unwrap_or_default(),
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/expression/tuple_init.rs b/asg/src/expression/tuple_init.rs
index 4181d94e6d..a076a18787 100644
--- a/asg/src/expression/tuple_init.rs
+++ b/asg/src/expression/tuple_init.rs
@@ -1,7 +1,24 @@
-use crate::Span;
-use crate::{ Expression, Node, Type, ExpressionNode, FromAst, Scope, AsgConvertError, ConstValue, PartialType };
-use std::sync::{ Weak, Arc };
-use std::cell::RefCell;
+// Copyright (C) 2019-2020 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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
pub struct TupleInitExpression {
pub parent: RefCell>>,
@@ -56,23 +73,46 @@ impl ExpressionNode for TupleInitExpression {
}
impl FromAst for TupleInitExpression {
- fn from_ast(scope: &Scope, value: &leo_ast::TupleInitExpression, expected_type: Option) -> Result {
+ fn from_ast(
+ scope: &Scope,
+ 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(AsgConvertError::unexpected_type("tuple", x.map(|x| x.to_string()).as_deref(), &value.span)),
+ x => {
+ return Err(AsgConvertError::unexpected_type(
+ "tuple",
+ x.map(|x| x.to_string()).as_deref(),
+ &value.span,
+ ));
+ }
};
if let Some(tuple_types) = tuple_types.as_ref() {
if tuple_types.len() != value.elements.len() {
- return Err(AsgConvertError::unexpected_type(&*format!("tuple of length {}", tuple_types.len()), Some(&*format!("tuple of length {}", value.elements.len())), &value.span));
+ return Err(AsgConvertError::unexpected_type(
+ &*format!("tuple of length {}", tuple_types.len()),
+ Some(&*format!("tuple of length {}", value.elements.len())),
+ &value.span,
+ ));
}
}
- let elements = value.elements.iter().enumerate()
- .map(|(i, e)| Arc::::from_ast(scope, e, tuple_types.as_ref().map(|x| x.get(i)).flatten().cloned().flatten()))
+ let elements = value
+ .elements
+ .iter()
+ .enumerate()
+ .map(|(i, e)| {
+ Arc::::from_ast(
+ scope,
+ e,
+ tuple_types.as_ref().map(|x| x.get(i)).flatten().cloned().flatten(),
+ )
+ })
.collect::, AsgConvertError>>()?;
-
+
Ok(TupleInitExpression {
parent: RefCell::new(None),
span: Some(value.span.clone()),
@@ -88,4 +128,4 @@ impl Into for &TupleInitExpression {
span: self.span.clone().unwrap_or_default(),
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/expression/unary.rs b/asg/src/expression/unary.rs
index d716bb414a..36b4546eab 100644
--- a/asg/src/expression/unary.rs
+++ b/asg/src/expression/unary.rs
@@ -1,8 +1,25 @@
+// Copyright (C) 2019-2020 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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
pub use leo_ast::UnaryOperation;
-use crate::Span;
-use crate::{ Expression, Node, Type, ExpressionNode, Scope, AsgConvertError, FromAst, ConstValue, PartialType };
-use std::sync::{ Weak, Arc };
-use std::cell::RefCell;
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
pub struct UnaryExpression {
pub parent: RefCell>>,
@@ -41,11 +58,9 @@ impl ExpressionNode for UnaryExpression {
fn const_value(&self) -> Option {
if let Some(inner) = self.inner.const_value() {
match self.operation {
- UnaryOperation::Not => {
- match inner {
- ConstValue::Boolean(value) => Some(ConstValue::Boolean(!value)),
- _ => None,
- }
+ UnaryOperation::Not => match inner {
+ ConstValue::Boolean(value) => Some(ConstValue::Boolean(!value)),
+ _ => None,
},
UnaryOperation::Negate => {
match inner {
@@ -54,7 +69,7 @@ impl ExpressionNode for UnaryExpression {
// ConstValue::Field(value) => Some(ConstValue::Field(-value)),
_ => None,
}
- },
+ }
}
} else {
None
@@ -63,18 +78,34 @@ impl ExpressionNode for UnaryExpression {
}
impl FromAst for UnaryExpression {
- fn from_ast(scope: &Scope, value: &leo_ast::UnaryExpression, expected_type: Option) -> Result {
+ fn from_ast(
+ scope: &Scope,
+ 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(AsgConvertError::unexpected_type(&type_.to_string(), Some(&*Type::Boolean.to_string()), &value.span)),
+ Some(type_) => {
+ return Err(AsgConvertError::unexpected_type(
+ &type_.to_string(),
+ Some(&*Type::Boolean.to_string()),
+ &value.span,
+ ));
+ }
},
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(AsgConvertError::unexpected_type(&type_.to_string(), Some("integer, group, field"), &value.span)),
+ Some(type_) => {
+ return Err(AsgConvertError::unexpected_type(
+ &type_.to_string(),
+ Some("integer, group, field"),
+ &value.span,
+ ));
+ }
},
};
Ok(UnaryExpression {
@@ -94,4 +125,4 @@ impl Into for &UnaryExpression {
span: self.span.clone().unwrap_or_default(),
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/expression/variable_ref.rs b/asg/src/expression/variable_ref.rs
index bef507f438..ab842ccf15 100644
--- a/asg/src/expression/variable_ref.rs
+++ b/asg/src/expression/variable_ref.rs
@@ -1,7 +1,37 @@
-use crate::Span;
-use crate::{ Expression, Variable, Node, Type, PartialType, ExpressionNode, FromAst, Scope, AsgConvertError, ConstValue, Constant };
-use std::sync::{ Weak, Arc };
-use std::cell::RefCell;
+// Copyright (C) 2019-2020 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::{
+ AsgConvertError,
+ ConstValue,
+ Constant,
+ Expression,
+ ExpressionNode,
+ FromAst,
+ Node,
+ PartialType,
+ Scope,
+ Span,
+ Type,
+ Variable,
+};
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
pub struct VariableRef {
pub parent: RefCell>>,
@@ -24,8 +54,7 @@ impl ExpressionNode for VariableRef {
self.parent.borrow().as_ref().map(Weak::upgrade).flatten()
}
- fn enforce_parents(&self, _expr: &Arc) {
- }
+ fn enforce_parents(&self, _expr: &Arc) {}
fn get_type(&self) -> Option {
Some(self.variable.borrow().type_.clone())
@@ -41,7 +70,11 @@ impl ExpressionNode for VariableRef {
}
impl FromAst for Arc {
- fn from_ast(scope: &Scope, value: &leo_ast::Identifier, expected_type: Option) -> Result, AsgConvertError> {
+ fn from_ast(
+ scope: &Scope,
+ value: &leo_ast::Identifier,
+ expected_type: Option,
+ ) -> Result, AsgConvertError> {
let variable = if value.name == "input" {
if let Some(function) = scope.borrow().resolve_current_function() {
if !function.has_input {
@@ -53,7 +86,9 @@ impl FromAst for Arc {
if let Some(input) = scope.borrow().resolve_input() {
input.container
} else {
- return Err(AsgConvertError::InternalError("attempted to reference input when none is in scope".to_string()))
+ return Err(AsgConvertError::InternalError(
+ "attempted to reference input when none is in scope".to_string(),
+ ));
}
} else {
match scope.borrow().resolve_variable(&value.name) {
@@ -79,9 +114,15 @@ impl FromAst for Arc {
let expression = Arc::new(Expression::VariableRef(variable_ref));
if let Some(expected_type) = expected_type {
- let type_ = expression.get_type().ok_or_else(|| AsgConvertError::unresolved_reference(&value.name, &value.span))?;
+ let type_ = expression
+ .get_type()
+ .ok_or_else(|| AsgConvertError::unresolved_reference(&value.name, &value.span))?;
if !expected_type.matches(&type_) {
- return Err(AsgConvertError::unexpected_type(&expected_type.to_string(), Some(&*type_.to_string()), &value.span));
+ return Err(AsgConvertError::unexpected_type(
+ &expected_type.to_string(),
+ Some(&*type_.to_string()),
+ &value.span,
+ ));
}
}
@@ -96,4 +137,4 @@ impl Into for &VariableRef {
fn into(self) -> leo_ast::Identifier {
self.variable.borrow().name.clone()
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/import.rs b/asg/src/import.rs
index b9682467f4..c5859d4905 100644
--- a/asg/src/import.rs
+++ b/asg/src/import.rs
@@ -1,5 +1,21 @@
+// Copyright (C) 2019-2020 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::{AsgConvertError, Program, Span};
use indexmap::IndexMap;
-use crate::{ Program, AsgConvertError, Span };
pub trait ImportResolver {
fn resolve_package(&mut self, package_segments: &[&str], span: &Span) -> Result, AsgConvertError>;
@@ -8,7 +24,11 @@ pub trait ImportResolver {
pub struct NullImportResolver;
impl ImportResolver for NullImportResolver {
- fn resolve_package(&mut self, _package_segments: &[&str], _span: &Span) -> Result , AsgConvertError> {
+ fn resolve_package(
+ &mut self,
+ _package_segments: &[&str],
+ _span: &Span,
+ ) -> Result , AsgConvertError> {
Ok(None)
}
}
@@ -29,7 +49,11 @@ pub struct StandardImportResolver;
//todo: move compiler ImportParser here
impl ImportResolver for StandardImportResolver {
- fn resolve_package(&mut self, _package_segments: &[&str], _span: &Span) -> Result , AsgConvertError> {
+ fn resolve_package(
+ &mut self,
+ _package_segments: &[&str],
+ _span: &Span,
+ ) -> Result , AsgConvertError> {
Ok(None)
}
}
@@ -42,4 +66,4 @@ impl ImportResolver for MockedImportResolver {
fn resolve_package(&mut self, package_segments: &[&str], _span: &Span) -> Result , AsgConvertError> {
Ok(self.packages.get(&package_segments.join(".")).cloned())
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/input.rs b/asg/src/input.rs
index 5c4e526024..c3137d64da 100644
--- a/asg/src/input.rs
+++ b/asg/src/input.rs
@@ -1,7 +1,25 @@
-use std::sync::{ Arc, Weak };
-use crate::{ Circuit, CircuitBody, Variable, Identifier, Type, CircuitMember, CircuitMemberBody, WeakType, Scope };
-use std::cell::RefCell;
+// Copyright (C) 2019-2020 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, CircuitBody, CircuitMember, CircuitMemberBody, Identifier, Scope, Type, Variable, WeakType};
use indexmap::IndexMap;
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
#[derive(Clone)]
pub struct Input {
@@ -34,23 +52,35 @@ impl Input {
scope: scope.clone(),
span: None,
circuit: circuit.clone(),
- members: RefCell::new(IndexMap::new()),
+ members: RefCell::new(IndexMap::new()),
});
circuit.body.replace(Arc::downgrade(&body));
body
}
-
+
pub fn new(scope: &Scope) -> Self {
let registers = Self::make_header(REGISTERS_PSUEDO_CIRCUIT);
let record = Self::make_header(RECORD_PSUEDO_CIRCUIT);
let state = Self::make_header(STATE_PSUEDO_CIRCUIT);
let state_leaf = Self::make_header(STATE_LEAF_PSUEDO_CIRCUIT);
-
+
let mut container_members = IndexMap::new();
- container_members.insert("registers".to_string(), CircuitMember::Variable(WeakType::Circuit(Arc::downgrade(®isters))));
- container_members.insert("record".to_string(), CircuitMember::Variable(WeakType::Circuit(Arc::downgrade(&record))));
- container_members.insert("state".to_string(), CircuitMember::Variable(WeakType::Circuit(Arc::downgrade(&state))));
- container_members.insert("state_leaf".to_string(), CircuitMember::Variable(WeakType::Circuit(Arc::downgrade(&state_leaf))));
+ container_members.insert(
+ "registers".to_string(),
+ CircuitMember::Variable(WeakType::Circuit(Arc::downgrade(®isters))),
+ );
+ container_members.insert(
+ "record".to_string(),
+ CircuitMember::Variable(WeakType::Circuit(Arc::downgrade(&record))),
+ );
+ container_members.insert(
+ "state".to_string(),
+ CircuitMember::Variable(WeakType::Circuit(Arc::downgrade(&state))),
+ );
+ container_members.insert(
+ "state_leaf".to_string(),
+ CircuitMember::Variable(WeakType::Circuit(Arc::downgrade(&state_leaf))),
+ );
let container_circuit = Arc::new(Circuit {
id: uuid::Uuid::new_v4(),
@@ -65,10 +95,22 @@ impl Input {
let state_leaf_body = Self::make_body(scope, &state_leaf);
let mut container_body_members = IndexMap::new();
- container_body_members.insert("registers".to_string(), CircuitMemberBody::Variable(Type::Circuit(registers.clone())));
- container_body_members.insert("record".to_string(), CircuitMemberBody::Variable(Type::Circuit(record.clone())));
- container_body_members.insert("state".to_string(), CircuitMemberBody::Variable(Type::Circuit(state.clone())));
- container_body_members.insert("state_leaf".to_string(), CircuitMemberBody::Variable(Type::Circuit(state_leaf.clone())));
+ container_body_members.insert(
+ "registers".to_string(),
+ CircuitMemberBody::Variable(Type::Circuit(registers.clone())),
+ );
+ container_body_members.insert(
+ "record".to_string(),
+ CircuitMemberBody::Variable(Type::Circuit(record.clone())),
+ );
+ container_body_members.insert(
+ "state".to_string(),
+ CircuitMemberBody::Variable(Type::Circuit(state.clone())),
+ );
+ container_body_members.insert(
+ "state_leaf".to_string(),
+ CircuitMemberBody::Variable(Type::Circuit(state_leaf.clone())),
+ );
let container_circuit_body = Arc::new(CircuitBody {
scope: scope.clone(),
@@ -101,11 +143,8 @@ impl Input {
impl Circuit {
pub fn is_input_psuedo_circuit(&self) -> bool {
match &*self.name.borrow().name {
- REGISTERS_PSUEDO_CIRCUIT |
- RECORD_PSUEDO_CIRCUIT |
- STATE_PSUEDO_CIRCUIT |
- STATE_LEAF_PSUEDO_CIRCUIT => true,
+ REGISTERS_PSUEDO_CIRCUIT | RECORD_PSUEDO_CIRCUIT | STATE_PSUEDO_CIRCUIT | STATE_LEAF_PSUEDO_CIRCUIT => true,
_ => false,
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/lib.rs b/asg/src/lib.rs
index f12222b7e0..9d3d9d8c82 100644
--- a/asg/src/lib.rs
+++ b/asg/src/lib.rs
@@ -1,3 +1,19 @@
+// Copyright (C) 2019-2020 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]
extern crate thiserror;
@@ -43,23 +59,26 @@ pub use reducer::*;
pub mod checks;
pub use checks::*;
-pub use leo_ast::{ Span, Identifier };
+pub use leo_ast::{Identifier, Span};
use std::path::Path;
pub fn load_ast, Y: AsRef>(path: T, content: Y) -> Result {
// Parses the Leo file and constructs a grammar ast.
- let ast = leo_grammar::Grammar::new(path.as_ref().clone(), content.as_ref())
+ let ast = leo_grammar::Grammar::new(path.as_ref(), content.as_ref())
.map_err(|e| AsgConvertError::InternalError(format!("ast: {:?}", e)))?;
// Parses the pest ast and constructs a Leo ast.
Ok(leo_ast::Ast::new("load_ast", &ast).into_repr())
}
-pub fn load_asg_from_ast(content: leo_ast::Program, resolver: &mut T) -> Result {
+pub fn load_asg_from_ast(
+ content: leo_ast::Program,
+ resolver: &mut T,
+) -> Result {
InnerProgram::new(&content, resolver)
}
pub fn load_asg(content: &str, resolver: &mut T) -> Result {
InnerProgram::new(&load_ast("input.leo", content)?, resolver)
-}
\ No newline at end of file
+}
diff --git a/asg/src/node.rs b/asg/src/node.rs
index 48fca47247..3e56ce9a0c 100644
--- a/asg/src/node.rs
+++ b/asg/src/node.rs
@@ -1,7 +1,22 @@
-use crate::{ PartialType, Span, Scope, AsgConvertError };
+// Copyright (C) 2019-2020 Aleo Systems Inc.
+// This file is part of the Leo library.
-pub trait Node {
+// 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::{AsgConvertError, PartialType, Scope, Span};
+
+pub trait Node {
fn span(&self) -> Option<&Span>;
}
diff --git a/asg/src/prelude.rs b/asg/src/prelude.rs
index 5bfe6b1aed..17da5b4fef 100644
--- a/asg/src/prelude.rs
+++ b/asg/src/prelude.rs
@@ -1,22 +1,38 @@
+// Copyright (C) 2019-2020 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 .
//todo: we should merge this with core
-use crate::{ Program, AsgConvertError };
+use crate::{AsgConvertError, Program};
// todo: make asg deep copy so we can cache resolved core modules
// todo: figure out how to do headers without bogus returns
pub fn resolve_core_module(module: &str) -> Result, AsgConvertError> {
match module {
- "unstable.blake2s" => {
- Ok(Some(crate::load_asg(r#"
+ "unstable.blake2s" => Ok(Some(crate::load_asg(
+ r#"
circuit Blake2s {
function hash(seed: [u8; 32], message: [u8; 32]) -> [u8; 32] {
return [0; 32]
}
}
- "#, &mut crate::NullImportResolver)?))
- },
+ "#,
+ &mut crate::NullImportResolver,
+ )?)),
_ => Ok(None),
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/program/circuit.rs b/asg/src/program/circuit.rs
index e3fc7d8467..d8fcc5f5d2 100644
--- a/asg/src/program/circuit.rs
+++ b/asg/src/program/circuit.rs
@@ -1,8 +1,26 @@
-use crate::{ Type, Identifier, Function, FunctionBody, Span, Node, AsgConvertError, InnerScope, Scope, WeakType };
+// Copyright (C) 2019-2020 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::{AsgConvertError, Function, FunctionBody, Identifier, InnerScope, Node, Scope, Span, Type, WeakType};
use indexmap::IndexMap;
-use std::sync::{ Arc, Weak };
-use std::cell::{ RefCell };
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
use uuid::Uuid;
pub enum CircuitMemberBody {
@@ -15,7 +33,6 @@ pub enum CircuitMember {
Function(Arc),
}
-
pub struct Circuit {
pub id: Uuid,
pub name: RefCell,
@@ -48,23 +65,20 @@ impl PartialEq for CircuitBody {
impl Eq for CircuitBody {}
impl Node for CircuitMemberBody {
-
fn span(&self) -> Option<&Span> {
None
}
}
-
impl Circuit {
pub(super) fn init(value: &leo_ast::Circuit) -> Result, AsgConvertError> {
-
let circuit = Arc::new(Circuit {
id: Uuid::new_v4(),
name: RefCell::new(value.circuit_name.clone()),
body: RefCell::new(Weak::new()),
members: RefCell::new(IndexMap::new()),
});
-
+
Ok(circuit)
}
@@ -76,13 +90,16 @@ impl Circuit {
for member in value.members.iter() {
match member {
leo_ast::CircuitMember::CircuitVariable(name, type_) => {
- members.insert(name.name.clone(), CircuitMember::Variable(new_scope.borrow().resolve_ast_type(type_)?.into()));
- },
+ members.insert(
+ name.name.clone(),
+ CircuitMember::Variable(new_scope.borrow().resolve_ast_type(type_)?.into()),
+ );
+ }
leo_ast::CircuitMember::CircuitFunction(function) => {
let asg_function = Arc::new(Function::from_ast(&new_scope, function)?);
members.insert(function.identifier.name.clone(), CircuitMember::Function(asg_function));
- },
+ }
}
}
@@ -91,15 +108,17 @@ impl Circuit {
func.circuit.borrow_mut().replace(Arc::downgrade(&self));
}
}
-
+
Ok(())
}
}
-
impl CircuitBody {
-
- pub(super) fn from_ast(scope: &Scope, value: &leo_ast::Circuit, circuit: Arc) -> Result {
+ pub(super) fn from_ast(
+ scope: &Scope,
+ value: &leo_ast::Circuit,
+ circuit: Arc,
+ ) -> Result {
let mut members = IndexMap::new();
let new_scope = InnerScope::make_subscope(scope);
new_scope.borrow_mut().circuit_self = Some(circuit.clone());
@@ -108,8 +127,11 @@ impl CircuitBody {
for member in value.members.iter() {
match member {
leo_ast::CircuitMember::CircuitVariable(name, type_) => {
- members.insert(name.name.clone(), CircuitMemberBody::Variable(new_scope.borrow().resolve_ast_type(type_)?));
- },
+ members.insert(
+ name.name.clone(),
+ CircuitMemberBody::Variable(new_scope.borrow().resolve_ast_type(type_)?),
+ );
+ }
leo_ast::CircuitMember::CircuitFunction(function) => {
let asg_function = {
let circuit_members = circuit.members.borrow();
@@ -121,8 +143,11 @@ impl CircuitBody {
let function_body = Arc::new(FunctionBody::from_ast(&new_scope, function, asg_function.clone())?);
asg_function.body.replace(Arc::downgrade(&function_body));
- members.insert(function.identifier.name.clone(), CircuitMemberBody::Function(function_body));
- },
+ members.insert(
+ function.identifier.name.clone(),
+ CircuitMemberBody::Function(function_body),
+ );
+ }
}
}
@@ -138,14 +163,19 @@ impl CircuitBody {
impl Into for &Circuit {
fn into(self) -> leo_ast::Circuit {
let members = match self.body.borrow().upgrade() {
- Some(body) => {
- body.members.borrow().iter().map(|(name, member)| {
- match &member {
- CircuitMemberBody::Variable(type_) => leo_ast::CircuitMember::CircuitVariable(Identifier::new(name.clone()), type_.into()),
- CircuitMemberBody::Function(func) => leo_ast::CircuitMember::CircuitFunction(func.function.as_ref().into()),
+ Some(body) => body
+ .members
+ .borrow()
+ .iter()
+ .map(|(name, member)| match &member {
+ CircuitMemberBody::Variable(type_) => {
+ leo_ast::CircuitMember::CircuitVariable(Identifier::new(name.clone()), type_.into())
+ }
+ CircuitMemberBody::Function(func) => {
+ leo_ast::CircuitMember::CircuitFunction(func.function.as_ref().into())
}
- }).collect()
- },
+ })
+ .collect(),
None => vec![],
};
leo_ast::Circuit {
@@ -153,4 +183,4 @@ impl Into for &Circuit {
members,
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/program/function.rs b/asg/src/program/function.rs
index 34a1514cbc..955144d221 100644
--- a/asg/src/program/function.rs
+++ b/asg/src/program/function.rs
@@ -1,8 +1,41 @@
-use crate::{ Identifier, Type, WeakType, Statement, Span, AsgConvertError, BlockStatement, FromAst, Scope, InnerScope, Circuit, Variable, ReturnPathReducer, MonoidalDirector };
+// Copyright (C) 2019-2020 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::{
+ AsgConvertError,
+ BlockStatement,
+ Circuit,
+ FromAst,
+ Identifier,
+ InnerScope,
+ MonoidalDirector,
+ ReturnPathReducer,
+ Scope,
+ Span,
+ Statement,
+ Type,
+ Variable,
+ WeakType,
+};
-use std::sync::{ Arc, Weak };
-use std::cell::RefCell;
use leo_ast::FunctionInput;
+use std::{
+ cell::RefCell,
+ sync::{Arc, Weak},
+};
use uuid::Uuid;
#[derive(PartialEq)]
@@ -50,7 +83,11 @@ impl Eq for FunctionBody {}
impl Function {
pub(crate) fn from_ast(scope: &Scope, value: &leo_ast::Function) -> Result {
- let output: Type = value.output.as_ref().map(|t| scope.borrow().resolve_ast_type(t)).transpose()?
+ let output: Type = value
+ .output
+ .as_ref()
+ .map(|t| scope.borrow().resolve_ast_type(t))
+ .transpose()?
.unwrap_or_else(|| Type::Tuple(vec![]));
let mut qualifier = FunctionQualifier::Static;
let mut has_input = false;
@@ -61,16 +98,16 @@ impl Function {
match input {
FunctionInput::InputKeyword(_) => {
has_input = true;
- },
+ }
FunctionInput::SelfKeyword(_) => {
qualifier = FunctionQualifier::SelfRef;
- },
+ }
FunctionInput::MutSelfKeyword(_) => {
qualifier = FunctionQualifier::MutSelfRef;
- },
+ }
FunctionInput::Variable(leo_ast::FunctionInputVariable { type_, .. }) => {
argument_types.push(scope.borrow().resolve_ast_type(&type_)?.into());
- },
+ }
}
}
}
@@ -88,12 +125,14 @@ impl Function {
qualifier,
})
}
-
}
-
impl FunctionBody {
- pub(super) fn from_ast(scope: &Scope, value: &leo_ast::Function, function: Arc) -> Result {
+ pub(super) fn from_ast(
+ scope: &Scope,
+ value: &leo_ast::Function,
+ function: Arc,
+ ) -> Result {
let new_scope = InnerScope::make_subscope(scope);
let mut arguments = vec![];
{
@@ -115,10 +154,15 @@ impl FunctionBody {
scope_borrow.function = Some(function.clone());
for input in value.input.iter() {
match input {
- FunctionInput::InputKeyword(_) => {},
- FunctionInput::SelfKeyword(_) => {},
- FunctionInput::MutSelfKeyword(_) => {},
- FunctionInput::Variable(leo_ast::FunctionInputVariable { identifier, mutable, type_, span: _span }) => {
+ FunctionInput::InputKeyword(_) => {}
+ FunctionInput::SelfKeyword(_) => {}
+ FunctionInput::MutSelfKeyword(_) => {}
+ FunctionInput::Variable(leo_ast::FunctionInputVariable {
+ identifier,
+ mutable,
+ type_,
+ span: _span,
+ }) => {
let variable = Arc::new(RefCell::new(crate::InnerVariable {
id: Uuid::new_v4(),
name: identifier.clone(),
@@ -131,17 +175,26 @@ impl FunctionBody {
}));
arguments.push(variable.clone());
scope_borrow.variables.insert(identifier.name.clone(), variable);
- },
+ }
}
}
}
let main_block = BlockStatement::from_ast(&new_scope, &value.block, None)?;
let mut director = MonoidalDirector::new(ReturnPathReducer::new());
if !director.reduce_block(&main_block).0 && !function.output.is_unit() {
- return Err(AsgConvertError::function_missing_return(&function.name.borrow().name, &value.span));
+ return Err(AsgConvertError::function_missing_return(
+ &function.name.borrow().name,
+ &value.span,
+ ));
}
+
+ #[allow(clippy::never_loop)] // TODO @Protryon: How should we return multiple errors?
for (span, error) in director.reducer().errors {
- return Err(AsgConvertError::function_return_validation(&function.name.borrow().name, &error, &span));
+ return Err(AsgConvertError::function_return_validation(
+ &function.name.borrow().name,
+ &error,
+ &span,
+ ));
}
Ok(FunctionBody {
@@ -157,9 +210,10 @@ impl FunctionBody {
impl Into for &Function {
fn into(self) -> leo_ast::Function {
let (input, body, span) = match self.body.borrow().upgrade() {
- Some(body) => {
- (
- body.arguments.iter().map(|variable| {
+ Some(body) => (
+ body.arguments
+ .iter()
+ .map(|variable| {
let variable = variable.borrow();
leo_ast::FunctionInput::Variable(leo_ast::FunctionInputVariable {
identifier: variable.name.clone(),
@@ -167,24 +221,22 @@ impl Into for &Function {
type_: (&variable.type_).into(),
span: Span::default(),
})
- }).collect(),
- match body.body.as_ref() {
- Statement::Block(block) => block.into(),
- _ => unimplemented!(),
- },
- body.span.clone().unwrap_or_default(),
- )
- },
- None => {
- (
- vec![],
- leo_ast::Block {
- statements: vec![],
- span: Default::default(),
- },
- Default::default(),
- )
- },
+ })
+ .collect(),
+ match body.body.as_ref() {
+ Statement::Block(block) => block.into(),
+ _ => unimplemented!(),
+ },
+ body.span.clone().unwrap_or_default(),
+ ),
+ None => (
+ vec![],
+ leo_ast::Block {
+ statements: vec![],
+ span: Default::default(),
+ },
+ Default::default(),
+ ),
};
let output: Type = self.output.clone().into();
leo_ast::Function {
@@ -195,4 +247,4 @@ impl Into for &Function {
span,
}
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/program/mod.rs b/asg/src/program/mod.rs
index 45079a7d44..b789efaf74 100644
--- a/asg/src/program/mod.rs
+++ b/asg/src/program/mod.rs
@@ -1,3 +1,18 @@
+// Copyright (C) 2019-2020 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 circuit;
pub use circuit::*;
@@ -5,12 +20,11 @@ pub use circuit::*;
mod function;
pub use function::*;
-use indexmap::{ IndexMap, IndexSet };
+use indexmap::{IndexMap, IndexSet};
-use std::sync::{ Arc };
-use crate::{ AsgConvertError, InnerScope, Scope, ImportResolver, Input };
-use std::cell::RefCell;
-use leo_ast::{Package, PackageAccess, Span, Identifier};
+use crate::{AsgConvertError, ImportResolver, InnerScope, Input, Scope};
+use leo_ast::{Identifier, Package, PackageAccess, Span};
+use std::{cell::RefCell, sync::Arc};
use uuid::Uuid;
#[derive(Clone)]
@@ -32,20 +46,28 @@ enum ImportSymbol {
All,
}
-fn resolve_import_package(output: &mut Vec<(Vec, ImportSymbol, Span)>, mut package_segments: Vec, package: &Package) {
+fn resolve_import_package(
+ output: &mut Vec<(Vec, ImportSymbol, Span)>,
+ mut package_segments: Vec,
+ package: &Package,
+) {
package_segments.push(package.name.name.clone());
resolve_import_package_access(output, &package_segments, &package.access);
}
-fn resolve_import_package_access(output: &mut Vec<(Vec, ImportSymbol, Span)>, package_segments: &Vec, package: &PackageAccess) {
+fn resolve_import_package_access(
+ output: &mut Vec<(Vec, ImportSymbol, Span)>,
+ package_segments: &Vec,
+ package: &PackageAccess,
+) {
match package {
PackageAccess::Star(span) => {
output.push((package_segments.clone(), ImportSymbol::All, span.clone()));
- },
+ }
PackageAccess::SubPackage(subpackage) => {
resolve_import_package(output, package_segments.clone(), &*subpackage);
- },
+ }
PackageAccess::Symbol(symbol) => {
let span = symbol.symbol.span.clone();
let symbol = if let Some(alias) = symbol.alias.as_ref() {
@@ -54,18 +76,16 @@ fn resolve_import_package_access(output: &mut Vec<(Vec, ImportSymbol, Sp
ImportSymbol::Direct(symbol.symbol.name.clone())
};
output.push((package_segments.clone(), symbol, span));
- },
+ }
PackageAccess::Multiple(subaccesses) => {
for subaccess in subaccesses.iter() {
resolve_import_package_access(output, &package_segments, &subaccess);
}
- },
-
+ }
}
}
impl InnerProgram {
-
/*
stages:
1. resolve imports into super scope
@@ -73,7 +93,10 @@ impl InnerProgram {
3. finalize declared functions
4. resolve all asg nodes
*/
- pub fn new<'a, T: ImportResolver + 'static>(value: &leo_ast::Program, import_resolver: &'a mut T) -> Result {
+ pub fn new<'a, T: ImportResolver + 'static>(
+ value: &leo_ast::Program,
+ import_resolver: &'a mut T,
+ ) -> Result {
// TODO: right now if some program A is imported from programs B and C, it will be copied to both, which is not optimal -- needs fixed
// recursively extract our imported symbols
@@ -90,14 +113,15 @@ impl InnerProgram {
let mut wrapped_resolver = crate::CoreImportResolver(import_resolver);
// load imported programs
- let mut resolved_packages: IndexMap, Program> = IndexMap::new();
+ let mut resolved_packages: IndexMap, Program> = IndexMap::new();
for (package, span) in deduplicated_imports.iter() {
let pretty_package = package.join(".");
- let resolved_package = match wrapped_resolver.resolve_package(&package.iter().map(|x| &**x).collect::>()[..], span)? {
- Some(x) => x,
- None => return Err(AsgConvertError::unresolved_import(&*pretty_package, &Span::default())), // todo: better span
- };
+ let resolved_package =
+ match wrapped_resolver.resolve_package(&package.iter().map(|x| &**x).collect::>()[..], span)? {
+ Some(x) => x,
+ None => return Err(AsgConvertError::unresolved_import(&*pretty_package, &Span::default())), // todo: better span
+ };
resolved_packages.insert(package.clone(), resolved_package);
}
@@ -109,31 +133,39 @@ impl InnerProgram {
for (package, symbol, span) in imported_symbols.into_iter() {
let pretty_package = package.join(".");
- let resolved_package = resolved_packages.get(&package).expect("could not find preloaded package");
+ let resolved_package = resolved_packages
+ .get(&package)
+ .expect("could not find preloaded package");
let resolved_package = resolved_package.borrow();
match symbol {
ImportSymbol::All => {
imported_functions.extend(resolved_package.functions.clone().into_iter());
imported_circuits.extend(resolved_package.circuits.clone().into_iter());
- },
+ }
ImportSymbol::Direct(name) => {
if let Some(function) = resolved_package.functions.get(&name) {
imported_functions.insert(name.clone(), function.clone());
} else if let Some(function) = resolved_package.circuits.get(&name) {
imported_circuits.insert(name.clone(), function.clone());
} else {
- return Err(AsgConvertError::unresolved_import(&*format!("{}.{}", pretty_package, name), &span));
+ return Err(AsgConvertError::unresolved_import(
+ &*format!("{}.{}", pretty_package, name),
+ &span,
+ ));
}
- },
+ }
ImportSymbol::Alias(name, alias) => {
if let Some(function) = resolved_package.functions.get(&name) {
imported_functions.insert(alias.clone(), function.clone());
} else if let Some(function) = resolved_package.circuits.get(&name) {
imported_circuits.insert(alias.clone(), function.clone());
} else {
- return Err(AsgConvertError::unresolved_import(&*format!("{}.{}", pretty_package, name), &span));
+ return Err(AsgConvertError::unresolved_import(
+ &*format!("{}.{}", pretty_package, name),
+ &span,
+ ));
}
- },
+ }
}
}
@@ -142,8 +174,14 @@ impl InnerProgram {
parent_scope: None,
circuit_self: None,
variables: IndexMap::new(),
- functions: imported_functions.iter().map(|(name, func)| (name.clone(), func.function.clone())).collect(),
- circuits: imported_circuits.iter().map(|(name, circuit)| (name.clone(), circuit.circuit.clone())).collect(),
+ functions: imported_functions
+ .iter()
+ .map(|(name, func)| (name.clone(), func.function.clone()))
+ .collect(),
+ circuits: imported_circuits
+ .iter()
+ .map(|(name, circuit)| (name.clone(), circuit.circuit.clone()))
+ .collect(),
function: None,
input: None,
}));
@@ -153,7 +191,7 @@ impl InnerProgram {
for (name, circuit) in value.circuits.iter() {
assert_eq!(name.name, circuit.circuit_name.name);
let asg_circuit = Circuit::init(circuit)?;
-
+
proto_circuits.insert(name.name.clone(), asg_circuit);
}
@@ -164,7 +202,10 @@ impl InnerProgram {
circuit_self: None,
variables: IndexMap::new(),
functions: IndexMap::new(),
- circuits: proto_circuits.iter().map(|(name, circuit)| (name.clone(), circuit.clone())).collect(),
+ circuits: proto_circuits
+ .iter()
+ .map(|(name, circuit)| (name.clone(), circuit.clone()))
+ .collect(),
function: None,
}));
@@ -187,7 +228,10 @@ impl InnerProgram {
assert_eq!(name.name, function.identifier.name);
let asg_function = Arc::new(Function::from_ast(&scope, function)?);
- scope.borrow_mut().functions.insert(name.name.clone(), asg_function.clone());
+ scope
+ .borrow_mut()
+ .functions
+ .insert(name.name.clone(), asg_function.clone());
proto_functions.insert(name.name.clone(), asg_function);
}
@@ -197,7 +241,11 @@ impl InnerProgram {
assert_eq!(name.name, test_function.function.identifier.name);
let function = proto_test_functions.get(&name.name).unwrap();
- let body = Arc::new(FunctionBody::from_ast(&scope, &test_function.function, function.clone())?);
+ let body = Arc::new(FunctionBody::from_ast(
+ &scope,
+ &test_function.function,
+ function.clone(),
+ )?);
function.body.replace(Arc::downgrade(&body));
test_functions.insert(name.name.clone(), (body, test_function.input_file.clone()));
@@ -228,7 +276,10 @@ impl InnerProgram {
test_functions,
functions,
circuits,
- imported_modules: resolved_packages.into_iter().map(|(package, program)| (package.join("."), program)).collect(),
+ imported_modules: resolved_packages
+ .into_iter()
+ .map(|(package, program)| (package.join("."), program))
+ .collect(),
scope,
})))
}
@@ -259,7 +310,11 @@ pub fn reform_ast(program: &Program) -> leo_ast::Program {
program_stack.extend(program.borrow().imported_modules.clone());
}
all_programs.insert("".to_string(), program.clone());
- let core_programs: Vec<_> = all_programs.iter().filter(|(module, _)| module.starts_with("core.")).map(|x| x.clone()).collect();
+ let core_programs: Vec<_> = all_programs
+ .iter()
+ .filter(|(module, _)| module.starts_with("core."))
+ .map(|x| x.clone())
+ .collect();
all_programs.retain(|module, _| !module.starts_with("core."));
let mut all_circuits: IndexMap> = IndexMap::new();
@@ -275,7 +330,7 @@ pub fn reform_ast(program: &Program) -> leo_ast::Program {
}
for (name, function) in program.functions.iter() {
let identifier = if name == "main" {
- "main".to_string()
+ "main".to_string()
} else {
format!("{}{}", identifiers.next().unwrap(), name)
};
@@ -288,33 +343,34 @@ pub fn reform_ast(program: &Program) -> leo_ast::Program {
all_test_functions.insert(identifier, function.clone());
}
}
-
+
//todo: core imports
leo_ast::Program {
name: "ast_aggregate".to_string(),
imports: vec![],
expected_input: vec![],
- tests: all_test_functions.into_iter().map(|(name, (function, ident))| {
- (
- function.function.name.borrow().clone(),
- leo_ast::TestFunction {
+ tests: all_test_functions
+ .into_iter()
+ .map(|(name, (function, ident))| {
+ (function.function.name.borrow().clone(), leo_ast::TestFunction {
function: function.function.as_ref().into(),
input_file: ident,
- }
- )
- }).collect(),
- functions: all_functions.into_iter().map(|(name, function)| {
- (
- function.function.name.borrow().clone(),
- function.function.as_ref().into(),
- )
- }).collect(),
- circuits: all_circuits.into_iter().map(|(name, circuit)| {
- (
- circuit.circuit.name.borrow().clone(),
- circuit.circuit.as_ref().into(),
- )
- }).collect(),
+ })
+ })
+ .collect(),
+ functions: all_functions
+ .into_iter()
+ .map(|(name, function)| {
+ (
+ function.function.name.borrow().clone(),
+ function.function.as_ref().into(),
+ )
+ })
+ .collect(),
+ circuits: all_circuits
+ .into_iter()
+ .map(|(name, circuit)| (circuit.circuit.name.borrow().clone(), circuit.circuit.as_ref().into()))
+ .collect(),
}
}
@@ -324,12 +380,31 @@ impl Into for &InnerProgram {
name: self.name.clone(),
imports: vec![],
expected_input: vec![],
- circuits: self.circuits.iter().map(|(_, circuit)| (circuit.circuit.name.borrow().clone(), circuit.circuit.as_ref().into())).collect(),
- functions: self.functions.iter().map(|(_, function)| (function.function.name.borrow().clone(), function.function.as_ref().into())).collect(),
- tests: self.test_functions.iter().map(|(_, function)| (function.0.function.name.borrow().clone(), leo_ast::TestFunction {
- function: function.0.function.as_ref().into(),
- input_file: function.1.clone(),
- })).collect(),
+ circuits: self
+ .circuits
+ .iter()
+ .map(|(_, circuit)| (circuit.circuit.name.borrow().clone(), circuit.circuit.as_ref().into()))
+ .collect(),
+ functions: self
+ .functions
+ .iter()
+ .map(|(_, function)| {
+ (
+ function.function.name.borrow().clone(),
+ function.function.as_ref().into(),
+ )
+ })
+ .collect(),
+ tests: self
+ .test_functions
+ .iter()
+ .map(|(_, function)| {
+ (function.0.function.name.borrow().clone(), leo_ast::TestFunction {
+ function: function.0.function.as_ref().into(),
+ input_file: function.1.clone(),
+ })
+ })
+ .collect(),
}
}
}
diff --git a/asg/src/reducer/mod.rs b/asg/src/reducer/mod.rs
index 15420a0f6d..393b1917b2 100644
--- a/asg/src/reducer/mod.rs
+++ b/asg/src/reducer/mod.rs
@@ -1,3 +1,18 @@
+// Copyright (C) 2019-2020 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 monoid;
pub use monoid::*;
diff --git a/asg/src/reducer/monoid/bool_and.rs b/asg/src/reducer/monoid/bool_and.rs
index 4a07bdfefb..fde095e99d 100644
--- a/asg/src/reducer/monoid/bool_and.rs
+++ b/asg/src/reducer/monoid/bool_and.rs
@@ -1,3 +1,19 @@
+// Copyright (C) 2019-2020 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 BoolAnd(pub bool);
@@ -13,10 +29,10 @@ impl Monoid for BoolAnd {
BoolAnd(self.0 && other.0)
}
- fn append_all(self, others: impl Iterator- ) -> Self {
+ fn append_all(self, others: impl Iterator
- ) -> Self {
for item in others {
if !item.0 {
- return BoolAnd(false)
+ return BoolAnd(false);
}
}
BoolAnd(true)
diff --git a/asg/src/reducer/monoid/mod.rs b/asg/src/reducer/monoid/mod.rs
index bd515e8802..e381f3b4c3 100644
--- a/asg/src/reducer/monoid/mod.rs
+++ b/asg/src/reducer/monoid/mod.rs
@@ -1,3 +1,18 @@
+// Copyright (C) 2019-2020 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 vec_append;
pub use vec_append::*;
@@ -11,7 +26,7 @@ pub use bool_and::*;
pub trait Monoid: Default {
fn append(self, other: Self) -> Self;
- fn append_all(self, others: impl Iterator- ) -> Self {
+ fn append_all(self, others: impl Iterator
- ) -> Self {
let mut current = self;
for item in others {
current = current.append(item);
diff --git a/asg/src/reducer/monoid/set_append.rs b/asg/src/reducer/monoid/set_append.rs
index 1ef47dc89c..c58774e6a3 100644
--- a/asg/src/reducer/monoid/set_append.rs
+++ b/asg/src/reducer/monoid/set_append.rs
@@ -1,3 +1,19 @@
+// Copyright (C) 2019-2020 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;
@@ -16,7 +32,7 @@ impl Monoid for SetAppend {
SetAppend(self.0)
}
- fn append_all(mut self, others: impl Iterator- ) -> Self {
+ 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);
@@ -31,4 +47,4 @@ impl Into> for SetAppend {
fn into(self) -> IndexSet {
self.0
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/reducer/monoid/vec_append.rs b/asg/src/reducer/monoid/vec_append.rs
index bd82feffe0..f38dc6d1db 100644
--- a/asg/src/reducer/monoid/vec_append.rs
+++ b/asg/src/reducer/monoid/vec_append.rs
@@ -1,3 +1,19 @@
+// Copyright (C) 2019-2020 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);
@@ -14,7 +30,7 @@ impl Monoid for VecAppend {
VecAppend(self.0)
}
- fn append_all(mut self, others: impl Iterator- ) -> Self {
+ 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);
@@ -29,4 +45,4 @@ impl Into> for VecAppend {
fn into(self) -> Vec {
self.0
}
-}
\ No newline at end of file
+}
diff --git a/asg/src/reducer/monoidal_director.rs b/asg/src/reducer/monoidal_director.rs
index abc7fa2e68..43a32085d5 100644
--- a/asg/src/reducer/monoidal_director.rs
+++ b/asg/src/reducer/monoidal_director.rs
@@ -1,7 +1,22 @@
+// Copyright (C) 2019-2020 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::*, statement::*, program::* };
-use std::sync::Arc;
-use std::marker::PhantomData;
+use crate::{expression::*, program::*, statement::*};
+use std::{marker::PhantomData, sync::Arc};
pub struct MonoidalDirector> {
reducer: R,
@@ -97,11 +112,11 @@ impl