Merge pull request #1242 from AleoHQ/feature/better-errors

[WIP Implementation] Better Errors
This commit is contained in:
Alessandro Coglio 2021-08-18 16:08:24 -07:00 committed by GitHub
commit 235daa9ee4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
859 changed files with 10774 additions and 9292 deletions

View File

@ -46,7 +46,7 @@ commands:
jobs:
check-style:
docker:
- image: cimg/rust:1.53
- image: cimg/rust:1.54.0
resource_class: xlarge
steps:
- checkout
@ -61,7 +61,7 @@ jobs:
clippy:
docker:
- image: cimg/rust:1.53
- image: cimg/rust:1.54.0
resource_class: xlarge
steps:
- checkout
@ -76,7 +76,7 @@ jobs:
# code-cov:
# docker:
# - image: cimg/rust:1.53.0
# - image: cimg/rust:1.54.0
# resource_class: xlarge
# environment:
# RUSTC_BOOTSTRAP: 1
@ -118,7 +118,7 @@ jobs:
leo-executable:
docker:
- image: cimg/rust:1.53
- image: cimg/rust:1.54.0
resource_class: xlarge
steps:
- checkout
@ -136,7 +136,7 @@ jobs:
leo-new:
docker:
- image: cimg/rust:1.53
- image: cimg/rust:1.54.0
resource_class: xlarge
steps:
- attach_workspace:
@ -149,7 +149,7 @@ jobs:
leo-init:
docker:
- image: cimg/rust:1.53
- image: cimg/rust:1.54.0
resource_class: xlarge
steps:
- attach_workspace:
@ -162,7 +162,7 @@ jobs:
leo-clean:
docker:
- image: cimg/rust:1.53
- image: cimg/rust:1.54.0
resource_class: xlarge
steps:
- attach_workspace:
@ -175,7 +175,7 @@ jobs:
leo-setup:
docker:
- image: cimg/rust:1.53
- image: cimg/rust:1.54.0
resource_class: xlarge
steps:
- attach_workspace:
@ -188,7 +188,7 @@ jobs:
leo-add-remove:
docker:
- image: cimg/rust:1.53
- image: cimg/rust:1.54.0
resource_class: xlarge
steps:
- attach_workspace:
@ -201,7 +201,7 @@ jobs:
leo-check-constraints:
docker:
- image: cimg/rust:1.53
- image: cimg/rust:1.54.0
resource_class: xlarge
steps:
- attach_workspace:
@ -214,7 +214,7 @@ jobs:
leo-login-logout:
docker:
- image: cimg/rust:1.53
- image: cimg/rust:1.54.0
resource_class: xlarge
steps:
- attach_workspace:
@ -227,7 +227,7 @@ jobs:
leo-clone:
docker:
- image: cimg/rust:1.53
- image: cimg/rust:1.54.0
resource_class: xlarge
steps:
- attach_workspace:
@ -240,7 +240,7 @@ jobs:
leo-publish:
docker:
- image: cimg/rust:1.53
- image: cimg/rust:1.54.0
resource_class: xlarge
steps:
- attach_workspace:

4
.gitattributes vendored Normal file
View File

@ -0,0 +1,4 @@
# Force certain files to be LF
*.leo text eol=lf
*.out text eol=lf
*.rs text eol=lf

View File

@ -93,14 +93,11 @@ jobs:
run: |
sccache --start-server
- name: Install cargo-all-features
run: |
cargo install cargo-all-features
- name: Test
run: |
cd package
cargo test-all-features
uses: actions-rs/cargo@v1
with:
command: test
args: --all --features ci_skip
- name: Print sccache stats
run: sccache --show-stats
@ -160,17 +157,79 @@ jobs:
run: |
sccache --start-server
- name: Install cargo-all-features
run: |
SDKROOT=$(xcrun -sdk macosx11.1 --show-sdk-path) \
MACOSX_DEPLOYMENT_TARGET=$(xcrun -sdk macosx11.1 --show-sdk-platform-version) \
cargo install cargo-all-features
- name: Test
run: |
SDKROOT=$(xcrun -sdk macosx11.1 --show-sdk-path) \
MACOSX_DEPLOYMENT_TARGET=$(xcrun -sdk macosx11.1 --show-sdk-platform-version) \
cd package && cargo test-all-features
cargo test --all --features ci_skip
- name: Print sccache stats
run: sccache --show-stats
- name: Stop sccache server
run: sccache --stop-server || true
test-docs:
name: Test Docs
runs-on: ubuntu-latest
env:
RUSTC_WRAPPER: sccache
SCCACHE_CACHE_SIZE: 2G
SCCACHE_DIR: /home/runner/.cache/sccache
steps:
- name: Checkout
uses: actions/checkout@v2
with:
ref: master
- name: Install sccache
env:
LINK: https://github.com/mozilla/sccache/releases/download
SCCACHE_VERSION: v0.2.15
run: |
SCCACHE_FILE=sccache-$SCCACHE_VERSION-x86_64-unknown-linux-musl
mkdir -p $HOME/.local/bin
curl -L "$LINK/$SCCACHE_VERSION/$SCCACHE_FILE.tar.gz" | tar xz
mv -f $SCCACHE_FILE/sccache $HOME/.local/bin/sccache
chmod +x $HOME/.local/bin/sccache
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Cache cargo registry
uses: actions/cache@v2
continue-on-error: false
with:
path: |
~/.cargo/registry
~/.cargo/git
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo-
- name: Install Rust Stable
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
override: true
- name: Save sccache
uses: actions/cache@v2
continue-on-error: false
with:
path: /home/runner/.cache/sccache
key: ubuntu-sccache-${{ hashFiles('**/Cargo.lock') }}
restore-keys: ubuntu-sccache-
- name: Start sccache server
run: sccache --start-server
- name: Build Cargo Docs
env:
RUSTDOCFLAGS: "--enable-index-page -Zunstable-options"
RUSTC_BOOTSTRAP: "1"
run: |
cargo doc --no-deps --document-private-items --workspace
rm -rf ./tests
- name: Print sccache stats
run: sccache --show-stats

69
.github/workflows/docs.yml vendored Normal file
View File

@ -0,0 +1,69 @@
name: Master Crates Docs
on:
push:
branches:
- master
jobs:
build-crates-docs:
name: Build Crates Docs
runs-on: ubuntu-latest
env:
RUSTC_WRAPPER: sccache
SCCACHE_CACHE_SIZE: 2G
SCCACHE_DIR: /home/runner/.cache/sccache
steps:
- name: Checkout
uses: actions/checkout@v2
with:
ref: master
- name: Install sccache
env:
LINK: https://github.com/mozilla/sccache/releases/download
SCCACHE_VERSION: v0.2.15
run: |
SCCACHE_FILE=sccache-$SCCACHE_VERSION-x86_64-unknown-linux-musl
mkdir -p $HOME/.local/bin
curl -L "$LINK/$SCCACHE_VERSION/$SCCACHE_FILE.tar.gz" | tar xz
mv -f $SCCACHE_FILE/sccache $HOME/.local/bin/sccache
chmod +x $HOME/.local/bin/sccache
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Install Rust Stable
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
override: true
- name: Save sccache
uses: actions/cache@v2
continue-on-error: false
with:
path: /home/runner/.cache/sccache
key: ubuntu-sccache-${{ hashFiles('**/Cargo.lock') }}
restore-keys: ubuntu-sccache-
- name: Start sccache server
run: sccache --start-server
- name: Build Cargo Docs
env:
RUSTDOCFLAGS: "--enable-index-page -Zunstable-options"
RUSTC_BOOTSTRAP: "1"
run: |
cargo doc --no-deps --document-private-items --workspace
rm -rf ./tests
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./target/doc/
- name: Print sccache stats
run: sccache --show-stats
- name: Stop sccache server
run: sccache --stop-server || true

3
.gitignore vendored
View File

@ -9,6 +9,9 @@
**/.crates2.json
**/bin/
# sccache from pipeline
sccache*/
# Emacs gitignore files
*~
\#*\#

View File

@ -1,5 +1,5 @@
[hooks]
pre-commit = "cargo clippy && cargo +nightly fmt --all -- --check"
pre-commit = "cargo clippy && cargo fmt --all -- --check"
[logging]
verbose = true

90
Cargo.lock generated
View File

