Merge pull request #1579 from AleoHQ/migrate-leo-ast

Migrate leo ast
This commit is contained in:
Collin Chin 2022-01-31 11:17:57 -08:00 committed by GitHub
commit 6c7e7985e8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
108 changed files with 1137 additions and 658 deletions

5
Cargo.lock generated
View File

@ -1361,9 +1361,11 @@ dependencies = [
"indexmap",
"leo-errors",
"leo-input",
"leo-span",
"pest",
"serde",
"serde_json",
"smallvec",
"tendril",
]
@ -2654,6 +2656,9 @@ name = "smallvec"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2dd574626839106c320a323308629dcb1acfc96e32a8cba364ddc61ac23ee83"
dependencies = [
"serde",
]
[[package]]
name = "snarkvm-algorithms"

View File

@ -16,7 +16,10 @@ categories = [ "cryptography::cryptocurrencies", "web-programming" ]
include = [ "Cargo.toml", "src", "README.md", "LICENSE.md" ]
license = "GPL-3.0"
edition = "2021"
rust-version = "1.56.1"
rust-version = "1.56"
[dependencies]
smallvec = { version = "1.8.0", features = ["serde"] }
[dependencies.leo-input]
path = "../input"
@ -26,6 +29,10 @@ version = "1.5.3"
path = "../errors"
version = "1.5.3"
[dependencies.leo-span]
path = "../span"
version = "1.5.3"
[dependencies.indexmap]
version = "1.8.0"
features = [ "serde-1" ]

View File

@ -28,10 +28,10 @@ It stores the path to an import and what is being imported.
#### [Circuits](./src/circuits/circuit.rs)
A circuit node represents a defined Circuit in a Leo Program.
A order preserving map of these are stored on the Program.
Contains the Circuit's name, as well as it's members.
The members are a function, or a variable.
For both of them the Circuit preserves their names.
An order-preserving map of these are stored on the Program.
Contains the Circuit's name, as well as its members.
The members are a function, or a variable, or a constant.
For all of them the Circuit preserves their names.
#### [Decorators](./src/annotation.rs)
@ -42,7 +42,7 @@ The node stores the name of the annotation, as well as any args passed to it.
#### [Functions](./src/functions/function.rs)
A function node represents a defined function in a Leo Program.
A order preserving map of these are stored on the Program.
An order-preserving map of these are stored on the Program.
A function node stores the following information:
- The annotations applied to the function.
@ -54,7 +54,7 @@ A function node stores the following information:
#### [Global Consts](./src/program.rs)
A global const is a bit special and has no special node for itself, but rather is a definition statement.
A order preserving map of these are stored on the Program.
An order-preserving map of these are stored on the Program.
### [Types](./src/types/type_.rs)
@ -75,7 +75,7 @@ The char type resents a character from the inclusive range [0, 10FFFF].
#### Field
The field type an unsigned number up to the modulus length of the field.
The field type an unsigned number less than the modulus of the field.
#### Group
@ -127,15 +127,20 @@ A integer in the inclusive range [-170141183460469231731687303715884105728, 1701
#### Array
The array type contains another type, then the number of elements of that type greater than 0.
The array type contains another type,
then the number of elements of that type greater than 0
for monodimensional arrays,
or a list of such numbers of elements
for multidimensional arrays.
#### Tuple
The tuple type contains n types, where n is greater than or equal to 0.
#### Circuit
#### Identifier
The circuit type, every circuit represents a different type.
An identifier type is either a circuit type or a type alias;
every circuit type represents a different type.
#### SelfType
@ -153,9 +158,9 @@ An assignment statement node stores the following:
- **=**
- **+=**
- **-=**
- **=**
- **\*=**
- **/=**
- **=**
- **\*\*=**
- **&&=**
- **||=**
- The assignee which is a variable that has context of any access expressions on it.
@ -188,7 +193,7 @@ A definition statement node stores the following:
- The declaration type:
- `let` for mutable definitions.
- `const` for cosntant definitions.
- The names of the varaibles defined.
- The names of the variables defined.
- The optional type.
- The values to be assigned to the varaibles.
@ -204,7 +209,8 @@ A iteration statement node stores the following:
- The loop iterator variable name.
- The expression to define the starting loop value.
- The expression to define the stoping loop value.
- The expression to define the stopping loop value.
- A flag indicating whether the stopping value is inclusive or not.
- The block to run for the loop.
#### [Return Statements](./src/statements/return_statement.rs)
@ -213,11 +219,11 @@ A return statement node stores the following:
- The expression that is being returned.
### Expressions
### [Expressions](./src/expressions/mod.rs)
The expression nodes in a Leo Program.
#### [ArrayAccess Expressions](./src/expression/array_acces.rs)
#### [ArrayAccess Expressions](./src/accesses/array_access.rs)
An array access expression node stores the following:
@ -235,9 +241,9 @@ An array init expression node stores the following:
An array inline expression node stores the following:
- The elments of an array which is either an spread or an expression.
- The elements of an array, each of which is either a spread or an expression.
#### [ArrayRangeAccess Expressions](./src/expression/array_range_access.rs)
#### [ArrayRangeAccess Expressions](./src/accesses/array_range_access.rs)
An array range access expression node stores the following:
@ -278,21 +284,23 @@ A call expression node stores the following:
A circuit init expression node stores the following:
- The name of the circuit expression being initialized.
- The aruments a list of expressions.
- The arguments a list of expressions.
#### [CircuitMemberAccess Expressions](./src/expression/circuit_member_access.rs)
#### [MemberAccess Expressions](./src/accesses/member_access.rs)
A circuit member access expression node stores the following:
A member access expression node stores the following:
- The circut expression being accessed.
- The name of the expression being accessed from the circuit.
- The expression being accessed.
- The name of the member being accessed.
- The optional inferred type.
#### [CircuitStaticFunctionAccess Expressions](./src/expression/circuit_static_function_access.rs)
#### [StaticAccess Expressions](./src/accesses/static_access.rs)
A circuit static function access expression node stores the following:
A static function access expression node stores the following:
- The circut expression being accessed.
- The name of the expression being statically accessed from the circuit.
- The expression being accessed.
- The name of the member being statically accessed.
- The optional inferred type.
#### [Identifier Expressions](./src/common/identifier.rs)
@ -308,7 +316,7 @@ A ternary expression node stores the following:
- The expression returned if the condition is true.
- The expression returned if the condition is false.
#### [TupleAccess Expressions](./src/expression/tuple_access.rs)
#### [TupleAccess Expressions](./src/accesses/tuple_access.rs)
A tuple access expression node stores the following:

View File

@ -0,0 +1,49 @@
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Expression, Node};
use leo_span::Span;
use std::fmt;
use serde::{Deserialize, Serialize};
/// An array element access expression `array[index]`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArrayAccess {
/// The expression, evaluating to an array, that is being indexed.
pub array: Box<Expression>,
/// The index in `array` that is being accessed.
pub index: Box<Expression>,
/// The span of the entire expression `array[index]`.
pub span: Span,
}
impl fmt::Display for ArrayAccess {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}[{}]", self.array, self.index)
}
}
impl Node for ArrayAccess {
fn span(&self) -> &Span {
&self.span
}
fn set_span(&mut self, span: Span) {
self.span = span;
}
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -14,17 +14,29 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use super::*;
use crate::{Expression, Node};
use leo_span::Span;
use std::fmt;
use serde::{Deserialize, Serialize};
/// An access to a certain range of elements in an `array`.
///
/// Examples include `array[0..3]`, `array[3..]`, `array[..3]`, and `array[..]`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArrayRangeAccessExpression {
pub struct ArrayRangeAccess {
/// The array to extract a range of elements from.
pub array: Box<Expression>,
/// The lower bound of the index-range, or the start of the array when `None`.
pub left: Option<Box<Expression>>,
/// The higher bound of the index-range, or the end of the array when `None`.
pub right: Option<Box<Expression>>,
/// A span for the entire expression `array[<range>]`.
pub span: Span,
}
impl fmt::Display for ArrayRangeAccessExpression {
impl fmt::Display for ArrayRangeAccess {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
@ -36,7 +48,7 @@ impl fmt::Display for ArrayRangeAccessExpression {
}
}
impl Node for ArrayRangeAccessExpression {
impl Node for ArrayRangeAccess {
fn span(&self) -> &Span {
&self.span
}

View File

@ -0,0 +1,54 @@
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Expression, Identifier, Node};
use leo_span::Span;
use std::fmt;
use serde::{Deserialize, Serialize};
/// A field access expression `inner.name` to some structure with *named fields*.
///
/// For accesses to a positional fields in e.g., a tuple, see `TupleAccess`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemberAccess {
/// The structure that the field `name` is being extracted from.
pub inner: Box<Expression>,
/// The name of the field to extract in `inner`.
pub name: Identifier,
/// The span covering all of `inner.name`.
pub span: Span,
// FIXME(Centril): Type information shouldn't be injected into an AST,
// so this field should eventually be removed.
pub type_: Option<crate::Type>,
}
impl fmt::Display for MemberAccess {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}.{}", self.inner, self.name)
}
}
impl Node for MemberAccess {
fn span(&self) -> &Span {
&self.span
}
fn set_span(&mut self, span: Span) {
self.span = span;
}
}

30
ast/src/accesses/mod.rs Normal file
View File