@ -23,9 +23,9 @@ dependencies = [
[[package]]
name = "addr2line"
version = "0.15.2"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a2e47a1fbe209ee101dd6d61285226744c6c8d3c21c8dc878ba6cb9f467f3a"
checksum = "3e61f2b7f93d2c7d2b08263acaa4a363b3e276806c68af6134c44f523bf1aacd"
dependencies = [
"gimli",
]
@ -119,9 +119,9 @@ checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
[[package]]
name = "backtrace"
version = "0.3.60"
version = "0.3.61"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7815ea54e4d821e791162e078acbebfd6d8c8939cd559c9335dceb1c8ca7282"
checksum = "e7a905d892734eea339e896738c14b9afce22b5318f64b951e70bf3844419b01"
dependencies = [
"addr2line",
"cc",
@ -340,6 +340,17 @@ dependencies = [
"vec_map",
]
[[package]]
name = "color-backtrace"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd6c04463c99389fff045d2b90ce84f5131332712c7ffbede020f5e9ad1ed685"
dependencies = [
"atty",
"backtrace",
"termcolor",
]
[[package]]
name = "colored"
version = "2.0.0"
@ -640,6 +651,16 @@ dependencies = [
"indexmap",
]
[[package]]
name = "eyre"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "221239d1d5ea86bf5d6f91c9d6bc3646ffe471b08ff9b0f91c44f115ac969d2b"
dependencies = [
"indenter",
"once_cell",
]
[[package]]
name = "failure"
version = "0.1.8"
@ -900,9 +921,9 @@ dependencies = [
[[package]]
name = "gimli"
version = "0.24.0"
version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e4075386626662786ddb0ec9081e7c7eeb1ba31951f447ca780ef9f5d568189"
checksum = "f0a01e0497841a3b2db4f8afa483cce65f7e96a3498bd6c541734792aeac8fe7"
[[package]]
name = "h2"
@ -1044,6 +1065,12 @@ dependencies = [
"unicode-normalization",
]
[[package]]
name = "indenter"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce23b50ad8242c51a442f3ff322d56b02f08852c77e4c0b4d3fd684abc89c683"
[[package]]
name = "indexmap"
version = "1.7.0"
@ -1172,12 +1199,12 @@ dependencies = [
"criterion",
"indexmap",
"leo-ast",
"leo-errors",
"leo-parser",
"num-bigint",
"serde",
"serde_json",
"tendril",
"thiserror",
"typed-arena",
]
@ -1186,21 +1213,21 @@ name = "leo-asg-passes"
version = "1.5.3"
dependencies = [
"leo-asg",
"leo-errors",
]
[[package]]
name = "leo-ast"
version = "1.5.3"
dependencies = [
"anyhow",
"criterion",
"indexmap",
"leo-errors",
"leo-input",
"pest",
"serde",
"serde_json",
"tendril",
"thiserror",
]
[[package]]
@ -1213,6 +1240,7 @@ dependencies = [
"leo-asg",
"leo-asg-passes",
"leo-ast",
"leo-errors",
"leo-imports",
"leo-input",
"leo-package",
@ -1237,10 +1265,25 @@ dependencies = [
"snarkvm-utilities",
"tempfile",
"tendril",
"thiserror",
"tracing",
]
[[package]]
name = "leo-errors"
version = "1.5.3"
dependencies = [
"backtrace",
"color-backtrace",
"colored",
"derivative",
"eyre",
"leo-input",
"pest",
"serde",
"tendril",
"thiserror",
]
[[package]]
name = "leo-imports"
version = "1.5.3"
@ -1248,8 +1291,8 @@ dependencies = [
"indexmap",
"leo-asg",
"leo-ast",
"leo-errors",
"leo-parser",
"thiserror",
"tracing",
]
@ -1270,9 +1313,9 @@ name = "leo-lang"
version = "1.5.3"
dependencies = [
"ansi_term 0.12.1",
"anyhow",
"assert_cmd",
"clap",
"color-backtrace",
"colored",
"console",
"dirs",
@ -1280,6 +1323,7 @@ dependencies = [
"lazy_static",
"leo-ast",
"leo-compiler",
"leo-errors",
"leo-imports",
"leo-input",
"leo-package",
@ -1301,7 +1345,6 @@ dependencies = [
"snarkvm-utilities",
"structopt",
"test_dir",
"thiserror",
"toml",
"tracing",
"tracing-subscriber",
@ -1317,8 +1360,8 @@ name = "leo-package"
version = "1.5.3"
dependencies = [
"lazy_static",
"leo-errors",
"serde",
"thiserror",
"toml",
"tracing",
"walkdir",
@ -1333,12 +1376,12 @@ dependencies = [
"indexmap",
"lazy_static",
"leo-ast",
"leo-errors",
"leo-test-framework",
"serde",
"serde_json",
"serde_yaml",
"tendril",
"thiserror",
"tracing",
]
@ -1348,6 +1391,7 @@ version = "1.5.3"
dependencies = [
"indexmap",
"leo-ast",
"leo-errors",
"leo-input",
"rand 0.8.4",
"rand_core 0.6.3",
@ -1356,14 +1400,15 @@ dependencies = [
"snarkvm-curves",
"snarkvm-dpc",
"snarkvm-utilities",
"thiserror",
]
[[package]]
name = "leo-synthesizer"
version = "1.5.3"
dependencies = [
"eyre",
"hex",
"leo-errors",
"num-bigint",
"serde",
"serde_json",
@ -1689,9 +1734,9 @@ checksum = "17b02fc0ff9a9e4b35b3342880f48e896ebf69f2967921fe8646bf5b7125956a"
[[package]]
name = "object"
version = "0.25.3"
version = "0.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a38f2be3697a57b4060074ff41b44c16870d916ad7877c17696e063257482bc7"
checksum = "c55827317fb4c08822499848a14237d2874d6f139828893017237e7ab93eb386"
dependencies = [
"memchr",
]
@ -2759,6 +2804,15 @@ dependencies = [
"utf-8",
]
[[package]]
name = "termcolor"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dfed899f0eb03f32ee8c6a0aabdb8a7949659e3466561fc0adf54e26d88c5f4"
dependencies = [
"winapi-util",
]
[[package]]
name = "terminal_size"
version = "0.1.17"

View File

@ -30,6 +30,7 @@ members = [
"asg-passes",
"ast",
"compiler",
"errors",
"grammar",
"imports",
"input",
@ -49,6 +50,10 @@ version = "1.5.3"
path = "./compiler"
version = "1.5.3"
[dependencies.leo-errors]
path = "./errors"
version = "1.5.3"
[dependencies.leo-imports]
path = "./imports"
version = "1.5.3"
@ -91,15 +96,15 @@ default-features = false
[dependencies.snarkvm-utilities]
version = "0.7.6"
[dependencies.anyhow]
version = "1.0"
[dependencies.structopt]
version = "0.3"
[dependencies.clap]
version = "2.33.3"
[dependencies]
color-backtrace = "0.5.1"
[dependencies.colored]
version = "2.0"
@ -139,9 +144,6 @@ features = [ "derive" ]
[dependencies.serde_json]
version = "1.0"
[dependencies.thiserror]
version = "1.0"
[dependencies.toml]
version = "0.5"

View File

@ -23,3 +23,7 @@ path = "src/lib.rs"
[dependencies.leo-asg]
path = "../asg"
version = "1.5.3"
[dependencies.leo-errors]
path = "../errors"
version = "1.5.3"

0
asg-passes/README.md Normal file
View File

View File

@ -17,6 +17,7 @@
use std::cell::Cell;
use leo_asg::*;
use leo_errors::LeoError;
pub struct ConstantFolding<'a, 'b> {
program: &'b Program<'a>,
@ -45,7 +46,7 @@ impl<'a, 'b> StatementVisitor<'a> for ConstantFolding<'a, 'b> {}
impl<'a, 'b> ProgramVisitor<'a> for ConstantFolding<'a, 'b> {}
impl<'a, 'b> AsgPass<'a> for ConstantFolding<'a, 'b> {
fn do_pass(asg: Program<'a>) -> Result<Program<'a>, FormattedError> {
fn do_pass(asg: Program<'a>) -> Result<Program<'a>, LeoError> {
let pass = ConstantFolding { program: &asg };
let mut director = VisitorDirector::new(pass);
director.visit_program(&asg).ok();

View File

@ -17,6 +17,7 @@
use std::cell::Cell;
use leo_asg::*;
use leo_errors::LeoError;
pub struct DeadCodeElimination {}
@ -65,7 +66,7 @@ impl<'a> ReconstructingReducerStatement<'a> for DeadCodeElimination {
}
impl<'a> AsgPass<'a> for DeadCodeElimination {
fn do_pass(asg: Program<'a>) -> Result<Program<'a>, FormattedError> {
fn do_pass(asg: Program<'a>) -> Result<Program<'a>, LeoError> {
let pass = DeadCodeElimination {};
let mut director = ReconstructingDirector::new(asg.context, pass);
Ok(director.reduce_program(asg))

View File

@ -14,6 +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/>.
#![doc = include_str!("../README.md")]
pub mod constant_folding;
pub use constant_folding::*;

View File

@ -26,13 +26,14 @@ version = "1.0"
[dependencies.indexmap]
version = "1.7"
[dependencies.thiserror]
version = "1.0"
[dependencies.leo-ast]
version = "1.5.3"
path = "../ast"
[dependencies.leo-errors]
path = "../errors"
version = "1.5.3"
[dependencies.leo-parser]
version = "1.5.3"
path = "../parser"

View File

@ -14,9 +14,9 @@
// 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::{
statement::*, BoolAnd, Expression, Monoid, MonoidalReducerExpression, MonoidalReducerStatement, Node, Span,
};
use crate::{statement::*, BoolAnd, Expression, Monoid, MonoidalReducerExpression, MonoidalReducerStatement, Node};
use leo_errors::Span;
pub struct ReturnPathReducer {
pub errors: Vec<(Span, String)>,

View File

@ -14,7 +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::{AsgConvertError, Circuit, Identifier, IntegerType, Span, Type};
use crate::{Circuit, Identifier, IntegerType, Type};
use leo_errors::{AsgError, Result, Span};
use indexmap::IndexMap;
use num_bigint::BigInt;
@ -313,18 +314,18 @@ impl ConstInt {
Type::Integer(self.get_int_type())
}
pub fn parse(int_type: &IntegerType, value: &str, span: &Span) -> Result<ConstInt, AsgConvertError> {
pub fn parse(int_type: &IntegerType, value: &str, span: &Span) -> Result<ConstInt> {
Ok(match int_type {
IntegerType::I8 => ConstInt::I8(value.parse().map_err(|_| AsgConvertError::invalid_int(value, span))?),
IntegerType::I16 => ConstInt::I16(value.parse().map_err(|_| AsgConvertError::invalid_int(value, span))?),
IntegerType::I32 => ConstInt::I32(value.parse().map_err(|_| AsgConvertError::invalid_int(value, span))?),
IntegerType::I64 => ConstInt::I64(value.parse().map_err(|_| AsgConvertError::invalid_int(value, span))?),
IntegerType::I128 => ConstInt::I128(value.parse().map_err(|_| AsgConvertError::invalid_int(value, span))?),
IntegerType::U8 => ConstInt::U8(value.parse().map_err(|_| AsgConvertError::invalid_int(value, span))?),
IntegerType::U16 => ConstInt::U16(value.parse().map_err(|_| AsgConvertError::invalid_int(value, span))?),
IntegerType::U32 => ConstInt::U32(value.parse().map_err(|_| AsgConvertError::invalid_int(value, span))?),
IntegerType::U64 => ConstInt::U64(value.parse().map_err(|_| AsgConvertError::invalid_int(value, span))?),
IntegerType::U128 => ConstInt::U128(value.parse().map_err(|_| AsgConvertError::invalid_int(value, span))?),
IntegerType::I8 => ConstInt::I8(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
IntegerType::I16 => ConstInt::I16(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
IntegerType::I32 => ConstInt::I32(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
IntegerType::I64 => ConstInt::I64(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
IntegerType::I128 => ConstInt::I128(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
IntegerType::U8 => ConstInt::U8(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
IntegerType::U16 => ConstInt::U16(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
IntegerType::U32 => ConstInt::U32(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
IntegerType::U64 => ConstInt::U64(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
IntegerType::U128 => ConstInt::U128(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
})
}
}

View File

@ -1,329 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
//! Errors encountered when attempting to convert to an asg from an ast.
use crate::Span;
use leo_ast::{AstError, FormattedError, LeoError};
use leo_parser::SyntaxError;
#[derive(Debug, Error)]
pub enum AsgConvertError {
#[error("{}", _0)]
Error(#[from] FormattedError),
#[error("{}", _0)]
ImportError(FormattedError),
#[error("{}", _0)]
AstError(#[from] AstError),
#[error("{}", _0)]
InternalError(String),
#[error("{}", _0)]
SyntaxError(#[from] SyntaxError),
}
impl LeoError for AsgConvertError {}
impl AsgConvertError {
fn new_from_span(message: String, span: &Span) -> Self {
AsgConvertError::Error(FormattedError::new_from_span(message, span))
}
pub fn unresolved_circuit(name: &str, span: &Span) -> Self {
Self::new_from_span(format!("failed to resolve circuit: '{}'", name), span)
}
pub fn unresolved_import(name: &str, span: &Span) -> Self {
Self::new_from_span(format!("failed to resolve import: '{}'", name), span)
}
pub fn unresolved_circuit_member(circuit_name: &str, name: &str, span: &Span) -> Self {
Self::new_from_span(
format!(
"illegal reference to non-existant member '{}' of circuit '{}'",
name, circuit_name
),
span,
)
}
pub fn missing_circuit_member(circuit_name: &str, name: &str, span: &Span) -> Self {
Self::new_from_span(
format!(
"missing circuit member '{}' for initialization of circuit '{}'",
name, circuit_name
),
span,
)
}
pub fn overridden_circuit_member(circuit_name: &str, name: &str, span: &Span) -> Self {
Self::new_from_span(
format!(
"cannot declare circuit member '{}' more than once for initialization of circuit '{}'",
name, circuit_name
),
span,
)
}
pub fn redefined_circuit_member(circuit_name: &str, name: &str, span: &Span) -> Self {
Self::new_from_span(
format!(
"cannot declare circuit member '{}' multiple times in circuit '{}'",
name, circuit_name
),
span,
)
}
pub fn extra_circuit_member(circuit_name: &str, name: &str, span: &Span) -> Self {
Self::new_from_span(
format!(
"extra circuit member '{}' for initialization of circuit '{}' is not allowed",
name, circuit_name
),
span,
)
}
pub fn illegal_function_assign(name: &str, span: &Span) -> Self {
Self::new_from_span(format!("attempt to assign to function '{}'", name), span)
}
pub fn circuit_variable_call(circuit_name: &str, name: &str, span: &Span) -> Self {
Self::new_from_span(
format!("cannot call variable member '{}' of circuit '{}'", name, circuit_name),
span,
)
}
pub fn circuit_static_call_invalid(circuit_name: &str, name: &str, span: &Span) -> Self {
Self::new_from_span(
format!(
"cannot call static function '{}' of circuit '{}' from target",
name, circuit_name
),
span,
)
}
pub fn circuit_member_mut_call_invalid(circuit_name: &str, name: &str, span: &Span) -> Self {
Self::new_from_span(
format!(
"cannot call mutable member function '{}' of circuit '{}' from immutable context",
name, circuit_name
),
span,
)
}
pub fn circuit_member_call_invalid(circuit_name: &str, name: &str, span: &Span) -> Self {
Self::new_from_span(
format!(
"cannot call member function '{}' of circuit '{}' from static context",
name, circuit_name
),
span,
)
}
pub fn circuit_function_ref(circuit_name: &str, name: &str, span: &Span) -> Self {
Self::new_from_span(
format!(
"cannot reference function member '{}' of circuit '{}' as value",
name, circuit_name
),
span,
)
}
pub fn index_into_non_array(name: &str, span: &Span) -> Self {
Self::new_from_span(format!("failed to index into non-array '{}'", name), span)
}
pub fn invalid_assign_index(name: &str, num: &str, span: &Span) -> Self {
Self::new_from_span(
format!("failed to index array with invalid integer '{}'[{}]", name, num),
span,
)
}
pub fn invalid_backwards_assignment(name: &str, left: usize, right: usize, span: &Span) -> Self {
Self::new_from_span(
format!(
"failed to index array range for assignment with left > right '{}'[{}..{}]",
name, left, right
),
span,
)
}
pub fn invalid_const_assign(name: &str, span: &Span) -> Self {
Self::new_from_span(
format!(
"failed to create const variable(s) '{}' with non constant values.",
name
),
span,
)
}
pub fn duplicate_function_definition(name: &str, span: &Span) -> Self {
Self::new_from_span(
format!("a function named \"{}\" already exists in this scope", name),
span,
)
}
pub fn duplicate_variable_definition(name: &str, span: &Span) -> Self {
Self::new_from_span(
format!("a variable named \"{}\" already exists in this scope", name),
span,
)
}
pub fn index_into_non_tuple(name: &str, span: &Span) -> Self {
Self::new_from_span(format!("failed to index into non-tuple '{}'", name), span)
}
pub fn tuple_index_out_of_bounds(index: usize, span: &Span) -> Self {
Self::new_from_span(format!("tuple index out of bounds: '{}'", index), span)
}
pub fn array_index_out_of_bounds(index: usize, span: &Span) -> Self {
Self::new_from_span(format!("array index out of bounds: '{}'", index), span)
}
pub fn ternary_different_types(left: &str, right: &str, span: &Span) -> Self {
let message = format!("ternary sides had different types: left {}, right {}", left, right);
Self::new_from_span(message, span)
}
pub fn unknown_array_size(span: &Span) -> Self {
Self::new_from_span("array size cannot be inferred, add explicit types".to_string(), span)
}
pub fn unexpected_call_argument_count(expected: usize, got: usize, span: &Span) -> Self {
Self::new_from_span(
format!("function call expected {} arguments, got {}", expected, got),
span,
)
}
pub fn unresolved_function(name: &str, span: &Span) -> Self {
Self::new_from_span(format!("failed to resolve function: '{}'", name), span)
}
pub fn unresolved_type(name: &str, span: &Span) -> Self {
Self::new_from_span(
format!("failed to resolve type for variable definition '{}'", name),
span,
)
}
pub fn unexpected_type(expected: &str, received: Option<&str>, span: &Span) -> Self {
Self::new_from_span(
format!(
"unexpected type, expected: '{}', received: '{}'",
expected,
received.unwrap_or("unknown")
),
span,
)
}
pub fn unexpected_nonconst(span: &Span) -> Self {
Self::new_from_span("expected const, found non-const value".to_string(), span)
}
pub fn unresolved_reference(name: &str, span: &Span) -> Self {
Self::new_from_span(format!("failed to resolve variable reference '{}'", name), span)
}
pub fn invalid_boolean(value: &str, span: &Span) -> Self {
Self::new_from_span(format!("failed to parse boolean value '{}'", value), span)
}
pub fn invalid_char(value: &str, span: &Span) -> Self {
Self::new_from_span(format!("failed to parse char value '{}'", value), span)
}
pub fn invalid_int(value: &str, span: &Span) -> Self {
Self::new_from_span(format!("failed to parse int value '{}'", value), span)
}
pub fn unsigned_negation(span: &Span) -> Self {
Self::new_from_span("cannot negate unsigned integer".to_string(), span)
}
pub fn immutable_assignment(name: &str, span: &Span) -> Self {
Self::new_from_span(format!("illegal assignment to immutable variable '{}'", name), span)
}
pub fn function_missing_return(name: &str, span: &Span) -> Self {
Self::new_from_span(format!("function '{}' missing return for all paths", name), span)
}
pub fn function_return_validation(name: &str, description: &str, span: &Span) -> Self {
Self::new_from_span(
format!("function '{}' failed to validate return path: '{}'", name, description),
span,
)
}
pub fn input_ref_needs_type(category: &str, name: &str, span: &Span) -> Self {
Self::new_from_span(
format!("could not infer type for input in '{}': '{}'", category, name),
span,
)
}
pub fn invalid_self_in_global(span: &Span) -> Self {
Self::new_from_span(
"cannot have `mut self` or `self` arguments in global functions".to_string(),
span,
)
}
pub fn call_test_function(span: &Span) -> Self {
Self::new_from_span("cannot call test function".to_string(), span)
}
pub fn circuit_test_function(span: &Span) -> Self {
Self::new_from_span("cannot have test function as member of circuit".to_string(), span)
}
pub fn parse_index_error() -> Self {
AsgConvertError::InternalError("failed to parse index".to_string())
}
pub fn parse_dimension_error() -> Self {
AsgConvertError::InternalError("failed to parse dimension".to_string())
}
pub fn reference_self_outside_circuit() -> Self {
AsgConvertError::InternalError("referenced self outside of circuit function".to_string())
}
pub fn illegal_ast_structure(details: &str) -> Self {
AsgConvertError::InternalError(format!("illegal ast structure: {}", details))
}
}

View File

@ -14,8 +14,9 @@
// 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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type};
use leo_ast::IntegerType;
use leo_errors::{AsgError, Result, Span};
use std::cell::Cell;
@ -83,7 +84,7 @@ impl<'a> FromAst<'a, leo_ast::ArrayAccessExpression> for ArrayAccessExpression<'
scope: &'a Scope<'a>,
value: &leo_ast::ArrayAccessExpression,
expected_type: Option<PartialType<'a>>,
) -> Result<ArrayAccessExpression<'a>, AsgConvertError> {
) -> Result<ArrayAccessExpression<'a>> {
let array = <&Expression<'a>>::from_ast(
scope,
&*value.array,
@ -92,11 +93,12 @@ impl<'a> FromAst<'a, leo_ast::ArrayAccessExpression> for ArrayAccessExpression<'
let array_len = match array.get_type() {
Some(Type::Array(_, len)) => len,
type_ => {
return Err(AsgConvertError::unexpected_type(
return Err(AsgError::unexpected_type(
"array",
type_.map(|x| x.to_string()).as_deref(),
type_.map(|x| x.to_string()).unwrap_or_else(|| "unknown".to_string()),
&value.span,
));
)
.into());
}
};
@ -112,10 +114,9 @@ impl<'a> FromAst<'a, leo_ast::ArrayAccessExpression> for ArrayAccessExpression<'
.flatten()
{
if index >= array_len {
return Err(AsgConvertError::array_index_out_of_bounds(
index,
&array.span().cloned().unwrap_or_default(),
));
return Err(
AsgError::array_index_out_of_bounds(index, &array.span().cloned().unwrap_or_default()).into(),
);
}
}

View File

@ -14,7 +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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type};
use leo_errors::{AsgError, Result, Span};
use std::cell::Cell;
@ -68,16 +69,12 @@ impl<'a> FromAst<'a, leo_ast::ArrayInitExpression> for ArrayInitExpression<'a> {
scope: &'a Scope<'a>,
value: &leo_ast::ArrayInitExpression,
expected_type: Option<PartialType<'a>>,
) -> Result<ArrayInitExpression<'a>, AsgConvertError> {
) -> Result<ArrayInitExpression<'a>> {
let (mut expected_item, expected_len) = match expected_type {
Some(PartialType::Array(item, dims)) => (item.map(|x| *x), dims),
None => (None, None),
Some(type_) => {
return Err(AsgConvertError::unexpected_type(
&type_.to_string(),
Some("array"),
&value.span,
));
return Err(AsgError::unexpected_type(type_, "array", &value.span).into());
}
};
let dimensions = value
@ -85,20 +82,23 @@ impl<'a> FromAst<'a, leo_ast::ArrayInitExpression> for ArrayInitExpression<'a> {
.0
.iter()
.map(|x| {
x.value
Ok(x.value
.parse::<usize>()
.map_err(|_| AsgConvertError::parse_dimension_error())
.map_err(|_| AsgError::parse_dimension_error(&value.span))?)
})
.collect::<Result<Vec<_>, AsgConvertError>>()?;
.collect::<Result<Vec<_>>>()?;
let len = *dimensions.get(0).ok_or_else(AsgConvertError::parse_dimension_error)?;
let len = *dimensions
.get(0)
.ok_or_else(|| AsgError::parse_dimension_error(&value.span))?;
if let Some(expected_len) = expected_len {
if expected_len != len {
return Err(AsgConvertError::unexpected_type(
&*format!("array of length {}", expected_len),
Some(&*format!("array of length {}", len)),
return Err(AsgError::unexpected_type(
format!("array of length {}", expected_len),
format!("array of length {}", len),
&value.span,
));
)
.into());
}
}
@ -107,11 +107,12 @@ impl<'a> FromAst<'a, leo_ast::ArrayInitExpression> for ArrayInitExpression<'a> {
Some(PartialType::Array(item, len)) => {
if let Some(len) = len {
if len != dimension {
return Err(AsgConvertError::unexpected_type(
&*format!("array of length {}", dimension),
Some(&*format!("array of length {}", len)),
return Err(AsgError::unexpected_type(
format!("array of length {}", dimension),
format!("array of length {}", len),
&value.span,
));
)
.into());
}
}
@ -119,11 +120,7 @@ impl<'a> FromAst<'a, leo_ast::ArrayInitExpression> for ArrayInitExpression<'a> {
}
None => None,
Some(type_) => {
return Err(AsgConvertError::unexpected_type(
"array",
Some(&type_.to_string()),
&value.span,
));
return Err(AsgError::unexpected_type("array", type_, &value.span).into());
}
}
}

View File

@ -14,8 +14,9 @@
// 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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type};
use leo_ast::SpreadOrExpression;
use leo_errors::{AsgError, Result, Span};
use std::cell::Cell;
@ -103,16 +104,12 @@ impl<'a> FromAst<'a, leo_ast::ArrayInlineExpression> for ArrayInlineExpression<'
scope: &'a Scope<'a>,
value: &leo_ast::ArrayInlineExpression,
expected_type: Option<PartialType<'a>>,
) -> Result<ArrayInlineExpression<'a>, AsgConvertError> {
) -> Result<ArrayInlineExpression<'a>> {
let (mut expected_item, expected_len) = match expected_type {
Some(PartialType::Array(item, dims)) => (item.map(|x| *x), dims),
None => (None, None),
Some(type_) => {
return Err(AsgConvertError::unexpected_type(
&type_.to_string(),
Some("array"),
&value.span,
));
return Err(AsgError::unexpected_type(type_, "array", &value.span).into());
}
};
@ -169,29 +166,31 @@ impl<'a> FromAst<'a, leo_ast::ArrayInlineExpression> for ArrayInlineExpression<'
len += spread_len;
}
type_ => {
return Err(AsgConvertError::unexpected_type(
return Err(AsgError::unexpected_type(
expected_item
.as_ref()
.map(|x| x.to_string())
.as_deref()
.unwrap_or("unknown"),
type_.map(|x| x.to_string()).as_deref(),
type_.map(|x| x.to_string()).unwrap_or_else(|| "unknown".to_string()),
&value.span,
));
)
.into());
}
}
Ok((Cell::new(expr), true))
}
})
.collect::<Result<Vec<_>, AsgConvertError>>()?,
.collect::<Result<Vec<_>>>()?,
};
if let Some(expected_len) = expected_len {
if len != expected_len {
return Err(AsgConvertError::unexpected_type(
&*format!("array of length {}", expected_len),
Some(&*format!("array of length {}", len)),
return Err(AsgError::unexpected_type(
format!("array of length {}", expected_len),
format!("array of length {}", len),
&value.span,
));
)
.into());
}
}
Ok(output)

View File

@ -14,8 +14,9 @@
// 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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type};
use leo_ast::IntegerType;
use leo_errors::{AsgError, Result, Span};
use std::cell::Cell;
@ -102,16 +103,12 @@ impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessEx
scope: &'a Scope<'a>,
value: &leo_ast::ArrayRangeAccessExpression,
expected_type: Option<PartialType<'a>>,
) -> Result<ArrayRangeAccessExpression<'a>, AsgConvertError> {
) -> Result<ArrayRangeAccessExpression<'a>> {
let (expected_array, expected_len) = match expected_type.clone() {
Some(PartialType::Array(element, len)) => (Some(PartialType::Array(element, None)), len),
None => (None, None),
Some(x) => {
return Err(AsgConvertError::unexpected_type(
&x.to_string(),
Some("array"),
&value.span,
));
return Err(AsgError::unexpected_type(x, "array", &value.span).into());
}
};
let array = <&Expression<'a>>::from_ast(scope, &*value.array, expected_array)?;
@ -119,11 +116,12 @@ impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessEx
let (parent_element, parent_size) = match array_type {
Some(Type::Array(inner, size)) => (inner, size),
type_ => {
return Err(AsgConvertError::unexpected_type(
return Err(AsgError::unexpected_type(
"array",
type_.map(|x| x.to_string()).as_deref(),
type_.map(|x| x.to_string()).unwrap_or_else(|| "unknown".to_string()),
&value.span,
));
)
.into());
}
};
@ -157,7 +155,7 @@ impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessEx
} else {
value.span.clone()
};
return Err(AsgConvertError::array_index_out_of_bounds(inner_value, &error_span));
return Err(AsgError::array_index_out_of_bounds(inner_value, &error_span).into());
} else if let Some(left) = const_left {
if left > inner_value {
let error_span = if let Some(right) = right {
@ -165,7 +163,7 @@ impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessEx
} else {
value.span.clone()
};
return Err(AsgConvertError::array_index_out_of_bounds(inner_value, &error_span));
return Err(AsgError::array_index_out_of_bounds(inner_value, &error_span).into());
}
}
}
@ -185,11 +183,9 @@ impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessEx
if let Some(length) = length {
if length != expected_len {
let concrete_type = Type::Array(parent_element, length);
return Err(AsgConvertError::unexpected_type(
&expected_type.as_ref().unwrap().to_string(),
Some(&concrete_type.to_string()),
&value.span,
));
return Err(
AsgError::unexpected_type(expected_type.as_ref().unwrap(), concrete_type, &value.span).into(),
);
}
}
if let Some(left_value) = const_left {
@ -199,13 +195,13 @@ impl<'a> FromAst<'a, leo_ast::ArrayRangeAccessExpression> for ArrayRangeAccessEx
} else {
value.span.clone()
};
return Err(AsgConvertError::array_index_out_of_bounds(left_value, &error_span));
return Err(AsgError::array_index_out_of_bounds(left_value, &error_span).into());
}
}
length = Some(expected_len);
}
if length.is_none() {
return Err(AsgConvertError::unknown_array_size(&value.span));
return Err(AsgError::unknown_array_size(&value.span).into());
}
Ok(ArrayRangeAccessExpression {

View File

@ -14,8 +14,9 @@
// 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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type};
pub use leo_ast::{BinaryOperation, BinaryOperationClass};
use leo_errors::{AsgError, Result, Span};
use std::cell::Cell;
@ -116,17 +117,13 @@ impl<'a> FromAst<'a, leo_ast::BinaryExpression> for BinaryExpression<'a> {
scope: &'a Scope<'a>,
value: &leo_ast::BinaryExpression,
expected_type: Option<PartialType<'a>>,
) -> Result<BinaryExpression<'a>, AsgConvertError> {
) -> Result<BinaryExpression<'a>> {
let class = value.op.class();
let expected_type = match class {
BinaryOperationClass::Boolean => match expected_type {
Some(PartialType::Type(Type::Boolean)) | None => None,
Some(x) => {
return Err(AsgConvertError::unexpected_type(
&x.to_string(),
Some(&*Type::Boolean.to_string()),
&value.span,
));
return Err(AsgError::unexpected_type(x, Type::Boolean, &value.span).into());
}
},
BinaryOperationClass::Numeric => match expected_type {
@ -134,11 +131,7 @@ impl<'a> FromAst<'a, leo_ast::BinaryExpression> for BinaryExpression<'a> {
Some(x @ PartialType::Type(Type::Field)) => Some(x),
Some(x @ PartialType::Type(Type::Group)) => Some(x),
Some(x) => {
return Err(AsgConvertError::unexpected_type(
&x.to_string(),
Some("integer, field, or group"),
&value.span,
));
return Err(AsgError::unexpected_type(x, "integer, field, or group", &value.span).into());
}
None => None,
},
@ -187,33 +180,26 @@ impl<'a> FromAst<'a, leo_ast::BinaryExpression> for BinaryExpression<'a> {
}
Some(Type::Field) if value.op == BinaryOperation::Mul || value.op == BinaryOperation::Div => (),
type_ => {
return Err(AsgConvertError::unexpected_type(
return Err(AsgError::unexpected_type(
"integer",
type_.map(|x| x.to_string()).as_deref(),
type_.map(|x| x.to_string()).unwrap_or_else(|| "unknown".to_string()),
&value.span,
));
)
.into());
}
},
BinaryOperationClass::Boolean => match &value.op {
BinaryOperation::And | BinaryOperation::Or => match left_type {
Some(Type::Boolean) | None => (),
Some(x) => {
return Err(AsgConvertError::unexpected_type(
&x.to_string(),
Some(&*Type::Boolean.to_string()),
&value.span,
));
return Err(AsgError::unexpected_type(x, Type::Boolean, &value.span).into());
}
},
BinaryOperation::Eq | BinaryOperation::Ne => (), // all types allowed
_ => match left_type {
Some(Type::Integer(_)) | None => (),
Some(x) => {
return Err(AsgConvertError::unexpected_type(
&x.to_string(),
Some("integer"),
&value.span,
));
return Err(AsgError::unexpected_type(x, "integer", &value.span).into());
}
},
},
@ -224,19 +210,11 @@ impl<'a> FromAst<'a, leo_ast::BinaryExpression> for BinaryExpression<'a> {
match (left_type, right_type) {
(Some(left_type), Some(right_type)) => {
if !left_type.is_assignable_from(&right_type) {
return Err(AsgConvertError::unexpected_type(
&left_type.to_string(),
Some(&*right_type.to_string()),
&value.span,
));
return Err(AsgError::unexpected_type(left_type, right_type, &value.span).into());
}
}
(None, None) => {
return Err(AsgConvertError::unexpected_type(
"any type",
Some("unknown type"),
&value.span,
));
return Err(AsgError::unexpected_type("any type", "unknown type", &value.span).into());
}
(_, _) => (),
}

View File

@ -15,10 +15,11 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
AsgConvertError, CircuitMember, ConstValue, Expression, ExpressionNode, FromAst, Function, FunctionQualifier, Node,
PartialType, Scope, Span, Type,
CircuitMember, ConstValue, Expression, ExpressionNode, FromAst, Function, FunctionQualifier, Node, PartialType,
Scope, Type,
};
pub use leo_ast::{BinaryOperation, Node as AstNode};
use leo_errors::{AsgError, Result, Span};
use std::cell::Cell;
@ -78,13 +79,13 @@ impl<'a> FromAst<'a, leo_ast::CallExpression> for CallExpression<'a> {
scope: &'a Scope<'a>,
value: &leo_ast::CallExpression,
expected_type: Option<PartialType<'a>>,
) -> Result<CallExpression<'a>, AsgConvertError> {
) -> Result<CallExpression<'a>> {
let (target, function) = match &*value.function {
leo_ast::Expression::Identifier(name) => (
None,
scope
.resolve_function(&name.name)
.ok_or_else(|| AsgConvertError::unresolved_function(&name.name, &name.span))?,
.ok_or_else(|| AsgError::unresolved_function(&name.name, &name.span))?,
),
leo_ast::Expression::CircuitMemberAccess(leo_ast::CircuitMemberAccessExpression {
circuit: ast_circuit,
@ -95,37 +96,32 @@ impl<'a> FromAst<'a, leo_ast::CallExpression> for CallExpression<'a> {
let circuit = match target.get_type() {
Some(Type::Circuit(circuit)) => circuit,
type_ => {
return Err(AsgConvertError::unexpected_type(
return Err(AsgError::unexpected_type(
"circuit",
type_.map(|x| x.to_string()).as_deref(),
type_.map(|x| x.to_string()).unwrap_or_else(|| "unknown".to_string()),
span,
));
)
.into());
}
};
let circuit_name = circuit.name.borrow().name.clone();
let member = circuit.members.borrow();
let member = member
.get(name.name.as_ref())
.ok_or_else(|| AsgConvertError::unresolved_circuit_member(&circuit_name, &name.name, span))?;
.ok_or_else(|| AsgError::unresolved_circuit_member(&circuit_name, &name.name, span))?;
match member {
CircuitMember::Function(body) => {
if body.qualifier == FunctionQualifier::Static {
return Err(AsgConvertError::circuit_static_call_invalid(
&circuit_name,
&name.name,
span,
));
return Err(AsgError::circuit_static_call_invalid(&circuit_name, &name.name, span).into());
} else if body.qualifier == FunctionQualifier::MutSelfRef && !target.is_mut_ref() {
return Err(AsgConvertError::circuit_member_mut_call_invalid(
&circuit_name,
&name.name,
span,
));
return Err(
AsgError::circuit_member_mut_call_invalid(circuit_name, &name.name, span).into(),
);
}
(Some(target), *body)
}
CircuitMember::Variable(_) => {
return Err(AsgConvertError::circuit_variable_call(&circuit_name, &name.name, span));
return Err(AsgError::circuit_variable_call(circuit_name, &name.name, span).into());
}
}
}
@ -137,54 +133,49 @@ impl<'a> FromAst<'a, leo_ast::CallExpression> for CallExpression<'a> {
let circuit = if let leo_ast::Expression::Identifier(circuit_name) = &**ast_circuit {
scope
.resolve_circuit(&circuit_name.name)
.ok_or_else(|| AsgConvertError::unresolved_circuit(&circuit_name.name, &circuit_name.span))?
.ok_or_else(|| AsgError::unresolved_circuit(&circuit_name.name, &circuit_name.span))?
} else {
return Err(AsgConvertError::unexpected_type("circuit", None, span));
return Err(AsgError::unexpected_type("circuit", "unknown", span).into());
};
let circuit_name = circuit.name.borrow().name.clone();
let member = circuit.members.borrow();
let member = member
.get(name.name.as_ref())
.ok_or_else(|| AsgConvertError::unresolved_circuit_member(&circuit_name, &name.name, span))?;
.ok_or_else(|| AsgError::unresolved_circuit_member(&circuit_name, &name.name, span))?;
match member {
CircuitMember::Function(body) => {
if body.qualifier != FunctionQualifier::Static {
return Err(AsgConvertError::circuit_member_call_invalid(
&circuit_name,
&name.name,
span,
));
return Err(AsgError::circuit_member_call_invalid(circuit_name, &name.name, span).into());
}
(None, *body)
}
CircuitMember::Variable(_) => {
return Err(AsgConvertError::circuit_variable_call(&circuit_name, &name.name, span));
return Err(AsgError::circuit_variable_call(circuit_name, &name.name, span).into());
}
}
}
_ => {
return Err(AsgConvertError::illegal_ast_structure(
return Err(AsgError::illegal_ast_structure(
"non Identifier/CircuitMemberAccess/CircuitStaticFunctionAccess as call target",
));
&value.span,
)
.into());
}
};
if let Some(expected) = expected_type {
let output: Type = function.output.clone();
if !expected.matches(&output) {
return Err(AsgConvertError::unexpected_type(
&expected.to_string(),
Some(&*output.to_string()),
&value.span,
));
return Err(AsgError::unexpected_type(expected, output, &value.span).into());
}
}
if value.arguments.len() != function.arguments.len() {
return Err(AsgConvertError::unexpected_call_argument_count(
return Err(AsgError::unexpected_call_argument_count(
function.arguments.len(),
value.arguments.len(),
&value.span,
));
)
.into());
}
let arguments = value
@ -195,14 +186,14 @@ impl<'a> FromAst<'a, leo_ast::CallExpression> for CallExpression<'a> {
let argument = argument.get().borrow();
let converted = <&Expression<'a>>::from_ast(scope, expr, Some(argument.type_.clone().partial()))?;
if argument.const_ && !converted.is_consty() {
return Err(AsgConvertError::unexpected_nonconst(expr.span()));
return Err(AsgError::unexpected_nonconst(expr.span()).into());
}
Ok(Cell::new(converted))
})
.collect::<Result<Vec<_>, AsgConvertError>>()?;
.collect::<Result<Vec<_>>>()?;
if function.is_test() {
return Err(AsgConvertError::call_test_function(&value.span));
return Err(AsgError::call_test_function(&value.span).into());
}
Ok(CallExpression {
parent: Cell::new(None),

View File

@ -14,8 +14,9 @@
// 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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type};
pub use leo_ast::UnaryOperation;
use leo_errors::{AsgError, Result, Span};
use std::cell::Cell;
@ -75,15 +76,11 @@ impl<'a> FromAst<'a, leo_ast::CastExpression> for CastExpression<'a> {
scope: &'a Scope<'a>,
value: &leo_ast::CastExpression,
expected_type: Option<PartialType<'a>>,
) -> Result<CastExpression<'a>, AsgConvertError> {
let target_type = scope.resolve_ast_type(&value.target_type)?;
) -> Result<CastExpression<'a>> {
let target_type = scope.resolve_ast_type(&value.target_type, &value.span)?;
if let Some(expected_type) = &expected_type {
if !expected_type.matches(&target_type) {
return Err(AsgConvertError::unexpected_type(
&expected_type.to_string(),
Some(&target_type.to_string()),
&value.span,
));
return Err(AsgError::unexpected_type(expected_type, target_type, &value.span).into());
}
}

View File

@ -15,10 +15,10 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
AsgConvertError, Circuit, CircuitMember, ConstValue, Expression, ExpressionNode, FromAst, Identifier, Node,
PartialType, Scope, Span, Type,
Circuit, CircuitMember, ConstValue, Expression, ExpressionNode, FromAst, Identifier, Node, PartialType, Scope, Type,
};
use leo_errors::{AsgError, Result, Span};
use std::cell::Cell;
#[derive(Clone)]
@ -92,16 +92,17 @@ impl<'a> FromAst<'a, leo_ast::CircuitMemberAccessExpression> for CircuitAccessEx
scope: &'a Scope<'a>,
value: &leo_ast::CircuitMemberAccessExpression,
expected_type: Option<PartialType<'a>>,
) -> Result<CircuitAccessExpression<'a>, AsgConvertError> {
) -> Result<CircuitAccessExpression<'a>> {
let target = <&'a Expression<'a>>::from_ast(scope, &*value.circuit, None)?;
let circuit = match target.get_type() {
Some(Type::Circuit(circuit)) => circuit,
x => {
return Err(AsgConvertError::unexpected_type(
return Err(AsgError::unexpected_type(
"circuit",
x.map(|x| x.to_string()).as_deref(),
x.map(|x| x.to_string()).unwrap_or_else(|| "unknown".to_string()),
&value.span,
));
)
.into());
}
};
@ -112,11 +113,7 @@ impl<'a> FromAst<'a, leo_ast::CircuitMemberAccessExpression> for CircuitAccessEx
if let CircuitMember::Variable(type_) = &member {
let type_: Type = type_.clone();
if !expected_type.matches(&type_) {
return Err(AsgConvertError::unexpected_type(
&expected_type.to_string(),
Some(&type_.to_string()),
&value.span,
));
return Err(AsgError::unexpected_type(expected_type, type_, &value.span).into());
}
} // used by call expression
}
@ -136,18 +133,17 @@ impl<'a> FromAst<'a, leo_ast::CircuitMemberAccessExpression> for CircuitAccessEx
CircuitMember::Variable(expected_type.clone()),
);
} else {
return Err(AsgConvertError::input_ref_needs_type(
&circuit.name.borrow().name,
&value.name.name,
&value.span,
));
return Err(
AsgError::input_ref_needs_type(&circuit.name.borrow().name, &value.name.name, &value.span).into(),
);
}
} else {
return Err(AsgConvertError::unresolved_circuit_member(
return Err(AsgError::unresolved_circuit_member(
&circuit.name.borrow().name,
&value.name.name,
&value.span,
));
)
.into());
}
Ok(CircuitAccessExpression {
@ -165,36 +161,29 @@ impl<'a> FromAst<'a, leo_ast::CircuitStaticFunctionAccessExpression> for Circuit
scope: &Scope<'a>,
value: &leo_ast::CircuitStaticFunctionAccessExpression,
expected_type: Option<PartialType>,
) -> Result<CircuitAccessExpression<'a>, AsgConvertError> {
) -> Result<CircuitAccessExpression<'a>> {
let circuit = match &*value.circuit {
leo_ast::Expression::Identifier(name) => scope
.resolve_circuit(&name.name)
.ok_or_else(|| AsgConvertError::unresolved_circuit(&name.name, &name.span))?,
.ok_or_else(|| AsgError::unresolved_circuit(&name.name, &name.span))?,
_ => {
return Err(AsgConvertError::unexpected_type(
"circuit",
Some("unknown"),
&value.span,
));
return Err(AsgError::unexpected_type("circuit", "unknown", &value.span).into());
}
};
if let Some(expected_type) = expected_type {
return Err(AsgConvertError::unexpected_type(
&expected_type.to_string(),
Some("none"),
&value.span,
));
return Err(AsgError::unexpected_type(expected_type, "none", &value.span).into());
}
if let Some(CircuitMember::Function(_)) = circuit.members.borrow().get(value.name.name.as_ref()) {
// okay
} else {
return Err(AsgConvertError::unresolved_circuit_member(
return Err(AsgError::unresolved_circuit_member(
&circuit.name.borrow().name,
&value.name.name,
&value.span,
));
)
.into());
}
Ok(CircuitAccessExpression {

View File

@ -15,10 +15,11 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
AsgConvertError, Circuit, CircuitMember, ConstValue, Expression, ExpressionNode, FromAst, Identifier, Node,
PartialType, Scope, Span, Type,
Circuit, CircuitMember, ConstValue, Expression, ExpressionNode, FromAst, Identifier, Node, PartialType, Scope, Type,
};
use leo_errors::{AsgError, Result, Span};
use indexmap::{IndexMap, IndexSet};
use std::cell::Cell;
@ -82,19 +83,15 @@ impl<'a> FromAst<'a, leo_ast::CircuitInitExpression> for CircuitInitExpression<'
scope: &'a Scope<'a>,
value: &leo_ast::CircuitInitExpression,
expected_type: Option<PartialType<'a>>,
) -> Result<CircuitInitExpression<'a>, AsgConvertError> {
) -> Result<CircuitInitExpression<'a>> {
let circuit = scope
.resolve_circuit(&value.name.name)
.ok_or_else(|| AsgConvertError::unresolved_circuit(&value.name.name, &value.name.span))?;
.ok_or_else(|| AsgError::unresolved_circuit(&value.name.name, &value.name.span))?;
match expected_type {
Some(PartialType::Type(Type::Circuit(expected_circuit))) if expected_circuit == circuit => (),
None => (),
Some(x) => {
return Err(AsgConvertError::unexpected_type(
&x.to_string(),
Some(&circuit.name.borrow().name),
&value.span,
));
return Err(AsgError::unexpected_type(x, circuit.name.borrow().name.to_string(), &value.span).into());
}
}
let members: IndexMap<&str, (&Identifier, Option<&leo_ast::Expression>)> = value
@ -110,11 +107,9 @@ impl<'a> FromAst<'a, leo_ast::CircuitInitExpression> for CircuitInitExpression<'
let circuit_members = circuit.members.borrow();
for (name, member) in circuit_members.iter() {
if defined_variables.contains(name) {
return Err(AsgConvertError::overridden_circuit_member(
&circuit.name.borrow().name,
name,
&value.span,
));
return Err(
AsgError::overridden_circuit_member(&circuit.name.borrow().name, name, &value.span).into(),
);
}
defined_variables.insert(name.clone());
let type_: Type = if let CircuitMember::Variable(type_) = &member {
@ -134,21 +129,17 @@ impl<'a> FromAst<'a, leo_ast::CircuitInitExpression> for CircuitInitExpression<'
};
values.push(((*identifier).clone(), Cell::new(received)));
} else {
return Err(AsgConvertError::missing_circuit_member(
&circuit.name.borrow().name,
name,
&value.span,
));
return Err(
AsgError::missing_circuit_member(&circuit.name.borrow().name, name, &value.span).into(),
);
}
}
for (name, (identifier, _expression)) in members.iter() {
if circuit_members.get(*name).is_none() {
return Err(AsgConvertError::extra_circuit_member(
&circuit.name.borrow().name,
*name,
&identifier.span,
));
return Err(
AsgError::extra_circuit_member(&circuit.name.borrow().name, name, &identifier.span).into(),
);
}
}
}