@ -0,0 +1,30 @@
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
mod array_access;
pub use array_access::*;
mod array_range_access;
pub use array_range_access::*;
mod member_access;
pub use member_access::*;
mod tuple_access;
pub use tuple_access::*;
mod static_access;
pub use static_access::*;

View File

@ -0,0 +1,54 @@
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Expression, Identifier, Node, Type};
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;
/// An access expression to a static member, e.g., a constant in a circuit.
/// An example would be `Foo::Const` or `Foo::function` in `Foo::function()`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StaticAccess {
/// Represents the container for the static member to access.
/// Usually this is a circuit.
pub inner: Box<Expression>,
/// The static member in `inner` that is being accessed.
pub name: Identifier,
/// An optional type initially None, it is later assigned during type inference snapshot if necessary.
// FIXME(Centril): Shouldn't be in an AST. Remove it as part of an architectural revamp.
pub type_: Option<Type>,
/// The span for the entire expression `inner::name`.
pub span: Span,
}
impl fmt::Display for StaticAccess {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}::{}", self.inner, self.name)
}
}
impl Node for StaticAccess {
fn span(&self) -> &Span {
&self.span
}
fn set_span(&mut self, span: Span) {
self.span = span;
}
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -14,23 +14,31 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use super::*;
use crate::{Expression, Node, PositiveNumber};
use leo_span::Span;
use std::fmt;
use serde::{Deserialize, Serialize};
/// An tuple access expression, e.g., `tuple.index`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CircuitMemberAccessExpression {
pub circuit: Box<Expression>,
pub name: Identifier,
pub struct TupleAccess {
/// An expression evaluating to some tuple type, e.g., `(5, 2)`.
pub tuple: Box<Expression>,
/// The index to access in the tuple expression. E.g., `0` for `(5, 2)` would yield `5`.
pub index: PositiveNumber,
/// The span for the entire expression `tuple.index`.
pub span: Span,
pub type_: Option<crate::Type>,
}
impl fmt::Display for CircuitMemberAccessExpression {
impl fmt::Display for TupleAccess {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}.{}", self.circuit, self.name)
write!(f, "{}.{}", self.tuple, self.index)
}
}
impl Node for CircuitMemberAccessExpression {
impl Node for TupleAccess {
fn span(&self) -> &Span {
&self.span
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,16 +15,23 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Identifier, Type};
use leo_errors::Span;
use leo_span::Span;
use std::fmt;
use serde::{Deserialize, Serialize};
/// A type alias `type name = represents;`.
///
/// That is, `name` will become another name for `represents`.
/// This does not create a new type, that is, `name` is the same type as `represents`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Alias {
/// The new name for `represents`.
pub name: Identifier,
/// A span for the entire `type name = represents;`.
pub span: Span,
/// The type that `name` will evaluate and is equal to.
pub represents: Type,
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,15 +15,32 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::Identifier;
use leo_errors::Span;
use leo_span::{sym, Span, Symbol};
use serde::{Deserialize, Serialize};
use tendril::StrTendril;
use std::fmt;
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct Annotation {
pub span: Span,
pub name: Identifier,
#[serde(with = "crate::common::vec_tendril_json")]
pub arguments: Vec<StrTendril>,
pub arguments: Vec<Symbol>,
}
const ALLOWED_ANNOTATIONS: &[Symbol] = &[sym::test];
impl Annotation {
pub fn is_valid_annotation(&self) -> bool {
ALLOWED_ANNOTATIONS.iter().any(|name| self.name.name == *name)
}
}
impl fmt::Display for Annotation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "@{:}(", self.name)?;
for arg in &self.arguments {
write!(f, "{:},", arg)?;
}
write!(f, ")")
}
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
// use serde::de::{Deserialize as SerDeserialize, Deserializer};

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -19,10 +19,17 @@ use crate::{CircuitMember, Identifier};
use serde::{Deserialize, Serialize};
use std::fmt;
/// A record type definition, e.g., `circuit Foo { my_field: Bar }`.
/// In some languages these are called `struct`s.
///
/// Type identity is decided by the full path including `circuit_name`,
/// as the record is nominal, not structural.
/// The fields are named so `circuit Foo(u8, u16)` is not allowed.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Circuit {
/// The name of the type in the type system in this module.
pub circuit_name: Identifier,
pub core_mapping: std::cell::RefCell<Option<String>>,
/// The fields, constant variables, and functions of this structure.
pub members: Vec<CircuitMember>,
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -14,22 +14,48 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Function, Identifier, Type};
use crate::{Expression, Function, Identifier, Type};
use serde::{Deserialize, Serialize};
use std::fmt;
#[allow(clippy::large_enum_variant)]
/// A member of a circuit definition.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CircuitMember {
// (variable_name, variable_type)
CircuitVariable(Identifier, Type),
// (function)
CircuitFunction(Function),
/// A static constant in a circuit.
/// For example: `const foobar: u8 = 42;`.
CircuitConst(
/// The identifier of the constant.
Identifier,
/// The type the constant has.
Type,
/// The expression representing the constant's value.
/// Checked to be of the type above.
Expression,
),
/// A varible definition in a circuit;
/// For example: `foobar: u8;`.
CircuitVariable(
/// The identifier of the constant.
Identifier,
/// The type the constant has.
Type,
),
/// A function definition in a circuit.
/// For example: `function bar() -> u8 { return 2u8; }`.
CircuitFunction(
/// The function.
Box<Function>,
),
}
impl fmt::Display for CircuitMember {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CircuitMember::CircuitConst(ref identifier, ref type_, ref value) => {
write!(f, "{}: {} = {}", identifier, type_, value)
}
CircuitMember::CircuitVariable(ref identifier, ref type_) => write!(f, "{}: {}", identifier, type_),
CircuitMember::CircuitFunction(ref function) => write!(f, "{}", function),
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -17,11 +17,5 @@
pub mod circuit;
pub use circuit::*;
pub mod circuit_variable_definition;
pub use circuit_variable_definition::*;
pub mod circuit_implied_variable_definition;
pub use circuit_implied_variable_definition::*;
pub mod circuit_member;
pub use circuit_member::*;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -17,102 +17,129 @@
use crate::PositiveNumber;
use leo_input::types::ArrayDimensions as InputArrayDimensions;
use serde::{Deserialize, Serialize};
use std::fmt;
use serde::{ser::SerializeSeq, Deserialize, Serialize, Serializer};
use smallvec::{smallvec, SmallVec};
use std::{fmt, ops::Deref};
/// A vector of positive numbers that represent array dimensions.
/// Can be used in an array [`Type`] or an array initializer [`Expression`].
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, Default, Hash)]
pub struct ArrayDimensions(pub Vec<PositiveNumber>);
/// A single array dimension.
#[derive(Clone, Deserialize, Debug, PartialEq, Eq, Hash)]
pub enum Dimension {
/// The dimension is `_`, that is unspecified and syntactically unknown.
Unspecified,
/// The dimension was specified, e.g., `5` elements.
Number(PositiveNumber),
}
impl fmt::Display for Dimension {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Unspecified => write!(f, "_"),
Self::Number(num) => write!(f, "{}", num),
}
}
}
impl Dimension {
/// } Returns `Some(n)` unless the dimension is [`Unspecified`].
pub fn as_specified(&self) -> Option<&PositiveNumber> {
match self {
Self::Unspecified => None,
Self::Number(n) => Some(n),
}
}
/// Returns true if the dimension is known to be zero.
fn is_zero(&self) -> bool {
self.as_specified().filter(|n| n.is_zero()).is_some()
}
}
/// Specifies array dimensions for array [`Type`]s or in array initializer [`Expression`]s.
#[derive(Clone, Deserialize, Debug, PartialEq, Eq, Hash)]
pub struct ArrayDimensions(pub SmallVec<[Dimension; 1]>);
impl Deref for ArrayDimensions {
type Target = [Dimension];
fn deref(&self) -> &Self::Target {
&*self.0
}
}
impl ArrayDimensions {
///
/// Appends a vector of array dimensions to the self array dimensions.
///
pub fn append(&mut self, other: &mut ArrayDimensions) {
self.0.append(&mut other.0)
pub fn single(dim: Dimension) -> Self {
Self(smallvec![dim])
}
///
/// Returns the array dimensions as strings.
///
pub fn to_strings(&self) -> Vec<String> {
self.0.iter().map(|number| number.to_string()).collect()
/// Returns true if the dimensions are not [`Unspecified`].
pub fn is_specified(&self) -> bool {
!self.contains(&Dimension::Unspecified)
}
///
/// Returns `true` if the all array dimensions have been removed.
///
/// This method is called after repeated calls to `remove_first`.
///
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
///
/// Returns `true` if there is an array dimension equal to zero.
///
pub fn is_zero(&self) -> bool {
self.0.iter().any(|number| number.is_zero())
self.iter().any(|d| d.is_zero())
}
///
/// Returns the first dimension of the array.
///
pub fn first(&self) -> Option<&PositiveNumber> {
self.0.first()
/// Attempts to remove the first dimension from the array, or returns `None` if it doesn't.
pub fn remove_first(&mut self) -> Option<Dimension> {
if self.is_empty() {
None
} else {
Some(self.0.remove(0))
}
}
///
/// Attempts to remove the first dimension from the array.
///
/// If the first dimension exists, then remove and return `Some(PositiveNumber)`.
/// If the first dimension does not exist, then return `None`.
///
pub fn remove_first(&mut self) -> Option<PositiveNumber> {
// If there are no dimensions in the array, then return None.
self.0.first()?;
// Remove the first dimension.
let removed = self.0.remove(0);
// Return the first dimension.
Some(removed)
}
///
/// Attempts to remove the last dimension from the array.
///
/// If the last dimension exists, then remove and return `Some(PositiveNumber)`.
/// If the last dimension does not exist, then return `None`.
///
pub fn remove_last(&mut self) -> Option<PositiveNumber> {
/// Attempts to remove the last dimension from the array, or returns `None` if it doesn't.
pub fn remove_last(&mut self) -> Option<Dimension> {
self.0.pop()
}
}
/// Custom Serializer for ArrayDimensios is required to ignore internal ArrayDimension nodes in the AST.
impl Serialize for ArrayDimensions {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
for dim in self.0.iter() {
match dim {
Dimension::Number(num) => seq.serialize_element(&num)?,
Dimension::Unspecified => seq.serialize_element(&PositiveNumber { value: "0".into() })?,
}
}
seq.end()
}
}
/// Create a new [`ArrayDimensions`] from a [`InputArrayDimensions`] in a Leo program file.
impl<'ast> From<InputArrayDimensions<'ast>> for ArrayDimensions {
fn from(dimensions: InputArrayDimensions<'ast>) -> Self {
Self(match dimensions {
InputArrayDimensions::Single(single) => vec![PositiveNumber::from(single.number)],
InputArrayDimensions::Multiple(multiple) => {
multiple.numbers.into_iter().map(PositiveNumber::from).collect()
match dimensions {
InputArrayDimensions::Single(single) => {
Self(smallvec![Dimension::Number(PositiveNumber::from(single.number))])
}
})
InputArrayDimensions::Multiple(multiple) => Self(
multiple
.numbers
.into_iter()
.map(|num| Dimension::Number(PositiveNumber::from(num)))
.collect(),
),
}
}
}
impl fmt::Display for ArrayDimensions {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.0.len() == 1 {
// Write dimensions without parenthesis.
write!(f, "{}", self.0[0])
} else {
// Write dimensions with parenthesis.
let dimensions = self.0.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
write!(f, "({})", dimensions)
match &*self.0 {
[dim] => write!(f, "{}", dim),
dimensions => write!(
f,
"({})",
dimensions.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ")
),
}
}
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Identifier, Node};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -16,6 +16,8 @@
use crate::{DefinitionStatement, Identifier};
use leo_span::Symbol;
use indexmap::IndexMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
@ -46,7 +48,7 @@ pub fn deserialize<'de, D: Deserializer<'de>>(
(
name.split(',')
.map(|ident_name| Identifier {
name: ident_name.into(),
name: Symbol::intern(ident_name),
span: Default::default(),
})
.collect::<Vec<Identifier>>(),

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -14,9 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_errors::Span;
use leo_input::common::Identifier as InputIdentifier;
use tendril::StrTendril;
use leo_span::{Span, Symbol};
use crate::Node;
use serde::{
@ -38,7 +37,7 @@ use std::{
/// to reflect the new struct instantiation.
#[derive(Clone)]
pub struct Identifier {
pub name: StrTendril,
pub name: Symbol,
pub span: Span,
}
@ -53,20 +52,13 @@ impl Node for Identifier {
}
impl Identifier {
pub fn new(name: StrTendril) -> Self {
pub fn new(name: Symbol) -> Self {
Self {
name,
span: Span::default(),
}
}
pub fn new_with_span(name: &str, span: Span) -> Self {
Self {
name: name.into(),
span,
}
}
/// Check if the Identifier name matches the other name
pub fn matches(&self, other: &Self) -> bool {
self.name == other.name
@ -76,7 +68,7 @@ impl Identifier {
impl<'ast> From<InputIdentifier<'ast>> for Identifier {
fn from(identifier: InputIdentifier<'ast>) -> Self {
Self {
name: identifier.value.into(),
name: Symbol::intern(&identifier.value),
span: Span::from(identifier.span),
}
}
@ -149,7 +141,7 @@ impl<'de> Deserialize<'de> for Identifier {
let key: BTreeMap<String, String> = to_json_string(value)?;
let name = match key.get("name") {
Some(name) => name.clone(),
Some(name) => Symbol::intern(name),
None => return Err(E::custom("missing 'name' in serialized Identifier struct")),
};
@ -158,10 +150,7 @@ impl<'de> Deserialize<'de> for Identifier {
None => return Err(E::custom("missing 'span' in serialized Identifier struct")),
};
Ok(Identifier {
name: name.into(),
span,
})
Ok(Identifier { name, span })
}
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -16,34 +16,30 @@
use crate::Program;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use leo_span::Symbol;
use indexmap::IndexMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[allow(clippy::ptr_arg)]
pub fn serialize<S: Serializer>(
imported_modules: &IndexMap<Vec<String>, Program>,
imported_modules: &IndexMap<Vec<Symbol>, Program>,
serializer: S,
) -> Result<S::Ok, S::Error> {
let joined: IndexMap<String, Program> = imported_modules
.into_iter()
.map(|(package, program)| (package.join("."), program.clone()))
.map(|(package, program)| {
let package = package.iter().map(|x| x.as_str().to_string()).collect::<Vec<_>>();
(package.join("."), program.clone())
})
.collect();
joined.serialize(serializer)
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<IndexMap<Vec<String>, Program>, D::Error> {
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<IndexMap<Vec<Symbol>, Program>, D::Error> {
Ok(IndexMap::<String, Program>::deserialize(deserializer)?
.into_iter()
.map(|(package, program)| {
(
package
.split('.')
.map(|segment| segment.to_string())
.collect::<Vec<String>>(),
program,
)
})
.map(|(package, program)| (package.split('.').map(Symbol::intern).collect(), program))
.collect())
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,25 +15,25 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Identifier, Node};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;
/// The `mut self` keyword can view and modify circuit values inside of a circuit function.
/// The `&self` keyword can view and modify circuit values inside of a circuit function.
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[serde(transparent)]
pub struct MutSelfKeyword {
pub struct RefSelfKeyword {
pub identifier: Identifier,
}
impl fmt::Display for MutSelfKeyword {
impl fmt::Display for RefSelfKeyword {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "mut self")
write!(f, "&self")
}
}
impl Node for MutSelfKeyword {
impl Node for RefSelfKeyword {
fn span(&self) -> &Span {
&self.identifier.span
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -23,7 +23,7 @@ use tendril::StrTendril;
/// A number string guaranteed to be positive by the pest grammar.
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, Hash)]
pub struct PositiveNumber {
#[serde(with = "leo_errors::common::tendril_json")]
#[serde(with = "leo_span::tendril_json")]
pub value: StrTendril,
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Identifier, Node};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Expression, Node};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -0,0 +1,67 @@
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use super::*;
use crate::accesses::*;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AccessExpression {
Array(ArrayAccess),
ArrayRange(ArrayRangeAccess),
Member(MemberAccess),
Tuple(TupleAccess),
Static(StaticAccess),
}
impl fmt::Display for AccessExpression {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use AccessExpression::*;
match self {
Array(access) => access.fmt(f),
ArrayRange(access) => access.fmt(f),
Member(access) => access.fmt(f),
Tuple(access) => access.fmt(f),
Static(access) => access.fmt(f),
}
}
}
impl Node for AccessExpression {
fn span(&self) -> &Span {
use AccessExpression::*;
match &self {
Array(access) => access.span(),
ArrayRange(access) => access.span(),
Member(access) => access.span(),
Tuple(access) => access.span(),
Static(access) => access.span(),
}
}
fn set_span(&mut self, span: Span) {
use AccessExpression::*;
match self {
Array(access) => access.set_span(span),
ArrayRange(access) => access.set_span(span),
Member(access) => access.set_span(span),
Tuple(access) => access.set_span(span),
Static(access) => access.set_span(span),
}
}
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -16,7 +16,7 @@
use super::*;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BinaryOperation {
Add,
Sub,

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -16,26 +16,47 @@
use super::*;
/// An initializer for a single field / variable of a circuit initializer expression.
/// That is, in `Foo { bar: 42, baz }`, this is either `bar: 42`, or `baz`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CircuitVariableInitializer {
/// The name of the field / variable to be initialized.
pub identifier: Identifier,
/// The expression to initialize the field with.
/// When `None`, a binding, in scope, with the name will be used instead.
pub expression: Option<Expression>,
}
impl fmt::Display for CircuitVariableInitializer {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(expr) = &self.expression {
write!(f, "{}: {}", self.identifier, expr)
} else {
write!(f, "{}", self.identifier)
}
}
}
/// A circuit initialization expression, e.g., `Foo { bar: 42, baz }`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CircuitInitExpression {
/// The name of the structure type to initialize.
pub name: Identifier,
pub members: Vec<CircuitImpliedVariableDefinition>,
/// Initializer expressions for each of the fields in the circuit.
///
/// N.B. Any functions or member constants in the circuit definition
/// are excluded from this list.
pub members: Vec<CircuitVariableInitializer>,
/// A span from `name` to `}`.
pub span: Span,
}
impl fmt::Display for CircuitInitExpression {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {{", self.name)?;
for (i, member) in self.members.iter().enumerate() {
if let Some(expression) = &member.expression {
write!(f, "{}: {}", member.identifier, expression)?;
} else {
write!(f, "{}", member.identifier)?;
}
if i < self.members.len() - 1 {
write!(f, ", ")?;
}
for member in self.members.iter() {
write!(f, "{}", member)?;
write!(f, ", ")?;
}
write!(f, "}}")
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -14,23 +14,20 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
// use crate::Type;
use super::*;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LengthOfExpression {
pub inner: Box<Expression>,
pub struct ErrExpression {
pub span: Span,
}
impl fmt::Display for LengthOfExpression {
impl fmt::Display for ErrExpression {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}.len()", self.inner)
f.write_str("error")
}
}
impl Node for LengthOfExpression {
impl Node for ErrExpression {
fn span(&self) -> &Span {
&self.span
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -17,19 +17,19 @@
use super::*;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CircuitStaticFunctionAccessExpression {
pub circuit: Box<Expression>,
pub name: Identifier,
pub struct FromBitsExpression {
pub named_type: Box<Expression>,
pub arg: Box<Expression>,
pub span: Span,
}
impl fmt::Display for CircuitStaticFunctionAccessExpression {
impl fmt::Display for FromBitsExpression {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}.{}", self.circuit, self.name)
write!(f, "{}.from_bits({})", self.named_type, self.arg)
}
}
impl Node for CircuitStaticFunctionAccessExpression {
impl Node for FromBitsExpression {
fn span(&self) -> &Span {
&self.span
}

View File

@ -0,0 +1,40 @@
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use super::*;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FromBytesExpression {
pub named_type: Box<Expression>,
pub arg: Box<Expression>,
pub span: Span,
}
impl fmt::Display for FromBytesExpression {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}.from_bytes({})", self.named_type, self.arg)
}
}
impl Node for FromBytesExpression {
fn span(&self) -> &Span {
&self.span
}
fn set_span(&mut self, span: Span) {
self.span = span;
}
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -14,38 +14,27 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
ArrayDimensions, CircuitImpliedVariableDefinition, GroupValue, Identifier, IntegerType, Node, PositiveNumber,
SpreadOrExpression,
};
use crate::{ArrayDimensions, GroupValue, Identifier, IntegerType, Node, SpreadOrExpression};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;
mod accesses;
pub use accesses::*;
mod binary;
pub use binary::*;
mod unary;
pub use unary::*;
mod ternary;
pub use ternary::*;
mod array_access;
pub use array_access::*;
mod array_range_access;
pub use array_range_access::*;
mod array_inline;
pub use array_inline::*;
mod array_init;
pub use array_init::*;
mod tuple_access;
pub use tuple_access::*;
mod tuple_init;
pub use tuple_init::*;
mod circuit_static_function_access;
pub use circuit_static_function_access::*;
mod circuit_member_access;
pub use circuit_member_access::*;
mod circuit_init;
pub use circuit_init::*;
mod value;
@ -54,8 +43,8 @@ mod call;
pub use call::*;
mod cast;
pub use cast::*;
mod lengthof;
pub use lengthof::*;
mod err;
pub use err::*;
/// Expression that evaluates to a value
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@ -66,21 +55,20 @@ pub enum Expression {
Unary(UnaryExpression),
Ternary(TernaryExpression),
Cast(CastExpression),
LengthOf(LengthOfExpression),
Access(AccessExpression),
ArrayInline(ArrayInlineExpression),
ArrayInit(ArrayInitExpression),
ArrayAccess(ArrayAccessExpression),
ArrayRangeAccess(ArrayRangeAccessExpression),
TupleInit(TupleInitExpression),
TupleAccess(TupleAccessExpression),
CircuitInit(CircuitInitExpression),
CircuitMemberAccess(CircuitMemberAccessExpression),
CircuitStaticFunctionAccess(CircuitStaticFunctionAccessExpression),
Call(CallExpression),
/// An expression of type "error".
/// Will result in a compile error eventually.
Err(ErrExpression),
}
impl Node for Expression {
@ -94,16 +82,12 @@ impl Node for Expression {
Ternary(n) => n.span(),
ArrayInline(n) => n.span(),
ArrayInit(n) => n.span(),
ArrayAccess(n) => n.span(),
ArrayRangeAccess(n) => n.span(),
TupleInit(n) => n.span(),
TupleAccess(n) => n.span(),
CircuitInit(n) => n.span(),
CircuitMemberAccess(n) => n.span(),
CircuitStaticFunctionAccess(n) => n.span(),
Call(n) => n.span(),
Cast(n) => n.span(),
LengthOf(n) => n.span(),
Access(n) => n.span(),
Err(n) => n.span(),
}
}
@ -117,16 +101,12 @@ impl Node for Expression {
Ternary(n) => n.set_span(span),
ArrayInline(n) => n.set_span(span),
ArrayInit(n) => n.set_span(span),
ArrayAccess(n) => n.set_span(span),
ArrayRangeAccess(n) => n.set_span(span),
TupleInit(n) => n.set_span(span),
TupleAccess(n) => n.set_span(span),
CircuitInit(n) => n.set_span(span),
CircuitMemberAccess(n) => n.set_span(span),
CircuitStaticFunctionAccess(n) => n.set_span(span),
Call(n) => n.set_span(span),
Cast(n) => n.set_span(span),
LengthOf(n) => n.set_span(span),
Access(n) => n.set_span(span),
Err(n) => n.set_span(span),
}
}
}
@ -142,16 +122,12 @@ impl fmt::Display for Expression {
Ternary(n) => n.fmt(f),
ArrayInline(n) => n.fmt(f),
ArrayInit(n) => n.fmt(f),
ArrayAccess(n) => n.fmt(f),
ArrayRangeAccess(n) => n.fmt(f),
TupleInit(n) => n.fmt(f),
TupleAccess(n) => n.fmt(f),
CircuitInit(n) => n.fmt(f),
CircuitMemberAccess(n) => n.fmt(f),
CircuitStaticFunctionAccess(n) => n.fmt(f),
Call(n) => n.fmt(f),
Cast(n) => n.fmt(f),
LengthOf(n) => n.fmt(f),
Access(n) => n.fmt(f),
Err(n) => n.fmt(f),
}
}
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -17,19 +17,18 @@
use super::*;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TupleAccessExpression {
pub tuple: Box<Expression>,
pub index: PositiveNumber,
pub struct ToBitsExpression {
pub value: Box<Expression>,
pub span: Span,
}
impl fmt::Display for TupleAccessExpression {
impl fmt::Display for ToBitsExpression {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}.{}", self.tuple, self.index)
write!(f, "{}.to_bits()", self.value)
}
}
impl Node for TupleAccessExpression {
impl Node for ToBitsExpression {
fn span(&self) -> &Span {
&self.span
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -17,19 +17,18 @@
use super::*;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArrayAccessExpression {
pub array: Box<Expression>,
pub index: Box<Expression>,
pub struct ToBytesExpression {
pub value: Box<Expression>,
pub span: Span,
}
impl fmt::Display for ArrayAccessExpression {
impl fmt::Display for ToBytesExpression {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}[{}]", self.array, self.index)
write!(f, "{}.to_bytes()", self.value)
}
}
impl Node for ArrayAccessExpression {
impl Node for ToBytesExpression {
fn span(&self) -> &Span {
&self.span
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -23,29 +23,29 @@ use crate::{Char, CharValue};
pub enum ValueExpression {
// todo: deserialize values here
Address(
#[serde(with = "leo_errors::common::tendril_json")] StrTendril,
#[serde(with = "leo_errors::common::span_json")] Span,
#[serde(with = "leo_span::tendril_json")] StrTendril,
#[serde(with = "leo_span::span_json")] Span,
),
Boolean(
#[serde(with = "leo_errors::common::tendril_json")] StrTendril,
#[serde(with = "leo_errors::common::span_json")] Span,
#[serde(with = "leo_span::tendril_json")] StrTendril,
#[serde(with = "leo_span::span_json")] Span,
),
Char(CharValue),
Field(
#[serde(with = "leo_errors::common::tendril_json")] StrTendril,
#[serde(with = "leo_errors::common::span_json")] Span,
#[serde(with = "leo_span::tendril_json")] StrTendril,
#[serde(with = "leo_span::span_json")] Span,
),
Group(Box<GroupValue>),
Implicit(
#[serde(with = "leo_errors::common::tendril_json")] StrTendril,
#[serde(with = "leo_errors::common::span_json")] Span,
#[serde(with = "leo_span::tendril_json")] StrTendril,
#[serde(with = "leo_span::span_json")] Span,
),
Integer(
IntegerType,
#[serde(with = "leo_errors::common::tendril_json")] StrTendril,
#[serde(with = "leo_errors::common::span_json")] Span,
#[serde(with = "leo_span::tendril_json")] StrTendril,
#[serde(with = "leo_span::span_json")] Span,
),
String(Vec<Char>, #[serde(with = "leo_errors::common::span_json")] Span),
String(Vec<Char>, #[serde(with = "leo_span::span_json")] Span),
}
impl fmt::Display for ValueExpression {

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,17 +15,21 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Annotation, Block, FunctionInput, Identifier, Node, Type};
use leo_errors::Span;
use leo_span::{sym, Span, Symbol};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::cell::Cell;
use std::fmt;
#[derive(Clone, Serialize, Deserialize)]
pub struct Function {
pub annotations: Vec<Annotation>,
pub annotations: IndexMap<Symbol, Annotation>,
pub identifier: Identifier,
pub input: Vec<FunctionInput>,
pub const_: bool,
pub output: Option<Type>,
pub core_mapping: Cell<Option<Symbol>>,
pub block: Block,
pub span: Span,
}
@ -39,8 +43,14 @@ impl PartialEq for Function {
impl Eq for Function {}
impl Function {
pub fn get_name(&self) -> &str {
&self.identifier.name
/// Returns function name.
pub fn name(&self) -> Symbol {
self.identifier.name
}
/// Returns `true` if the function name is `main`.
pub fn is_main(&self) -> bool {
self.name() == sym::main
}
///
@ -66,6 +76,9 @@ impl Function {
self.input.iter().filter(|input| !input.is_self())
}
///
/// Private formatting method used for optimizing [fmt::Debug] and [fmt::Display] implementations.
///
fn format(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "function {}", self.identifier)?;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Identifier, Node, Type};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -14,8 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ConstSelfKeyword, FunctionInputVariable, MutSelfKeyword, Node, SelfKeyword};
use leo_errors::Span;
use crate::{ConstSelfKeyword, FunctionInputVariable, Node, RefSelfKeyword, SelfKeyword};
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;
@ -25,7 +25,7 @@ use std::fmt;
pub enum FunctionInput {
SelfKeyword(SelfKeyword),
ConstSelfKeyword(ConstSelfKeyword),
MutSelfKeyword(MutSelfKeyword),
RefSelfKeyword(RefSelfKeyword),
Variable(FunctionInputVariable),
}
@ -38,7 +38,7 @@ impl FunctionInput {
match self {
FunctionInput::SelfKeyword(_) => true,
FunctionInput::ConstSelfKeyword(_) => true,
FunctionInput::MutSelfKeyword(_) => true,
FunctionInput::RefSelfKeyword(_) => true,
FunctionInput::Variable(_) => false,
}
}
@ -51,7 +51,7 @@ impl FunctionInput {
match self {
FunctionInput::SelfKeyword(_) => false,
FunctionInput::ConstSelfKeyword(_) => true,
FunctionInput::MutSelfKeyword(_) => false,
FunctionInput::RefSelfKeyword(_) => false,
FunctionInput::Variable(_) => false,
}
}
@ -64,16 +64,28 @@ impl FunctionInput {
match self {
FunctionInput::SelfKeyword(_) => false,
FunctionInput::ConstSelfKeyword(_) => false,
FunctionInput::MutSelfKeyword(_) => true,
FunctionInput::RefSelfKeyword(_) => true,
FunctionInput::Variable(_) => false,
}
}
///
/// Returns Option with FunctionInputVariable if the input is a variable.
/// Returns None otherwise.
///
pub fn get_variable(&self) -> Option<&FunctionInputVariable> {
if let FunctionInput::Variable(var) = self {
Some(var)
} else {
None
}
}
fn format(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
FunctionInput::SelfKeyword(keyword) => write!(f, "{}", keyword),
FunctionInput::ConstSelfKeyword(keyword) => write!(f, "{}", keyword),
FunctionInput::MutSelfKeyword(keyword) => write!(f, "{}", keyword),
FunctionInput::RefSelfKeyword(keyword) => write!(f, "{}", keyword),
FunctionInput::Variable(function_input) => write!(f, "{}", function_input),
}
}
@ -97,7 +109,7 @@ impl PartialEq for FunctionInput {
match (self, other) {
(FunctionInput::SelfKeyword(_), FunctionInput::SelfKeyword(_)) => true,
(FunctionInput::ConstSelfKeyword(_), FunctionInput::ConstSelfKeyword(_)) => true,
(FunctionInput::MutSelfKeyword(_), FunctionInput::MutSelfKeyword(_)) => true,
(FunctionInput::RefSelfKeyword(_), FunctionInput::RefSelfKeyword(_)) => true,
(FunctionInput::Variable(left), FunctionInput::Variable(right)) => left.eq(right),
_ => false,
}
@ -112,7 +124,7 @@ impl Node for FunctionInput {
match self {
SelfKeyword(keyword) => &keyword.identifier.span,
ConstSelfKeyword(keyword) => &keyword.identifier.span,
MutSelfKeyword(keyword) => &keyword.identifier.span,
RefSelfKeyword(keyword) => &keyword.identifier.span,
Variable(variable) => &variable.span,
}
}
@ -122,7 +134,7 @@ impl Node for FunctionInput {
match self {
SelfKeyword(keyword) => keyword.identifier.span = span,
ConstSelfKeyword(keyword) => keyword.identifier.span = span,
MutSelfKeyword(keyword) => keyword.identifier.span = span,
RefSelfKeyword(keyword) => keyword.identifier.span = span,
Variable(variable) => variable.span = span,
}
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -14,11 +14,11 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_errors::Span;
use leo_input::values::{
GroupCoordinate as InputGroupCoordinate, Inferred as InputInferred, NumberValue as InputNumberValue,
SignHigh as InputSignHigh, SignLow as InputSignLow,
};
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;
@ -27,8 +27,8 @@ use tendril::StrTendril;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum GroupCoordinate {
Number(
#[serde(with = "leo_errors::common::tendril_json")] StrTendril,
#[serde(with = "leo_errors::common::span_json")] Span,
#[serde(with = "leo_span::tendril_json")] StrTendril,
#[serde(with = "leo_span::span_json")] Span,
),
SignHigh,
SignLow,

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,10 +15,10 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::groups::GroupCoordinate;
use leo_errors::Span;
use leo_input::values::{
GroupRepresentation as InputGroupRepresentation, GroupTuple as InputGroupTuple, GroupValue as InputGroupValue,
};
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;
@ -27,8 +27,8 @@ use tendril::StrTendril;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum GroupValue {
Single(
#[serde(with = "leo_errors::common::tendril_json")] StrTendril,
#[serde(with = "leo_errors::common::span_json")] Span,
#[serde(with = "leo_span::tendril_json")] StrTendril,
#[serde(with = "leo_span::span_json")] Span,
),
Tuple(GroupTuple),
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::PackageOrPackages;
use leo_errors::Span;
use leo_span::{Span, Symbol};
use serde::{Deserialize, Serialize};
use std::fmt;
@ -28,13 +28,11 @@ pub struct ImportStatement {
}
impl ImportStatement {
///
/// Returns the the package file name of the self import statement.
///
pub fn get_file_name(&self) -> &str {
pub fn get_file_name(&self) -> Symbol {
match self.package_or_packages {
PackageOrPackages::Package(ref package) => &package.name.name,
PackageOrPackages::Packages(ref packages) => &packages.name.name,
PackageOrPackages::Package(ref package) => package.name.name,
PackageOrPackages::Packages(ref packages) => packages.name.name,
}
}
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,8 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::Identifier;
use leo_errors::Span;
use leo_span::{sym, Span};
use serde::{Deserialize, Serialize};
use std::fmt;
@ -52,7 +53,7 @@ impl ImportSymbol {
pub fn star(span: &Span) -> Self {
Self {
symbol: Identifier {
name: "*".into(),
name: sym::Star,
span: span.clone(),
},
alias: None,
@ -61,6 +62,6 @@ impl ImportSymbol {
}
pub fn is_star(&self) -> bool {
self.symbol.name.as_ref().eq("*")
self.symbol.name == sym::Star
}
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{common::Identifier, PackageAccess};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ImportSymbol, Node, Package, Packages};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Node, Package, Packages};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{common::Identifier, PackageAccess};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -14,11 +14,12 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{InputValue, MainInput, ProgramInput, ProgramState, Record, Registers, State, StateLeaf};
use crate::{ConstantInput, InputValue, MainInput, ProgramInput, ProgramState, Record, Registers, State, StateLeaf};
use leo_input::{
files::{File, TableOrSection},
InputParserError,
};
use leo_span::Symbol;
#[derive(Clone, PartialEq, Eq)]
pub struct Input {
@ -96,16 +97,26 @@ impl Input {
/// Returns the main function input value with the given `name`.
#[allow(clippy::ptr_arg)]
pub fn get(&self, name: &str) -> Option<Option<InputValue>> {
pub fn get(&self, name: Symbol) -> Option<Option<InputValue>> {
self.program_input.get(name)
}
/// Returns the constant input value with the given `name`.
#[allow(clippy::ptr_arg)]
pub fn get_constant(&self, name: &str) -> Option<Option<InputValue>> {
pub fn get_constant(&self, name: Symbol) -> Option<Option<InputValue>> {
self.program_input.get_constant(name)
}
/// Returns the main input values
pub fn get_main_inputs(&self) -> &MainInput {
&self.program_input.main
}
/// Returns the main input values
pub fn get_constant_inputs(&self) -> &ConstantInput {
&self.program_input.constants
}
/// Returns the runtime register input values
pub fn get_registers(&self) -> &Registers {
self.program_input.get_registers()

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -14,17 +14,17 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ArrayDimensions, Char, CharValue, GroupValue};
use leo_errors::Span as AstSpan;
use crate::{ArrayDimensions, Char, CharValue, GroupValue, IntegerType};
use leo_input::{
errors::InputParserError,
expressions::{ArrayInitializerExpression, ArrayInlineExpression, Expression, StringExpression, TupleExpression},
types::{ArrayType, CharType, DataType, IntegerType, TupleType, Type},
types::{ArrayType, CharType, DataType, IntegerType as InputIntegerType, TupleType, Type},
values::{
Address, AddressValue, BooleanValue, CharValue as InputCharValue, FieldValue, GroupValue as InputGroupValue,
IntegerValue, NumberValue, Value,
},
};
use leo_span::Span as AstSpan;
use pest::Span;
use std::fmt;
@ -68,8 +68,8 @@ impl InputValue {
Ok(InputValue::Char(CharValue { character, span }))
}
fn from_number(integer_type: IntegerType, number: String) -> Self {
InputValue::Integer(integer_type, number)
fn from_number(integer_type: InputIntegerType, number: String) -> Self {
InputValue::Integer(integer_type.into(), number)
}
fn from_group(group: InputGroupValue) -> Self {
@ -99,24 +99,24 @@ impl InputValue {
(DataType::Integer(integer_type), Value::Integer(integer)) => {
match integer.clone() {
IntegerValue::Signed(signed) => {
if let IntegerType::Signed(inner) = integer_type.clone() {
if let InputIntegerType::Signed(inner) = integer_type.clone() {
let singed_type = signed.clone().type_;
if std::mem::discriminant(&inner) != std::mem::discriminant(&singed_type) {
return Err(InputParserError::integer_type_mismatch(
integer_type,
IntegerType::Signed(singed_type),
InputIntegerType::Signed(singed_type),
integer.span(),
));
}
}
}
IntegerValue::Unsigned(unsigned) => {
if let IntegerType::Unsigned(inner) = integer_type.clone() {
if let InputIntegerType::Unsigned(inner) = integer_type.clone() {
let unsinged_type = unsigned.clone().type_;
if std::mem::discriminant(&inner) != std::mem::discriminant(&unsinged_type) {
return Err(InputParserError::integer_type_mismatch(
integer_type,
IntegerType::Unsigned(unsinged_type),
InputIntegerType::Unsigned(unsinged_type),
integer.span(),
));
}
@ -341,18 +341,16 @@ impl InputValue {
}
}
///
/// Returns a new vector of usize values from an [`ArrayDimensions`] type.
///
/// Attempts to parse each dimension in the array from a `String` to a `usize` value. If parsing
/// is successful, the `usize` value is appended to the return vector. If parsing fails, an error
/// is returned.
///
fn parse_array_dimensions(array_dimensions_type: ArrayDimensions, span: &Span) -> Result<Vec<usize>, InputParserError> {
fn parse_array_dimensions(dimensions: ArrayDimensions, span: &Span) -> Result<Vec<usize>, InputParserError> {
// Convert the array dimensions to usize.
let mut array_dimensions = Vec::with_capacity(array_dimensions_type.0.len());
let mut result_array_dimensions = Vec::with_capacity(dimensions.len());
for dimension in array_dimensions_type.0 {
for dimension in dimensions.iter() {
// Convert the dimension to a string.
let dimension_string = dimension.to_string();
@ -363,10 +361,10 @@ fn parse_array_dimensions(array_dimensions_type: ArrayDimensions, span: &Span) -
};
// Collect dimension usize values.
array_dimensions.push(dimension_usize);
result_array_dimensions.push(dimension_usize);
}
Ok(array_dimensions)
Ok(result_array_dimensions)
}
///

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -69,6 +69,21 @@ macro_rules! record_input_section {
pub fn values(&self) -> IndexMap<Parameter, Option<InputValue>> {
self.values.clone()
}
/// a list of all defined name -> type pairs
pub fn types(&self) -> Vec<(String, crate::Type)> {
self.values.iter()
.map(|(parameter, _)| (parameter.variable.name.to_string(), parameter.type_.clone()))
.collect()
}
/// a map of all defined name -> value pairs, if present
pub fn raw_values(&self) -> IndexMap<String, InputValue> {
self.values.iter()
.filter(|(_, value)| value.is_some())
.map(|(parameter, value)| (parameter.variable.name.to_string(), value.as_ref().unwrap().clone()))
.collect()
}
}
)*)
}
@ -82,7 +97,7 @@ macro_rules! main_input_section {
/// `[$name]` program input section.
#[derive(Clone, PartialEq, Eq, Default)]
pub struct $name {
input: IndexMap<String, Option<InputValue>>,
input: IndexMap<leo_span::Symbol, Option<InputValue>>,
}
#[allow(clippy::len_without_is_empty)]
@ -107,14 +122,14 @@ macro_rules! main_input_section {
self.input.len()
}
pub fn insert(&mut self, key: String, value: Option<InputValue>) {
pub fn insert(&mut self, key: leo_span::Symbol, value: Option<InputValue>) {
self.input.insert(key, value);
}
/// Parses main input definitions and stores them in `self`.
pub fn parse(&mut self, definitions: Vec<Definition>) -> Result<(), InputParserError> {
for definition in definitions {
let name = definition.parameter.variable.value;
let name = leo_span::Symbol::intern(&definition.parameter.variable.value);
let value = InputValue::from_expression(definition.parameter.type_, definition.expression)?;
self.insert(name, Some(value));
@ -124,8 +139,12 @@ macro_rules! main_input_section {
}
/// Returns an `Option` of the main function input at `name`.
pub fn get(&self, name: &str) -> Option<Option<InputValue>> {
self.input.get(name).cloned()
pub fn get(&self, name: leo_span::Symbol) -> Option<Option<InputValue>> {
self.input.get(&name).cloned()
}
pub fn iter(&self) -> impl Iterator<Item=(&leo_span::Symbol, &Option<InputValue>)> {
self.input.iter()
}
}
)*)

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,8 +15,8 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Identifier, Type};
use leo_errors::Span;
use leo_input::parameters::Parameter as GrammarParameter;
use leo_span::Span;
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Parameter {

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -19,6 +19,7 @@ use leo_input::{
sections::{Header, Section},
InputParserError,
};
use leo_span::Symbol;
#[derive(Clone, PartialEq, Eq, Default)]
pub struct ProgramInput {
@ -74,12 +75,12 @@ impl ProgramInput {
/// Returns the main function input value with the given `name`
#[allow(clippy::ptr_arg)]
pub fn get(&self, name: &str) -> Option<Option<InputValue>> {
pub fn get(&self, name: Symbol) -> Option<Option<InputValue>> {
self.main.get(name)
}
#[allow(clippy::ptr_arg)]
pub fn get_constant(&self, name: &str) -> Option<Option<InputValue>> {
pub fn get_constant(&self, name: Symbol) -> Option<Option<InputValue>> {
self.constants.get(name)
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -22,6 +22,9 @@
#![doc = include_str!("../README.md")]
pub mod accesses;
pub use self::accesses::*;
pub mod aliases;
pub use self::aliases::*;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_errors::Span;
use leo_span::Span;
pub trait Node:
std::fmt::Debug + std::fmt::Display + Clone + PartialEq + Eq + serde::Serialize + serde::de::DeserializeOwned

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -18,5 +18,5 @@ use crate::{Ast, Program};
use leo_errors::Result;
pub trait AstPass {
fn do_pass(asg: Program) -> Result<Ast>;
fn do_pass(self, ast: Program) -> Result<Ast>;
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -17,7 +17,9 @@
//! A Leo program consists of import, circuit, and function definitions.
//! Each defined type consists of ast statements and expressions.
use crate::{Alias, Circuit, DefinitionStatement, Function, FunctionInput, Identifier, ImportStatement};
use crate::{Alias, Circuit, CircuitMember, DefinitionStatement, Function, FunctionInput, Identifier, ImportStatement};
use leo_span::{sym, Symbol};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
@ -30,7 +32,7 @@ pub struct Program {
pub expected_input: Vec<FunctionInput>,
pub import_statements: Vec<ImportStatement>,
#[serde(with = "crate::common::imported_modules")]
pub imports: IndexMap<Vec<String>, Program>,
pub imports: IndexMap<Vec<Symbol>, Program>,
pub aliases: IndexMap<Identifier, Alias>,
pub circuits: IndexMap<Identifier, Circuit>,
#[serde(with = "crate::common::global_consts_json")]
@ -88,10 +90,35 @@ impl Program {
}
}
pub fn set_core_mapping(&self, mapping: Option<&str>) {
for (_, circuit) in self.circuits.iter() {
circuit.core_mapping.replace(mapping.map(str::to_string));
}
pub fn handle_internal_annotations(&mut self) {
self.circuits
.iter_mut()
.flat_map(|(_, circuit)| &mut circuit.members)
.filter_map(|member| {
if let CircuitMember::CircuitFunction(function) = member {
Some(function)
} else {
None
}
})
.for_each(|function| {
function.annotations.retain(|name, core_map| {
match *name {
sym::CoreFunction => {
let new = core_map.arguments.get(0).copied().or(Some(function.identifier.name));
function.core_mapping.replace(new);
false
}
sym::AlwaysConst => {
function.const_ = true;
false
}
// Could still be a valid annotation.
// Carry on and let ASG handle.
_ => true,
}
})
});
}
pub fn get_name(&self) -> String {

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -18,8 +18,11 @@
//! asg nodes and saving relevant information.
use crate::*;
use leo_errors::{AstError, Result};
use leo_span::{Span, Symbol};
use indexmap::IndexMap;
use leo_errors::{AstError, Result, Span};
pub struct ReconstructingDirector<R: ReconstructingReducer> {
reducer: R,
@ -57,27 +60,17 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
Expression::Unary(unary) => Expression::Unary(self.reduce_unary(unary)?),
Expression::Ternary(ternary) => Expression::Ternary(self.reduce_ternary(ternary)?),
Expression::Cast(cast) => Expression::Cast(self.reduce_cast(cast)?),
Expression::LengthOf(lengthof) => Expression::LengthOf(lengthof.clone()), // Expression::LengthOf(self.reduce_lengthof(lengthof)?), // TODO: add reducer
Expression::Access(access) => Expression::Access(self.reduce_access(access)?),
Expression::ArrayInline(array_inline) => Expression::ArrayInline(self.reduce_array_inline(array_inline)?),
Expression::ArrayInit(array_init) => Expression::ArrayInit(self.reduce_array_init(array_init)?),
Expression::ArrayAccess(array_access) => Expression::ArrayAccess(self.reduce_array_access(array_access)?),
Expression::ArrayRangeAccess(array_range_access) => {
Expression::ArrayRangeAccess(self.reduce_array_range_access(array_range_access)?)
}
Expression::TupleInit(tuple_init) => Expression::TupleInit(self.reduce_tuple_init(tuple_init)?),
Expression::TupleAccess(tuple_access) => Expression::TupleAccess(self.reduce_tuple_access(tuple_access)?),
Expression::CircuitInit(circuit_init) => Expression::CircuitInit(self.reduce_circuit_init(circuit_init)?),
Expression::CircuitMemberAccess(circuit_member_access) => {
Expression::CircuitMemberAccess(self.reduce_circuit_member_access(circuit_member_access)?)
}
Expression::CircuitStaticFunctionAccess(circuit_static_fn_access) => {
Expression::CircuitStaticFunctionAccess(self.reduce_circuit_static_fn_access(circuit_static_fn_access)?)
}
Expression::Call(call) => Expression::Call(self.reduce_call(call)?),
Expression::Err(s) => Expression::Err(s.clone()),
};
self.reducer.reduce_expression(expression, new)
@ -120,7 +113,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
let left = self.reduce_expression(&binary.left)?;
let right = self.reduce_expression(&binary.right)?;
self.reducer.reduce_binary(binary, left, right, binary.op.clone())
self.reducer.reduce_binary(binary, left, right, binary.op)
}
pub fn reduce_unary(&mut self, unary: &UnaryExpression) -> Result<UnaryExpression> {
@ -144,6 +137,74 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_cast(cast, inner, target_type)
}
pub fn reduce_array_access(&mut self, array_access: &ArrayAccess) -> Result<ArrayAccess> {
let array = self.reduce_expression(&array_access.array)?;
let index = self.reduce_expression(&array_access.index)?;
self.reducer.reduce_array_access(array_access, array, index)
}
pub fn reduce_array_range_access(&mut self, array_range_access: &ArrayRangeAccess) -> Result<ArrayRangeAccess> {
let array = self.reduce_expression(&array_range_access.array)?;
let left = array_range_access
.left
.as_ref()
.map(|left| self.reduce_expression(left))
.transpose()?;
let right = array_range_access
.right
.as_ref()
.map(|right| self.reduce_expression(right))
.transpose()?;
self.reducer
.reduce_array_range_access(array_range_access, array, left, right)
}
pub fn reduce_member_access(&mut self, member_access: &MemberAccess) -> Result<MemberAccess> {
let inner = self.reduce_expression(&member_access.inner)?;
let name = self.reduce_identifier(&member_access.name)?;
let type_ = member_access
.type_
.as_ref()
.map(|type_| self.reduce_type(type_, &member_access.span))
.transpose()?;
self.reducer.reduce_member_access(member_access, inner, name, type_)
}
pub fn reduce_tuple_access(&mut self, tuple_access: &TupleAccess) -> Result<TupleAccess> {
let tuple = self.reduce_expression(&tuple_access.tuple)?;
self.reducer.reduce_tuple_access(tuple_access, tuple)
}
pub fn reduce_static_access(&mut self, static_access: &StaticAccess) -> Result<StaticAccess> {
let value = self.reduce_expression(&static_access.inner)?;
let name = self.reduce_identifier(&static_access.name)?;
let type_ = static_access
.type_
.as_ref()
.map(|type_| self.reduce_type(type_, &static_access.span))
.transpose()?;
self.reducer.reduce_static_access(static_access, value, type_, name)
}
pub fn reduce_access(&mut self, access: &AccessExpression) -> Result<AccessExpression> {
use AccessExpression::*;
let new = match access {
Array(access) => Array(self.reduce_array_access(access)?),
ArrayRange(access) => ArrayRange(self.reduce_array_range_access(access)?),
Member(access) => Member(self.reduce_member_access(access)?),
Tuple(access) => Tuple(self.reduce_tuple_access(access)?),
Static(access) => Static(self.reduce_static_access(access)?),
};
Ok(new)
}
pub fn reduce_array_inline(&mut self, array_inline: &ArrayInlineExpression) -> Result<ArrayInlineExpression> {
let mut elements = vec![];
for element in array_inline.elements.iter() {
@ -168,33 +229,6 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_array_init(array_init, element)
}
pub fn reduce_array_access(&mut self, array_access: &ArrayAccessExpression) -> Result<ArrayAccessExpression> {
let array = self.reduce_expression(&array_access.array)?;
let index = self.reduce_expression(&array_access.index)?;
self.reducer.reduce_array_access(array_access, array, index)
}
pub fn reduce_array_range_access(
&mut self,
array_range_access: &ArrayRangeAccessExpression,
) -> Result<ArrayRangeAccessExpression> {
let array = self.reduce_expression(&array_range_access.array)?;
let left = array_range_access
.left
.as_ref()
.map(|left| self.reduce_expression(left))
.transpose()?;
let right = array_range_access
.right
.as_ref()
.map(|right| self.reduce_expression(right))
.transpose()?;
self.reducer
.reduce_array_range_access(array_range_access, array, left, right)
}
pub fn reduce_tuple_init(&mut self, tuple_init: &TupleInitExpression) -> Result<TupleInitExpression> {
let mut elements = vec![];
for element in tuple_init.elements.iter() {
@ -204,16 +238,10 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_tuple_init(tuple_init, elements)
}
pub fn reduce_tuple_access(&mut self, tuple_access: &TupleAccessExpression) -> Result<TupleAccessExpression> {
let tuple = self.reduce_expression(&tuple_access.tuple)?;
self.reducer.reduce_tuple_access(tuple_access, tuple)
}
pub fn reduce_circuit_implied_variable_definition(
pub fn reduce_circuit_variable_initializer(
&mut self,
variable: &CircuitImpliedVariableDefinition,
) -> Result<CircuitImpliedVariableDefinition> {
variable: &CircuitVariableInitializer,
) -> Result<CircuitVariableInitializer> {
let identifier = self.reduce_identifier(&variable.identifier)?;
let expression = variable
.expression
@ -222,7 +250,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
.transpose()?;
self.reducer
.reduce_circuit_implied_variable_definition(variable, identifier, expression)
.reduce_circuit_variable_initializer(variable, identifier, expression)
}
pub fn reduce_circuit_init(&mut self, circuit_init: &CircuitInitExpression) -> Result<CircuitInitExpression> {
@ -230,39 +258,12 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
let mut members = vec![];
for member in circuit_init.members.iter() {
members.push(self.reduce_circuit_implied_variable_definition(member)?);
members.push(self.reduce_circuit_variable_initializer(member)?);
}
self.reducer.reduce_circuit_init(circuit_init, name, members)
}
pub fn reduce_circuit_member_access(
&mut self,
circuit_member_access: &CircuitMemberAccessExpression,
) -> Result<CircuitMemberAccessExpression> {
let circuit = self.reduce_expression(&circuit_member_access.circuit)?;
let name = self.reduce_identifier(&circuit_member_access.name)?;
let type_ = circuit_member_access
.type_
.as_ref()
.map(|type_| self.reduce_type(type_, &circuit_member_access.span))
.transpose()?;
self.reducer
.reduce_circuit_member_access(circuit_member_access, circuit, name, type_)
}
pub fn reduce_circuit_static_fn_access(
&mut self,
circuit_static_fn_access: &CircuitStaticFunctionAccessExpression,
) -> Result<CircuitStaticFunctionAccessExpression> {
let circuit = self.reduce_expression(&circuit_static_fn_access.circuit)?;
let name = self.reduce_identifier(&circuit_static_fn_access.name)?;
self.reducer
.reduce_circuit_static_fn_access(circuit_static_fn_access, circuit, name)
}
pub fn reduce_call(&mut self, call: &CallExpression) -> Result<CallExpression> {
let function = self.reduce_expression(&call.function)?;
@ -518,7 +519,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_import_statement(import, package_or_packages)
}
pub fn reduce_import(&mut self, identifier: &[String], import: &Program) -> Result<(Vec<String>, Program)> {
pub fn reduce_import(&mut self, identifier: &[Symbol], import: &Program) -> Result<(Vec<Symbol>, Program)> {
let new_identifer = identifier.to_vec();
let new_import = self.reduce_program(import)?;
self.reducer.reduce_import(new_identifer, new_import)
@ -526,11 +527,18 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
pub fn reduce_circuit_member(&mut self, circuit_member: &CircuitMember) -> Result<CircuitMember> {
let new = match circuit_member {
CircuitMember::CircuitConst(identifier, type_, value) => CircuitMember::CircuitConst(
self.reduce_identifier(identifier)?,
self.reduce_type(type_, &identifier.span)?,
self.reduce_expression(value)?,
),
CircuitMember::CircuitVariable(identifier, type_) => CircuitMember::CircuitVariable(
self.reduce_identifier(identifier)?,
self.reduce_type(type_, &identifier.span)?,
),
CircuitMember::CircuitFunction(function) => CircuitMember::CircuitFunction(self.reduce_function(function)?),
CircuitMember::CircuitFunction(function) => {
CircuitMember::CircuitFunction(Box::new(self.reduce_function(function)?))
}
};
self.reducer.reduce_circuit_member(circuit_member, new)
@ -556,9 +564,9 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
pub fn reduce_function(&mut self, function: &Function) -> Result<Function> {
let identifier = self.reduce_identifier(&function.identifier)?;
let mut annotations = vec![];
for annotation in function.annotations.iter() {
annotations.push(self.reduce_annotation(annotation)?);
let mut annotations = IndexMap::new();
for (name, annotation) in function.annotations.iter() {
annotations.insert(*name, self.reduce_annotation(annotation)?);
}
let mut inputs = vec![];
@ -574,7 +582,14 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
let block = self.reduce_block(&function.block)?;
self.reducer
.reduce_function(function, identifier, annotations, inputs, output, block)
self.reducer.reduce_function(
function,
identifier,
annotations,
inputs,
function.const_,
output,
block,
)
}
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,8 +15,11 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::*;
use leo_errors::Result;
use leo_span::{Span, Symbol};
use indexmap::IndexMap;
use leo_errors::{Result, Span};
// Needed to fix clippy bug.
#[allow(clippy::redundant_closure)]
@ -35,7 +38,7 @@ pub trait ReconstructingReducer {
fn reduce_identifier(&mut self, identifier: &Identifier) -> Result<Identifier> {
Ok(Identifier {
name: identifier.name.clone(),
name: identifier.name,
span: identifier.span.clone(),
})
}
@ -114,6 +117,72 @@ pub trait ReconstructingReducer {
})
}
fn reduce_array_access(
&mut self,
array_access: &ArrayAccess,
array: Expression,
index: Expression,
) -> Result<ArrayAccess> {
Ok(ArrayAccess {
array: Box::new(array),
index: Box::new(index),
span: array_access.span.clone(),
})
}
fn reduce_array_range_access(
&mut self,
array_rage_access: &ArrayRangeAccess,
array: Expression,
left: Option<Expression>,
right: Option<Expression>,
) -> Result<ArrayRangeAccess> {
Ok(ArrayRangeAccess {
array: Box::new(array),
left: left.map(|expr| Box::new(expr)),
right: right.map(|expr| Box::new(expr)),
span: array_rage_access.span.clone(),
})
}
fn reduce_member_access(
&mut self,
member_access: &MemberAccess,
inner: Expression,
name: Identifier,
type_: Option<Type>,
) -> Result<MemberAccess> {
Ok(MemberAccess {
inner: Box::new(inner),
name,
span: member_access.span.clone(),
type_,
})
}
fn reduce_tuple_access(&mut self, tuple_access: &TupleAccess, tuple: Expression) -> Result<TupleAccess> {
Ok(TupleAccess {
tuple: Box::new(tuple),
index: tuple_access.index.clone(),
span: tuple_access.span.clone(),
})
}
fn reduce_static_access(
&mut self,
static_access: &StaticAccess,
value: Expression,
type_: Option<Type>,
name: Identifier,
) -> Result<StaticAccess> {
Ok(StaticAccess {
inner: Box::new(value),
name,
type_,
span: static_access.span.clone(),
})
}
fn reduce_array_inline(
&mut self,
array_inline: &ArrayInlineExpression,
@ -137,34 +206,6 @@ pub trait ReconstructingReducer {
})
}
fn reduce_array_access(
&mut self,
array_access: &ArrayAccessExpression,
array: Expression,
index: Expression,
) -> Result<ArrayAccessExpression> {
Ok(ArrayAccessExpression {
array: Box::new(array),
index: Box::new(index),
span: array_access.span.clone(),
})
}
fn reduce_array_range_access(
&mut self,
array_rage_access: &ArrayRangeAccessExpression,
array: Expression,
left: Option<Expression>,
right: Option<Expression>,
) -> Result<ArrayRangeAccessExpression> {
Ok(ArrayRangeAccessExpression {
array: Box::new(array),
left: left.map(|expr| Box::new(expr)),
right: right.map(|expr| Box::new(expr)),
span: array_rage_access.span.clone(),
})
}
fn reduce_tuple_init(
&mut self,
tuple_init: &TupleInitExpression,
@ -176,32 +217,20 @@ pub trait ReconstructingReducer {
})
}
fn reduce_tuple_access(
fn reduce_circuit_variable_initializer(
&mut self,
tuple_access: &TupleAccessExpression,
tuple: Expression,
) -> Result<TupleAccessExpression> {
Ok(TupleAccessExpression {
tuple: Box::new(tuple),
index: tuple_access.index.clone(),
span: tuple_access.span.clone(),
})
}
fn reduce_circuit_implied_variable_definition(
&mut self,
_variable: &CircuitImpliedVariableDefinition,
_variable: &CircuitVariableInitializer,
identifier: Identifier,
expression: Option<Expression>,
) -> Result<CircuitImpliedVariableDefinition> {
Ok(CircuitImpliedVariableDefinition { identifier, expression })
) -> Result<CircuitVariableInitializer> {
Ok(CircuitVariableInitializer { identifier, expression })
}
fn reduce_circuit_init(
&mut self,
circuit_init: &CircuitInitExpression,
name: Identifier,
members: Vec<CircuitImpliedVariableDefinition>,
members: Vec<CircuitVariableInitializer>,
) -> Result<CircuitInitExpression> {
Ok(CircuitInitExpression {
name,
@ -210,34 +239,6 @@ pub trait ReconstructingReducer {
})
}
fn reduce_circuit_member_access(
&mut self,
circuit_member_access: &CircuitMemberAccessExpression,
circuit: Expression,
name: Identifier,
type_: Option<Type>,
) -> Result<CircuitMemberAccessExpression> {
Ok(CircuitMemberAccessExpression {
circuit: Box::new(circuit),
name,
span: circuit_member_access.span.clone(),
type_,
})
}
fn reduce_circuit_static_fn_access(
&mut self,
circuit_static_fn_access: &CircuitStaticFunctionAccessExpression,
circuit: Expression,
name: Identifier,
) -> Result<CircuitStaticFunctionAccessExpression> {
Ok(CircuitStaticFunctionAccessExpression {
circuit: Box::new(circuit),
name,
span: circuit_static_fn_access.span.clone(),
})
}
fn reduce_call(
&mut self,
call: &CallExpression,
@ -383,7 +384,7 @@ pub trait ReconstructingReducer {
program: &Program,
expected_input: Vec<FunctionInput>,
import_statements: Vec<ImportStatement>,
imports: IndexMap<Vec<String>, Program>,
imports: IndexMap<Vec<Symbol>, Program>,
aliases: IndexMap<Identifier, Alias>,
circuits: IndexMap<Identifier, Circuit>,
functions: IndexMap<Identifier, Function>,
@ -439,7 +440,7 @@ pub trait ReconstructingReducer {
})
}
fn reduce_import(&mut self, identifier: Vec<String>, import: Program) -> Result<(Vec<String>, Program)> {
fn reduce_import(&mut self, identifier: Vec<Symbol>, import: Program) -> Result<(Vec<Symbol>, Program)> {
Ok((identifier, import))
}
@ -449,15 +450,11 @@ pub trait ReconstructingReducer {
fn reduce_circuit(
&mut self,
circuit: &Circuit,
_circuit: &Circuit,
circuit_name: Identifier,
members: Vec<CircuitMember>,
) -> Result<Circuit> {
Ok(Circuit {
circuit_name,
core_mapping: circuit.core_mapping.clone(),
members,
})
Ok(Circuit { circuit_name, members })
}
fn reduce_annotation(&mut self, annotation: &Annotation, name: Identifier) -> Result<Annotation> {
@ -473,8 +470,9 @@ pub trait ReconstructingReducer {
&mut self,
function: &Function,
identifier: Identifier,
annotations: Vec<Annotation>,
annotations: IndexMap<Symbol, Annotation>,
input: Vec<FunctionInput>,
const_: bool,
output: Option<Type>,
block: Block,
) -> Result<Function> {
@ -482,8 +480,10 @@ pub trait ReconstructingReducer {
identifier,
annotations,
input,
const_,
output,
block,
core_mapping: function.core_mapping.clone(),
span: function.span.clone(),
})
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,16 +15,17 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Expression, Identifier, PositiveNumber};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AssigneeAccess {
ArrayRange(Option<Expression>, Option<Expression>),
ArrayIndex(Expression),
Tuple(PositiveNumber, #[serde(with = "leo_errors::common::span_json")] Span),
Tuple(PositiveNumber, #[serde(with = "leo_span::span_json")] Span),
Member(Identifier),
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -16,7 +16,7 @@
use crate::{Expression, Node};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Node, Statement};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Block, Expression, Node, Statement};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Char, Expression, Node};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ConsoleArgs, Expression, Node};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{ConsoleFunction, Node};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Expression, Node, Type};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Identifier, Node};
use leo_errors::Span;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

Some files were not shown because too many files have changed in this diff Show More