View File

@ -15,10 +15,11 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
AsgConvertError, CharValue, ConstInt, ConstValue, Expression, ExpressionNode, FromAst, GroupValue, Node,
PartialType, Scope, Span, Type,
CharValue, ConstInt, ConstValue, Expression, ExpressionNode, FromAst, GroupValue, Node, PartialType, Scope, Type,
};
use leo_errors::{AsgError, Result, Span};
use std::cell::Cell;
#[derive(Clone)]
@ -67,18 +68,14 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
_scope: &'a Scope<'a>,
value: &leo_ast::ValueExpression,
expected_type: Option<PartialType<'a>>,
) -> Result<Constant<'a>, AsgConvertError> {
) -> Result<Constant<'a>> {
use leo_ast::ValueExpression::*;
Ok(match value {
Address(value, span) => {
match expected_type.map(PartialType::full).flatten() {
Some(Type::Address) | None => (),
Some(x) => {
return Err(AsgConvertError::unexpected_type(
&x.to_string(),
Some(&*Type::Address.to_string()),
span,
));
return Err(AsgError::unexpected_type(x, Type::Address, span).into());
}
}
Constant {
@ -91,11 +88,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
match expected_type.map(PartialType::full).flatten() {
Some(Type::Boolean) | None => (),
Some(x) => {
return Err(AsgConvertError::unexpected_type(
&x.to_string(),
Some(&*Type::Boolean.to_string()),
span,
));
return Err(AsgError::unexpected_type(x, Type::Boolean, span).into());
}
}
Constant {
@ -104,7 +97,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
value: ConstValue::Boolean(
value
.parse::<bool>()
.map_err(|_| AsgConvertError::invalid_boolean(value, span))?,
.map_err(|_| AsgError::invalid_boolean(value, span))?,
),
}
}
@ -112,11 +105,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
match expected_type.map(PartialType::full).flatten() {
Some(Type::Char) | None => (),
Some(x) => {
return Err(AsgConvertError::unexpected_type(
&x.to_string(),
Some(&*Type::Char.to_string()),
value.span(),
));
return Err(AsgError::unexpected_type(x, Type::Char, value.span()).into());
}
}
@ -130,28 +119,20 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
match expected_type.map(PartialType::full).flatten() {
Some(Type::Field) | None => (),
Some(x) => {
return Err(AsgConvertError::unexpected_type(
&x.to_string(),
Some(&*Type::Field.to_string()),
span,
));
return Err(AsgError::unexpected_type(x, Type::Field, span).into());
}
}
Constant {
parent: Cell::new(None),
span: Some(span.clone()),
value: ConstValue::Field(value.parse().map_err(|_| AsgConvertError::invalid_int(value, span))?),
value: ConstValue::Field(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
}
}
Group(value) => {
match expected_type.map(PartialType::full).flatten() {
Some(Type::Group) | None => (),
Some(x) => {
return Err(AsgConvertError::unexpected_type(
&x.to_string(),
Some(&*Type::Group.to_string()),
value.span(),
));
return Err(AsgError::unexpected_type(x, Type::Group, value.span()).into());
}
}
Constant {
@ -166,7 +147,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
}
}
Implicit(value, span) => match expected_type {
None => return Err(AsgConvertError::unresolved_type("unknown", span)),
None => return Err(AsgError::unresolved_type("unknown", span).into()),
Some(PartialType::Integer(Some(sub_type), _)) | Some(PartialType::Integer(None, Some(sub_type))) => {
Constant {
parent: Cell::new(None),
@ -177,7 +158,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
Some(PartialType::Type(Type::Field)) => Constant {
parent: Cell::new(None),
span: Some(span.clone()),
value: ConstValue::Field(value.parse().map_err(|_| AsgConvertError::invalid_int(value, span))?),
value: ConstValue::Field(value.parse().map_err(|_| AsgError::invalid_int(value, span))?),
},
Some(PartialType::Type(Type::Group)) => Constant {
parent: Cell::new(None),
@ -189,7 +170,9 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
span: Some(span.clone()),
value: ConstValue::Address(value.clone()),
},
Some(x) => return Err(AsgConvertError::unexpected_type(&x.to_string(), Some("unknown"), span)),
Some(x) => {
return Err(AsgError::unexpected_type(x, "unknown", span).into());
}
},
Integer(int_type, value, span) => {
match expected_type {
@ -197,11 +180,7 @@ impl<'a> FromAst<'a, leo_ast::ValueExpression> for Constant<'a> {
Some(PartialType::Integer(None, Some(_))) => (),
None => (),
Some(x) => {
return Err(AsgConvertError::unexpected_type(
&x.to_string(),
Some(&*int_type.to_string()),
span,
));
return Err(AsgError::unexpected_type(x, int_type, span).into());
}
}
Constant {

View File

@ -65,7 +65,8 @@ pub use variable_ref::*;
mod cast;
pub use cast::*;
use crate::{AsgConvertError, ConstValue, FromAst, Node, PartialType, Scope, Span, Type};
use crate::{ConstValue, FromAst, Node, PartialType, Scope, Type};
use leo_errors::{Result, Span};
#[derive(Clone)]
pub enum Expression<'a> {
@ -284,7 +285,7 @@ impl<'a> FromAst<'a, leo_ast::Expression> for &'a Expression<'a> {
scope: &'a Scope<'a>,
value: &leo_ast::Expression,
expected_type: Option<PartialType<'a>>,
) -> Result<Self, AsgConvertError> {
) -> Result<Self> {
use leo_ast::Expression::*;
let expression = match value {
Identifier(identifier) => Self::from_ast(scope, identifier, expected_type)?,

View File

@ -14,7 +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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type};
use leo_errors::{AsgError, Result, Span};
use std::cell::Cell;
@ -78,7 +79,7 @@ impl<'a> FromAst<'a, leo_ast::TernaryExpression> for TernaryExpression<'a> {
scope: &'a Scope<'a>,
value: &leo_ast::TernaryExpression,
expected_type: Option<PartialType<'a>>,
) -> Result<TernaryExpression<'a>, AsgConvertError> {
) -> Result<TernaryExpression<'a>> {
let if_true = Cell::new(<&Expression<'a>>::from_ast(
scope,
&*value.if_true,
@ -90,11 +91,7 @@ impl<'a> FromAst<'a, leo_ast::TernaryExpression> for TernaryExpression<'a> {
let right = if_false.get().get_type().unwrap().into();
if left != right {
return Err(AsgConvertError::ternary_different_types(
&left.to_string(),
&right.to_string(),
&value.span,
));
return Err(AsgError::ternary_different_types(left, right, &value.span).into());
}
Ok(TernaryExpression {

View File

@ -14,7 +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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type};
use leo_errors::{AsgError, Result, Span};
use std::cell::Cell;
@ -74,12 +75,12 @@ impl<'a> FromAst<'a, leo_ast::TupleAccessExpression> for TupleAccessExpression<'
scope: &'a Scope<'a>,
value: &leo_ast::TupleAccessExpression,
expected_type: Option<PartialType<'a>>,
) -> Result<TupleAccessExpression<'a>, AsgConvertError> {
) -> Result<TupleAccessExpression<'a>> {
let index = value
.index
.value
.parse::<usize>()
.map_err(|_| AsgConvertError::parse_index_error())?;
.map_err(|_| AsgError::parse_index_error(&value.span))?;
let mut expected_tuple = vec![None; index + 1];
expected_tuple[index] = expected_type;
@ -88,11 +89,14 @@ impl<'a> FromAst<'a, leo_ast::TupleAccessExpression> for TupleAccessExpression<'
let tuple_type = tuple.get_type();
if let Some(Type::Tuple(_items)) = tuple_type {
} else {
return Err(AsgConvertError::unexpected_type(
return Err(AsgError::unexpected_type(
"a tuple",
tuple_type.map(|x| x.to_string()).as_deref(),
tuple_type
.map(|x| x.to_string())
.unwrap_or_else(|| "unknown".to_string()),
&value.span,
));
)
.into());
}
Ok(TupleAccessExpression {

View File

@ -14,7 +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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type};
use leo_errors::{AsgError, Result, Span};
use std::cell::Cell;
@ -80,16 +81,17 @@ impl<'a> FromAst<'a, leo_ast::TupleInitExpression> for TupleInitExpression<'a> {
scope: &'a Scope<'a>,
value: &leo_ast::TupleInitExpression,
expected_type: Option<PartialType<'a>>,
) -> Result<TupleInitExpression<'a>, AsgConvertError> {
) -> Result<TupleInitExpression<'a>> {
let tuple_types = match expected_type {
Some(PartialType::Tuple(sub_types)) => Some(sub_types),
None => None,
x => {
return Err(AsgConvertError::unexpected_type(
return Err(AsgError::unexpected_type(
"tuple",
x.map(|x| x.to_string()).as_deref(),
x.map(|x| x.to_string()).unwrap_or_else(|| "unknown".to_string()),
&value.span,
));
)
.into());
}
};
@ -97,11 +99,12 @@ impl<'a> FromAst<'a, leo_ast::TupleInitExpression> for TupleInitExpression<'a> {
// Expected type can be equal or less than actual size of a tuple.
// Size of expected tuple can be based on accessed index.
if tuple_types.len() > value.elements.len() {
return Err(AsgConvertError::unexpected_type(
&*format!("tuple of length {}", tuple_types.len()),
Some(&*format!("tuple of length {}", value.elements.len())),
return Err(AsgError::unexpected_type(
format!("tuple of length {}", tuple_types.len()),
format!("tuple of length {}", value.elements.len()),
&value.span,
));
)
.into());
}
}
@ -117,7 +120,7 @@ impl<'a> FromAst<'a, leo_ast::TupleInitExpression> for TupleInitExpression<'a> {
)
.map(Cell::new)
})
.collect::<Result<Vec<_>, AsgConvertError>>()?;
.collect::<Result<Vec<_>>>()?;
Ok(TupleInitExpression {
parent: Cell::new(None),

View File

@ -14,8 +14,9 @@
// 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::{AsgConvertError, ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Span, Type};
use crate::{ConstValue, Expression, ExpressionNode, FromAst, Node, PartialType, Scope, Type};
pub use leo_ast::UnaryOperation;
use leo_errors::{AsgError, Result, Span};
use std::cell::Cell;
@ -89,16 +90,12 @@ impl<'a> FromAst<'a, leo_ast::UnaryExpression> for UnaryExpression<'a> {
scope: &'a Scope<'a>,
value: &leo_ast::UnaryExpression,
expected_type: Option<PartialType<'a>>,
) -> Result<UnaryExpression<'a>, AsgConvertError> {
) -> Result<UnaryExpression<'a>> {
let expected_type = match value.op {
UnaryOperation::Not => match expected_type.map(|x| x.full()).flatten() {
Some(Type::Boolean) | None => Some(Type::Boolean),
Some(type_) => {
return Err(AsgConvertError::unexpected_type(
&type_.to_string(),
Some(&*Type::Boolean.to_string()),
&value.span,
));
return Err(AsgError::unexpected_type(type_, Type::Boolean, &value.span).into());
}
},
UnaryOperation::Negate => match expected_type.map(|x| x.full()).flatten() {
@ -107,22 +104,14 @@ impl<'a> FromAst<'a, leo_ast::UnaryExpression> for UnaryExpression<'a> {
Some(Type::Field) => Some(Type::Field),
None => None,
Some(type_) => {
return Err(AsgConvertError::unexpected_type(
&type_.to_string(),
Some("integer, group, field"),
&value.span,
));
return Err(AsgError::unexpected_type(type_, "integer, group, field", &value.span).into());
}
},
UnaryOperation::BitNot => match expected_type.map(|x| x.full()).flatten() {
Some(type_ @ Type::Integer(_)) => Some(type_),
None => None,
Some(type_) => {
return Err(AsgConvertError::unexpected_type(
&type_.to_string(),
Some("integer"),
&value.span,
));
return Err(AsgError::unexpected_type(type_, "integer", &value.span).into());
}
},
};
@ -137,7 +126,7 @@ impl<'a> FromAst<'a, leo_ast::UnaryExpression> for UnaryExpression<'a> {
})
.unwrap_or(false);
if is_expr_unsigned {
return Err(AsgConvertError::unsigned_negation(&value.span));
return Err(AsgError::unsigned_negation(&value.span).into());
}
}
Ok(UnaryExpression {

View File

@ -15,10 +15,12 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
AsgConvertError, ConstValue, Constant, DefinitionStatement, Expression, ExpressionNode, FromAst, Node, PartialType,
Scope, Span, Statement, Type, Variable,
ConstValue, Constant, DefinitionStatement, Expression, ExpressionNode, FromAst, Node, PartialType, Scope,
Statement, Type, Variable,
};
use leo_errors::{AsgError, Result, Span};
use std::cell::Cell;
#[derive(Clone)]
@ -123,14 +125,12 @@ impl<'a> FromAst<'a, leo_ast::Identifier> for &'a Expression<'a> {
scope: &'a Scope<'a>,
value: &leo_ast::Identifier,
expected_type: Option<PartialType<'a>>,
) -> Result<&'a Expression<'a>, AsgConvertError> {
) -> Result<&'a Expression<'a>> {
let variable = if value.name.as_ref() == "input" {
if let Some(input) = scope.resolve_input() {
input.container
} else {
return Err(AsgConvertError::InternalError(
"attempted to reference input when none is in scope".to_string(),
));
return Err(AsgError::illegal_input_variable_reference(&value.span).into());
}
} else {
match scope.resolve_variable(&value.name) {
@ -143,7 +143,7 @@ impl<'a> FromAst<'a, leo_ast::Identifier> for &'a Expression<'a> {
value: ConstValue::Address(value.name.clone()),
})));
}
return Err(AsgConvertError::unresolved_reference(&value.name, &value.span));
return Err(AsgError::unresolved_reference(&value.name, &value.span).into());
}
}
};
@ -158,13 +158,9 @@ impl<'a> FromAst<'a, leo_ast::Identifier> for &'a Expression<'a> {
if let Some(expected_type) = expected_type {
let type_ = expression
.get_type()
.ok_or_else(|| AsgConvertError::unresolved_reference(&value.name, &value.span))?;
.ok_or_else(|| AsgError::unresolved_reference(&value.name, &value.span))?;
if !expected_type.matches(&type_) {
return Err(AsgConvertError::unexpected_type(
&expected_type.to_string(),
Some(&*type_.to_string()),
&value.span,
));
return Err(AsgError::unexpected_type(expected_type, type_, &value.span).into());
}
}

View File

@ -18,7 +18,8 @@
use std::marker::PhantomData;
use crate::{AsgContext, AsgConvertError, Program, Span};
use crate::{AsgContext, Program};
use leo_errors::{Result, Span};
use indexmap::IndexMap;
@ -28,7 +29,7 @@ pub trait ImportResolver<'a> {
context: AsgContext<'a>,
package_segments: &[&str],
span: &Span,
) -> Result<Option<Program<'a>>, AsgConvertError>;
) -> Result<Option<Program<'a>>>;
}
pub struct NullImportResolver;
@ -39,7 +40,7 @@ impl<'a> ImportResolver<'a> for NullImportResolver {
_context: AsgContext<'a>,
_package_segments: &[&str],
_span: &Span,
) -> Result<Option<Program<'a>>, AsgConvertError> {
) -> Result<Option<Program<'a>>> {
Ok(None)
}
}
@ -64,7 +65,7 @@ impl<'a, 'b, T: ImportResolver<'b>> ImportResolver<'b> for CoreImportResolver<'a
context: AsgContext<'b>,
package_segments: &[&str],
span: &Span,
) -> Result<Option<Program<'b>>, AsgConvertError> {
) -> Result<Option<Program<'b>>> {
if !package_segments.is_empty() && package_segments.get(0).unwrap() == &"core" {
Ok(crate::resolve_core_module(context, &*package_segments[1..].join("."))?)
} else {
@ -83,7 +84,7 @@ impl<'a> ImportResolver<'a> for MockedImportResolver<'a> {
_context: AsgContext<'a>,
package_segments: &[&str],
_span: &Span,
) -> Result<Option<Program<'a>>, AsgConvertError> {
) -> Result<Option<Program<'a>>> {
Ok(self.packages.get(&package_segments.join(".")).cloned())
}
}

View File

@ -15,6 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Circuit, CircuitMember, Identifier, Scope, Type, Variable};
use leo_errors::Span;
use indexmap::IndexMap;
use std::cell::RefCell;
@ -44,7 +45,7 @@ impl<'a> Input<'a> {
members: RefCell::new(IndexMap::new()),
core_mapping: RefCell::new(None),
scope,
span: Default::default(),
span: Some(Span::default()),
})
}
@ -73,7 +74,7 @@ impl<'a> Input<'a> {
members: RefCell::new(container_members),
core_mapping: RefCell::new(None),
scope: input_scope,
span: Default::default(),
span: Some(Span::default()),
});
Input {

View File

@ -24,9 +24,7 @@
#![allow(clippy::from_over_into)]
#![allow(clippy::result_unit_err)]
#[macro_use]
extern crate thiserror;
#![doc = include_str!("../README.md")]
pub mod checks;
pub use checks::*;
@ -34,9 +32,6 @@ pub use checks::*;
pub mod const_value;
pub use const_value::*;
pub mod error;
pub use error::*;
pub mod expression;
pub use expression::*;
@ -77,7 +72,8 @@ pub use pass::*;
pub mod context;
pub use context::*;
pub use leo_ast::{Ast, Identifier, Span};
pub use leo_ast::{Ast, Identifier};
use leo_errors::Result;
/// The abstract semantic graph (ASG) for a Leo program.
///
@ -97,7 +93,7 @@ impl<'a> Asg<'a> {
context: AsgContext<'a>,
ast: Y,
resolver: &mut T,
) -> Result<Self, AsgConvertError> {
) -> Result<Self> {
Ok(Self {
context,
asg: Program::new(context, ast.as_ref(), resolver)?,
@ -130,7 +126,7 @@ pub fn load_asg<'a, T: ImportResolver<'a>>(
context: AsgContext<'a>,
content: &str,
resolver: &mut T,
) -> Result<Program<'a>, AsgConvertError> {
) -> Result<Program<'a>> {
// Parses the Leo file and constructs a grammar ast.
let ast = leo_parser::parse_ast("input.leo", content)?;

View File

@ -14,9 +14,9 @@
// 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::{
AsgContextInner, AsgConvertError, Circuit, Expression, Function, PartialType, Scope, Span, Statement, Variable,
};
use crate::{AsgContextInner, Circuit, Expression, Function, PartialType, Scope, Statement, Variable};
use leo_errors::{Result, Span};
/// A node in the abstract semantic graph.
pub trait Node {
@ -26,11 +26,7 @@ pub trait Node {
pub(super) trait FromAst<'a, T: leo_ast::Node + 'static>: Sized {
// expected_type contract: if present, output expression must be of type expected_type.
// type of an element may NEVER be None unless it is functionally a non-expression. (static call targets, function ref call targets are not expressions)
fn from_ast(
scope: &'a Scope<'a>,
value: &T,
expected_type: Option<PartialType<'a>>,
) -> Result<Self, AsgConvertError>;
fn from_ast(scope: &'a Scope<'a>, value: &T, expected_type: Option<PartialType<'a>>) -> Result<Self>;
}
pub enum ArenaNode<'a> {

View File

@ -15,8 +15,8 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::Program;
pub use leo_ast::FormattedError;
use leo_errors::Result;
pub trait AsgPass<'a> {
fn do_pass(asg: Program<'a>) -> Result<Program<'a>, FormattedError>;
fn do_pass(asg: Program<'a>) -> Result<Program<'a>>;
}

View File

@ -16,12 +16,13 @@
// TODO (protryon): We should merge this with core
use crate::{AsgContext, AsgConvertError, Program};
use crate::{AsgContext, Program};
use leo_errors::Result;
// TODO (protryon): Make asg deep copy so we can cache resolved core modules
// TODO (protryon): Figure out how to do headers without bogus returns
pub fn resolve_core_module<'a>(context: AsgContext<'a>, module: &str) -> Result<Option<Program<'a>>, AsgConvertError> {
pub fn resolve_core_module<'a>(context: AsgContext<'a>, module: &str) -> Result<Option<Program<'a>>> {
match module {
"unstable.blake2s" => {
let asg = crate::load_asg(

View File

@ -14,7 +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::{AsgConvertError, Function, Identifier, Node, Scope, Span, Type};
use crate::{Function, Identifier, Node, Scope, Type};
use leo_errors::{AsgError, Result, Span};
use indexmap::IndexMap;
use std::cell::RefCell;
@ -53,7 +54,7 @@ impl<'a> Node for Circuit<'a> {
}
impl<'a> Circuit<'a> {
pub(super) fn init(scope: &'a Scope<'a>, value: &leo_ast::Circuit) -> Result<&'a Circuit<'a>, AsgConvertError> {
pub(super) fn init(scope: &'a Scope<'a>, value: &leo_ast::Circuit) -> Result<&'a Circuit<'a>> {
let new_scope = scope.make_subscope();
let circuit = scope.context.alloc_circuit(Circuit {
@ -64,21 +65,18 @@ impl<'a> Circuit<'a> {
span: Some(value.circuit_name.span.clone()),
scope: new_scope,
});
new_scope.circuit_self.replace(Some(circuit));
let mut members = circuit.members.borrow_mut();
for member in value.members.iter() {
if let leo_ast::CircuitMember::CircuitVariable(name, type_) = member {
if members.contains_key(name.name.as_ref()) {
return Err(AsgConvertError::redefined_circuit_member(
&value.circuit_name.name,
&name.name,
&name.span,
));
return Err(
AsgError::redefined_circuit_member(&value.circuit_name.name, &name.name, &name.span).into(),
);
}
members.insert(
name.name.to_string(),
CircuitMember::Variable(new_scope.resolve_ast_type(type_)?),
CircuitMember::Variable(new_scope.resolve_ast_type(type_, &name.span)?),
);
}
}
@ -86,30 +84,27 @@ impl<'a> Circuit<'a> {
Ok(circuit)
}
pub(super) fn init_member(
scope: &'a Scope<'a>,
value: &leo_ast::Circuit,
) -> Result<&'a Circuit<'a>, AsgConvertError> {
pub(super) fn init_member(scope: &'a Scope<'a>, value: &leo_ast::Circuit) -> Result<&'a Circuit<'a>> {
let new_scope = scope.make_subscope();
let circuits = scope.circuits.borrow();
let circuit = circuits.get(value.circuit_name.name.as_ref()).unwrap();
new_scope.circuit_self.replace(Some(circuit));
let mut members = circuit.members.borrow_mut();
for member in value.members.iter() {
if let leo_ast::CircuitMember::CircuitFunction(function) = member {
if members.contains_key(function.identifier.name.as_ref()) {
return Err(AsgConvertError::redefined_circuit_member(
return Err(AsgError::redefined_circuit_member(
&value.circuit_name.name,
&function.identifier.name,
&function.identifier.span,
));
)
.into());
}
let asg_function = Function::init(new_scope, function)?;
asg_function.circuit.replace(Some(circuit));
if asg_function.is_test() {
return Err(AsgConvertError::circuit_test_function(&function.identifier.span));
return Err(AsgError::circuit_test_function(&function.identifier.span).into());
}
members.insert(
function.identifier.name.to_string(),
@ -121,7 +116,7 @@ impl<'a> Circuit<'a> {
Ok(circuit)
}
pub(super) fn fill_from_ast(self: &'a Circuit<'a>, value: &leo_ast::Circuit) -> Result<(), AsgConvertError> {
pub(super) fn fill_from_ast(self: &'a Circuit<'a>, value: &leo_ast::Circuit) -> Result<()> {
for member in value.members.iter() {
match member {
leo_ast::CircuitMember::CircuitVariable(..) => {}

View File

@ -15,12 +15,12 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
AsgConvertError, BlockStatement, Circuit, FromAst, Identifier, MonoidalDirector, ReturnPathReducer, Scope, Span,
Statement, Type, Variable,
BlockStatement, Circuit, FromAst, Identifier, MonoidalDirector, ReturnPathReducer, Scope, Statement, Type, Variable,
};
use indexmap::IndexMap;
pub use leo_ast::Annotation;
use leo_ast::FunctionInput;
use leo_errors::{AsgError, Result, Span};
use std::cell::{Cell, RefCell};
@ -58,11 +58,11 @@ impl<'a> PartialEq for Function<'a> {
impl<'a> Eq for Function<'a> {}
impl<'a> Function<'a> {
pub(crate) fn init(scope: &'a Scope<'a>, value: &leo_ast::Function) -> Result<&'a Function<'a>, AsgConvertError> {
pub(crate) fn init(scope: &'a Scope<'a>, value: &leo_ast::Function) -> Result<&'a Function<'a>> {
let output: Type<'a> = value
.output
.as_ref()
.map(|t| scope.resolve_ast_type(t))
.map(|t| scope.resolve_ast_type(t, &value.span))
.transpose()?
.unwrap_or_else(|| Type::Tuple(vec![]));
let mut qualifier = FunctionQualifier::Static;
@ -81,31 +81,22 @@ impl<'a> Function<'a> {
FunctionInput::MutSelfKeyword(_) => {
qualifier = FunctionQualifier::MutSelfRef;
}
FunctionInput::Variable(leo_ast::FunctionInputVariable {
type_,
identifier,
const_,
mutable,
..
}) => {
FunctionInput::Variable(input_variable) => {
let variable = scope.context.alloc_variable(RefCell::new(crate::InnerVariable {
id: scope.context.get_id(),
name: identifier.clone(),
type_: scope.resolve_ast_type(type_)?,
mutable: *mutable,
const_: *const_,
name: input_variable.identifier.clone(),
type_: scope.resolve_ast_type(&input_variable.type_, &value.span)?,
mutable: input_variable.mutable,
const_: input_variable.const_,
declaration: crate::VariableDeclaration::Parameter,
references: vec![],
assignments: vec![],
}));
arguments.insert(identifier.name.to_string(), Cell::new(&*variable));
arguments.insert(input_variable.identifier.name.to_string(), Cell::new(&*variable));
}
}
}
}
if qualifier != FunctionQualifier::Static && scope.circuit_self.get().is_none() {
return Err(AsgConvertError::invalid_self_in_global(&value.span));
}
let function = scope.context.alloc_function(Function {
id: scope.context.get_id(),
name: RefCell::new(value.identifier.clone()),
@ -123,7 +114,7 @@ impl<'a> Function<'a> {
Ok(function)
}
pub(super) fn fill_from_ast(self: &'a Function<'a>, value: &leo_ast::Function) -> Result<(), AsgConvertError> {
pub(super) fn fill_from_ast(self: &'a Function<'a>, value: &leo_ast::Function) -> Result<()> {
if self.qualifier != FunctionQualifier::Static {
let circuit = self.circuit.get();
let self_variable = self.scope.context.alloc_variable(RefCell::new(crate::InnerVariable {
@ -148,19 +139,12 @@ impl<'a> Function<'a> {
let main_block = BlockStatement::from_ast(self.scope, &value.block, None)?;
let mut director = MonoidalDirector::new(ReturnPathReducer::new());
if !director.reduce_block(&main_block).0 && !self.output.is_unit() {
return Err(AsgConvertError::function_missing_return(
&self.name.borrow().name,
&value.span,
));
return Err(AsgError::function_missing_return(&self.name.borrow().name, &value.span).into());
}
#[allow(clippy::never_loop)] // TODO @Protryon: How should we return multiple errors?
for (span, error) in director.reducer().errors {
return Err(AsgConvertError::function_return_validation(
&self.name.borrow().name,
&error,
&span,
));
return Err(AsgError::function_return_validation(&self.name.borrow().name, error, &span).into());
}
self.body

View File

@ -24,10 +24,9 @@ pub use circuit::*;
mod function;
pub use function::*;
use crate::{
node::FromAst, ArenaNode, AsgContext, AsgConvertError, DefinitionStatement, ImportResolver, Input, Scope, Statement,
};
use leo_ast::{Identifier, PackageAccess, PackageOrPackages, Span};
use crate::{node::FromAst, ArenaNode, AsgContext, DefinitionStatement, ImportResolver, Input, Scope, Statement};
use leo_ast::{Identifier, PackageAccess, PackageOrPackages};
use leo_errors::{AsgError, Result, Span};
use indexmap::IndexMap;
use std::cell::{Cell, RefCell};
@ -138,7 +137,7 @@ impl<'a> Program<'a> {
context: AsgContext<'a>,
program: &leo_ast::Program,
import_resolver: &mut T,
) -> Result<Program<'a>, AsgConvertError> {
) -> Result<Program<'a>> {
// Recursively extract imported symbols.
let mut imported_symbols: Vec<(Vec<String>, ImportSymbol, Span)> = vec![];
for import in program.imports.iter() {
@ -164,7 +163,9 @@ impl<'a> Program<'a> {
span,
)? {
Some(x) => x,
None => return Err(AsgConvertError::unresolved_import(&*pretty_package, &Span::default())),
None => {
return Err(AsgError::unresolved_import(pretty_package, &Span::default()).into());
}
};
resolved_packages.insert(package.clone(), resolved_package);
@ -195,10 +196,7 @@ impl<'a> Program<'a> {
} else if let Some(global_const) = resolved_package.global_consts.get(&name) {
imported_global_consts.insert(name.clone(), *global_const);
} else {
return Err(AsgConvertError::unresolved_import(
&*format!("{}.{}", pretty_package, name),
&span,
));
return Err(AsgError::unresolved_import(format!("{}.{}", pretty_package, name), &span).into());
}
}
ImportSymbol::Alias(name, alias) => {
@ -209,10 +207,7 @@ impl<'a> Program<'a> {
} else if let Some(global_const) = resolved_package.global_consts.get(&name) {
imported_global_consts.insert(alias.clone(), *global_const);
} else {
return Err(AsgConvertError::unresolved_import(
&*format!("{}.{}", pretty_package, name),
&span,
));
return Err(AsgError::unresolved_import(format!("{}.{}", pretty_package, name), &span).into());
}
}
}
@ -222,7 +217,6 @@ impl<'a> Program<'a> {
context,
id: context.get_id(),
parent_scope: Cell::new(None),
circuit_self: Cell::new(None),
variables: RefCell::new(IndexMap::new()),
functions: RefCell::new(imported_functions),
global_consts: RefCell::new(imported_global_consts),
@ -239,7 +233,6 @@ impl<'a> Program<'a> {
input: Cell::new(Some(Input::new(import_scope))), // we use import_scope to avoid recursive scope ref here
id: context.get_id(),
parent_scope: Cell::new(Some(import_scope)),
circuit_self: Cell::new(None),
variables: RefCell::new(IndexMap::new()),
functions: RefCell::new(IndexMap::new()),
global_consts: RefCell::new(IndexMap::new()),
@ -303,7 +296,7 @@ impl<'a> Program<'a> {
let name = name.name.to_string();
if functions.contains_key(&name) {
return Err(AsgConvertError::duplicate_function_definition(&name, &function.span));
return Err(AsgError::duplicate_function_definition(name, &function.span).into());
}
functions.insert(name, asg_function);

View File

@ -14,7 +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::{AsgContext, AsgConvertError, Circuit, DefinitionStatement, Function, Input, Type, Variable};
use crate::{AsgContext, Circuit, DefinitionStatement, Function, Input, Type, Variable};
use leo_errors::{AsgError, Result, Span};
use indexmap::IndexMap;
use std::cell::{Cell, RefCell};
@ -33,9 +34,6 @@ pub struct Scope<'a> {
/// The function definition that this scope occurs in.
pub function: Cell<Option<&'a Function<'a>>>,
/// The circuit definition that this scope occurs in.
pub circuit_self: Cell<Option<&'a Circuit<'a>>>,
/// Maps variable name => variable.
pub variables: RefCell<IndexMap<String, &'a Variable<'a>>>,
@ -127,8 +125,6 @@ impl<'a> Scope<'a> {
pub fn resolve_circuit(&self, name: &str) -> Option<&'a Circuit<'a>> {
if let Some(resolved) = self.circuits.borrow().get(name) {
Some(*resolved)
} else if name == "Self" && self.circuit_self.get().is_some() {
self.circuit_self.get()
} else if let Some(resolved) = self.parent_scope.get() {
resolved.resolve_circuit(name)
} else {
@ -136,22 +132,6 @@ impl<'a> Scope<'a> {
}
}
///
/// Returns a reference to the current circuit.
///
/// If the current scope did not have a circuit self present, then the parent scope is checked.
/// If there is no parent scope, then `None` is returned.
///
pub fn resolve_circuit_self(&self) -> Option<&'a Circuit<'a>> {
if let Some(resolved) = self.circuit_self.get() {
Some(resolved)
} else if let Some(resolved) = self.parent_scope.get() {
resolved.resolve_circuit_self()
} else {
None
}
}
///
/// Returns a new scope given a parent scope.
///
@ -160,7 +140,6 @@ impl<'a> Scope<'a> {
context: self.context,
id: self.context.get_id(),
parent_scope: Cell::new(Some(self)),
circuit_self: Cell::new(None),
variables: RefCell::new(IndexMap::new()),
functions: RefCell::new(IndexMap::new()),
circuits: RefCell::new(IndexMap::new()),
@ -173,7 +152,7 @@ impl<'a> Scope<'a> {
///
/// Returns the type returned by the current scope.
///
pub fn resolve_ast_type(&self, type_: &leo_ast::Type) -> Result<Type<'a>, AsgConvertError> {
pub fn resolve_ast_type(&self, type_: &leo_ast::Type, span: &Span) -> Result<Type<'a>> {
use leo_ast::Type::*;
Ok(match type_ {
Address => Type::Address,
@ -183,12 +162,12 @@ impl<'a> Scope<'a> {
Group => Type::Group,
IntegerType(int_type) => Type::Integer(int_type.clone()),
Array(sub_type, dimensions) => {
let mut item = Box::new(self.resolve_ast_type(&*sub_type)?);
let mut item = Box::new(self.resolve_ast_type(&*sub_type, span)?);
for dimension in dimensions.0.iter().rev() {
let dimension = dimension
.value
.parse::<usize>()
.map_err(|_| AsgConvertError::parse_index_error())?;
.map_err(|_| AsgError::parse_index_error(span))?;
item = Box::new(Type::Array(item, dimension));
}
*item
@ -196,20 +175,13 @@ impl<'a> Scope<'a> {
Tuple(sub_types) => Type::Tuple(
sub_types
.iter()
.map(|x| self.resolve_ast_type(x))
.collect::<Result<Vec<_>, AsgConvertError>>()?,
),
Circuit(name) if name.name.as_ref() == "Self" => Type::Circuit(
self.resolve_circuit_self()
.ok_or_else(|| AsgConvertError::unresolved_circuit(&name.name, &name.span))?,
),
SelfType => Type::Circuit(
self.resolve_circuit_self()
.ok_or_else(AsgConvertError::reference_self_outside_circuit)?,
.map(|x| self.resolve_ast_type(x, span))
.collect::<Result<Vec<_>>>()?,
),
SelfType => return Err(AsgError::unexpected_big_self(span).into()),
Circuit(name) => Type::Circuit(
self.resolve_circuit(&name.name)
.ok_or_else(|| AsgConvertError::unresolved_circuit(&name.name, &name.span))?,
.ok_or_else(|| AsgError::unresolved_circuit(&name.name, &name.span))?,
),
})
}

View File

@ -15,11 +15,12 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
AsgConvertError, CircuitMember, ConstInt, ConstValue, Expression, ExpressionNode, FromAst, Identifier, IntegerType,
Node, PartialType, Scope, Span, Statement, Type, Variable,
CircuitMember, ConstInt, ConstValue, Expression, ExpressionNode, FromAst, Identifier, IntegerType, Node,
PartialType, Scope, Statement, Type, Variable,
};
pub use leo_ast::AssignOperation;
use leo_ast::AssigneeAccess as AstAssigneeAccess;
use leo_errors::{AsgError, Result, Span};
use std::cell::Cell;
@ -52,25 +53,26 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> {
scope: &'a Scope<'a>,
statement: &leo_ast::AssignStatement,
_expected_type: Option<PartialType<'a>>,
) -> Result<Self, AsgConvertError> {
let (name, span) = (&statement.assignee.identifier.name, &statement.assignee.identifier.span);
) -> Result<Self> {
let (name, span) = (
&statement.assignee.identifier.name.clone(),
&statement.assignee.identifier.span,
);
let variable = if name.as_ref() == "input" {
if let Some(input) = scope.resolve_input() {
input.container
} else {
return Err(AsgConvertError::InternalError(
"attempted to reference input when none is in scope".to_string(),
));
return Err(AsgError::illegal_input_variable_reference(&statement.span).into());
}
} else {
scope
.resolve_variable(name)
.ok_or_else(|| AsgConvertError::unresolved_reference(name, span))?
.ok_or_else(|| AsgError::unresolved_reference(name, span))?
};
if !variable.borrow().mutable {
return Err(AsgConvertError::immutable_assignment(name, &statement.span));
return Err(AsgError::immutable_assignment(name, &statement.span).into());
}
let mut target_type: Option<PartialType> = Some(variable.borrow().type_.clone().into());
@ -81,19 +83,15 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> {
let index_type = Some(PartialType::Integer(None, Some(IntegerType::U32)));
let left = left
.as_ref()
.map(
|left: &leo_ast::Expression| -> Result<&'a Expression<'a>, AsgConvertError> {
.map(|left: &leo_ast::Expression| -> Result<&'a Expression<'a>> {
<&Expression<'a>>::from_ast(scope, left, index_type.clone())
},
)
})
.transpose()?;
let right = right
.as_ref()
.map(
|right: &leo_ast::Expression| -> Result<&'a Expression<'a>, AsgConvertError> {
.map(|right: &leo_ast::Expression| -> Result<&'a Expression<'a>> {
<&Expression<'a>>::from_ast(scope, right, index_type)
},
)
})
.transpose()?;
match &target_type {
@ -109,29 +107,30 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> {
) {
let left = match left {
ConstValue::Int(x) => x.to_usize().ok_or_else(|| {
AsgConvertError::invalid_assign_index(name, &x.to_string(), &statement.span)
AsgError::invalid_assign_index(name, x.to_string(), &statement.span)
})?,
_ => unimplemented!(),
};
let right = match right {
ConstValue::Int(x) => x.to_usize().ok_or_else(|| {
AsgConvertError::invalid_assign_index(name, &x.to_string(), &statement.span)
AsgError::invalid_assign_index(name, x.to_string(), &statement.span)
})?,
_ => unimplemented!(),
};
if right >= left {
target_type = Some(PartialType::Array(item.clone(), Some((right - left) as usize)))
} else {
return Err(AsgConvertError::invalid_backwards_assignment(
return Err(AsgError::invalid_backwards_assignment(
name,
left,
right,
&statement.span,
));
)
.into());
}
}
}
_ => return Err(AsgConvertError::index_into_non_array(name, &statement.span)),
_ => return Err(AsgError::index_into_non_array(name, &statement.span).into()),
}
AssignAccess::ArrayRange(Cell::new(left), Cell::new(right))
@ -139,7 +138,7 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> {
AstAssigneeAccess::ArrayIndex(index) => {
target_type = match target_type.clone() {
Some(PartialType::Array(item, _)) => item.map(|x| *x),
_ => return Err(AsgConvertError::index_into_non_array(name, &statement.span)),
_ => return Err(AsgError::index_into_non_array(name, &statement.span).into()),
};
AssignAccess::ArrayIndex(Cell::new(<&Expression<'a>>::from_ast(
scope,
@ -147,17 +146,17 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> {
Some(PartialType::Integer(None, Some(IntegerType::U32))),
)?))
}
AstAssigneeAccess::Tuple(index, _) => {
AstAssigneeAccess::Tuple(index, span) => {
let index = index
.value
.parse::<usize>()
.map_err(|_| AsgConvertError::parse_index_error())?;
.map_err(|_| AsgError::parse_index_error(span))?;
target_type = match target_type {
Some(PartialType::Tuple(types)) => types
.get(index)
.cloned()
.ok_or_else(|| AsgConvertError::tuple_index_out_of_bounds(index, &statement.span))?,
_ => return Err(AsgConvertError::index_into_non_tuple(name, &statement.span)),
.ok_or_else(|| AsgError::tuple_index_out_of_bounds(index, &statement.span))?,
_ => return Err(AsgError::index_into_non_tuple(name, &statement.span).into()),
};
AssignAccess::Tuple(index)
}
@ -168,7 +167,7 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> {
let members = circuit.members.borrow();
let member = members.get(name.name.as_ref()).ok_or_else(|| {
AsgConvertError::unresolved_circuit_member(
AsgError::unresolved_circuit_member(
&circuit.name.borrow().name,
&name.name,
&statement.span,
@ -178,16 +177,17 @@ impl<'a> FromAst<'a, leo_ast::AssignStatement> for &'a Statement<'a> {
let x = match &member {
CircuitMember::Variable(type_) => type_.clone(),
CircuitMember::Function(_) => {
return Err(AsgConvertError::illegal_function_assign(&name.name, &statement.span));
return Err(AsgError::illegal_function_assign(&name.name, &statement.span).into());
}
};
Some(x.partial())
}
_ => {
return Err(AsgConvertError::index_into_non_tuple(
return Err(AsgError::index_into_non_tuple(
&statement.assignee.identifier.name,
&statement.span,
));
)
.into());
}
};
AssignAccess::Member(name.clone())

View File

@ -14,7 +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::{AsgConvertError, FromAst, Node, PartialType, Scope, Span, Statement};
use crate::{FromAst, Node, PartialType, Scope, Statement};
use leo_errors::{Result, Span};
use std::cell::Cell;
@ -37,7 +38,7 @@ impl<'a> FromAst<'a, leo_ast::Block> for BlockStatement<'a> {
scope: &'a Scope<'a>,
statement: &leo_ast::Block,
_expected_type: Option<PartialType<'a>>,
) -> Result<Self, AsgConvertError> {
) -> Result<Self> {
let new_scope = scope.make_subscope();
let mut output = vec![];

View File

@ -14,7 +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::{AsgConvertError, BlockStatement, Expression, FromAst, Node, PartialType, Scope, Span, Statement, Type};
use crate::{BlockStatement, Expression, FromAst, Node, PartialType, Scope, Statement, Type};
use leo_errors::{Result, Span};
use std::cell::Cell;
@ -38,7 +39,7 @@ impl<'a> FromAst<'a, leo_ast::ConditionalStatement> for ConditionalStatement<'a>
scope: &'a Scope<'a>,
statement: &leo_ast::ConditionalStatement,
_expected_type: Option<PartialType<'a>>,
) -> Result<Self, AsgConvertError> {
) -> Result<Self> {
let condition = <&Expression<'a>>::from_ast(scope, &statement.condition, Some(Type::Boolean.into()))?;
let result = scope.context.alloc_statement(Statement::Block(BlockStatement::from_ast(
scope,
@ -48,9 +49,7 @@ impl<'a> FromAst<'a, leo_ast::ConditionalStatement> for ConditionalStatement<'a>
let next = statement
.next
.as_deref()
.map(|next| -> Result<&'a Statement<'a>, AsgConvertError> {
<&'a Statement<'a>>::from_ast(scope, next, None)
})
.map(|next| -> Result<&'a Statement<'a>> { <&'a Statement<'a>>::from_ast(scope, next, None) })
.transpose()?;
Ok(ConditionalStatement {

View File

@ -14,8 +14,9 @@
// 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::{AsgConvertError, CharValue, Expression, FromAst, Node, PartialType, Scope, Span, Statement, Type};
use crate::{CharValue, Expression, FromAst, Node, PartialType, Scope, Statement, Type};
use leo_ast::ConsoleFunction as AstConsoleFunction;
use leo_errors::{Result, Span};
use std::cell::Cell;
@ -52,7 +53,7 @@ impl<'a> FromAst<'a, leo_ast::ConsoleArgs> for ConsoleArgs<'a> {
scope: &'a Scope<'a>,
value: &leo_ast::ConsoleArgs,
_expected_type: Option<PartialType<'a>>,
) -> Result<Self, AsgConvertError> {
) -> Result<Self> {
let mut parameters = vec![];
for parameter in value.parameters.iter() {
parameters.push(Cell::new(<&Expression<'a>>::from_ast(scope, parameter, None)?));
@ -80,7 +81,7 @@ impl<'a> FromAst<'a, leo_ast::ConsoleStatement> for ConsoleStatement<'a> {
scope: &'a Scope<'a>,
statement: &leo_ast::ConsoleStatement,
_expected_type: Option<PartialType<'a>>,
) -> Result<Self, AsgConvertError> {
) -> Result<Self> {
Ok(ConsoleStatement {
parent: Cell::new(None),
span: Some(statement.span.clone()),

View File

@ -14,10 +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::{
AsgConvertError, Expression, ExpressionNode, FromAst, InnerVariable, Node, PartialType, Scope, Span, Statement,
Type, Variable,
};
use crate::{Expression, ExpressionNode, FromAst, InnerVariable, Node, PartialType, Scope, Statement, Type, Variable};
use leo_errors::{AsgError, Result, Span};
use std::cell::{Cell, RefCell};
@ -59,11 +57,11 @@ impl<'a> FromAst<'a, leo_ast::DefinitionStatement> for &'a Statement<'a> {
scope: &'a Scope<'a>,
statement: &leo_ast::DefinitionStatement,
_expected_type: Option<PartialType<'a>>,
) -> Result<Self, AsgConvertError> {
) -> Result<Self> {
let type_ = statement
.type_
.as_ref()
.map(|x| scope.resolve_ast_type(x))
.map(|x| scope.resolve_ast_type(x, &statement.span))
.transpose()?;
let value = <&Expression<'a>>::from_ast(scope, &statement.value, type_.clone().map(Into::into))?;
@ -76,7 +74,7 @@ impl<'a> FromAst<'a, leo_ast::DefinitionStatement> for &'a Statement<'a> {
.collect::<Vec<String>>()
.join(" ,");
return Err(AsgConvertError::invalid_const_assign(&var_names, &statement.span));
return Err(AsgError::invalid_const_assign(var_names, &statement.span).into());
}
let type_ = type_.or_else(|| value.get_type());
@ -85,9 +83,11 @@ impl<'a> FromAst<'a, leo_ast::DefinitionStatement> for &'a Statement<'a> {
let mut variables = vec![];
if statement.variable_names.is_empty() {
return Err(AsgConvertError::illegal_ast_structure(
return Err(AsgError::illegal_ast_structure(
"cannot have 0 variable names in destructuring tuple",
));
&statement.span,
)
.into());
}
if statement.variable_names.len() == 1 {
// any return type is fine
@ -99,11 +99,12 @@ impl<'a> FromAst<'a, leo_ast::DefinitionStatement> for &'a Statement<'a> {
output_types.extend(sub_types.clone().into_iter().map(Some).collect::<Vec<_>>());
}
type_ => {
return Err(AsgConvertError::unexpected_type(
&*format!("{}-ary tuple", statement.variable_names.len()),
type_.map(|x| x.to_string()).as_deref(),
return Err(AsgError::unexpected_type(
format!("{}-ary tuple", statement.variable_names.len()),
type_.map(|x| x.to_string()).unwrap_or_else(|| "unknown".to_string()),
&statement.span,
));
)
.into());
}
}
}
@ -112,8 +113,7 @@ impl<'a> FromAst<'a, leo_ast::DefinitionStatement> for &'a Statement<'a> {
variables.push(&*scope.context.alloc_variable(RefCell::new(InnerVariable {
id: scope.context.get_id(),
name: variable.identifier.clone(),
type_:
type_.ok_or_else(|| AsgConvertError::unresolved_type(&variable.identifier.name, &statement.span))?,
type_: type_.ok_or_else(|| AsgError::unresolved_type(&variable.identifier.name, &statement.span))?,
mutable: variable.mutable,
const_: false,
declaration: crate::VariableDeclaration::Definition,
@ -126,10 +126,7 @@ impl<'a> FromAst<'a, leo_ast::DefinitionStatement> for &'a Statement<'a> {
let mut variables = scope.variables.borrow_mut();
let var_name = variable.borrow().name.name.to_string();
if variables.contains_key(&var_name) {
return Err(AsgConvertError::duplicate_variable_definition(
&var_name,
&statement.span,
));
return Err(AsgError::duplicate_variable_definition(var_name, &statement.span).into());
}
variables.insert(var_name, *variable);

View File

@ -14,7 +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::{AsgConvertError, Expression, FromAst, Node, PartialType, Scope, Span, Statement};
use crate::{Expression, FromAst, Node, PartialType, Scope, Statement};
use leo_errors::{Result, Span};
use std::cell::Cell;
@ -36,7 +37,7 @@ impl<'a> FromAst<'a, leo_ast::ExpressionStatement> for ExpressionStatement<'a> {
scope: &'a Scope<'a>,
statement: &leo_ast::ExpressionStatement,
_expected_type: Option<PartialType<'a>>,
) -> Result<Self, AsgConvertError> {
) -> Result<Self> {
let expression = <&Expression<'a>>::from_ast(scope, &statement.expression, None)?;
Ok(ExpressionStatement {

View File

@ -16,10 +16,8 @@
use leo_ast::IntegerType;
use crate::{
AsgConvertError, Expression, ExpressionNode, FromAst, InnerVariable, Node, PartialType, Scope, Span, Statement,
Variable,
};
use crate::{Expression, ExpressionNode, FromAst, InnerVariable, Node, PartialType, Scope, Statement, Variable};
use leo_errors::{AsgError, Result, Span};
use std::cell::{Cell, RefCell};
@ -45,21 +43,17 @@ impl<'a> FromAst<'a, leo_ast::IterationStatement> for &'a Statement<'a> {
scope: &'a Scope<'a>,
statement: &leo_ast::IterationStatement,
_expected_type: Option<PartialType<'a>>,
) -> Result<Self, AsgConvertError> {
) -> Result<Self> {
let expected_index_type = Some(PartialType::Integer(Some(IntegerType::U32), None));
let start = <&Expression<'a>>::from_ast(scope, &statement.start, expected_index_type.clone())?;
let stop = <&Expression<'a>>::from_ast(scope, &statement.stop, expected_index_type)?;
// Return an error if start or stop is not constant.
if !start.is_consty() {
return Err(AsgConvertError::unexpected_nonconst(
&start.span().cloned().unwrap_or_default(),
));
return Err(AsgError::unexpected_nonconst(&start.span().cloned().unwrap_or_default()).into());
}
if !stop.is_consty() {
return Err(AsgConvertError::unexpected_nonconst(
&stop.span().cloned().unwrap_or_default(),
));
return Err(AsgError::unexpected_nonconst(&stop.span().cloned().unwrap_or_default()).into());
}
let variable = scope.context.alloc_variable(RefCell::new(InnerVariable {
@ -67,7 +61,7 @@ impl<'a> FromAst<'a, leo_ast::IterationStatement> for &'a Statement<'a> {
name: statement.variable.clone(),
type_: start
.get_type()
.ok_or_else(|| AsgConvertError::unresolved_type(&statement.variable.name, &statement.span))?,
.ok_or_else(|| AsgError::unresolved_type(&statement.variable.name, &statement.span))?,
mutable: false,
const_: true,
declaration: crate::VariableDeclaration::IterationDefinition,

View File

@ -42,7 +42,8 @@ pub use iteration::*;
mod return_;
pub use return_::*;
use crate::{AsgConvertError, FromAst, Node, PartialType, Scope, Span};
use crate::{FromAst, Node, PartialType, Scope};
use leo_errors::{Result, Span};
#[derive(Clone)]
pub enum Statement<'a> {
@ -79,14 +80,14 @@ impl<'a> FromAst<'a, leo_ast::Statement> for &'a Statement<'a> {
scope: &'a Scope<'a>,
value: &leo_ast::Statement,
_expected_type: Option<PartialType<'a>>,
) -> Result<&'a Statement<'a>, AsgConvertError> {
) -> Result<&'a Statement<'a>> {
use leo_ast::Statement::*;
Ok(match value {
Return(statement) => scope
.context
.alloc_statement(Statement::Return(ReturnStatement::from_ast(scope, statement, None)?)),
Definition(statement) => Self::from_ast(scope, statement, None)?,
Assign(statement) => Self::from_ast(scope, statement, None)?,
Assign(statement) => Self::from_ast(scope, &**statement, None)?,
Conditional(statement) => {
scope
.context
@ -94,7 +95,7 @@ impl<'a> FromAst<'a, leo_ast::Statement> for &'a Statement<'a> {
scope, statement, None,
)?))
}
Iteration(statement) => Self::from_ast(scope, statement, None)?,
Iteration(statement) => Self::from_ast(scope, &**statement, None)?,
Console(statement) => scope
.context
.alloc_statement(Statement::Console(ConsoleStatement::from_ast(scope, statement, None)?)),
@ -118,9 +119,9 @@ impl<'a> Into<leo_ast::Statement> for &Statement<'a> {
match self {
Return(statement) => leo_ast::Statement::Return(statement.into()),
Definition(statement) => leo_ast::Statement::Definition(statement.into()),
Assign(statement) => leo_ast::Statement::Assign(statement.into()),
Assign(statement) => leo_ast::Statement::Assign(Box::new(statement.into())),
Conditional(statement) => leo_ast::Statement::Conditional(statement.into()),
Iteration(statement) => leo_ast::Statement::Iteration(statement.into()),
Iteration(statement) => leo_ast::Statement::Iteration(Box::new(statement.into())),
Console(statement) => leo_ast::Statement::Console(statement.into()),
Expression(statement) => leo_ast::Statement::Expression(statement.into()),
Block(statement) => leo_ast::Statement::Block(statement.into()),

View File

@ -14,7 +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::{AsgConvertError, Expression, FromAst, Node, PartialType, Scope, Span, Statement, Type};
use crate::{Expression, FromAst, Node, PartialType, Scope, Statement, Type};
use leo_errors::{Result, Span};
use std::cell::Cell;
#[derive(Clone)]
@ -35,7 +36,7 @@ impl<'a> FromAst<'a, leo_ast::ReturnStatement> for ReturnStatement<'a> {
scope: &'a Scope<'a>,
statement: &leo_ast::ReturnStatement,
_expected_type: Option<PartialType<'a>>,
) -> Result<Self, AsgConvertError> {
) -> Result<Self> {
let return_type: Option<Type> = scope
.resolve_current_function()
.map(|x| x.output.clone())

View File

@ -15,6 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::*;
use leo_errors::LeoError;
use leo_parser::parse_ast;
mod fail;
@ -22,7 +23,7 @@ mod pass;
const TESTING_FILEPATH: &str = "input.leo";
fn load_asg(program_string: &str) -> Result<Program<'static>, AsgConvertError> {
fn load_asg(program_string: &str) -> Result<Program<'static>, LeoError> {
load_asg_imports(make_test_context(), program_string, &mut NullImportResolver)
}
@ -30,8 +31,9 @@ fn load_asg_imports<'a, T: ImportResolver<'a>>(
context: AsgContext<'a>,
program_string: &str,
imports: &mut T,
) -> Result<Program<'a>, AsgConvertError> {
let ast = parse_ast(&TESTING_FILEPATH, program_string)?;
) -> Result<Program<'a>, LeoError> {
let mut ast = parse_ast(&TESTING_FILEPATH, program_string)?;
ast.canonicalize()?;
Program::new(context, &ast.as_repr(), imports)
}

View File

@ -21,6 +21,10 @@ edition = "2018"
path = "../input"
version = "1.5.3"
[dependencies.leo-errors]
path = "../errors"
version = "1.5.3"
[dependencies.indexmap]
version = "1.7.0"
features = [ "serde-1" ]
@ -35,12 +39,6 @@ features = [ "derive", "rc" ]
[dependencies.serde_json]
version = "1.0"
[dependencies.anyhow]
version = "1.0"
[dependencies.thiserror]
version = "1.0"
[dependencies.tendril]
version = "0.4"

View File

@ -1,4 +1,5 @@
# leo-ast
[![Crates.io](https://img.shields.io/crates/v/leo-ast.svg?color=neon)](https://crates.io/crates/leo-ast)
[![Authors](https://img.shields.io/badge/authors-Aleo-orange.svg)](../AUTHORS)
[![License](https://img.shields.io/badge/License-GPLv3-blue.svg)](./LICENSE.md)

View File

@ -14,7 +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::{Identifier, Span};
use crate::Identifier;
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use tendril::StrTendril;

View File

@ -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 crate::common::span::Span;
use leo_errors::Span;
use serde::{Deserialize, Serialize};
// use serde::de::{Deserialize as SerDeserialize, Deserializer};

View File

@ -14,7 +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::{Identifier, Node, Span};
use crate::{Identifier, Node};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -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 crate::Span;
use leo_errors::Span;
use leo_input::common::Identifier as InputIdentifier;
use tendril::StrTendril;

View File

@ -32,12 +32,7 @@ pub use positive_number::*;
pub mod self_keyword;
pub use self_keyword::*;
pub mod span;
pub use span::*;
pub mod spread_or_expression;
pub use spread_or_expression::*;
pub mod tendril_json;
pub mod vec_tendril_json;

View File

@ -14,7 +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::{Identifier, Node, Span};
use crate::{Identifier, Node};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -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 = "crate::common::tendril_json")]
#[serde(with = "leo_errors::common::tendril_json")]
pub value: StrTendril,
}

View File

@ -14,7 +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::{Identifier, Node, Span};
use crate::{Identifier, Node};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{Expression, Node, Span};
use crate::{Expression, Node};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -1,40 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{FormattedError, LeoError, ReducerError, Span};
#[derive(Debug, Error)]
pub enum AstError {
#[error("{}", _0)]
Error(#[from] FormattedError),
#[error("{}", _0)]
IOError(#[from] std::io::Error),
#[error("{}", _0)]
ReducerError(#[from] ReducerError),
#[error("{}", _0)]
SerdeJsonError(#[from] ::serde_json::Error),
}
impl LeoError for AstError {}
impl AstError {
fn _new_from_span(message: String, span: &Span) -> Self {
AstError::Error(FormattedError::new_from_span(message, span))
}
}

View File

@ -1,43 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{FormattedError, LeoError, Span};
#[derive(Debug, Error)]
pub enum CanonicalizeError {
#[error("{}", _0)]
Error(#[from] FormattedError),
}
impl LeoError for CanonicalizeError {}
impl CanonicalizeError {
fn new_from_span(message: String, span: &Span) -> Self {
CanonicalizeError::Error(FormattedError::new_from_span(message, span))
}
pub fn big_self_outside_of_circuit(span: &Span) -> Self {
let message = "cannot call keyword `Self` outside of a circuit function".to_string();
Self::new_from_span(message, span)
}
pub fn invalid_array_dimension_size(span: &Span) -> Self {
let message = "received dimension size of 0, expected it to be 1 or larger.".to_string();
Self::new_from_span(message, span)
}
}

View File

@ -1,142 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{LeoError, Span};
use std::{fmt, sync::Arc};
pub const INDENT: &str = " ";
/// Formatted compiler error type
/// --> file.leo: 2:8
/// |
/// 2 | let a = x;
/// | ^
/// |
/// = undefined value `x`
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct FormattedError {
pub line_start: usize,
pub line_stop: usize,
pub col_start: usize,
pub col_stop: usize,
pub path: Arc<String>,
pub content: String,
pub message: String,
}
impl FormattedError {
pub fn new_from_span(message: String, span: &Span) -> Self {
Self {
line_start: span.line_start,
line_stop: span.line_stop,
col_start: span.col_start,
col_stop: span.col_stop,
path: span.path.clone(),
content: span.content.to_string(),
message,
}
}
}
impl LeoError for FormattedError {}
fn underline(mut start: usize, mut end: usize) -> String {
if start > end {
std::mem::swap(&mut start, &mut end)
}
let mut underline = String::new();
for _ in 0..start {
underline.push(' ');
end -= 1;
}
for _ in 0..end {
underline.push('^');
}
underline
}
impl fmt::Display for FormattedError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let underline = underline(self.col_start, self.col_stop);
let error_message = format!(
"{indent }--> {path}:{line_start}:{start}\n\
{indent } ",
indent = INDENT,
path = &*self.path,
line_start = self.line_start,
start = self.col_start,
);
write!(f, "{}", error_message)?;
for (line_no, line) in self.content.lines().enumerate() {
writeln!(
f,
"|\n{line_no:width$} | {text}",
width = INDENT.len(),
line_no = self.line_start + line_no,
text = line,
)?;
}
write!(
f,
"{indent } |{underline}\n\
{indent } |\n\
{indent } = {message}",
indent = INDENT,
underline = underline,
message = self.message,
)
}
}
impl std::error::Error for FormattedError {
fn description(&self) -> &str {
&self.message
}
}
#[test]
fn test_error() {
let err = FormattedError {
path: std::sync::Arc::new("file.leo".to_string()),
line_start: 2,
line_stop: 2,
col_start: 9,
col_stop: 10,
content: "let a = x;".into(),
message: "undefined value `x`".to_string(),
};
assert_eq!(
err.to_string(),
vec![
" --> file.leo:2:9",
" |",
" 2 | let a = x;",
" | ^",
" |",
" = undefined value `x`",
]
.join("\n")
);
}

View File

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

View File

@ -1,50 +0,0 @@
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{CanonicalizeError, CombinerError, FormattedError, LeoError, Span};
#[derive(Debug, Error)]
pub enum ReducerError {
#[error("{}", _0)]
Error(#[from] FormattedError),
#[error("{}", _0)]
CanonicalizeError(#[from] CanonicalizeError),
#[error("{}", _0)]
CombinerError(#[from] CombinerError),
}
impl LeoError for ReducerError {}
impl ReducerError {
fn new_from_span(message: String, span: &Span) -> Self {
ReducerError::Error(FormattedError::new_from_span(message, span))
}
pub fn empty_string(span: &Span) -> Self {
let message =
"Cannot constrcut an empty string: it has the type of [char; 0] which is not possible.".to_string();
Self::new_from_span(message, span)
}
pub fn impossible_console_assert_call(span: &Span) -> Self {
let message = "Console::Assert cannot be matched here, its handled in another case.".to_string();
Self::new_from_span(message, span)
}
}

View File

@ -15,15 +15,15 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{
ArrayDimensions, CircuitImpliedVariableDefinition, GroupValue, Identifier, IntegerType, PositiveNumber, Span,
ArrayDimensions, CircuitImpliedVariableDefinition, GroupValue, Identifier, IntegerType, Node, PositiveNumber,
SpreadOrExpression,
};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;
use crate::Node;
mod binary;
pub use binary::*;
mod unary;

View File

@ -17,20 +17,20 @@
use tendril::StrTendril;
use super::*;
use crate::{Char, CharValue, GroupTuple};
use crate::{Char, CharValue};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ValueExpression {
// todo: deserialize values here
Address(#[serde(with = "crate::common::tendril_json")] StrTendril, Span),
Boolean(#[serde(with = "crate::common::tendril_json")] StrTendril, Span),
Address(#[serde(with = "leo_errors::common::tendril_json")] StrTendril, Span),
Boolean(#[serde(with = "leo_errors::common::tendril_json")] StrTendril, Span),
Char(CharValue),
Field(#[serde(with = "crate::common::tendril_json")] StrTendril, Span),
Field(#[serde(with = "leo_errors::common::tendril_json")] StrTendril, Span),
Group(Box<GroupValue>),
Implicit(#[serde(with = "crate::common::tendril_json")] StrTendril, Span),
Implicit(#[serde(with = "leo_errors::common::tendril_json")] StrTendril, Span),
Integer(
IntegerType,
#[serde(with = "crate::common::tendril_json")] StrTendril,
#[serde(with = "leo_errors::common::tendril_json")] StrTendril,
Span,
),
String(Vec<Char>, Span),
@ -69,7 +69,8 @@ impl Node for ValueExpression {
| String(_, span) => span,
Char(character) => &character.span,
Group(group) => match &**group {
GroupValue::Single(_, span) | GroupValue::Tuple(GroupTuple { span, .. }) => span,
GroupValue::Single(_, span) => span,
GroupValue::Tuple(tuple) => &tuple.span,
},
}
}
@ -85,7 +86,8 @@ impl Node for ValueExpression {
| String(_, span) => *span = new_span,
Char(character) => character.span = new_span,
Group(group) => match &mut **group {
GroupValue::Single(_, span) | GroupValue::Tuple(GroupTuple { span, .. }) => *span = new_span,
GroupValue::Single(_, span) => *span = new_span,
GroupValue::Tuple(tuple) => tuple.span = new_span,
},
}
}

View File

@ -14,7 +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::{Annotation, Block, FunctionInput, Identifier, Node, Span, Type};
use crate::{Annotation, Block, FunctionInput, Identifier, Node, Type};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{Identifier, Node, Span, Type};
use crate::{Identifier, Node, Type};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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, Span};
use crate::{ConstSelfKeyword, FunctionInputVariable, MutSelfKeyword, Node, SelfKeyword};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -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 crate::common::span::Span;
use leo_errors::Span;
use leo_input::values::{
GroupCoordinate as InputGroupCoordinate, Inferred as InputInferred, NumberValue as InputNumberValue,
SignHigh as InputSignHigh, SignLow as InputSignLow,
@ -26,7 +26,7 @@ use tendril::StrTendril;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum GroupCoordinate {
Number(#[serde(with = "crate::common::tendril_json")] StrTendril, Span),
Number(#[serde(with = "leo_errors::common::tendril_json")] StrTendril, Span),
SignHigh,
SignLow,
Inferred,

View File

@ -14,7 +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::{common::span::Span, groups::GroupCoordinate};
use crate::groups::GroupCoordinate;
use leo_errors::Span;
use leo_input::values::{
GroupRepresentation as InputGroupRepresentation, GroupTuple as InputGroupTuple, GroupValue as InputGroupValue,
};
@ -25,7 +26,7 @@ use tendril::StrTendril;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum GroupValue {
Single(#[serde(with = "crate::common::tendril_json")] StrTendril, Span),
Single(#[serde(with = "leo_errors::common::tendril_json")] StrTendril, Span),
Tuple(GroupTuple),
}

View File

@ -14,7 +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::{PackageOrPackages, Span};
use crate::PackageOrPackages;
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{Identifier, Span};
use crate::Identifier;
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{common::Identifier, PackageAccess, Span};
use crate::{common::Identifier, PackageAccess};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{ImportSymbol, Node, Package, Packages, Span};
use crate::{ImportSymbol, Node, Package, Packages};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{Node, Package, Packages, Span};
use crate::{Node, Package, Packages};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{common::Identifier, PackageAccess, Span};
use crate::{common::Identifier, PackageAccess};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{ArrayDimensions, Char, CharValue, GroupValue, Span as AstSpan};
use crate::{ArrayDimensions, Char, CharValue, GroupValue};
use leo_errors::Span as AstSpan;
use leo_input::{
errors::InputParserError,
expressions::{ArrayInitializerExpression, ArrayInlineExpression, Expression, StringExpression, TupleExpression},

View File

@ -14,7 +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::{Identifier, Span, Type};
use crate::{Identifier, Type};
use leo_errors::Span;
use leo_input::parameters::Parameter as GrammarParameter;
#[derive(Clone, PartialEq, Eq, Hash)]

View File

@ -20,8 +20,7 @@
//! The [`Ast`] type is intended to be parsed and modified by different passes
//! of the Leo compiler. The Leo compiler can generate a set of R1CS constraints from any [`Ast`].
#[macro_use]
extern crate thiserror;
#![doc = include_str!("../README.md")]
pub mod annotation;
pub use self::annotation::*;
@ -35,9 +34,6 @@ pub use self::chars::*;
pub mod common;
pub use self::common::*;
pub mod errors;
pub use self::errors::*;
pub mod expression;
pub use self::expression::*;
@ -68,6 +64,8 @@ pub use self::types::*;
mod node;
pub use node::*;
use leo_errors::{AstError, Result};
/// The abstract syntax tree (AST) for a Leo program.
///
/// The [`Ast`] type represents a Leo program as a series of recursive data types.
@ -86,7 +84,7 @@ impl Ast {
}
/// Mutates the program ast by preforming canonicalization on it.
pub fn canonicalize(&mut self) -> Result<(), AstError> {
pub fn canonicalize(&mut self) -> Result<()> {
self.ast = ReconstructingDirector::new(Canonicalizer::default()).reduce_program(self.as_repr())?;
Ok(())
}
@ -101,26 +99,28 @@ impl Ast {
}
/// Serializes the ast into a JSON string.
pub fn to_json_string(&self) -> Result<String, AstError> {
Ok(serde_json::to_string_pretty(&self.ast)?)
pub fn to_json_string(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(&self.ast).map_err(|e| AstError::failed_to_convert_ast_to_json_string(&e))?)
}
pub fn to_json_file(&self, mut path: std::path::PathBuf, file_name: &str) -> Result<(), AstError> {
/// Serializes the ast into a JSON file.
pub fn to_json_file(&self, mut path: std::path::PathBuf, file_name: &str) -> Result<()> {
path.push(file_name);
let file = std::fs::File::create(path)?;
let file = std::fs::File::create(&path).map_err(|e| AstError::failed_to_create_ast_json_file(&path, &e))?;
let writer = std::io::BufWriter::new(file);
serde_json::to_writer_pretty(writer, &self.ast)?;
Ok(())
Ok(serde_json::to_writer_pretty(writer, &self.ast)
.map_err(|e| AstError::failed_to_write_ast_to_json_file(&path, &e))?)
}
/// Deserializes the JSON string into a ast.
pub fn from_json_string(json: &str) -> Result<Self, AstError> {
let ast: Program = serde_json::from_str(json)?;
pub fn from_json_string(json: &str) -> Result<Self> {
let ast: Program = serde_json::from_str(json).map_err(|e| AstError::failed_to_read_json_string_to_ast(&e))?;
Ok(Self { ast })
}
pub fn from_json_file(path: std::path::PathBuf) -> Result<Self, AstError> {
let data = std::fs::read_to_string(path)?;
/// Deserializes the JSON string into a ast from a file.
pub fn from_json_file(path: std::path::PathBuf) -> Result<Self> {
let data = std::fs::read_to_string(&path).map_err(|e| AstError::failed_to_read_json_file(&path, &e))?;
Self::from_json_string(&data)
}
}

View File

@ -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 crate::Span;
use leo_errors::Span;
pub trait Node:
std::fmt::Debug + std::fmt::Display + Clone + PartialEq + Eq + serde::Serialize + serde::de::DeserializeOwned

View File

@ -15,11 +15,12 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::*;
use leo_errors::{AstError, Result, Span};
/// Replace Self when it is in a enclosing circuit type.
/// Error when Self is outside an enclosing circuit type.
/// Tuple array types and expressions expand to nested arrays.
/// Tuple array types and expressions error if a size of 0 is given.anyhow
/// Tuple array types and expressions error if a size of 0 is given.
/// Compound operators become simple assignments.
/// Functions missing output type return a empty tuple.
pub struct Canonicalizer {
@ -43,7 +44,7 @@ impl Canonicalizer {
start: Expression,
accesses: &[AssigneeAccess],
span: &Span,
) -> Result<Box<Expression>, ReducerError> {
) -> Result<Box<Expression>> {
let mut left = Box::new(start);
for access in accesses.iter() {
@ -83,10 +84,7 @@ impl Canonicalizer {
Ok(left)
}
pub fn compound_operation_converstion(
&mut self,
operation: &AssignOperation,
) -> Result<BinaryOperation, ReducerError> {
pub fn compound_operation_converstion(&mut self, operation: &AssignOperation) -> Result<BinaryOperation> {
match operation {
AssignOperation::Assign => unreachable!(),
AssignOperation::Add => Ok(BinaryOperation::Add),
@ -106,8 +104,24 @@ impl Canonicalizer {
}
}
fn is_self_type(&mut self, type_option: Option<&Type>) -> bool {
matches!(type_option, Some(Type::SelfType))
fn canonicalize_self_type(&self, type_option: Option<&Type>) -> Option<Type> {
match type_option {
Some(type_) => match type_ {
Type::SelfType => Some(Type::Circuit(self.circuit_name.as_ref().unwrap().clone())),
Type::Array(type_, dimensions) => Some(Type::Array(
Box::new(self.canonicalize_self_type(Some(type_)).unwrap()),
dimensions.clone(),
)),
Type::Tuple(types) => Some(Type::Tuple(
types
.iter()
.map(|type_| self.canonicalize_self_type(Some(type_)).unwrap())
.collect(),
)),
_ => Some(type_.clone()),
},
None => None,
}
}
fn canonicalize_expression(&mut self, expression: &Expression) -> Expression {
@ -147,11 +161,7 @@ impl Canonicalizer {
Expression::Cast(cast) => {
let inner = Box::new(self.canonicalize_expression(&cast.inner));
let mut target_type = cast.target_type.clone();
if matches!(target_type, Type::SelfType) {
target_type = Type::Circuit(self.circuit_name.as_ref().unwrap().clone());
}
let target_type = self.canonicalize_self_type(Some(&cast.target_type)).unwrap();
return Expression::Cast(CastExpression {
inner,
@ -338,11 +348,7 @@ impl Canonicalizer {
}
Statement::Definition(definition) => {
let value = self.canonicalize_expression(&definition.value);
let mut type_ = definition.type_.clone();
if self.is_self_type(type_.as_ref()) {
type_ = Some(Type::Circuit(self.circuit_name.as_ref().unwrap().clone()));
}
let type_ = self.canonicalize_self_type(definition.type_.as_ref());
Statement::Definition(DefinitionStatement {
declaration_type: definition.declaration_type.clone(),
@ -356,12 +362,12 @@ impl Canonicalizer {
let assignee = self.canonicalize_assignee(&assign.assignee);
let value = self.canonicalize_expression(&assign.value);
Statement::Assign(AssignStatement {
Statement::Assign(Box::new(AssignStatement {
assignee,
value,
operation: assign.operation,
span: assign.span.clone(),
})
}))
}
Statement::Conditional(conditional) => {
let condition = self.canonicalize_expression(&conditional.condition);
@ -383,14 +389,14 @@ impl Canonicalizer {
let stop = self.canonicalize_expression(&iteration.stop);
let block = self.canonicalize_block(&iteration.block);
Statement::Iteration(IterationStatement {
Statement::Iteration(Box::new(IterationStatement {
variable: iteration.variable.clone(),
start,
stop,
inclusive: iteration.inclusive,
block,
span: iteration.span.clone(),
})
}))
}
Statement::Console(console_function_call) => {
let function = match &console_function_call.function {
@ -436,13 +442,9 @@ impl Canonicalizer {
CircuitMember::CircuitVariable(_, _) => {}
CircuitMember::CircuitFunction(function) => {
let input = function.input.clone();
let mut output = function.output.clone();
let output = self.canonicalize_self_type(function.output.as_ref());
let block = self.canonicalize_block(&function.block);
if self.is_self_type(output.as_ref()) {
output = Some(Type::Circuit(self.circuit_name.as_ref().unwrap().clone()));
}
return CircuitMember::CircuitFunction(Function {
annotations: function.annotations.clone(),
identifier: function.identifier.clone(),
@ -467,13 +469,11 @@ impl ReconstructingReducer for Canonicalizer {
self.in_circuit = !self.in_circuit;
}
fn reduce_type(&mut self, _type_: &Type, new: Type, span: &Span) -> Result<Type, ReducerError> {
fn reduce_type(&mut self, _type_: &Type, new: Type, span: &Span) -> Result<Type> {
match new {
Type::Array(type_, mut dimensions) => {
if dimensions.is_zero() {
return Err(ReducerError::from(CanonicalizeError::invalid_array_dimension_size(
span,
)));
return Err(AstError::invalid_array_dimension_size(span).into());
}
let mut next = Type::Array(type_, ArrayDimensions(vec![dimensions.remove_last().unwrap()]));
@ -490,16 +490,14 @@ impl ReconstructingReducer for Canonicalizer {
Ok(array)
}
Type::SelfType if !self.in_circuit => {
Err(ReducerError::from(CanonicalizeError::big_self_outside_of_circuit(span)))
}
Type::SelfType if !self.in_circuit => Err(AstError::big_self_outside_of_circuit(span).into()),
_ => Ok(new.clone()),
}
}
fn reduce_string(&mut self, string: &[Char], span: &Span) -> Result<Expression, ReducerError> {
fn reduce_string(&mut self, string: &[Char], span: &Span) -> Result<Expression> {
if string.is_empty() {
return Err(ReducerError::empty_string(span));
return Err(AstError::empty_string(span).into());
}
let mut elements = Vec::new();
@ -534,14 +532,14 @@ impl ReconstructingReducer for Canonicalizer {
elements.push(SpreadOrExpression::Expression(Expression::Value(
ValueExpression::Char(CharValue {
character: character.clone(),
span: Span {
line_start: span.line_start,
line_stop: span.line_stop,
span: Span::new(
span.line_start,
span.line_stop,
col_start,
col_stop,
path: span.path.clone(),
content: span.content.clone(),
},
span.path.clone(),
span.content.clone(),
),
}),
)));
}
@ -556,11 +554,9 @@ impl ReconstructingReducer for Canonicalizer {
&mut self,
array_init: &ArrayInitExpression,
element: Expression,
) -> Result<ArrayInitExpression, ReducerError> {
) -> Result<ArrayInitExpression> {
if array_init.dimensions.is_zero() {
return Err(ReducerError::from(CanonicalizeError::invalid_array_dimension_size(
&array_init.span,
)));
return Err(AstError::invalid_array_dimension_size(&array_init.span).into());
}
let element = Box::new(element);
@ -607,7 +603,7 @@ impl ReconstructingReducer for Canonicalizer {
assign: &AssignStatement,
assignee: Assignee,
value: Expression,
) -> Result<AssignStatement, ReducerError> {
) -> Result<AssignStatement> {
match value {
value if assign.operation != AssignOperation::Assign => {
let left = self.canonicalize_accesses(
@ -649,7 +645,7 @@ impl ReconstructingReducer for Canonicalizer {
input: Vec<FunctionInput>,
output: Option<Type>,
block: Block,
) -> Result<Function, ReducerError> {
) -> Result<Function> {
let new_output = match output {
None => Some(Type::Tuple(vec![])),
_ => output,
@ -670,7 +666,7 @@ impl ReconstructingReducer for Canonicalizer {
_circuit: &Circuit,
circuit_name: Identifier,
members: Vec<CircuitMember>,
) -> Result<Circuit, ReducerError> {
) -> Result<Circuit> {
self.circuit_name = Some(circuit_name.clone());
let circ = Circuit {
circuit_name,

View File

@ -19,6 +19,7 @@
use crate::*;
use indexmap::IndexMap;
use leo_errors::{AstError, Result, Span};
pub struct ReconstructingDirector<R: ReconstructingReducer> {
reducer: R,
@ -29,7 +30,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
Self { reducer }
}
pub fn reduce_type(&mut self, type_: &Type, span: &Span) -> Result<Type, ReducerError> {
pub fn reduce_type(&mut self, type_: &Type, span: &Span) -> Result<Type> {
let new = match type_ {
Type::Array(type_, dimensions) => Type::Array(Box::new(self.reduce_type(type_, span)?), dimensions.clone()),
Type::Tuple(types) => {
@ -48,7 +49,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
}
// Expressions
pub fn reduce_expression(&mut self, expression: &Expression) -> Result<Expression, ReducerError> {
pub fn reduce_expression(&mut self, expression: &Expression) -> Result<Expression> {
let new = match expression {
Expression::Identifier(identifier) => Expression::Identifier(self.reduce_identifier(identifier)?),
Expression::Value(value) => self.reduce_value(value)?,
@ -81,15 +82,15 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_expression(expression, new)
}
pub fn reduce_identifier(&mut self, identifier: &Identifier) -> Result<Identifier, ReducerError> {
pub fn reduce_identifier(&mut self, identifier: &Identifier) -> Result<Identifier> {
self.reducer.reduce_identifier(identifier)
}
pub fn reduce_group_tuple(&mut self, group_tuple: &GroupTuple) -> Result<GroupTuple, ReducerError> {
pub fn reduce_group_tuple(&mut self, group_tuple: &GroupTuple) -> Result<GroupTuple> {
self.reducer.reduce_group_tuple(group_tuple)
}
pub fn reduce_group_value(&mut self, group_value: &GroupValue) -> Result<GroupValue, ReducerError> {
pub fn reduce_group_value(&mut self, group_value: &GroupValue) -> Result<GroupValue> {
let new = match group_value {
GroupValue::Tuple(group_tuple) => GroupValue::Tuple(self.reduce_group_tuple(group_tuple)?),
_ => group_value.clone(),
@ -98,11 +99,11 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_group_value(group_value, new)
}
pub fn reduce_string(&mut self, string: &[Char], span: &Span) -> Result<Expression, ReducerError> {
pub fn reduce_string(&mut self, string: &[Char], span: &Span) -> Result<Expression> {
self.reducer.reduce_string(string, span)
}
pub fn reduce_value(&mut self, value: &ValueExpression) -> Result<Expression, ReducerError> {
pub fn reduce_value(&mut self, value: &ValueExpression) -> Result<Expression> {
let new = match value {
ValueExpression::Group(group_value) => {
Expression::Value(ValueExpression::Group(Box::new(self.reduce_group_value(group_value)?)))
@ -114,20 +115,20 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_value(value, new)
}
pub fn reduce_binary(&mut self, binary: &BinaryExpression) -> Result<BinaryExpression, ReducerError> {
pub fn reduce_binary(&mut self, binary: &BinaryExpression) -> Result<BinaryExpression> {
let left = self.reduce_expression(&binary.left)?;
let right = self.reduce_expression(&binary.right)?;
self.reducer.reduce_binary(binary, left, right, binary.op.clone())
}
pub fn reduce_unary(&mut self, unary: &UnaryExpression) -> Result<UnaryExpression, ReducerError> {
pub fn reduce_unary(&mut self, unary: &UnaryExpression) -> Result<UnaryExpression> {
let inner = self.reduce_expression(&unary.inner)?;
self.reducer.reduce_unary(unary, inner, unary.op.clone())
}
pub fn reduce_ternary(&mut self, ternary: &TernaryExpression) -> Result<TernaryExpression, ReducerError> {
pub fn reduce_ternary(&mut self, ternary: &TernaryExpression) -> Result<TernaryExpression> {
let condition = self.reduce_expression(&ternary.condition)?;
let if_true = self.reduce_expression(&ternary.if_true)?;
let if_false = self.reduce_expression(&ternary.if_false)?;
@ -135,17 +136,14 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_ternary(ternary, condition, if_true, if_false)
}
pub fn reduce_cast(&mut self, cast: &CastExpression) -> Result<CastExpression, ReducerError> {
pub fn reduce_cast(&mut self, cast: &CastExpression) -> Result<CastExpression> {
let inner = self.reduce_expression(&cast.inner)?;
let target_type = self.reduce_type(&cast.target_type, &cast.span)?;
self.reducer.reduce_cast(cast, inner, target_type)
}
pub fn reduce_array_inline(
&mut self,
array_inline: &ArrayInlineExpression,
) -> Result<ArrayInlineExpression, ReducerError> {
pub fn reduce_array_inline(&mut self, array_inline: &ArrayInlineExpression) -> Result<ArrayInlineExpression> {
let mut elements = vec![];
for element in array_inline.elements.iter() {
let reduced_element = match element {
@ -163,16 +161,13 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_array_inline(array_inline, elements)
}
pub fn reduce_array_init(&mut self, array_init: &ArrayInitExpression) -> Result<ArrayInitExpression, ReducerError> {
pub fn reduce_array_init(&mut self, array_init: &ArrayInitExpression) -> Result<ArrayInitExpression> {
let element = self.reduce_expression(&array_init.element)?;
self.reducer.reduce_array_init(array_init, element)
}
pub fn reduce_array_access(
&mut self,
array_access: &ArrayAccessExpression,
) -> Result<ArrayAccessExpression, ReducerError> {
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)?;
@ -182,7 +177,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
pub fn reduce_array_range_access(
&mut self,
array_range_access: &ArrayRangeAccessExpression,
) -> Result<ArrayRangeAccessExpression, ReducerError> {
) -> Result<ArrayRangeAccessExpression> {
let array = self.reduce_expression(&array_range_access.array)?;
let left = array_range_access
.left
@ -199,7 +194,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
.reduce_array_range_access(array_range_access, array, left, right)
}
pub fn reduce_tuple_init(&mut self, tuple_init: &TupleInitExpression) -> Result<TupleInitExpression, ReducerError> {
pub fn reduce_tuple_init(&mut self, tuple_init: &TupleInitExpression) -> Result<TupleInitExpression> {
let mut elements = vec![];
for element in tuple_init.elements.iter() {
elements.push(self.reduce_expression(element)?);
@ -208,10 +203,7 @@ 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, ReducerError> {
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)
@ -220,7 +212,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
pub fn reduce_circuit_implied_variable_definition(
&mut self,
variable: &CircuitImpliedVariableDefinition,
) -> Result<CircuitImpliedVariableDefinition, ReducerError> {
) -> Result<CircuitImpliedVariableDefinition> {
let identifier = self.reduce_identifier(&variable.identifier)?;
let expression = variable
.expression
@ -232,10 +224,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
.reduce_circuit_implied_variable_definition(variable, identifier, expression)
}
pub fn reduce_circuit_init(
&mut self,
circuit_init: &CircuitInitExpression,
) -> Result<CircuitInitExpression, ReducerError> {
pub fn reduce_circuit_init(&mut self, circuit_init: &CircuitInitExpression) -> Result<CircuitInitExpression> {
let name = self.reduce_identifier(&circuit_init.name)?;
let mut members = vec![];
@ -249,7 +238,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
pub fn reduce_circuit_member_access(
&mut self,
circuit_member_access: &CircuitMemberAccessExpression,
) -> Result<CircuitMemberAccessExpression, ReducerError> {
) -> Result<CircuitMemberAccessExpression> {
let circuit = self.reduce_expression(&circuit_member_access.circuit)?;
let name = self.reduce_identifier(&circuit_member_access.name)?;
@ -260,7 +249,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
pub fn reduce_circuit_static_fn_access(
&mut self,
circuit_static_fn_access: &CircuitStaticFunctionAccessExpression,
) -> Result<CircuitStaticFunctionAccessExpression, ReducerError> {
) -> Result<CircuitStaticFunctionAccessExpression> {
let circuit = self.reduce_expression(&circuit_static_fn_access.circuit)?;
let name = self.reduce_identifier(&circuit_static_fn_access.name)?;
@ -268,7 +257,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
.reduce_circuit_static_fn_access(circuit_static_fn_access, circuit, name)
}
pub fn reduce_call(&mut self, call: &CallExpression) -> Result<CallExpression, ReducerError> {
pub fn reduce_call(&mut self, call: &CallExpression) -> Result<CallExpression> {
let function = self.reduce_expression(&call.function)?;
let mut arguments = vec![];
@ -280,13 +269,13 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
}
// Statements
pub fn reduce_statement(&mut self, statement: &Statement) -> Result<Statement, ReducerError> {
pub fn reduce_statement(&mut self, statement: &Statement) -> Result<Statement> {
let new = match statement {
Statement::Return(return_statement) => Statement::Return(self.reduce_return(return_statement)?),
Statement::Definition(definition) => Statement::Definition(self.reduce_definition(definition)?),
Statement::Assign(assign) => Statement::Assign(self.reduce_assign(assign)?),
Statement::Assign(assign) => Statement::Assign(Box::new(self.reduce_assign(assign)?)),
Statement::Conditional(conditional) => Statement::Conditional(self.reduce_conditional(conditional)?),
Statement::Iteration(iteration) => Statement::Iteration(self.reduce_iteration(iteration)?),
Statement::Iteration(iteration) => Statement::Iteration(Box::new(self.reduce_iteration(iteration)?)),
Statement::Console(console) => Statement::Console(self.reduce_console(console)?),
Statement::Expression(expression) => Statement::Expression(self.reduce_expression_statement(expression)?),
Statement::Block(block) => Statement::Block(self.reduce_block(block)?),
@ -295,19 +284,19 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_statement(statement, new)
}
pub fn reduce_return(&mut self, return_statement: &ReturnStatement) -> Result<ReturnStatement, ReducerError> {
pub fn reduce_return(&mut self, return_statement: &ReturnStatement) -> Result<ReturnStatement> {
let expression = self.reduce_expression(&return_statement.expression)?;
self.reducer.reduce_return(return_statement, expression)
}
pub fn reduce_variable_name(&mut self, variable_name: &VariableName) -> Result<VariableName, ReducerError> {
pub fn reduce_variable_name(&mut self, variable_name: &VariableName) -> Result<VariableName> {
let identifier = self.reduce_identifier(&variable_name.identifier)?;
self.reducer.reduce_variable_name(variable_name, identifier)
}
pub fn reduce_definition(&mut self, definition: &DefinitionStatement) -> Result<DefinitionStatement, ReducerError> {
pub fn reduce_definition(&mut self, definition: &DefinitionStatement) -> Result<DefinitionStatement> {
let mut variable_names = vec![];
for variable_name in definition.variable_names.iter() {
variable_names.push(self.reduce_variable_name(variable_name)?);
@ -324,7 +313,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_definition(definition, variable_names, type_, value)
}
pub fn reduce_assignee_access(&mut self, access: &AssigneeAccess) -> Result<AssigneeAccess, ReducerError> {
pub fn reduce_assignee_access(&mut self, access: &AssigneeAccess) -> Result<AssigneeAccess> {
let new = match access {
AssigneeAccess::ArrayRange(left, right) => {
let left = left.as_ref().map(|left| self.reduce_expression(left)).transpose()?;
@ -340,7 +329,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_assignee_access(access, new)
}
pub fn reduce_assignee(&mut self, assignee: &Assignee) -> Result<Assignee, ReducerError> {
pub fn reduce_assignee(&mut self, assignee: &Assignee) -> Result<Assignee> {
let identifier = self.reduce_identifier(&assignee.identifier)?;
let mut accesses = vec![];
@ -351,17 +340,14 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_assignee(assignee, identifier, accesses)
}
pub fn reduce_assign(&mut self, assign: &AssignStatement) -> Result<AssignStatement, ReducerError> {
pub fn reduce_assign(&mut self, assign: &AssignStatement) -> Result<AssignStatement> {
let assignee = self.reduce_assignee(&assign.assignee)?;
let value = self.reduce_expression(&assign.value)?;
self.reducer.reduce_assign(assign, assignee, value)
}
pub fn reduce_conditional(
&mut self,
conditional: &ConditionalStatement,
) -> Result<ConditionalStatement, ReducerError> {
pub fn reduce_conditional(&mut self, conditional: &ConditionalStatement) -> Result<ConditionalStatement> {
let condition = self.reduce_expression(&conditional.condition)?;
let block = self.reduce_block(&conditional.block)?;
let next = conditional
@ -373,7 +359,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_conditional(conditional, condition, block, next)
}
pub fn reduce_iteration(&mut self, iteration: &IterationStatement) -> Result<IterationStatement, ReducerError> {
pub fn reduce_iteration(&mut self, iteration: &IterationStatement) -> Result<IterationStatement> {
let variable = self.reduce_identifier(&iteration.variable)?;
let start = self.reduce_expression(&iteration.start)?;
let stop = self.reduce_expression(&iteration.stop)?;
@ -382,10 +368,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_iteration(iteration, variable, start, stop, block)
}
pub fn reduce_console(
&mut self,
console_function_call: &ConsoleStatement,
) -> Result<ConsoleStatement, ReducerError> {
pub fn reduce_console(&mut self, console_function_call: &ConsoleStatement) -> Result<ConsoleStatement> {
let function = match &console_function_call.function {
ConsoleFunction::Assert(expression) => ConsoleFunction::Assert(self.reduce_expression(expression)?),
ConsoleFunction::Error(args) | ConsoleFunction::Log(args) => {
@ -403,7 +386,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
match &console_function_call.function {
ConsoleFunction::Error(_) => ConsoleFunction::Error(formatted),
ConsoleFunction::Log(_) => ConsoleFunction::Log(formatted),
_ => return Err(ReducerError::impossible_console_assert_call(&args.span)),
_ => return Err(AstError::impossible_console_assert_call(&args.span).into()),
}
}
};
@ -411,15 +394,12 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_console(console_function_call, function)
}
pub fn reduce_expression_statement(
&mut self,
expression: &ExpressionStatement,
) -> Result<ExpressionStatement, ReducerError> {
pub fn reduce_expression_statement(&mut self, expression: &ExpressionStatement) -> Result<ExpressionStatement> {
let inner_expression = self.reduce_expression(&expression.expression)?;
self.reducer.reduce_expression_statement(expression, inner_expression)
}
pub fn reduce_block(&mut self, block: &Block) -> Result<Block, ReducerError> {
pub fn reduce_block(&mut self, block: &Block) -> Result<Block> {
let mut statements = vec![];
for statement in block.statements.iter() {
statements.push(self.reduce_statement(statement)?);
@ -429,7 +409,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
}
// Program
pub fn reduce_program(&mut self, program: &Program) -> Result<Program, ReducerError> {
pub fn reduce_program(&mut self, program: &Program) -> Result<Program> {
let mut inputs = vec![];
for input in program.expected_input.iter() {
inputs.push(self.reduce_function_input(input)?);
@ -464,14 +444,14 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
pub fn reduce_function_input_variable(
&mut self,
variable: &FunctionInputVariable,
) -> Result<FunctionInputVariable, ReducerError> {
) -> Result<FunctionInputVariable> {
let identifier = self.reduce_identifier(&variable.identifier)?;
let type_ = self.reduce_type(&variable.type_, &variable.span)?;
self.reducer.reduce_function_input_variable(variable, identifier, type_)
}
pub fn reduce_function_input(&mut self, input: &FunctionInput) -> Result<FunctionInput, ReducerError> {
pub fn reduce_function_input(&mut self, input: &FunctionInput) -> Result<FunctionInput> {
let new = match input {
FunctionInput::Variable(function_input_variable) => {
FunctionInput::Variable(self.reduce_function_input_variable(function_input_variable)?)
@ -482,10 +462,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_function_input(input, new)
}
pub fn reduce_package_or_packages(
&mut self,
package_or_packages: &PackageOrPackages,
) -> Result<PackageOrPackages, ReducerError> {
pub fn reduce_package_or_packages(&mut self, package_or_packages: &PackageOrPackages) -> Result<PackageOrPackages> {
let new = match package_or_packages {
PackageOrPackages::Package(package) => PackageOrPackages::Package(Package {
name: self.reduce_identifier(&package.name)?,
@ -502,13 +479,13 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_package_or_packages(package_or_packages, new)
}
pub fn reduce_import(&mut self, import: &ImportStatement) -> Result<ImportStatement, ReducerError> {
pub fn reduce_import(&mut self, import: &ImportStatement) -> Result<ImportStatement> {
let package_or_packages = self.reduce_package_or_packages(&import.package_or_packages)?;
self.reducer.reduce_import(import, package_or_packages)
}
pub fn reduce_circuit_member(&mut self, circuit_member: &CircuitMember) -> Result<CircuitMember, ReducerError> {
pub fn reduce_circuit_member(&mut self, circuit_member: &CircuitMember) -> Result<CircuitMember> {
let new = match circuit_member {
CircuitMember::CircuitVariable(identifier, type_) => CircuitMember::CircuitVariable(
self.reduce_identifier(identifier)?,
@ -520,7 +497,7 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_circuit_member(circuit_member, new)
}
pub fn reduce_circuit(&mut self, circuit: &Circuit) -> Result<Circuit, ReducerError> {
pub fn reduce_circuit(&mut self, circuit: &Circuit) -> Result<Circuit> {
let circuit_name = self.reduce_identifier(&circuit.circuit_name)?;
let mut members = vec![];
@ -531,13 +508,13 @@ impl<R: ReconstructingReducer> ReconstructingDirector<R> {
self.reducer.reduce_circuit(circuit, circuit_name, members)
}
fn reduce_annotation(&mut self, annotation: &Annotation) -> Result<Annotation, ReducerError> {
fn reduce_annotation(&mut self, annotation: &Annotation) -> Result<Annotation> {
let name = self.reduce_identifier(&annotation.name)?;
self.reducer.reduce_annotation(annotation, name)
}
pub fn reduce_function(&mut self, function: &Function) -> Result<Function, ReducerError> {
pub fn reduce_function(&mut self, function: &Function) -> Result<Function> {
let identifier = self.reduce_identifier(&function.identifier)?;
let mut annotations = vec![];

View File

@ -16,6 +16,7 @@
use crate::*;
use indexmap::IndexMap;
use leo_errors::{Result, Span};
// Needed to fix clippy bug.
#[allow(clippy::redundant_closure)]
@ -23,23 +24,23 @@ pub trait ReconstructingReducer {
fn in_circuit(&self) -> bool;
fn swap_in_circuit(&mut self);
fn reduce_type(&mut self, _type_: &Type, new: Type, _span: &Span) -> Result<Type, ReducerError> {
fn reduce_type(&mut self, _type_: &Type, new: Type, _span: &Span) -> Result<Type> {
Ok(new)
}
// Expressions
fn reduce_expression(&mut self, _expression: &Expression, new: Expression) -> Result<Expression, ReducerError> {
fn reduce_expression(&mut self, _expression: &Expression, new: Expression) -> Result<Expression> {
Ok(new)
}
fn reduce_identifier(&mut self, identifier: &Identifier) -> Result<Identifier, ReducerError> {
fn reduce_identifier(&mut self, identifier: &Identifier) -> Result<Identifier> {
Ok(Identifier {
name: identifier.name.clone(),
span: identifier.span.clone(),
})
}
fn reduce_group_tuple(&mut self, group_tuple: &GroupTuple) -> Result<GroupTuple, ReducerError> {
fn reduce_group_tuple(&mut self, group_tuple: &GroupTuple) -> Result<GroupTuple> {
Ok(GroupTuple {
x: group_tuple.x.clone(),
y: group_tuple.y.clone(),
@ -47,18 +48,18 @@ pub trait ReconstructingReducer {
})
}
fn reduce_group_value(&mut self, _group_value: &GroupValue, new: GroupValue) -> Result<GroupValue, ReducerError> {
fn reduce_group_value(&mut self, _group_value: &GroupValue, new: GroupValue) -> Result<GroupValue> {
Ok(new)
}
fn reduce_string(&mut self, string: &[Char], span: &Span) -> Result<Expression, ReducerError> {
fn reduce_string(&mut self, string: &[Char], span: &Span) -> Result<Expression> {
Ok(Expression::Value(ValueExpression::String(
string.to_vec(),
span.clone(),
)))
}
fn reduce_value(&mut self, _value: &ValueExpression, new: Expression) -> Result<Expression, ReducerError> {
fn reduce_value(&mut self, _value: &ValueExpression, new: Expression) -> Result<Expression> {
Ok(new)
}
@ -68,7 +69,7 @@ pub trait ReconstructingReducer {
left: Expression,
right: Expression,
op: BinaryOperation,
) -> Result<BinaryExpression, ReducerError> {
) -> Result<BinaryExpression> {
Ok(BinaryExpression {
left: Box::new(left),
right: Box::new(right),
@ -82,7 +83,7 @@ pub trait ReconstructingReducer {
unary: &UnaryExpression,
inner: Expression,
op: UnaryOperation,
) -> Result<UnaryExpression, ReducerError> {
) -> Result<UnaryExpression> {
Ok(UnaryExpression {
inner: Box::new(inner),
op,
@ -96,7 +97,7 @@ pub trait ReconstructingReducer {
condition: Expression,
if_true: Expression,
if_false: Expression,
) -> Result<TernaryExpression, ReducerError> {
) -> Result<TernaryExpression> {
Ok(TernaryExpression {
condition: Box::new(condition),
if_true: Box::new(if_true),
@ -105,12 +106,7 @@ pub trait ReconstructingReducer {
})
}
fn reduce_cast(
&mut self,
cast: &CastExpression,
inner: Expression,
target_type: Type,
) -> Result<CastExpression, ReducerError> {
fn reduce_cast(&mut self, cast: &CastExpression, inner: Expression, target_type: Type) -> Result<CastExpression> {
Ok(CastExpression {
inner: Box::new(inner),
target_type,
@ -122,7 +118,7 @@ pub trait ReconstructingReducer {
&mut self,
array_inline: &ArrayInlineExpression,
elements: Vec<SpreadOrExpression>,
) -> Result<ArrayInlineExpression, ReducerError> {
) -> Result<ArrayInlineExpression> {
Ok(ArrayInlineExpression {
elements,
span: array_inline.span.clone(),
@ -133,7 +129,7 @@ pub trait ReconstructingReducer {
&mut self,
array_init: &ArrayInitExpression,
element: Expression,
) -> Result<ArrayInitExpression, ReducerError> {
) -> Result<ArrayInitExpression> {
Ok(ArrayInitExpression {
element: Box::new(element),
dimensions: array_init.dimensions.clone(),
@ -146,7 +142,7 @@ pub trait ReconstructingReducer {
array_access: &ArrayAccessExpression,
array: Expression,
index: Expression,
) -> Result<ArrayAccessExpression, ReducerError> {
) -> Result<ArrayAccessExpression> {
Ok(ArrayAccessExpression {
array: Box::new(array),
index: Box::new(index),
@ -160,7 +156,7 @@ pub trait ReconstructingReducer {
array: Expression,
left: Option<Expression>,
right: Option<Expression>,
) -> Result<ArrayRangeAccessExpression, ReducerError> {
) -> Result<ArrayRangeAccessExpression> {
Ok(ArrayRangeAccessExpression {
array: Box::new(array),
left: left.map(|expr| Box::new(expr)),
@ -173,7 +169,7 @@ pub trait ReconstructingReducer {
&mut self,
tuple_init: &TupleInitExpression,
elements: Vec<Expression>,
) -> Result<TupleInitExpression, ReducerError> {
) -> Result<TupleInitExpression> {
Ok(TupleInitExpression {
elements,
span: tuple_init.span.clone(),
@ -184,7 +180,7 @@ pub trait ReconstructingReducer {
&mut self,
tuple_access: &TupleAccessExpression,
tuple: Expression,
) -> Result<TupleAccessExpression, ReducerError> {
) -> Result<TupleAccessExpression> {
Ok(TupleAccessExpression {
tuple: Box::new(tuple),
index: tuple_access.index.clone(),
@ -197,7 +193,7 @@ pub trait ReconstructingReducer {
_variable: &CircuitImpliedVariableDefinition,
identifier: Identifier,
expression: Option<Expression>,
) -> Result<CircuitImpliedVariableDefinition, ReducerError> {
) -> Result<CircuitImpliedVariableDefinition> {
Ok(CircuitImpliedVariableDefinition { identifier, expression })
}
@ -206,7 +202,7 @@ pub trait ReconstructingReducer {
circuit_init: &CircuitInitExpression,
name: Identifier,
members: Vec<CircuitImpliedVariableDefinition>,
) -> Result<CircuitInitExpression, ReducerError> {
) -> Result<CircuitInitExpression> {
Ok(CircuitInitExpression {
name,
members,
@ -219,7 +215,7 @@ pub trait ReconstructingReducer {
circuit_member_access: &CircuitMemberAccessExpression,
circuit: Expression,
name: Identifier,
) -> Result<CircuitMemberAccessExpression, ReducerError> {
) -> Result<CircuitMemberAccessExpression> {
Ok(CircuitMemberAccessExpression {
circuit: Box::new(circuit),
name,
@ -232,7 +228,7 @@ pub trait ReconstructingReducer {
circuit_static_fn_access: &CircuitStaticFunctionAccessExpression,
circuit: Expression,
name: Identifier,
) -> Result<CircuitStaticFunctionAccessExpression, ReducerError> {
) -> Result<CircuitStaticFunctionAccessExpression> {
Ok(CircuitStaticFunctionAccessExpression {
circuit: Box::new(circuit),
name,
@ -245,7 +241,7 @@ pub trait ReconstructingReducer {
call: &CallExpression,
function: Expression,
arguments: Vec<Expression>,
) -> Result<CallExpression, ReducerError> {
) -> Result<CallExpression> {
Ok(CallExpression {
function: Box::new(function),
arguments,
@ -254,26 +250,18 @@ pub trait ReconstructingReducer {
}
// Statements
fn reduce_statement(&mut self, _statement: &Statement, new: Statement) -> Result<Statement, ReducerError> {
fn reduce_statement(&mut self, _statement: &Statement, new: Statement) -> Result<Statement> {
Ok(new)
}
fn reduce_return(
&mut self,
return_statement: &ReturnStatement,
expression: Expression,
) -> Result<ReturnStatement, ReducerError> {
fn reduce_return(&mut self, return_statement: &ReturnStatement, expression: Expression) -> Result<ReturnStatement> {
Ok(ReturnStatement {
expression,
span: return_statement.span.clone(),
})
}
fn reduce_variable_name(
&mut self,
variable_name: &VariableName,
identifier: Identifier,
) -> Result<VariableName, ReducerError> {
fn reduce_variable_name(&mut self, variable_name: &VariableName, identifier: Identifier) -> Result<VariableName> {
Ok(VariableName {
mutable: variable_name.mutable,
identifier,
@ -287,7 +275,7 @@ pub trait ReconstructingReducer {
variable_names: Vec<VariableName>,
type_: Option<Type>,
value: Expression,
) -> Result<DefinitionStatement, ReducerError> {
) -> Result<DefinitionStatement> {
Ok(DefinitionStatement {
declaration_type: definition.declaration_type.clone(),
variable_names,
@ -297,11 +285,7 @@ pub trait ReconstructingReducer {
})
}
fn reduce_assignee_access(
&mut self,
_access: &AssigneeAccess,
new: AssigneeAccess,
) -> Result<AssigneeAccess, ReducerError> {
fn reduce_assignee_access(&mut self, _access: &AssigneeAccess, new: AssigneeAccess) -> Result<AssigneeAccess> {
Ok(new)
}
@ -310,7 +294,7 @@ pub trait ReconstructingReducer {
assignee: &Assignee,
identifier: Identifier,
accesses: Vec<AssigneeAccess>,
) -> Result<Assignee, ReducerError> {
) -> Result<Assignee> {
Ok(Assignee {
identifier,
accesses,
@ -323,7 +307,7 @@ pub trait ReconstructingReducer {
assign: &AssignStatement,
assignee: Assignee,
value: Expression,
) -> Result<AssignStatement, ReducerError> {
) -> Result<AssignStatement> {
Ok(AssignStatement {
operation: assign.operation,
assignee,
@ -338,7 +322,7 @@ pub trait ReconstructingReducer {
condition: Expression,
block: Block,
statement: Option<Statement>,
) -> Result<ConditionalStatement, ReducerError> {
) -> Result<ConditionalStatement> {
Ok(ConditionalStatement {
condition,
block,
@ -354,7 +338,7 @@ pub trait ReconstructingReducer {
start: Expression,
stop: Expression,
block: Block,
) -> Result<IterationStatement, ReducerError> {
) -> Result<IterationStatement> {
Ok(IterationStatement {
variable,
start,
@ -365,11 +349,7 @@ pub trait ReconstructingReducer {
})
}
fn reduce_console(
&mut self,
console: &ConsoleStatement,
function: ConsoleFunction,
) -> Result<ConsoleStatement, ReducerError> {
fn reduce_console(&mut self, console: &ConsoleStatement, function: ConsoleFunction) -> Result<ConsoleStatement> {
Ok(ConsoleStatement {
function,
span: console.span.clone(),
@ -380,14 +360,14 @@ pub trait ReconstructingReducer {
&mut self,
expression_statement: &ExpressionStatement,
expression: Expression,
) -> Result<ExpressionStatement, ReducerError> {
) -> Result<ExpressionStatement> {
Ok(ExpressionStatement {
expression,
span: expression_statement.span.clone(),
})
}
fn reduce_block(&mut self, block: &Block, statements: Vec<Statement>) -> Result<Block, ReducerError> {
fn reduce_block(&mut self, block: &Block, statements: Vec<Statement>) -> Result<Block> {
Ok(Block {
statements,
span: block.span.clone(),
@ -403,7 +383,7 @@ pub trait ReconstructingReducer {
circuits: IndexMap<Identifier, Circuit>,
functions: IndexMap<Identifier, Function>,
global_consts: IndexMap<String, DefinitionStatement>,
) -> Result<Program, ReducerError> {
) -> Result<Program> {
Ok(Program {
name: program.name.clone(),
expected_input,
@ -419,7 +399,7 @@ pub trait ReconstructingReducer {
variable: &FunctionInputVariable,
identifier: Identifier,
type_: Type,
) -> Result<FunctionInputVariable, ReducerError> {
) -> Result<FunctionInputVariable> {
Ok(FunctionInputVariable {
identifier,
const_: variable.const_,
@ -429,11 +409,7 @@ pub trait ReconstructingReducer {
})
}
fn reduce_function_input(
&mut self,
_input: &FunctionInput,
new: FunctionInput,
) -> Result<FunctionInput, ReducerError> {
fn reduce_function_input(&mut self, _input: &FunctionInput, new: FunctionInput) -> Result<FunctionInput> {
Ok(new)
}
@ -441,7 +417,7 @@ pub trait ReconstructingReducer {
&mut self,
_package_or_packages: &PackageOrPackages,
new: PackageOrPackages,
) -> Result<PackageOrPackages, ReducerError> {
) -> Result<PackageOrPackages> {
Ok(new)
}
@ -449,18 +425,14 @@ pub trait ReconstructingReducer {
&mut self,
import: &ImportStatement,
package_or_packages: PackageOrPackages,
) -> Result<ImportStatement, ReducerError> {
) -> Result<ImportStatement> {
Ok(ImportStatement {
package_or_packages,
span: import.span.clone(),
})
}
fn reduce_circuit_member(
&mut self,
_circuit_member: &CircuitMember,
new: CircuitMember,
) -> Result<CircuitMember, ReducerError> {
fn reduce_circuit_member(&mut self, _circuit_member: &CircuitMember, new: CircuitMember) -> Result<CircuitMember> {
Ok(new)
}
@ -469,11 +441,11 @@ pub trait ReconstructingReducer {
_circuit: &Circuit,
circuit_name: Identifier,
members: Vec<CircuitMember>,
) -> Result<Circuit, ReducerError> {
) -> Result<Circuit> {
Ok(Circuit { circuit_name, members })
}
fn reduce_annotation(&mut self, annotation: &Annotation, name: Identifier) -> Result<Annotation, ReducerError> {
fn reduce_annotation(&mut self, annotation: &Annotation, name: Identifier) -> Result<Annotation> {
Ok(Annotation {
span: annotation.span.clone(),
name,
@ -490,7 +462,7 @@ pub trait ReconstructingReducer {
input: Vec<FunctionInput>,
output: Option<Type>,
block: Block,
) -> Result<Function, ReducerError> {
) -> Result<Function> {
Ok(Function {
identifier,
annotations,

View File

@ -14,7 +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::{Expression, Identifier, PositiveNumber, Span};
use crate::{Expression, Identifier, PositiveNumber};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +14,9 @@
// 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, Span};
use crate::{Expression, Node};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{Node, Span, Statement};
use crate::{Node, Statement};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{Block, Expression, Node, Span, Statement};
use crate::{Block, Expression, Node, Statement};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{Char, Expression, Node, Span};
use crate::{Char, Expression, Node};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{ConsoleArgs, Expression, Node, Span};
use crate::{ConsoleArgs, Expression, Node};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{ConsoleFunction, Node, Span};
use crate::{ConsoleFunction, Node};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{Expression, Node, Span, Type};
use crate::{Expression, Node, Type};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{Identifier, Node, Span};
use crate::{Identifier, Node};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{Expression, Node, Span};
use crate::{Expression, Node};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

View File

@ -14,7 +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::{Block, Expression, Identifier, Node, Span};
use crate::{Block, Expression, Identifier, Node};
use leo_errors::Span;
use serde::{Deserialize, Serialize};
use std::fmt;

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