Merge branch 'master' into console-assert-error

This commit is contained in:
damirka 2021-02-25 20:24:43 +03:00
commit efd193f187
101 changed files with 1026 additions and 1045 deletions

163
.circleci/config.yml Normal file
View File

@ -0,0 +1,163 @@
version: 2.1
commands:
setup_environment:
description: "Setup environment"
parameters:
cache_key:
type: string
default: leo-stable-cache
steps:
- run: set -e
- setup_remote_docker
- run:
name: Prepare environment and install dependencies
command: |
export SCCACHE_CACHE_SIZE=200M
export WORK_DIR="$CIRCLE_WORKING_DIRECTORY/.cache/sccache"
export SCCACHE_DIR="$CIRCLE_WORKING_DIRECTORY/.cache/sccache"
mkdir -p "$CIRCLE_WORKING_DIRECTORY/.bin"
wget https://github.com/mozilla/sccache/releases/download/0.2.13/sccache-0.2.13-x86_64-unknown-linux-musl.tar.gz
tar -C "$CIRCLE_WORKING_DIRECTORY/.bin" -xvf sccache-0.2.13-x86_64-unknown-linux-musl.tar.gz
mv $CIRCLE_WORKING_DIRECTORY/.bin/sccache-0.2.13-x86_64-unknown-linux-musl/sccache $CIRCLE_WORKING_DIRECTORY/.bin/sccache
export PATH="$PATH:$CIRCLE_WORKING_DIRECTORY/.bin"
export RUSTC_WRAPPER="sccache"
rm -rf "$CIRCLE_WORKING_DIRECTORY/.cargo/registry"
sudo apt-get update && sudo apt-get install -y clang llvm-dev llvm pkg-config xz-utils make libssl-dev libssl-dev
- restore_cache:
keys:
- << parameters.cache_key >>
clear_environment:
description: "Clear environment"
parameters:
cache_key:
type: string
default: leo-stable-cache
steps:
- run: (sccache -s||true)
- run: set +e
- save_cache:
key: << parameters.cache_key >>
paths:
- .cache/sccache
- .cargo
jobs:
rust-stable:
docker:
- image: cimg/rust:1.50.0
resource_class: xlarge
steps:
- checkout
- setup_environment:
cache_key: leo-stable-cache
- run:
name: Build and run tests
no_output_timeout: 30m
command: cargo install --path . --root .
- persist_to_workspace:
root: ~/
paths: project/
- clear_environment:
cache_key: leo-stable-cache
leo-new:
docker:
- image: cimg/rust:1.50.0
resource_class: xlarge
steps:
- attach_workspace:
at: /home/circleci/project/
- run:
name: leo new
command: |
export LEO=/home/circleci/project/project/bin/leo
./project/.circleci/leo-new.sh
leo-init:
docker:
- image: cimg/rust:1.50.0
resource_class: xlarge
steps:
- attach_workspace:
at: /home/circleci/project/
- run:
name: leo init
command: |
export LEO=/home/circleci/project/project/bin/leo
./project/.circleci/leo-init.sh
leo-clean:
docker:
- image: cimg/rust:1.50.0
resource_class: xlarge
steps:
- attach_workspace:
at: /home/circleci/project/
- run:
name: leo clean
command: |
export LEO=/home/circleci/project/project/bin/leo
./project/.circleci/leo-clean.sh
leo-setup:
docker:
- image: cimg/rust:1.50.0
resource_class: xlarge
steps:
- attach_workspace:
at: /home/circleci/project/
- run:
name: leo setup
command: |
export LEO=/home/circleci/project/project/bin/leo
./project/.circleci/leo-setup.sh
leo-add-remove:
docker:
- image: cimg/rust:1.50.0
resource_class: xlarge
steps:
- attach_workspace:
at: /home/circleci/project/
- run:
name: leo add & remove
command: |
export LEO=/home/circleci/project/project/bin/leo
./project/.circleci/leo-add-remove.sh
leo-login-logout:
docker:
- image: cimg/rust:1.50.0
resource_class: xlarge
steps:
- attach_workspace:
at: /home/circleci/project/
- run:
name: leo login & logout
command: |
export LEO=/home/circleci/project/project/bin/leo
./project/.circleci/leo-login-logout.sh
workflows:
version: 2
main-workflow:
jobs:
- rust-stable
- leo-new:
requires:
- rust-stable
- leo-init:
requires:
- rust-stable
- leo-clean:
requires:
- rust-stable
- leo-setup:
requires:
- rust-stable
- leo-add-remove:
requires:
- rust-stable
- leo-login-logout:
requires:
- rust-stable

6
.circleci/leo-add-remove.sh Executable file
View File

@ -0,0 +1,6 @@
# leo add (w/o login) & remove
$LEO new my-app && cd my-app
$LEO add howard/silly-sudoku
$LEO remove silly-sudoku
$LEO clean

34
.circleci/leo-clean.sh Executable file
View File

@ -0,0 +1,34 @@
# leo new hello-world
$LEO new hello-world
ls -la
cd hello-world && ls -la
$LEO run
# Assert that the 'outputs' folder is not empty
cd outputs || exit 1
if [ "$(ls -A $DIR)" ]; then
echo "$DIR is not empty"
else
echo "$DIR is empty"
exit 1
fi
cd ..
# leo clean
$LEO clean
cd outputs && ls -la
cd ..
# Assert that the 'outputs' folder is empty
cd outputs || exit 1
if [ "$(ls -A $DIR)" ]; then
echo "$DIR is not empty"
exit 1
else
echo "$DIR is empty"
exit 0
fi

4
.circleci/leo-init.sh Executable file
View File

@ -0,0 +1,4 @@
mkdir hello-world && cd hello-world || exit 1
$LEO init
ls -la
$LEO run

7
.circleci/leo-login-logout.sh Executable file
View File

@ -0,0 +1,7 @@
# leo login & logout
$LEO new my-app && cd my-app || exit 1
$LEO login -u "$ALEO_PM_USERNAME" -p "$ALEO_PM_PASSWORD"
$LEO add howard/silly-sudoku
$LEO remove silly-sudoku
$LEO logout

4
.circleci/leo-new.sh Executable file
View File

@ -0,0 +1,4 @@
$LEO new hello-world
ls -la
cd hello-world && ls -la
$LEO run

7
.circleci/leo-setup.sh Executable file
View File

@ -0,0 +1,7 @@
# leo setup
cd ./project/examples/pedersen-hash || exit 1
$LEO setup
$LEO setup
$LEO setup --skip-key-check
$LEO clean

View File

@ -1,43 +0,0 @@
name: leo-add-remove
on:
pull_request:
push:
branches:
- master
paths-ignore:
- 'docs/**'
- 'documentation/**'
env:
RUST_BACKTRACE: 1
jobs:
add:
name: Add Package ('leo add')
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v1
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true
components: rustfmt
- name: Install Leo
uses: actions-rs/cargo@v1
env:
CARGO_NET_GIT_FETCH_WITH_CLI: true
with:
command: install
args: --path .
- name: 'leo add (w/o login) & remove'
run: |
cd .. && leo new my-app && cd my-app
leo add argus4130/xnor
leo remove xnor
leo clean

View File

@ -1,76 +0,0 @@
name: leo-clean
on:
pull_request:
push:
branches:
- master
paths-ignore:
- 'docs/**'
- 'documentation/**'
env:
RUST_BACKTRACE: 1
jobs:
new:
name: Hello Leo ('leo new hello-world')
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v1
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true
components: rustfmt
- uses: actions/cache@v2
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Install Leo
uses: actions-rs/cargo@v1
with:
command: install
args: --path .
- name: 'leo new hello-world'
run: |
cd ..
leo new hello-world
ls -la
cd hello-world && ls -la
leo run
- name: Assert that the 'outputs' folder is not empty
run: |
cd ../hello-world/outputs
if [ "$(ls -A $DIR)" ]; then
echo "$DIR is not empty"
else
echo "$DIR is empty"
exit 1
fi
- name: 'leo clean'
run: |
cd ../hello-world
leo clean
cd outputs && ls -la
- name: Assert that the 'outputs' folder is empty
run: |
cd ../hello-world/outputs
if [ "$(ls -A $DIR)" ]; then
echo "$DIR is not empty"
exit 1
else
echo "$DIR is empty"
exit 0
fi

View File

@ -1,48 +0,0 @@
name: leo-init
on:
pull_request:
push:
branches:
- master
paths-ignore:
- 'docs/**'
- 'documentation/**'
env:
RUST_BACKTRACE: 1
jobs:
init:
name: Hello Leo ('leo init')
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v1
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true
components: rustfmt
- uses: actions/cache@v2
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Install Leo
uses: actions-rs/cargo@v1
with:
command: install
args: --path .
- name: 'leo init'
run: |
cd .. && mkdir hello-world && cd hello-world
leo init
ls -la
leo run

View File

@ -1,47 +0,0 @@
name: leo-login-logout
on:
pull_request:
push:
branches:
- master
paths-ignore:
- 'docs/**'
- 'documentation/**'
env:
RUST_BACKTRACE: 1
jobs:
add:
name: Add Package ('leo add')
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v1
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true
components: rustfmt
- name: Install Leo
uses: actions-rs/cargo@v1
env:
CARGO_NET_GIT_FETCH_WITH_CLI: true
with:
command: install
args: --path .
- name: 'leo login & logout'
env:
USER: ${{ secrets.ALEO_PM_USERNAME }}
PASS: ${{ secrets.ALEO_PM_PASSWORD }}
run: |
cd .. && leo new my-app && cd my-app
leo login -u "$USER" -p "$PASS"
leo add argus4130/xnor
leo remove xnor
leo logout

View File

@ -1,49 +0,0 @@
name: leo-new
on:
pull_request:
push:
branches:
- master
paths-ignore:
- 'docs/**'
- 'documentation/**'
env:
RUST_BACKTRACE: 1
jobs:
new:
name: Hello Leo ('leo new hello-world')
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v1
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true
components: rustfmt
- uses: actions/cache@v2
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Install Leo
uses: actions-rs/cargo@v1
with:
command: install
args: --path .
- name: 'leo new hello-world'
run: |
cd ..
leo new hello-world
ls -la
cd hello-world && ls -la
leo run

View File

@ -1,47 +0,0 @@
name: leo-setup
on:
pull_request:
push:
branches:
- master
paths-ignore:
- 'docs/**'
- 'documentation/**'
env:
RUST_BACKTRACE: 1
jobs:
add:
name: Add Package ('leo add')
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v1
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true
components: rustfmt
- name: Install Leo
uses: actions-rs/cargo@v1
env:
CARGO_NET_GIT_FETCH_WITH_CLI: true
with:
command: install
args: --path .
- name: 'leo setup for examples'
env:
USER: ${{ secrets.ALEO_PM_USERNAME }}
PASS: ${{ secrets.ALEO_PM_PASSWORD }}
run: |
cd examples/pedersen-hash
leo setup
leo setup
leo setup --skip-key-check
leo clean

6
.gitignore vendored
View File

@ -2,3 +2,9 @@
/tmp/
**.idea/
*.DS_Store
**/process.yml
**/.crates.toml
**/.crates2.json
**/bin/

View File

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 29 KiB

41
Cargo.lock generated
View File

@ -117,9 +117,9 @@ checksum = "58946044516aa9dc922182e0d6e9d124a31aafe6b421614654eb27cf90cec09c"
[[package]]
name = "bincode"
version = "1.3.1"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f30d3a39baa26f9651f17b375061f3233dde33424a8b72b0dbe93a68a0bc896d"
checksum = "d175dfa69e619905c4c3cdb7c3c203fa3bdd5d51184e3afdb2742c0280493772"
dependencies = [
"byteorder",
"serde",
@ -955,17 +955,6 @@ dependencies = [
"wasi 0.9.0+wasi-snapshot-preview1",
]
[[package]]
name = "getrandom"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9495705279e7140bf035dde1f6e750c162df8b625267cd52cc44e0b156732c8"
dependencies = [
"cfg-if 1.0.0",
"libc",
"wasi 0.10.0+wasi-snapshot-preview1",
]
[[package]]
name = "gimli"
version = "0.23.0"
@ -1290,7 +1279,6 @@ dependencies = [
"serde_json",
"thiserror",
"typed-arena",
"uuid",
]
[[package]]
@ -1338,7 +1326,6 @@ dependencies = [
"snarkvm-utilities",
"thiserror",
"tracing",
"uuid",
]
[[package]]
@ -2148,7 +2135,7 @@ version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03"
dependencies = [
"getrandom 0.1.15",
"getrandom",
"libc",
"rand_chacha",
"rand_core 0.5.1",
@ -2171,7 +2158,7 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19"
dependencies = [
"getrandom 0.1.15",
"getrandom",
]
[[package]]
@ -2235,7 +2222,7 @@ version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de0737333e7a9502c789a36d7c7fa6092a49895d4faa31ca5df163857ded2e9d"
dependencies = [
"getrandom 0.1.15",
"getrandom",
"redox_syscall",
"rust-argon2",
]
@ -2439,9 +2426,9 @@ dependencies = [
[[package]]
name = "self_update"
version = "0.24.0"
version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e350b457809b67e2de1c0205843929a6fa6da94a2660f772d28379bb14c36d97"
checksum = "5abe13436707b8fd0044592de0b8d9565ab700fbb06611d6e4d89384687da195"
dependencies = [
"hyper",
"indicatif",
@ -3061,9 +3048,9 @@ checksum = "e987b6bf443f4b5b3b6f38704195592cca41c5bb7aedd3c3693c7081f8289860"
[[package]]
name = "tracing"
version = "0.1.24"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f77d3842f76ca899ff2dbcf231c5c65813dea431301d6eb686279c15c4464f12"
checksum = "01ebdc2bb4498ab1ab5f5b73c5803825e60199229ccba0698170e3be0e7f959f"
dependencies = [
"cfg-if 1.0.0",
"pin-project-lite",
@ -3231,16 +3218,6 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "uuid"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7"
dependencies = [
"getrandom 0.2.2",
"serde",
]
[[package]]
name = "vcpkg"
version = "0.2.11"

View File

@ -130,7 +130,7 @@ version = "0.11.1"
features = [ "blocking", "json", "multipart" ]
[dependencies.self_update]
version = "0.24.0"
version = "0.25.0"
features = [ "archive-zip" ]
[dependencies.serde]

31
DEVELOPMENT.md Normal file
View File

@ -0,0 +1,31 @@
# Development Guide
## Running CircleCI locally
### Step 1: Install CircleCI
If you wish to run CircleCI locally, start by installing it:
- macOS
```
brew install circleci
```
- Linux (via Snap)
```
sudo snap install docker circleci
sudo snap connect circleci:docker docker
```
- Windows (via Chocolatey)
```
choco install circleci-cli -y
```
### Step 2: Run CircleCI
To run a job, export the config to `process.yml`, and specify it when executing:
```shell
circleci config process .circleci/config.yml > process.yml
circleci local execute -c process.yml --job JOB_NAME
```

View File

@ -1,5 +1,5 @@
<p align="center">
<img width="1412" src="./.resources/leo.png">
<img width="1412" src=".resources/banner.png">
</p>
<h1 align="center">The Leo Programming Language</h1>
@ -27,6 +27,7 @@ Leo is a functional, statically-typed programming language built for writing pri
## 1. Overview
Welcome to the Leo programming language.
Leo provides a high-level language that abstracts low-level cryptographic concepts and makes it easy to

View File

@ -37,10 +37,6 @@ path = "../ast"
version = "1.2.2"
path = "../grammar"
[dependencies.uuid]
version = "0.8"
features = [ "v4", "serde" ]
[dependencies.num-bigint]
version = "0.3"

46
asg/src/context.rs Normal file
View File

@ -0,0 +1,46 @@
// 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 std::{cell::Cell, unimplemented};
use typed_arena::Arena;
use crate::ArenaNode;
pub struct AsgContextInner<'a> {
pub arena: &'a Arena<ArenaNode<'a>>,
pub next_id: Cell<u32>,
}
impl<'a> AsgContextInner<'a> {
pub fn new(arena: &'a Arena<ArenaNode<'a>>) -> &'a Self {
match arena.alloc(ArenaNode::Inner(AsgContextInner {
arena,
next_id: Cell::new(0),
})) {
ArenaNode::Inner(x) => x,
_ => unimplemented!(),
}
}
pub fn get_id(&self) -> u32 {
let next_id = self.next_id.get();
self.next_id.replace(next_id + 1);
next_id
}
}
pub type AsgContext<'a> = &'a AsgContextInner<'a>;

View File

@ -39,7 +39,7 @@ pub const STATE_LEAF_PSEUDO_CIRCUIT: &str = "$InputStateLeaf";
impl<'a> Input<'a> {
fn make_header(scope: &'a Scope<'a>, name: &str) -> &'a Circuit<'a> {
scope.alloc_circuit(Circuit {
id: uuid::Uuid::new_v4(),
id: scope.context.get_id(),
name: RefCell::new(Identifier::new(name.to_string())),
members: RefCell::new(IndexMap::new()),
core_mapping: RefCell::new(None),
@ -68,7 +68,7 @@ impl<'a> Input<'a> {
);
let container_circuit = input_scope.alloc_circuit(Circuit {
id: uuid::Uuid::new_v4(),
id: scope.context.get_id(),
name: RefCell::new(Identifier::new(CONTAINER_PSEUDO_CIRCUIT.to_string())),
members: RefCell::new(container_members),
core_mapping: RefCell::new(None),
@ -83,7 +83,7 @@ impl<'a> Input<'a> {
state_leaf,
container_circuit,
container: input_scope.alloc_variable(RefCell::new(crate::InnerVariable {
id: uuid::Uuid::new_v4(),
id: scope.context.get_id(),
name: Identifier::new("input".to_string()),
type_: Type::Circuit(container_circuit),
mutable: false,

View File

@ -71,9 +71,10 @@ pub use variable::*;
pub mod pass;
pub use pass::*;
pub use leo_ast::{Ast, Identifier, Span};
pub mod context;
pub use context::*;
pub type AsgContext<'a> = &'a Arena<ArenaNode<'a>>;
pub use leo_ast::{Ast, Identifier, Span};
use std::path::Path;
@ -132,6 +133,10 @@ pub fn load_asg<'a, T: ImportResolver<'a>>(
InternalProgram::new(context, leo_ast::Ast::new("load_ast", &ast)?.as_repr(), resolver)
}
pub fn new_context<'a>() -> Arena<ArenaNode<'a>> {
pub fn new_alloc_context<'a>() -> Arena<ArenaNode<'a>> {
Arena::new()
}
pub fn new_context<'a>(arena: &'a Arena<ArenaNode<'a>>) -> AsgContext<'a> {
AsgContextInner::new(arena)
}

View File

@ -14,7 +14,18 @@
// 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, Expression, Function, PartialType, Scope, Span, Statement, Variable};
use crate::{
AsgContextInner,
AsgConvertError,
Circuit,
Expression,
Function,
PartialType,
Scope,
Span,
Statement,
Variable,
};
/// A node in the abstract semantic graph.
pub trait Node {
@ -38,4 +49,5 @@ pub enum ArenaNode<'a> {
Variable(Variable<'a>),
Circuit(Circuit<'a>),
Function(Function<'a>),
Inner(AsgContextInner<'a>),
}

View File

@ -18,7 +18,6 @@ use crate::{AsgConvertError, Function, Identifier, Node, Scope, Span, Type};
use indexmap::IndexMap;
use std::cell::RefCell;
use uuid::Uuid;
#[derive(Clone)]
pub enum CircuitMember<'a> {
@ -28,7 +27,7 @@ pub enum CircuitMember<'a> {
#[derive(Clone)]
pub struct Circuit<'a> {
pub id: Uuid,
pub id: u32,
pub name: RefCell<Identifier>,
pub core_mapping: RefCell<Option<String>>,
pub scope: &'a Scope<'a>,
@ -58,7 +57,7 @@ impl<'a> Circuit<'a> {
let new_scope = scope.make_subscope();
let circuit = scope.alloc_circuit(Circuit {
id: Uuid::new_v4(),
id: scope.context.get_id(),
name: RefCell::new(value.circuit_name.clone()),
members: RefCell::new(IndexMap::new()),
core_mapping: RefCell::new(None),

View File

@ -32,7 +32,6 @@ use indexmap::IndexMap;
use leo_ast::FunctionInput;
use std::cell::{Cell, RefCell};
use uuid::Uuid;
#[derive(Clone, Copy, PartialEq)]
pub enum FunctionQualifier {
@ -43,7 +42,7 @@ pub enum FunctionQualifier {
#[derive(Clone)]
pub struct Function<'a> {
pub id: Uuid,
pub id: u32,
pub name: RefCell<Identifier>,
pub output: Type<'a>,
pub has_input: bool,
@ -99,7 +98,7 @@ impl<'a> Function<'a> {
..
}) => {
let variable = scope.alloc_variable(RefCell::new(crate::InnerVariable {
id: Uuid::new_v4(),
id: scope.context.get_id(),
name: identifier.clone(),
type_: scope.resolve_ast_type(&type_)?,
mutable: *mutable,
@ -117,7 +116,7 @@ impl<'a> Function<'a> {
return Err(AsgConvertError::invalid_self_in_global(&value.span));
}
let function = scope.alloc_function(Function {
id: Uuid::new_v4(),
id: scope.context.get_id(),
name: RefCell::new(value.identifier.clone()),
output,
has_input,
@ -137,7 +136,7 @@ impl<'a> Function<'a> {
if self.qualifier != FunctionQualifier::Static {
let circuit = self.circuit.get();
let self_variable = self.scope.alloc_variable(RefCell::new(crate::InnerVariable {
id: Uuid::new_v4(),
id: self.scope.context.get_id(),
name: Identifier::new("self".to_string()),
type_: Type::Circuit(circuit.as_ref().unwrap()),
mutable: self.qualifier == FunctionQualifier::MutSelfRef,

View File

@ -29,7 +29,6 @@ use leo_ast::{Identifier, PackageAccess, PackageOrPackages, Span};
use indexmap::IndexMap;
use std::cell::{Cell, RefCell};
use uuid::Uuid;
/// Stores the Leo program abstract semantic graph (ASG).
#[derive(Clone)]
@ -37,7 +36,7 @@ pub struct InternalProgram<'a> {
pub context: AsgContext<'a>,
/// The unique id of the program.
pub id: Uuid,
pub id: u32,
/// The program file name.
pub name: String,
@ -137,7 +136,7 @@ impl<'a> InternalProgram<'a> {
/// 4. resolve all asg nodes
///
pub fn new<T: ImportResolver<'a>>(
arena: AsgContext<'a>,
context: AsgContext<'a>,
program: &leo_ast::Program,
import_resolver: &mut T,
) -> Result<Program<'a>, AsgConvertError> {
@ -161,7 +160,7 @@ impl<'a> InternalProgram<'a> {
let pretty_package = package.join(".");
let resolved_package = match wrapped_resolver.resolve_package(
arena,
context,
&package.iter().map(|x| &**x).collect::<Vec<_>>()[..],
span,
)? {
@ -214,9 +213,9 @@ impl<'a> InternalProgram<'a> {
}
}
let import_scope = match arena.alloc(ArenaNode::Scope(Scope {
arena,
id: uuid::Uuid::new_v4(),
let import_scope = match context.arena.alloc(ArenaNode::Scope(Scope {
context,
id: context.get_id(),
parent_scope: Cell::new(None),
circuit_self: Cell::new(None),
variables: RefCell::new(IndexMap::new()),
@ -230,9 +229,9 @@ impl<'a> InternalProgram<'a> {
};
let scope = import_scope.alloc_scope(Scope {
arena,
context,
input: Cell::new(Some(Input::new(import_scope))), // we use import_scope to avoid recursive scope ref here
id: uuid::Uuid::new_v4(),
id: context.get_id(),
parent_scope: Cell::new(Some(import_scope)),
circuit_self: Cell::new(None),
variables: RefCell::new(IndexMap::new()),
@ -296,8 +295,8 @@ impl<'a> InternalProgram<'a> {
}
Ok(InternalProgram {
context: arena,
id: Uuid::new_v4(),
context,
id: context.get_id(),
name: program.name.clone(),
test_functions,
functions,

View File

@ -14,20 +14,18 @@
// 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::{ArenaNode, AsgConvertError, Circuit, Expression, Function, Input, Statement, Type, Variable};
use crate::{ArenaNode, AsgContext, AsgConvertError, Circuit, Expression, Function, Input, Statement, Type, Variable};
use indexmap::IndexMap;
use std::cell::{Cell, RefCell};
use typed_arena::Arena;
use uuid::Uuid;
/// An abstract data type that track the current bindings for variables, functions, and circuits.
#[derive(Clone)]
pub struct Scope<'a> {
pub arena: &'a Arena<ArenaNode<'a>>,
pub context: AsgContext<'a>,
/// The unique id of the scope.
pub id: Uuid,
pub id: u32,
/// The parent scope that this scope inherits.
pub parent_scope: Cell<Option<&'a Scope<'a>>>,
@ -54,42 +52,42 @@ pub struct Scope<'a> {
#[allow(clippy::mut_from_ref)]
impl<'a> Scope<'a> {
pub fn alloc_expression(&'a self, expr: Expression<'a>) -> &'a mut Expression<'a> {
match self.arena.alloc(ArenaNode::Expression(expr)) {
match self.context.arena.alloc(ArenaNode::Expression(expr)) {
ArenaNode::Expression(e) => e,
_ => unimplemented!(),
}
}
pub fn alloc_statement(&'a self, statement: Statement<'a>) -> &'a mut Statement<'a> {
match self.arena.alloc(ArenaNode::Statement(statement)) {
match self.context.arena.alloc(ArenaNode::Statement(statement)) {
ArenaNode::Statement(e) => e,
_ => unimplemented!(),
}
}
pub fn alloc_variable(&'a self, variable: Variable<'a>) -> &'a mut Variable<'a> {
match self.arena.alloc(ArenaNode::Variable(variable)) {
match self.context.arena.alloc(ArenaNode::Variable(variable)) {
ArenaNode::Variable(e) => e,
_ => unimplemented!(),
}
}
pub fn alloc_scope(&'a self, scope: Scope<'a>) -> &'a mut Scope<'a> {
match self.arena.alloc(ArenaNode::Scope(scope)) {
match self.context.arena.alloc(ArenaNode::Scope(scope)) {
ArenaNode::Scope(e) => e,
_ => unimplemented!(),
}
}
pub fn alloc_circuit(&'a self, circuit: Circuit<'a>) -> &'a mut Circuit<'a> {
match self.arena.alloc(ArenaNode::Circuit(circuit)) {
match self.context.arena.alloc(ArenaNode::Circuit(circuit)) {
ArenaNode::Circuit(e) => e,
_ => unimplemented!(),
}
}
pub fn alloc_function(&'a self, function: Function<'a>) -> &'a mut Function<'a> {
match self.arena.alloc(ArenaNode::Function(function)) {
match self.context.arena.alloc(ArenaNode::Function(function)) {
ArenaNode::Function(e) => e,
_ => unimplemented!(),
}
@ -198,8 +196,8 @@ impl<'a> Scope<'a> {
///
pub fn make_subscope(self: &'a Scope<'a>) -> &'a Scope<'a> {
self.alloc_scope(Scope::<'a> {
arena: self.arena,
id: Uuid::new_v4(),
context: self.context,
id: self.context.get_id(),
parent_scope: Cell::new(Some(self)),
circuit_self: Cell::new(None),
variables: RefCell::new(IndexMap::new()),

View File

@ -96,7 +96,7 @@ impl<'a> FromAst<'a, leo_ast::DefinitionStatement> for &'a Statement<'a> {
)));
}
variables.push(&*scope.alloc_variable(RefCell::new(InnerVariable {
id: uuid::Uuid::new_v4(),
id: scope.context.get_id(),
name: variable.identifier.clone(),
type_:
type_.ok_or_else(|| AsgConvertError::unresolved_type(&variable.identifier.name, &statement.span))?,

View File

@ -58,7 +58,7 @@ impl<'a> FromAst<'a, leo_ast::IterationStatement> for &'a Statement<'a> {
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)?;
let variable = scope.alloc_variable(RefCell::new(InnerVariable {
id: uuid::Uuid::new_v4(),
id: scope.context.get_id(),
name: statement.variable.clone(),
type_: start
.get_type()

View File

@ -19,8 +19,6 @@ use std::cell::RefCell;
use crate::{Expression, Statement, Type};
use leo_ast::Identifier;
use uuid::Uuid;
/// Specifies how a program variable was declared.
#[derive(Clone, Copy, PartialEq)]
pub enum VariableDeclaration {
@ -33,7 +31,7 @@ pub enum VariableDeclaration {
/// Stores information on a program variable.
#[derive(Clone)]
pub struct InnerVariable<'a> {
pub id: Uuid,
pub id: u32,
pub name: Identifier,
pub type_: Type<'a>,
pub mutable: bool,

View File

@ -14,12 +14,10 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_implicit_invalid() {
let program_string = include_str!("implicit_invalid.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}

View File

@ -14,8 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
// Expressions
@ -23,49 +21,49 @@ use crate::load_asg;
#[test]
fn test_initializer_fail() {
let program_string = include_str!("initializer_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_input_nested_3x2_fail() {
let program_string = include_str!("input_nested_3x2_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_input_tuple_3x2_fail() {
let program_string = include_str!("input_tuple_3x2_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_multi_fail_initializer() {
let program_string = include_str!("multi_fail_initializer.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_multi_inline_fail() {
let program_string = include_str!("multi_fail_inline.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_multi_initializer_fail() {
let program_string = include_str!("multi_initializer_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_nested_3x2_value_fail() {
let program_string = include_str!("nested_3x2_value_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_tuple_3x2_value_fail() {
let program_string = include_str!("tuple_3x2_value_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
// Array type tests
@ -73,65 +71,65 @@ fn test_tuple_3x2_value_fail() {
#[test]
fn test_type_fail() {
let program_string = include_str!("type_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_type_nested_value_nested_3x2_fail() {
let program_string = include_str!("type_nested_value_nested_3x2_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_type_nested_value_nested_4x3x2_fail() {
let program_string = include_str!("type_nested_value_nested_4x3x2_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_type_nested_value_tuple_3x2_fail() {
let program_string = include_str!("type_nested_value_tuple_3x2_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_type_nested_value_tuple_4x3x2_fail() {
let program_string = include_str!("type_nested_value_tuple_4x3x2_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_type_tuple_value_nested_3x2_fail() {
let program_string = include_str!("type_tuple_value_nested_3x2_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_type_tuple_value_nested_3x2_swap_fail() {
let program_string = include_str!("type_tuple_value_nested_3x2_swap_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_type_tuple_value_nested_4x3x2_fail() {
let program_string = include_str!("type_tuple_value_nested_4x3x2_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_type_tuple_value_tuple_3x2_fail() {
let program_string = include_str!("type_tuple_value_tuple_3x2_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_type_tuple_value_tuple_3x2_swap_fail() {
let program_string = include_str!("type_tuple_value_tuple_3x2_swap_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_type_tuple_value_tuple_4x3x2_fail() {
let program_string = include_str!("type_tuple_value_tuple_4x3x2_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}

View File

@ -14,24 +14,22 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_not_u32() {
let program_string = include_str!("not_u32.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_true_or_u32() {
let program_string = include_str!("true_or_u32.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_true_and_u32() {
let program_string = include_str!("true_and_u32.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}

View File

@ -14,8 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
// Expressions
@ -23,13 +21,13 @@ use crate::load_asg;
#[test]
fn test_inline_fail() {
let program_string = include_str!("inline_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_inline_undefined() {
let program_string = include_str!("inline_undefined.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
// Members
@ -37,19 +35,19 @@ fn test_inline_undefined() {
#[test]
fn test_member_variable_fail() {
let program_string = include_str!("member_variable_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_member_function_fail() {
let program_string = include_str!("member_function_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_member_function_invalid() {
let program_string = include_str!("member_function_invalid.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
@ -66,19 +64,19 @@ fn test_mut_member_function_fail() {
console.assert(a.echo(1u32) == 1u32);
}"#;
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_member_static_function_invalid() {
let program_string = include_str!("member_static_function_invalid.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_member_static_function_undefined() {
let program_string = include_str!("member_static_function_undefined.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
// Mutability
@ -86,37 +84,37 @@ fn test_member_static_function_undefined() {
#[test]
fn test_mutate_function_fail() {
let program_string = include_str!("mut_function_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_mutate_self_variable_fail() {
let program_string = include_str!("mut_self_variable_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_mutate_self_function_fail() {
let program_string = include_str!("mut_self_function_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_mutate_self_static_function_fail() {
let program_string = include_str!("mut_self_static_function_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_mutate_static_function_fail() {
let program_string = include_str!("mut_static_function_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_mutate_variable_fail() {
let program_string = include_str!("mut_variable_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
// Self
@ -124,17 +122,17 @@ fn test_mutate_variable_fail() {
#[test]
fn test_self_fail() {
let program_string = include_str!("self_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_self_member_invalid() {
let program_string = include_str!("self_member_invalid.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_self_member_undefined() {
let program_string = include_str!("self_member_undefined.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}

View File

@ -14,30 +14,28 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_log_fail() {
let program_string = include_str!("log_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_log_parameter_fail_unknown() {
let program_string = include_str!("log_parameter_fail_unknown.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_log_parameter_fail_empty() {
let program_string = include_str!("log_parameter_fail_empty.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_log_parameter_fail_none() {
let program_string = include_str!("log_parameter_fail_empty.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}

View File

@ -14,30 +14,28 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_core_circuit_invalid() {
let program_string = include_str!("core_package_invalid.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_core_circuit_star_fail() {
let program_string = include_str!("core_circuit_star_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_core_package_invalid() {
let program_string = include_str!("core_package_invalid.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_core_unstable_package_invalid() {
let program_string = include_str!("core_unstable_package_invalid.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}

View File

@ -14,44 +14,42 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_multiple_returns_fail() {
let program_string = include_str!("multiple_returns_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_multiple_returns_input_ambiguous() {
let program_string = include_str!("multiple_returns_input_ambiguous.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_multiple_returns_fail_conditional() {
let program_string = include_str!("multiple_returns_fail_conditional.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_scope_fail() {
let program_string = include_str!("scope_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_undefined() {
let program_string = include_str!("undefined.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_array_input() {
let program_string = include_str!("array_input.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
// Test return multidimensional arrays
@ -59,11 +57,11 @@ fn test_array_input() {
#[test]
fn test_return_array_nested_fail() {
let program_string = include_str!("return_array_nested_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_return_array_tuple_fail() {
let program_string = include_str!("return_array_tuple_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}

View File

@ -19,17 +19,17 @@ use crate::load_asg;
#[test]
fn test_both_sign_high() {
let program_string = include_str!("both_sign_high.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_both_sign_low() {
let program_string = include_str!("both_sign_low.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_both_sign_inferred() {
let program_string = include_str!("both_sign_inferred.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}

View File

@ -16,27 +16,25 @@
macro_rules! test_int {
($name: ident) => {
use leo_asg::new_context;
pub struct $name {}
// we are not doing constant folding here, so asg doesnt catch this
// impl $name {
// fn test_negate_min_fail() {
// let program_string = include_str!("negate_min.leo");
// crate::load_asg(&new_context(), program_string).err().unwrap();
// crate::load_asg(program_string).err().unwrap();
// }
// }
impl super::IntegerTester for $name {
fn test_min_fail() {
let program_string = include_str!("min_fail.leo");
crate::load_asg(&new_context(), program_string).err().unwrap();
crate::load_asg(program_string).err().unwrap();
}
fn test_max_fail() {
let program_string = include_str!("max_fail.leo");
crate::load_asg(&new_context(), program_string).err().unwrap();
crate::load_asg(program_string).err().unwrap();
}
}
};

View File

@ -16,19 +16,17 @@
macro_rules! test_uint {
($name: ident) => {
use leo_asg::new_context;
pub struct $name {}
impl super::IntegerTester for $name {
fn test_min_fail() {
let program_string = include_str!("min_fail.leo");
crate::load_asg(&new_context(), program_string).err().unwrap();
crate::load_asg(program_string).err().unwrap();
}
fn test_max_fail() {
let program_string = include_str!("max_fail.leo");
crate::load_asg(&new_context(), program_string).err().unwrap();
crate::load_asg(program_string).err().unwrap();
}
}
};

View File

@ -14,48 +14,46 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_let() {
let program_string = include_str!("let.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_const_fail() {
let program_string = include_str!("const.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_array() {
let program_string = include_str!("array.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_circuit() {
let program_string = include_str!("circuit.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_circuit_function_mut() {
let program_string = include_str!("circuit_function_mut.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_circuit_static_function_mut() {
let program_string = include_str!("circuit_static_function_mut.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_function_input() {
let program_string = include_str!("function_input.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}

View File

@ -14,18 +14,16 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_num_returns_fail() {
let program_string = include_str!("num_returns_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_const_declaration_fail() {
let program_string = include_str!("const_declaration_fail.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}

View File

@ -26,8 +26,8 @@ mod pass;
const TESTING_FILEPATH: &str = "input.leo";
const TESTING_PROGRAM_NAME: &str = "test_program";
fn load_asg<'a>(context: AsgContext<'a>, program_string: &str) -> Result<Program<'a>, AsgConvertError> {
load_asg_imports(context, program_string, &mut NullImportResolver)
fn load_asg(program_string: &str) -> Result<Program<'static>, AsgConvertError> {
load_asg_imports(make_test_context(), program_string, &mut NullImportResolver)
}
fn load_asg_imports<'a, T: ImportResolver<'a>>(
@ -40,7 +40,13 @@ fn load_asg_imports<'a, T: ImportResolver<'a>>(
InternalProgram::new(context, &ast.as_repr(), imports)
}
fn mocked_resolver<'a>(_ctx: AsgContext<'a>) -> MockedImportResolver<'a> {
fn mocked_resolver<'a>(_context: AsgContext<'a>) -> MockedImportResolver<'a> {
let packages = indexmap::IndexMap::new();
MockedImportResolver { packages }
}
//convenience function for tests, leaks memory
pub(crate) fn make_test_context() -> AsgContext<'static> {
let allocator = Box::leak(Box::new(new_alloc_context()));
new_context(allocator)
}

View File

@ -14,37 +14,35 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_valid() {
let program_string = include_str!("valid.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_implicit_valid() {
let program_string = include_str!("implicit_valid.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_console_assert_pass() {
let program_string = include_str!("console_assert_pass.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_ternary() {
let program_string = include_str!("ternary.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_equal() {
let program_string = include_str!("equal.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}

View File

@ -14,8 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
// Registers
@ -23,7 +21,7 @@ use crate::load_asg;
#[test]
fn test_registers() {
let program_string = include_str!("registers.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
// Expressions
@ -31,173 +29,173 @@ fn test_registers() {
#[test]
fn test_inline() {
let program_string = include_str!("inline.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_initializer() {
let program_string = include_str!("initializer.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_initializer_input() {
let program_string = include_str!("initializer_input.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_input_nested_3x2() {
let program_string = include_str!("input_nested_3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_input_tuple_3x2() {
let program_string = include_str!("input_tuple_3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_multi_initializer() {
let program_string = include_str!("multi_initializer.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_nested_3x2_value() {
let program_string = include_str!("nested_3x2_value.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_tuple_3x2_value() {
let program_string = include_str!("tuple_3x2_value.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_spread() {
let program_string = include_str!("spread.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_slice() {
let program_string = include_str!("slice.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_index_u8() {
let program_string = include_str!("index_u8.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_slice_i8() {
let program_string = include_str!("slice_i8.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_slice_lower() {
let program_string = include_str!("slice_lower.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_type_nested_value_nested_3x2() {
let program_string = include_str!("type_nested_value_nested_3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_type_nested_value_nested_4x3x2() {
let program_string = include_str!("type_nested_value_nested_4x3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_type_nested_value_tuple_3x2() {
let program_string = include_str!("type_nested_value_tuple_3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_type_nested_value_tuple_4x3x2() {
let program_string = include_str!("type_nested_value_tuple_4x3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_type_tuple_value_nested_3x2() {
let program_string = include_str!("type_tuple_value_nested_3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_type_tuple_value_nested_4x3x2() {
let program_string = include_str!("type_tuple_value_nested_4x3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_type_tuple_value_tuple_3x2() {
let program_string = include_str!("type_tuple_value_tuple_3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_type_tuple_value_tuple_4x3x2() {
let program_string = include_str!("type_tuple_value_tuple_4x3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_input_type_nested_value_nested_3x2() {
let program_string = include_str!("type_input_3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_input_type_nested_value_nested_4x3x2() {
let program_string = include_str!("type_input_4x3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_input_type_nested_value_tuple_3x2() {
let program_string = include_str!("type_input_3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_input_type_nested_value_tuple_4x3x2() {
let program_string = include_str!("type_input_4x3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_input_type_tuple_value_nested_3x2() {
let program_string = include_str!("type_input_3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_input_type_tuple_value_nested_4x3x2() {
let program_string = include_str!("type_input_4x3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_input_type_tuple_value_tuple_3x2() {
let program_string = include_str!("type_input_3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_input_type_tuple_value_tuple_4x3x2() {
let program_string = include_str!("type_input_4x3x2.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}

View File

@ -14,20 +14,18 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_input_pass() {
let program_string = include_str!("assert_eq_input.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_registers() {
let program_string = include_str!("output_register.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
// Boolean not !
@ -35,19 +33,19 @@ fn test_registers() {
#[test]
fn test_not_true() {
let program_string = include_str!("not_true.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_not_false() {
let program_string = include_str!("not_false.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_not_mutable() {
let program_string = include_str!("not_mutable.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
// Boolean or ||
@ -55,19 +53,19 @@ fn test_not_mutable() {
#[test]
fn test_true_or_true() {
let program_string = include_str!("true_or_true.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_true_or_false() {
let program_string = include_str!("true_or_false.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_false_or_false() {
let program_string = include_str!("false_or_false.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
// Boolean and &&
@ -75,19 +73,19 @@ fn test_false_or_false() {
#[test]
fn test_true_and_true() {
let program_string = include_str!("true_and_true.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_true_and_false() {
let program_string = include_str!("true_and_false.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_false_and_false() {
let program_string = include_str!("false_and_false.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
// All
@ -95,5 +93,5 @@ fn test_false_and_false() {
#[test]
fn test_all() {
let program_string = include_str!("all.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}

View File

@ -14,8 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
// Expressions
@ -23,7 +21,7 @@ use crate::load_asg;
#[test]
fn test_inline() {
let program_string = include_str!("inline.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
// Members
@ -31,19 +29,19 @@ fn test_inline() {
#[test]
fn test_member_variable() {
let program_string = include_str!("member_variable.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_member_variable_and_function() {
let program_string = include_str!("member_variable_and_function.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_member_function() {
let program_string = include_str!("member_function.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
@ -60,25 +58,25 @@ fn test_mut_member_function() {
console.assert(a.echo(1u32) == 1u32);
}"#;
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_member_function_nested() {
let program_string = include_str!("member_function_nested.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_member_static_function() {
let program_string = include_str!("member_static_function.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_member_static_function_nested() {
let program_string = include_str!("member_static_function_nested.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
// Mutability
@ -86,19 +84,19 @@ fn test_member_static_function_nested() {
#[test]
fn test_mutate_self_variable() {
let program_string = include_str!("mut_self_variable.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_mutate_self_variable_conditional() {
let program_string = include_str!("mut_self_variable_conditional.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_mutate_variable() {
let program_string = include_str!("mut_variable.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
// Self
@ -106,7 +104,7 @@ fn test_mutate_variable() {
#[test]
fn test_self_member_pass() {
let program_string = include_str!("self_member.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
// All
@ -114,13 +112,13 @@ fn test_self_member_pass() {
#[test]
fn test_pedersen_mock() {
let program_string = include_str!("pedersen_mock.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_define_circuit_inside_circuit_function() {
let program_string = include_str!("define_circuit_inside_circuit_function.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
@ -133,5 +131,5 @@ fn test_circuit_explicit_define() {
let x: One = One {x: 5};
}
"#;
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}

View File

@ -14,32 +14,30 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_log() {
let program_string = include_str!("log.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_log_parameter() {
let program_string = include_str!("log_parameter.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_log_parameter_many() {
let program_string = include_str!("log_parameter_many.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_log_input() {
let program_string = include_str!("log_input.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
// Debug
@ -47,7 +45,7 @@ fn test_log_input() {
#[test]
fn test_debug() {
let program_string = include_str!("debug.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
// Error
@ -55,7 +53,7 @@ fn test_debug() {
#[test]
fn test_error() {
let program_string = include_str!("error.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
// Assertion
@ -63,11 +61,11 @@ fn test_error() {
#[test]
fn test_assert() {
let program_string = include_str!("assert.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_conditional_assert() {
let program_string = include_str!("conditional_assert.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}

View File

@ -14,24 +14,22 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_unstable_blake2s() {
let program_string = include_str!("unstable_blake2s.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_blake2s_input() {
let program_string = include_str!("blake2s_input.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_blake2s_random() {
let program_string = include_str!("blake2s_random.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}

View File

@ -14,19 +14,17 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_out_of_order() {
let program_string = include_str!("out_of_order.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
// #[test]
// #[ignore]
// fn test_out_of_order_with_import() {
// let program_string = include_str!("out_of_order_with_import.leo");
// load_asg(&new_context(), program_string).unwrap();
// load_asg(program_string).unwrap();
// }

View File

@ -14,20 +14,18 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_negate() {
let program_string = include_str!("negate.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_add() {
let program_string = include_str!("add.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
@ -37,41 +35,41 @@ fn test_add_explicit() {
let c: field = 0field + 1field;
}
"#;
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_sub() {
let program_string = include_str!("sub.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_div() {
let program_string = include_str!("div.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_mul() {
let program_string = include_str!("mul.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_eq() {
let program_string = include_str!("eq.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_console_assert_pass() {
let program_string = include_str!("console_assert.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_ternary() {
let program_string = include_str!("ternary.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}

View File

@ -14,9 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
use crate::{load_asg, make_test_context};
use leo_ast::Ast;
use leo_grammar::Grammar;
@ -25,8 +23,7 @@ use std::path::Path;
#[test]
fn test_basic() {
let program_string = include_str!("./circuits/pedersen_mock.leo");
let ctx = new_context();
let asg = load_asg(&ctx, program_string).unwrap();
let asg = load_asg(program_string).unwrap();
let reformed_ast = leo_asg::reform_ast(&asg);
println!("{}", reformed_ast);
// panic!();
@ -51,8 +48,7 @@ fn test_function_rename() {
console.assert(total == 20);
}
"#;
let ctx = new_context();
let asg = load_asg(&ctx, program_string).unwrap();
let asg = load_asg(program_string).unwrap();
let reformed_ast = leo_asg::reform_ast(&asg);
println!("{}", reformed_ast);
// panic!();
@ -60,8 +56,8 @@ fn test_function_rename() {
#[test]
fn test_imports() {
let ctx = new_context();
let mut imports = crate::mocked_resolver(&ctx);
let context = make_test_context();
let mut imports = crate::mocked_resolver(&context);
let test_import = r#"
circuit Point {
x: u32
@ -74,7 +70,7 @@ fn test_imports() {
"#;
imports
.packages
.insert("test-import".to_string(), load_asg(&ctx, test_import).unwrap());
.insert("test-import".to_string(), load_asg(test_import).unwrap());
let program_string = r#"
import test-import.foo;
@ -95,7 +91,7 @@ fn test_imports() {
serde_json::to_string(Ast::new("test", &test_grammar).unwrap().as_repr()).unwrap()
);
let asg = crate::load_asg_imports(&ctx, program_string, &mut imports).unwrap();
let asg = crate::load_asg_imports(&context, program_string, &mut imports).unwrap();
let reformed_ast = leo_asg::reform_ast(&asg);
println!("{}", serde_json::to_string(&reformed_ast).unwrap());
// panic!();

View File

@ -14,20 +14,18 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_empty() {
let program_string = include_str!("empty.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_iteration() {
let program_string = include_str!("iteration.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
@ -47,7 +45,7 @@ fn test_const_args() {
console.assert(a == 20u32);
}
"#;
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
@ -68,7 +66,7 @@ fn test_const_args_used() {
console.assert(a == 6u8);
}
"#;
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
@ -87,61 +85,61 @@ fn test_const_args_fail() {
console.assert(a == 1u8);
}
"#;
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_iteration_repeated() {
let program_string = include_str!("iteration_repeated.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_newlines() {
let program_string = include_str!("newlines.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_multiple_returns() {
let program_string = include_str!("multiple_returns.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_multiple_returns_main() {
let program_string = include_str!("multiple_returns_main.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_repeated_function_call() {
let program_string = include_str!("repeated.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_return() {
let program_string = include_str!("return.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_undefined() {
let program_string = include_str!("undefined.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
#[test]
fn test_value_unchanged() {
let program_string = include_str!("value_unchanged.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_array_input() {
let program_string = include_str!("array_input.leo");
load_asg(&new_context(), program_string).err().unwrap();
load_asg(program_string).err().unwrap();
}
// Test return multidimensional arrays
@ -149,13 +147,13 @@ fn test_array_input() {
#[test]
fn test_return_array_nested_pass() {
let program_string = include_str!("return_array_nested_pass.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_return_array_tuple_pass() {
let program_string = include_str!("return_array_tuple_pass.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
// Test return tuples
@ -163,11 +161,11 @@ fn test_return_array_tuple_pass() {
#[test]
fn test_return_tuple() {
let program_string = include_str!("return_tuple.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_return_tuple_conditional() {
let program_string = include_str!("return_tuple_conditional.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}

View File

@ -14,14 +14,12 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_one() {
let program_string = include_str!("one.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
@ -31,79 +29,79 @@ fn test_implicit() {
let element: group = 0;
}
"#;
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_zero() {
let program_string = include_str!("zero.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_point() {
let program_string = include_str!("point.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_x_sign_high() {
let program_string = include_str!("x_sign_high.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_x_sign_low() {
let program_string = include_str!("x_sign_low.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_x_sign_inferred() {
let program_string = include_str!("x_sign_inferred.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_y_sign_high() {
let program_string = include_str!("y_sign_high.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_y_sign_low() {
let program_string = include_str!("y_sign_low.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_y_sign_inferred() {
let program_string = include_str!("y_sign_inferred.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_point_input() {
let program_string = include_str!("point_input.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_input() {
let program_string = include_str!("input.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_negate() {
let program_string = include_str!("negate.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_add() {
let program_string = include_str!("add.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
@ -113,29 +111,29 @@ fn test_add_explicit() {
let c: group = 0group + 1group;
}
"#;
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_sub() {
let program_string = include_str!("sub.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_console_assert_pass() {
let program_string = include_str!("assert_eq.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_eq() {
let program_string = include_str!("eq.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_ternary() {
let program_string = include_str!("ternary.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}

View File

@ -14,144 +14,141 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::{load_asg, load_asg_imports, mocked_resolver};
use crate::{load_asg, load_asg_imports, make_test_context, mocked_resolver};
#[test]
fn test_basic() {
let ctx = new_context();
let mut imports = mocked_resolver(&ctx);
let context = make_test_context();
let mut imports = mocked_resolver(&context);
imports.packages.insert(
"test-import".to_string(),
load_asg(&ctx, include_str!("src/test-import.leo")).unwrap(),
load_asg(include_str!("src/test-import.leo")).unwrap(),
);
let program_string = include_str!("basic.leo");
load_asg_imports(&ctx, program_string, &mut imports).unwrap();
load_asg_imports(&context, program_string, &mut imports).unwrap();
}
#[test]
fn test_multiple() {
let ctx = new_context();
let mut imports = mocked_resolver(&ctx);
let context = make_test_context();
let mut imports = mocked_resolver(&context);
imports.packages.insert(
"test-import".to_string(),
load_asg(&ctx, include_str!("src/test-import.leo")).unwrap(),
load_asg(include_str!("src/test-import.leo")).unwrap(),
);
let program_string = include_str!("multiple.leo");
load_asg_imports(&ctx, program_string, &mut imports).unwrap();
load_asg_imports(&context, program_string, &mut imports).unwrap();
}
#[test]
fn test_star() {
let ctx = new_context();
let mut imports = mocked_resolver(&ctx);
let context = make_test_context();
let mut imports = mocked_resolver(&context);
imports.packages.insert(
"test-import".to_string(),
load_asg(&ctx, include_str!("src/test-import.leo")).unwrap(),
load_asg(include_str!("src/test-import.leo")).unwrap(),
);
let program_string = include_str!("star.leo");
load_asg_imports(&ctx, program_string, &mut imports).unwrap();
load_asg_imports(&context, program_string, &mut imports).unwrap();
}
#[test]
fn test_alias() {
let ctx = new_context();
let mut imports = mocked_resolver(&ctx);
let context = make_test_context();
let mut imports = mocked_resolver(&context);
imports.packages.insert(
"test-import".to_string(),
load_asg(&ctx, include_str!("src/test-import.leo")).unwrap(),
load_asg(include_str!("src/test-import.leo")).unwrap(),
);
let program_string = include_str!("alias.leo");
load_asg_imports(&ctx, program_string, &mut imports).unwrap();
load_asg_imports(&context, program_string, &mut imports).unwrap();
}
// naming tests
#[test]
fn test_name() {
let ctx = new_context();
let mut imports = mocked_resolver(&ctx);
let context = make_test_context();
let mut imports = mocked_resolver(&context);
imports.packages.insert(
"hello-world".to_string(),
load_asg(&ctx, include_str!("src/hello-world.leo")).unwrap(),
);
imports.packages.insert(
"a0-f".to_string(),
load_asg(&ctx, include_str!("src/a0-f.leo")).unwrap(),
load_asg(include_str!("src/hello-world.leo")).unwrap(),
);
imports
.packages
.insert("a-9".to_string(), load_asg(&ctx, include_str!("src/a-9.leo")).unwrap());
.insert("a0-f".to_string(), load_asg(include_str!("src/a0-f.leo")).unwrap());
imports
.packages
.insert("a-9".to_string(), load_asg(include_str!("src/a-9.leo")).unwrap());
let program_string = include_str!("names.leo");
load_asg_imports(&ctx, program_string, &mut imports).unwrap();
load_asg_imports(&context, program_string, &mut imports).unwrap();
}
// more complex tests
#[test]
fn test_many_import() {
let ctx = new_context();
let mut imports = mocked_resolver(&ctx);
let context = make_test_context();
let mut imports = mocked_resolver(&context);
imports.packages.insert(
"test-import".to_string(),
load_asg(&ctx, include_str!("src/test-import.leo")).unwrap(),
load_asg(include_str!("src/test-import.leo")).unwrap(),
);
imports.packages.insert(
"bar".to_string(),
load_asg(&ctx, include_str!("imports/bar/src/lib.leo")).unwrap(),
load_asg(include_str!("imports/bar/src/lib.leo")).unwrap(),
);
imports.packages.insert(
"bar.baz".to_string(),
load_asg(&ctx, include_str!("imports/bar/src/baz.leo")).unwrap(),
load_asg(include_str!("imports/bar/src/baz.leo")).unwrap(),
);
imports.packages.insert(
"bar.baz".to_string(),
load_asg(&ctx, include_str!("imports/bar/src/baz.leo")).unwrap(),
load_asg(include_str!("imports/bar/src/baz.leo")).unwrap(),
);
imports.packages.insert(
"bar.bat.bat".to_string(),
load_asg(&ctx, include_str!("imports/bar/src/bat/bat.leo")).unwrap(),
load_asg(include_str!("imports/bar/src/bat/bat.leo")).unwrap(),
);
imports.packages.insert(
"car".to_string(),
load_asg(&ctx, include_str!("imports/car/src/lib.leo")).unwrap(),
load_asg(include_str!("imports/car/src/lib.leo")).unwrap(),
);
let program_string = include_str!("many_import.leo");
load_asg_imports(&ctx, program_string, &mut imports).unwrap();
load_asg_imports(&context, program_string, &mut imports).unwrap();
}
#[test]
fn test_many_import_star() {
let ctx = new_context();
let mut imports = mocked_resolver(&ctx);
let context = make_test_context();
let mut imports = mocked_resolver(&context);
imports.packages.insert(
"test-import".to_string(),
load_asg(&ctx, include_str!("src/test-import.leo")).unwrap(),
load_asg(include_str!("src/test-import.leo")).unwrap(),
);
imports.packages.insert(
"bar".to_string(),
load_asg(&ctx, include_str!("imports/bar/src/lib.leo")).unwrap(),
load_asg(include_str!("imports/bar/src/lib.leo")).unwrap(),
);
imports.packages.insert(
"bar.baz".to_string(),
load_asg(&ctx, include_str!("imports/bar/src/baz.leo")).unwrap(),
load_asg(include_str!("imports/bar/src/baz.leo")).unwrap(),
);
imports.packages.insert(
"bar.baz".to_string(),
load_asg(&ctx, include_str!("imports/bar/src/baz.leo")).unwrap(),
load_asg(include_str!("imports/bar/src/baz.leo")).unwrap(),
);
imports.packages.insert(
"bar.bat.bat".to_string(),
load_asg(&ctx, include_str!("imports/bar/src/bat/bat.leo")).unwrap(),
load_asg(include_str!("imports/bar/src/bat/bat.leo")).unwrap(),
);
imports.packages.insert(
"car".to_string(),
load_asg(&ctx, include_str!("imports/car/src/lib.leo")).unwrap(),
load_asg(include_str!("imports/car/src/lib.leo")).unwrap(),
);
let program_string = include_str!("many_import_star.leo");
load_asg_imports(&ctx, program_string, &mut imports).unwrap();
load_asg_imports(&context, program_string, &mut imports).unwrap();
}

View File

@ -14,18 +14,16 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_input_pass() {
let program_string = include_str!("main.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_input_multiple() {
let program_string = include_str!("main_multiple.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}

View File

@ -14,12 +14,10 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_access() {
let program_string = include_str!("access.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}

View File

@ -14,18 +14,16 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_access_state() {
let program_string = include_str!("access_state.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_access_all() {
let program_string = include_str!("access_all.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}

View File

@ -16,96 +16,94 @@
macro_rules! test_int {
($name: ident) => {
use leo_asg::new_context;
pub struct $name {}
impl $name {
fn test_negate() {
let program_string = include_str!("negate.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_negate_zero() {
let program_string = include_str!("negate_zero.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
}
impl super::IntegerTester for $name {
fn test_min() {
let program_string = include_str!("min.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_max() {
let program_string = include_str!("max.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_add() {
let program_string = include_str!("add.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_sub() {
let program_string = include_str!("sub.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_mul() {
let program_string = include_str!("mul.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_div() {
let program_string = include_str!("div.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_pow() {
let program_string = include_str!("pow.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_eq() {
let program_string = include_str!("eq.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_ne() {
let program_string = include_str!("ne.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_ge() {
let program_string = include_str!("ge.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_gt() {
let program_string = include_str!("gt.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_le() {
let program_string = include_str!("le.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_lt() {
let program_string = include_str!("lt.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_console_assert() {
let program_string = include_str!("console_assert.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_ternary() {
let program_string = include_str!("ternary.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
}
};

View File

@ -16,84 +16,82 @@
macro_rules! test_uint {
($name: ident) => {
use leo_asg::new_context;
pub struct $name {}
impl super::IntegerTester for $name {
fn test_min() {
let program_string = include_str!("min.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_max() {
let program_string = include_str!("max.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_add() {
let program_string = include_str!("add.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_sub() {
let program_string = include_str!("sub.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_mul() {
let program_string = include_str!("mul.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_div() {
let program_string = include_str!("div.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_pow() {
let program_string = include_str!("pow.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_eq() {
let program_string = include_str!("eq.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_ne() {
let program_string = include_str!("ne.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_ge() {
let program_string = include_str!("ge.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_gt() {
let program_string = include_str!("gt.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_le() {
let program_string = include_str!("le.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_lt() {
let program_string = include_str!("lt.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_console_assert() {
let program_string = include_str!("console_assert.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
fn test_ternary() {
let program_string = include_str!("ternary.leo");
crate::load_asg(&new_context(), program_string).unwrap();
crate::load_asg(program_string).unwrap();
}
}
};

View File

@ -14,60 +14,58 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_let_mut() {
let program_string = include_str!("let_mut.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_let_mut_nested() {
let program_string = include_str!("let_mut_nested.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_array_mut() {
let program_string = include_str!("array_mut.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_array_tuple_mut() {
let program_string = include_str!("array_tuple_mut.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_array_splice_mut() {
let program_string = include_str!("array_splice_mut.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_circuit_mut() {
let program_string = include_str!("circuit_mut.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_circuit_variable_mut() {
let program_string = include_str!("circuit_variable_mut.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_function_input_mut() {
let program_string = include_str!("function_input_mut.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_swap() {
let program_string = include_str!("swap.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}

View File

@ -14,42 +14,40 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_assert() {
let program_string = include_str!("assert.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_mutate() {
let program_string = include_str!("mutate.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_for_loop() {
let program_string = include_str!("for_loop.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_chain() {
let program_string = include_str!("chain.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_nested() {
let program_string = include_str!("nested.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_multiple_returns() {
let program_string = include_str!("multiple_returns.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}

View File

@ -14,8 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
pub mod conditional;
@ -25,7 +23,7 @@ pub mod conditional;
#[test]
fn test_ternary_basic() {
let program_string = include_str!("ternary_basic.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
// Iteration for i {start}..{stop} { statements }
@ -33,11 +31,11 @@ fn test_ternary_basic() {
#[test]
fn test_iteration_basic() {
let program_string = include_str!("iteration_basic.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_block() {
let program_string = include_str!("block.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}

View File

@ -14,72 +14,70 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_asg::new_context;
use crate::load_asg;
#[test]
fn test_tuple_basic() {
let program_string = include_str!("basic.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_tuple_access() {
let program_string = include_str!("access.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_tuple_typed() {
let program_string = include_str!("typed.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_multiple() {
let program_string = include_str!("multiple.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_multiple_typed() {
let program_string = include_str!("multiple_typed.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_function() {
let program_string = include_str!("function.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_function_typed() {
let program_string = include_str!("function_typed.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_function_multiple() {
let program_string = include_str!("function_multiple.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_nested() {
let program_string = include_str!("nested.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_nested_access() {
let program_string = include_str!("nested_access.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}
#[test]
fn test_nested_typed() {
let program_string = include_str!("nested_typed.leo");
load_asg(&new_context(), program_string).unwrap();
load_asg(program_string).unwrap();
}

View File

@ -77,7 +77,7 @@ default-features = false
version = "0.0.4"
[dependencies.bincode]
version = "1.0"
version = "1.3"
[dependencies.hex]
version = "0.4.2"
@ -108,10 +108,6 @@ version = "1.0"
[dependencies.tracing]
version = "0.1"
[dependencies.uuid]
version = "0.8"
features = [ "v4", "serde" ]
[dev-dependencies.num-bigint]
version = "0.3"

View File

@ -47,7 +47,10 @@ use std::{
pub use leo_asg::{new_context, AsgContext as Context, AsgContext};
thread_local! {
static THREAD_GLOBAL_CONTEXT: AsgContext<'static> = Box::leak(Box::new(new_context()));
static THREAD_GLOBAL_CONTEXT: AsgContext<'static> = {
let leaked = Box::leak(Box::new(leo_asg::new_alloc_context()));
leo_asg::new_context(leaked)
}
}
/// Conventience function to return a leaked thread-local global context. Should only be used for transient programs (like cli).
@ -63,7 +66,7 @@ pub struct Compiler<'a, F: PrimeField, G: GroupType<F>> {
output_directory: PathBuf,
program: Program,
program_input: Input,
ctx: AsgContext<'a>,
context: AsgContext<'a>,
asg: Option<Asg<'a>>,
_engine: PhantomData<F>,
_group: PhantomData<G>,
@ -73,7 +76,12 @@ impl<'a, F: PrimeField, G: GroupType<F>> Compiler<'a, F, G> {
///
/// Returns a new Leo program compiler.
///
pub fn new(package_name: String, main_file_path: PathBuf, output_directory: PathBuf, ctx: AsgContext<'a>) -> Self {
pub fn new(
package_name: String,
main_file_path: PathBuf,
output_directory: PathBuf,
context: AsgContext<'a>,
) -> Self {
Self {
program_name: package_name.clone(),
main_file_path,
@ -81,7 +89,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> Compiler<'a, F, G> {
program: Program::new(package_name),
program_input: Input::new(),
asg: None,
ctx,
context,
_engine: PhantomData,
_group: PhantomData,
}
@ -98,9 +106,9 @@ impl<'a, F: PrimeField, G: GroupType<F>> Compiler<'a, F, G> {
package_name: String,
main_file_path: PathBuf,
output_directory: PathBuf,
ctx: AsgContext<'a>,
context: AsgContext<'a>,
) -> Result<Self, CompilerError> {
let mut compiler = Self::new(package_name, main_file_path, output_directory, ctx);
let mut compiler = Self::new(package_name, main_file_path, output_directory, context);
compiler.parse_program()?;
@ -124,9 +132,9 @@ impl<'a, F: PrimeField, G: GroupType<F>> Compiler<'a, F, G> {
input_path: &Path,
state_string: &str,
state_path: &Path,
ctx: AsgContext<'a>,
context: AsgContext<'a>,
) -> Result<Self, CompilerError> {
let mut compiler = Self::new(package_name, main_file_path, output_directory, ctx);
let mut compiler = Self::new(package_name, main_file_path, output_directory, context);
compiler.parse_input(input_string, input_path, state_string, state_path)?;
@ -205,7 +213,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> Compiler<'a, F, G> {
tracing::debug!("Program parsing complete\n{:#?}", self.program);
// Create a new symbol table from the program, imported_programs, and program_input.
let asg = Asg::new(self.ctx, &core_ast, &mut leo_imports::ImportParser::default())?;
let asg = Asg::new(self.context, &core_ast, &mut leo_imports::ImportParser::default())?;
tracing::debug!("ASG generation complete");

View File

@ -26,10 +26,11 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
pub fn evaluate_ref(&mut self, variable_ref: &VariableRef) -> Result<ConstrainedValue<'a, F, G>, ExpressionError> {
// Evaluate the identifier name in the current function scope
let variable = variable_ref.variable.borrow();
let result_value = if let Some(value) = self.get(&variable.id) {
let result_value = if let Some(value) = self.get(variable.id) {
value.clone()
} else {
return Err(ExpressionError::undefined_identifier(variable.name.clone())); // todo: probably can be a panic here instead
return Err(ExpressionError::undefined_identifier(variable.name.clone()));
// todo: probably can be a panic here instead
};
Ok(result_value)

View File

@ -83,7 +83,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
if function.qualifier == FunctionQualifier::MutSelfRef {
if let (Some(self_var), Some(target)) = (self_var, target) {
let new_self = self
.get(&self_var.borrow().id)
.get(self_var.borrow().id)
.expect("no self variable found in mut self context")
.clone();
if let Some(assignable_target) = self.resolve_mut_ref(cs, target)? {

View File

@ -104,7 +104,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let variable = target.unwrap();
let variable = variable.borrow();
let mut result = vec![match self.get_mut(&variable.id) {
let mut result = vec![match self.get_mut(variable.id) {
Some(value) => value,
None => return Err(StatementError::undefined_variable(variable.name.to_string(), span)),
}];

View File

@ -22,11 +22,10 @@ use leo_asg::Program;
use snarkvm_models::curves::PrimeField;
use indexmap::IndexMap;
use uuid::Uuid;
pub struct ConstrainedProgram<'a, F: PrimeField, G: GroupType<F>> {
pub asg: Program<'a>,
identifiers: IndexMap<Uuid, ConstrainedValue<'a, F, G>>,
identifiers: IndexMap<u32, ConstrainedValue<'a, F, G>>,
}
impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
@ -37,15 +36,15 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
}
}
pub(crate) fn store(&mut self, name: Uuid, value: ConstrainedValue<'a, F, G>) {
self.identifiers.insert(name, value);
pub(crate) fn store(&mut self, id: u32, value: ConstrainedValue<'a, F, G>) {
self.identifiers.insert(id, value);
}
pub(crate) fn get(&self, name: &Uuid) -> Option<&ConstrainedValue<'a, F, G>> {
self.identifiers.get(name)
pub(crate) fn get(&self, id: u32) -> Option<&ConstrainedValue<'a, F, G>> {
self.identifiers.get(&id)
}
pub(crate) fn get_mut(&mut self, name: &Uuid) -> Option<&mut ConstrainedValue<'a, F, G>> {
self.identifiers.get_mut(name)
pub(crate) fn get_mut(&mut self, id: u32) -> Option<&mut ConstrainedValue<'a, F, G>> {
self.identifiers.get_mut(&id)
}
}

View File

@ -60,7 +60,7 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
let variable = assignee.target_variable.get().borrow();
let mut result = vec![match self.get_mut(&variable.id) {
let mut result = vec![match self.get_mut(variable.id) {
Some(value) => value,
None => return Err(StatementError::undefined_variable(variable.name.to_string(), span)),
}];

View File

@ -36,7 +36,7 @@ pub mod statements;
pub mod syntax;
pub mod tuples;
use leo_asg::{new_context, AsgContext};
use leo_asg::{new_alloc_context, new_context, AsgContext};
use leo_ast::{InputValue, MainInput};
use leo_compiler::{
compiler::Compiler,
@ -60,7 +60,8 @@ pub type EdwardsConstrainedValue = ConstrainedValue<'static, Fq, EdwardsGroupTyp
//convenience function for tests, leaks memory
pub(crate) fn make_test_context() -> AsgContext<'static> {
Box::leak(Box::new(new_context()))
let allocator = Box::leak(Box::new(new_alloc_context()));
new_context(allocator)
}
fn new_compiler() -> EdwardsTestCompiler {

View File

@ -34,7 +34,7 @@ pub struct ImportParser<'a> {
impl<'a> ImportResolver<'a> for ImportParser<'a> {
fn resolve_package(
&mut self,
ctx: AsgContext<'a>,
context: AsgContext<'a>,
package_segments: &[&str],
span: &Span,
) -> Result<Option<Program<'a>>, AsgConvertError> {
@ -51,7 +51,7 @@ impl<'a> ImportResolver<'a> for ImportParser<'a> {
self.partial_imports.insert(full_path.clone());
let program = imports
.parse_package(ctx, path, package_segments, span)
.parse_package(context, path, package_segments, span)
.map_err(|x| -> AsgConvertError { x.into() })?;
self.partial_imports.remove(&full_path);
self.imports.insert(full_path, program.clone());

View File

@ -26,16 +26,16 @@ static IMPORTS_DIRECTORY_NAME: &str = "imports/";
impl<'a> ImportParser<'a> {
fn parse_package_access(
&mut self,
ctx: AsgContext<'a>,
context: AsgContext<'a>,
package: &DirEntry,
remaining_segments: &[&str],
span: &Span,
) -> Result<Program<'a>, ImportParserError> {
if !remaining_segments.is_empty() {
return self.parse_package(ctx, package.path(), remaining_segments, span);
return self.parse_package(context, package.path(), remaining_segments, span);
}
let program = Self::parse_import_file(package, span)?;
let asg = leo_asg::InternalProgram::new(ctx, &program, self)?;
let asg = leo_asg::InternalProgram::new(context, &program, self)?;
Ok(asg)
}
@ -47,7 +47,7 @@ impl<'a> ImportParser<'a> {
///
pub(crate) fn parse_package(
&mut self,
ctx: AsgContext<'a>,
context: AsgContext<'a>,
mut path: PathBuf,
segments: &[&str],
span: &Span,
@ -113,8 +113,8 @@ impl<'a> ImportParser<'a> {
package_name,
span,
))),
(Some(source_entry), None) => self.parse_package_access(ctx, &source_entry, &segments[1..], span),
(None, Some(import_entry)) => self.parse_package_access(ctx, &import_entry, &segments[1..], span),
(Some(source_entry), None) => self.parse_package_access(context, &source_entry, &segments[1..], span),
(None, Some(import_entry)) => self.parse_package_access(context, &import_entry, &segments[1..], span),
(None, None) => Err(ImportParserError::unknown_package(Identifier::new_with_span(
package_name,
span,
@ -123,7 +123,7 @@ impl<'a> ImportParser<'a> {
} else {
// Enforce local package access with no found imports directory
match matched_source_entry {
Some(source_entry) => self.parse_package_access(ctx, &source_entry, &segments[1..], span),
Some(source_entry) => self.parse_package_access(context, &source_entry, &segments[1..], span),
None => Err(ImportParserError::unknown_package(Identifier::new_with_span(
package_name,
span,

View File

@ -36,16 +36,10 @@ use structopt::StructOpt;
use tracing::span::Span;
/// Compile and build program command
#[derive(StructOpt, Debug, Default)]
#[derive(StructOpt, Debug)]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
pub struct Build {}
impl Build {
pub fn new() -> Build {
Build {}
}
}
impl Command for Build {
type Input = ();
type Output = Option<(Compiler<'static, Fq, EdwardsGroupType>, bool)>;
@ -58,9 +52,9 @@ impl Command for Build {
Ok(())
}
fn apply(self, ctx: Context, _: Self::Input) -> Result<Self::Output> {
let path = ctx.dir()?;
let package_name = ctx.manifest()?.get_package_name();
fn apply(self, context: Context, _: Self::Input) -> Result<Self::Output> {
let path = context.dir()?;
let package_name = context.manifest()?.get_package_name();
// Sanitize the package path to the root directory
let mut package_path = path.clone();
@ -140,8 +134,8 @@ impl Command for Build {
let temporary_program = program.clone();
let output = temporary_program.compile_constraints(&mut cs)?;
tracing::debug!("Compiled constraints - {:#?}", output);
tracing::debug!("Number of constraints - {:#?}", cs.num_constraints());
tracing::debug!("Compiled output - {:#?}", output);
tracing::info!("Number of constraints - {:#?}", cs.num_constraints());
// Serialize the circuit
let circuit_object = SerializedCircuit::from(cs);

View File

@ -23,16 +23,10 @@ use structopt::StructOpt;
use tracing::span::Span;
/// Clean outputs folder command
#[derive(StructOpt, Debug, Default)]
#[derive(StructOpt, Debug)]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
pub struct Clean {}
impl Clean {
pub fn new() -> Clean {
Clean {}
}
}
impl Command for Clean {
type Input = ();
type Output = ();
@ -45,9 +39,9 @@ impl Command for Clean {
Ok(())
}
fn apply(self, ctx: Context, _: Self::Input) -> Result<Self::Output> {
let path = ctx.dir()?;
let package_name = ctx.manifest()?.get_package_name();
fn apply(self, context: Context, _: Self::Input) -> Result<Self::Output> {
let path = context.dir()?;
let package_name = context.manifest()?.get_package_name();
// Remove the checksum from the output directory
ChecksumFile::new(&package_name).remove(&path)?;

View File

@ -21,16 +21,10 @@ use structopt::StructOpt;
use tracing::span::Span;
/// Deploy Leo program to the network
#[derive(StructOpt, Debug, Default)]
#[derive(StructOpt, Debug)]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
pub struct Deploy {}
impl Deploy {
pub fn new() -> Deploy {
Deploy {}
}
}
impl Command for Deploy {
type Input = ();
type Output = ();

View File

@ -23,16 +23,10 @@ use structopt::StructOpt;
use tracing::span::Span;
/// Init Leo project command within current directory
#[derive(StructOpt, Debug, Default)]
#[derive(StructOpt, Debug)]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
pub struct Init {}
impl Init {
pub fn new() -> Init {
Init {}
}
}
impl Command for Init {
type Input = ();
type Output = ();
@ -46,13 +40,20 @@ impl Command for Init {
}
fn apply(self, _: Context, _: Self::Input) -> Result<Self::Output> {
// Derive the package directory path.
let path = current_dir()?;
// Check that the given package name is valid.
let package_name = path
.file_stem()
.ok_or_else(|| anyhow!("Project name invalid"))?
.to_string_lossy()
.to_string();
if !LeoPackage::is_package_name_valid(&package_name) {
return Err(anyhow!("Invalid Leo project name"));
}
// Check that the current package directory path exists.
if !path.exists() {
return Err(anyhow!("Directory does not exist"));
}

View File

@ -21,16 +21,10 @@ use structopt::StructOpt;
use tracing::span::Span;
/// Lint Leo code command
#[derive(StructOpt, Debug, Default)]
#[derive(StructOpt, Debug)]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
pub struct Lint {}
impl Lint {
pub fn new() -> Lint {
Lint {}
}
}
impl Command for Lint {
type Input = ();
type Output = ();

View File

@ -52,7 +52,7 @@ pub mod test;
pub use test::Test;
pub mod update;
pub use update::{Sub as UpdateAutomatic, Update};
pub use update::{Automatic as UpdateAutomatic, Update};
pub mod watch;
pub use watch::Watch;
@ -60,57 +60,55 @@ pub use watch::Watch;
// Aleo PM related commands
pub mod package;
/// Base trait for Leo CLI, see methods and their documentation for details
/// Base trait for the Leo CLI, see methods and their documentation for details.
pub trait Command {
/// If current command requires running another command before
/// and needs its output results, this is the place to set.
/// If the current command requires running another command beforehand
/// and needs its output result, this is where the result type is defined.
/// Example: type Input: <CommandA as Command>::Out
type Input;
/// Define output of the command to be reused as an Input for another
/// command. If this command is not used as a prelude for another, keep empty
/// Defines the output of this command, which may be used as `Input` for another
/// command. If this command is not used as a prelude for another command,
/// this field may be left empty.
type Output;
/// Returns project context, currently keeping it simple but it is possible
/// that in the future leo will not depend on current directory, and we're keeping
/// option for extending current core
/// Returns the project context, which is defined as the current directory.
fn context(&self) -> Result<Context> {
get_context()
}
/// Add span to the logger tracing::span.
/// Due to specifics of macro implementation it is impossible to set
/// span name with non-literal i.e. dynamic variable even if this
/// variable is &'static str
/// Adds a span to the logger via `tracing::span`.
/// Because of the specifics of the macro implementation, it is not possible
/// to set the span name with a non-literal i.e. a dynamic variable even if this
/// variable is a &'static str.
fn log_span(&self) -> Span {
tracing::span!(tracing::Level::INFO, "Leo")
}
/// Run prelude and get Input for current command. As simple as that.
/// But due to inability to pass default implementation of a type, this
/// method must be present in every trait implementation.
/// Runs the prelude and returns the Input of the current command.
fn prelude(&self) -> Result<Self::Input>
where
Self: std::marker::Sized;
/// Core of the execution - do what is necessary. This function is run within
/// context of 'execute' function, which sets logging and timers
fn apply(self, ctx: Context, input: Self::Input) -> Result<Self::Output>
/// Runs the main operation of this command. This function is run within
/// context of 'execute' function, which sets logging and timers.
fn apply(self, context: Context, input: Self::Input) -> Result<Self::Output>
where
Self: std::marker::Sized;
/// Wrapper around apply function, sets up tracing, time tracking and context
/// A wrapper around the `apply` method.
/// This function sets up tracing, timing, and the context.
fn execute(self) -> Result<Self::Output>
where
Self: std::marker::Sized,
{
let input = self.prelude()?;
// create span for this command
// Create the span for this command.
let span = self.log_span();
let span = span.enter();
// calculate execution time for each run
// Calculate the execution time for this command.
let timer = Instant::now();
let context = self.context()?;
@ -118,7 +116,7 @@ pub trait Command {
drop(span);
// use done context to print time
// Use the done context to print the execution time for this command.
tracing::span!(tracing::Level::INFO, "Done").in_scope(|| {
tracing::info!("Finished in {} milliseconds \n", timer.elapsed().as_millis());
});
@ -126,7 +124,7 @@ pub trait Command {
out
}
/// Execute command but empty the result. Comes in handy where there's a
/// Executes command but empty the result. Comes in handy where there's a
/// need to make match arms compatible while keeping implementation-specific
/// output possible. Errors however are all of the type Error
fn try_execute(self) -> Result<()>

View File

@ -30,12 +30,6 @@ pub struct New {
name: String,
}
impl New {
pub fn new(name: String) -> New {
New { name }
}
}
impl Command for New {
type Input = ();
type Output = ();
@ -49,13 +43,17 @@ impl Command for New {
}
fn apply(self, _: Context, _: Self::Input) -> Result<Self::Output> {
let mut path = current_dir()?;
// Check that the given package name is valid.
let package_name = self.name;
if !LeoPackage::is_package_name_valid(&package_name) {
return Err(anyhow!("Invalid Leo project name"));
}
// Derive the package directory path
// Derive the package directory path.
let mut path = current_dir()?;
path.push(&package_name);
// Verify the package directory path does not exist yet
// Verify the package directory path does not exist yet.
if path.exists() {
return Err(anyhow!("Directory already exists {:?}", path));
}

View File

@ -90,9 +90,9 @@ impl Command for Add {
Ok(())
}
fn apply(self, ctx: Context, _: Self::Input) -> Result<Self::Output> {
fn apply(self, context: Context, _: Self::Input) -> Result<Self::Output> {
// checking that manifest exists...
if ctx.manifest().is_err() {
if context.manifest().is_err() {
return Err(anyhow!("Package Manifest not found, try running leo init or leo new"));
};
@ -109,8 +109,8 @@ impl Command for Add {
version,
};
let bytes = ctx.api.run_route(fetch)?.bytes()?;
let mut path = ctx.dir()?;
let bytes = context.api.run_route(fetch)?.bytes()?;
let mut path = context.dir()?;
{
// setup directory structure since request was success

View File

@ -58,14 +58,14 @@ impl Command for Login {
Ok(())
}
fn apply(self, ctx: Context, _: Self::Input) -> Result<Self::Output> {
fn apply(self, context: Context, _: Self::Input) -> Result<Self::Output> {
// quick hack to check if user is already logged in. ;)
if ctx.api.auth_token().is_some() {
if context.api.auth_token().is_some() {
tracing::info!("You are already logged in");
return Ok(ctx.api.auth_token().unwrap());
return Ok(context.api.auth_token().unwrap());
};
let mut api = ctx.api;
let mut api = context.api;
// ...or trying to use arguments to either get token or user-pass
let token = match (self.token, self.user, self.pass) {

View File

@ -22,16 +22,10 @@ use structopt::StructOpt;
use tracing::Span;
/// Remove credentials for Aleo PM from .leo directory
#[derive(StructOpt, Debug, Default)]
#[derive(StructOpt, Debug)]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
pub struct Logout {}
impl Logout {
pub fn new() -> Logout {
Logout {}
}
}
impl Command for Logout {
type Input = ();
type Output = ();
@ -44,7 +38,7 @@ impl Command for Logout {
Ok(())
}
fn apply(self, _ctx: Context, _: Self::Input) -> Result<Self::Output> {
fn apply(self, _context: Context, _: Self::Input) -> Result<Self::Output> {
// the only error we're interested here is NotFound
// however err in this case can also be of kind PermissionDenied or other
if let Err(err) = remove_token() {

View File

@ -37,29 +37,23 @@ struct ResponseJson {
}
/// Publish package to Aleo Package Manager
#[derive(StructOpt, Debug, Default)]
#[derive(StructOpt, Debug)]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
pub struct Publish {}
impl Publish {
pub fn new() -> Publish {
Publish {}
}
}
impl Command for Publish {
type Input = <Build as Command>::Output;
type Output = Option<String>;
/// Build program before publishing
fn prelude(&self) -> Result<Self::Input> {
Build::new().execute()
(Build {}).execute()
}
fn apply(self, ctx: Context, _input: Self::Input) -> Result<Self::Output> {
fn apply(self, context: Context, _input: Self::Input) -> Result<Self::Output> {
// Get the package manifest
let path = ctx.dir()?;
let manifest = ctx.manifest()?;
let path = context.dir()?;
let manifest = context.manifest()?;
let package_name = manifest.get_package_name();
let package_version = manifest.get_package_version();
@ -99,7 +93,7 @@ impl Command for Publish {
// Client for make POST request
let client = Client::new();
let token = match ctx.api.auth_token() {
let token = match context.api.auth_token() {
Some(token) => token,
None => return Err(anyhow!("Login before publishing package: try leo login --help")),
};

View File

@ -22,19 +22,13 @@ use structopt::StructOpt;
use tracing::span::Span;
/// Remove imported package
#[derive(StructOpt, Debug, Default)]
#[derive(StructOpt, Debug)]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
pub struct Remove {
#[structopt(name = "PACKAGE")]
name: String,
}
impl Remove {
pub fn new(name: String) -> Remove {
Remove { name }
}
}
impl Command for Remove {
type Input = ();
type Output = ();
@ -47,8 +41,8 @@ impl Command for Remove {
Ok(())
}
fn apply(self, ctx: Context, _: Self::Input) -> Result<Self::Output> {
let path = ctx.dir()?;
fn apply(self, context: Context, _: Self::Input) -> Result<Self::Output> {
let path = context.dir()?;
let package_name = self.name;
LeoPackage::remove_imported_package(&package_name, &path)?;

View File

@ -28,17 +28,11 @@ use structopt::StructOpt;
use tracing::span::Span;
/// Run the program and produce a proof
#[derive(StructOpt, Debug, Default)]
#[derive(StructOpt, Debug)]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
pub struct Prove {
#[structopt(long = "skip-key-check", help = "Skip key verification on Setup stage")]
skip_key_check: bool,
}
impl Prove {
pub fn new(skip_key_check: bool) -> Prove {
Prove { skip_key_check }
}
pub(crate) skip_key_check: bool,
}
impl Command for Prove {
@ -50,15 +44,16 @@ impl Command for Prove {
}
fn prelude(&self) -> Result<Self::Input> {
Setup::new(self.skip_key_check).execute()
let skip_key_check = self.skip_key_check;
(Setup { skip_key_check }).execute()
}
fn apply(self, ctx: Context, input: Self::Input) -> Result<Self::Output> {
fn apply(self, context: Context, input: Self::Input) -> Result<Self::Output> {
let (program, parameters, prepared_verifying_key) = input;
// Get the package name
let path = ctx.dir()?;
let package_name = ctx.manifest()?.get_package_name();
let path = context.dir()?;
let package_name = context.manifest()?.get_package_name();
tracing::info!("Starting...");

View File

@ -26,17 +26,11 @@ use structopt::StructOpt;
use tracing::span::Span;
/// Build, Prove and Run Leo program with inputs
#[derive(StructOpt, Debug, Default)]
#[derive(StructOpt, Debug)]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
pub struct Run {
#[structopt(long = "skip-key-check", help = "Skip key verification on Setup stage")]
skip_key_check: bool,
}
impl Run {
pub fn new(skip_key_check: bool) -> Run {
Run { skip_key_check }
}
pub(crate) skip_key_check: bool,
}
impl Command for Run {
@ -48,10 +42,11 @@ impl Command for Run {
}
fn prelude(&self) -> Result<Self::Input> {
Prove::new(self.skip_key_check).execute()
let skip_key_check = self.skip_key_check;
(Prove { skip_key_check }).execute()
}
fn apply(self, _ctx: Context, input: Self::Input) -> Result<Self::Output> {
fn apply(self, _context: Context, input: Self::Input) -> Result<Self::Output> {
let (proof, prepared_verifying_key) = input;
tracing::info!("Starting...");

View File

@ -28,17 +28,11 @@ use structopt::StructOpt;
use tracing::span::Span;
/// Executes the setup command for a Leo program
#[derive(StructOpt, Debug, Default)]
#[derive(StructOpt, Debug)]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
pub struct Setup {
#[structopt(long = "skip-key-check", help = "Skip key verification")]
skip_key_check: bool,
}
impl Setup {
pub fn new(skip_key_check: bool) -> Setup {
Setup { skip_key_check }
}
pub(crate) skip_key_check: bool,
}
impl Command for Setup {
@ -54,38 +48,32 @@ impl Command for Setup {
}
fn prelude(&self) -> Result<Self::Input> {
Build::new().execute()
(Build {}).execute()
}
fn apply(self, ctx: Context, input: Self::Input) -> Result<Self::Output> {
let path = ctx.dir()?;
let package_name = ctx.manifest()?.get_package_name();
fn apply(self, context: Context, input: Self::Input) -> Result<Self::Output> {
let path = context.dir()?;
let package_name = context.manifest()?.get_package_name();
// If Build failed - exit.
if input.is_none() {
return Err(anyhow!("Unable to build, check that main file exists"));
}
let (program, checksum_differs) = input.unwrap();
// Check if a proving key and verification key already exists
let keys_exist = ProvingKeyFile::new(&package_name).exists_at(&path)
&& VerificationKeyFile::new(&package_name).exists_at(&path);
// If keys do not exist or the checksum differs, run the program setup
// If keys do not exist or the checksum differs, run the program setup
let (proving_key, prepared_verifying_key) = if !keys_exist || checksum_differs {
tracing::info!("Starting...");
// Run the program setup operation
let (proving_key, prepared_verifying_key) = {
let rng = &mut thread_rng();
let setup_res = Groth16::<Bls12_377, Compiler<Fr, _>, Vec<Fr>>::setup(&program, rng);
match setup_res {
Ok((proving_key, prepared_verifying_key)) => (proving_key, prepared_verifying_key),
// for some reason, using `anyhow!("{}", err)` here causes stack overflow - FIXME
Err(_err) => return Err(anyhow!("{}", "Unable to setup, see command output for more details")),
}
};
let rng = &mut thread_rng();
let (proving_key, prepared_verifying_key) =
Groth16::<Bls12_377, Compiler<Fr, _>, Vec<Fr>>::setup(&program, rng)
.map_err(|_| anyhow!("{}", "Unable to setup, see command output for more details"))?;
// TODO (howardwu): Convert parameters to a 'proving key' struct for serialization.
// Write the proving key file to the output directory

View File

@ -32,17 +32,11 @@ use structopt::StructOpt;
use tracing::span::Span;
/// Build program and run tests command
#[derive(StructOpt, Debug, Default)]
#[derive(StructOpt, Debug)]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
pub struct Test {
#[structopt(short = "f", long = "file", name = "file")]
files: Vec<PathBuf>,
}
impl Test {
pub fn new(files: Vec<PathBuf>) -> Test {
Test { files }
}
pub(crate) files: Vec<PathBuf>,
}
impl Command for Test {
@ -57,12 +51,12 @@ impl Command for Test {
Ok(())
}
fn apply(self, ctx: Context, _: Self::Input) -> Result<Self::Output> {
fn apply(self, context: Context, _: Self::Input) -> Result<Self::Output> {
// Get the package name
let package_name = ctx.manifest()?.get_package_name();
let package_name = context.manifest()?.get_package_name();
// Sanitize the package path to the root directory
let mut package_path = ctx.dir()?;
let mut package_path = context.dir()?;
if package_path.is_file() {
package_path.pop();
}

View File

@ -22,7 +22,7 @@ use tracing::span::Span;
/// Setting for automatic updates of Leo
#[derive(Debug, StructOpt, PartialEq)]
pub enum Sub {
pub enum Automatic {
Automatic {
#[structopt(name = "bool", help = "Boolean value: true or false", parse(try_from_str))]
value: bool,
@ -30,30 +30,20 @@ pub enum Sub {
}
/// Update Leo to the latest version
#[derive(StructOpt, Debug, Default)]
#[derive(StructOpt, Debug)]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
pub struct Update {
/// List all available versions of Leo
#[structopt(short, long)]
list: bool,
pub(crate) list: bool,
/// For Aleo Studio only
#[structopt(short, long)]
studio: bool,
pub(crate) studio: bool,
/// Setting for automatic updates of Leo
#[structopt(subcommand)]
automatic: Option<Sub>,
}
impl Update {
pub fn new(list: bool, studio: bool, automatic: Option<Sub>) -> Update {
Update {
list,
studio,
automatic,
}
}
pub(crate) automatic: Option<Automatic>,
}
impl Command for Update {
@ -69,13 +59,13 @@ impl Command for Update {
}
fn apply(self, _: Context, _: Self::Input) -> Result<Self::Output> {
// if --list is passed - simply list everything and exit
// If --list is passed, list all available versions and return.
if self.list {
return Updater::show_available_releases().map_err(|e| anyhow!("Could not fetch versions: {}", e));
}
// in case automatic subcommand was called
if let Some(Sub::Automatic { value }) = self.automatic {
// Handles enabling and disabling automatic updates in the config file.
if let Some(Automatic::Automatic { value }) = self.automatic {
Config::set_update_automatic(value)?;
match value {

View File

@ -27,7 +27,7 @@ use tracing::span::Span;
const LEO_SOURCE_DIR: &str = "src/";
/// Watch file changes in src/ directory and run Build Command
#[derive(StructOpt, Debug, Default)]
#[derive(StructOpt, Debug)]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
pub struct Watch {
/// Set up watch interval
@ -35,12 +35,6 @@ pub struct Watch {
interval: u64,
}
impl Watch {
pub fn new(interval: u64) -> Watch {
Watch { interval }
}
}
impl Command for Watch {
type Input = ();
type Output = ();
@ -53,7 +47,7 @@ impl Command for Watch {
Ok(())
}
fn apply(self, _ctx: Context, _: Self::Input) -> Result<Self::Output> {
fn apply(self, _context: Context, _: Self::Input) -> Result<Self::Output> {
let (tx, rx) = channel();
let mut watcher = watcher(tx, Duration::from_secs(self.interval)).unwrap();
@ -70,7 +64,7 @@ impl Command for Watch {
match rx.recv() {
// See changes on the write event
Ok(DebouncedEvent::Write(_write)) => {
match Build::new().execute() {
match (Build {}).execute() {
Ok(_output) => {
tracing::info!("Built successfully");
}

View File

@ -158,7 +158,12 @@ where
N: for<'a> FormatFields<'a> + 'static,
T: FormatTime,
{
fn format_event(&self, ctx: &FmtContext<'_, S, N>, writer: &mut dyn fmt::Write, event: &Event<'_>) -> fmt::Result {
fn format_event(
&self,
context: &FmtContext<'_, S, N>,
writer: &mut dyn fmt::Write,
event: &Event<'_>,
) -> fmt::Result {
let meta = event.metadata();
if self.display_level {
@ -174,7 +179,7 @@ where
let mut message = "".to_string();
let scope = ctx.scope();
let scope = context.scope();
for span in scope {
message += span.metadata().name();
@ -190,7 +195,7 @@ where
write!(writer, "{:>10} ", colored_string(meta.level(), &message)).expect("Error writing event");
}
ctx.format_fields(writer, event)?;
context.format_fields(writer, event)?;
writeln!(writer)
}
}

View File

@ -39,34 +39,34 @@ const PEDERSEN_HASH_PATH: &str = "./examples/pedersen-hash/";
#[test]
pub fn build_pedersen_hash() -> Result<()> {
Build::new().apply(ctx()?, ())?;
(Build {}).apply(context()?, ())?;
Ok(())
}
#[test]
pub fn setup_pedersen_hash() -> Result<()> {
let build = Build::new().apply(ctx()?, ())?;
Setup::new(false).apply(ctx()?, build.clone())?;
Setup::new(true).apply(ctx()?, build)?;
let build = (Build {}).apply(context()?, ())?;
(Setup { skip_key_check: false }).apply(context()?, build.clone())?;
(Setup { skip_key_check: true }).apply(context()?, build)?;
Ok(())
}
#[test]
pub fn prove_pedersen_hash() -> Result<()> {
let build = Build::new().apply(ctx()?, ())?;
let setup = Setup::new(false).apply(ctx()?, build)?;
Prove::new(false).apply(ctx()?, setup.clone())?;
Prove::new(true).apply(ctx()?, setup)?;
let build = (Build {}).apply(context()?, ())?;
let setup = (Setup { skip_key_check: false }).apply(context()?, build)?;
(Prove { skip_key_check: false }).apply(context()?, setup.clone())?;
(Prove { skip_key_check: true }).apply(context()?, setup)?;
Ok(())
}
#[test]
pub fn run_pedersen_hash() -> Result<()> {
let build = Build::new().apply(ctx()?, ())?;
let setup = Setup::new(false).apply(ctx()?, build)?;
let prove = Prove::new(false).apply(ctx()?, setup)?;
Run::new(false).apply(ctx()?, prove.clone())?;
Run::new(true).apply(ctx()?, prove)?;
let build = (Build {}).apply(context()?, ())?;
let setup = (Setup { skip_key_check: false }).apply(context()?, build)?;
let prove = (Prove { skip_key_check: false }).apply(context()?, setup)?;
(Run { skip_key_check: false }).apply(context()?, prove.clone())?;
(Run { skip_key_check: true }).apply(context()?, prove)?;
Ok(())
}
@ -75,14 +75,14 @@ pub fn test_pedersen_hash() -> Result<()> {
let mut main_file = PathBuf::from(PEDERSEN_HASH_PATH);
main_file.push("src/main.leo");
Test::new(Vec::new()).apply(ctx()?, ())?;
Test::new(vec![main_file]).apply(ctx()?, ())?;
(Test { files: vec![] }).apply(context()?, ())?;
(Test { files: vec![main_file] }).apply(context()?, ())?;
Ok(())
}
#[test]
pub fn test_logout() -> Result<()> {
Logout::new().apply(ctx()?, ())?;
(Logout {}).apply(context()?, ())?;
Ok(())
}
@ -91,19 +91,19 @@ pub fn test_logout() -> Result<()> {
#[test]
pub fn login_incorrect_credentials_or_token() -> Result<()> {
// no credentials passed
let login = Login::new(None, None, None).apply(ctx()?, ());
let login = Login::new(None, None, None).apply(context()?, ());
assert!(login.is_err());
// incorrect token
let login = Login::new(Some("none".to_string()), None, None).apply(ctx()?, ());
let login = Login::new(Some("none".to_string()), None, None).apply(context()?, ());
assert!(login.is_err());
// only user, no pass
let login = Login::new(None, Some("user".to_string()), None).apply(ctx()?, ());
let login = Login::new(None, Some("user".to_string()), None).apply(context()?, ());
assert!(login.is_err());
// no user, only pass
let login = Login::new(None, None, Some("pass".to_string())).apply(ctx()?, ());
let login = Login::new(None, None, Some("pass".to_string())).apply(context()?, ());
assert!(login.is_err());
Ok(())
@ -111,20 +111,48 @@ pub fn login_incorrect_credentials_or_token() -> Result<()> {
#[test]
pub fn leo_update_and_update_automatic() -> Result<()> {
Update::new(true, true, None).apply(ctx()?, ())?;
Update::new(false, true, None).apply(ctx()?, ())?;
Update::new(false, false, None).apply(ctx()?, ())?;
let update = Update {
list: true,
studio: true,
automatic: None,
};
update.apply(context()?, ())?;
Update::new(false, false, Some(UpdateAutomatic::Automatic { value: true })).apply(ctx()?, ())?;
Update::new(false, false, Some(UpdateAutomatic::Automatic { value: false })).apply(ctx()?, ())?;
let update = Update {
list: false,
studio: true,
automatic: None,
};
update.apply(context()?, ())?;
let update = Update {
list: false,
studio: false,
automatic: None,
};
update.apply(context()?, ())?;
let update = Update {
list: false,
studio: false,
automatic: Some(UpdateAutomatic::Automatic { value: true }),
};
update.apply(context()?, ())?;
let update = Update {
list: false,
studio: false,
automatic: Some(UpdateAutomatic::Automatic { value: false }),
};
update.apply(context()?, ())?;
Ok(())
}
/// Create context for Pedersen Hash example
fn ctx() -> Result<Context> {
fn context() -> Result<Context> {
let path = PathBuf::from(&PEDERSEN_HASH_PATH);
let ctx = create_context(path)?;
let context = create_context(path)?;
Ok(ctx)
Ok(context)
}

View File

@ -26,6 +26,9 @@ pub enum PackageError {
#[error("Failed to initialize package {:?} ({:?})", _0, _1)]
FailedToInitialize(String, OsString),
#[error("Invalid project name: {:?}", _0)]
InvalidPackageName(String),
#[error("`{}` metadata: {}", _0, _1)]
Removing(&'static str, io::Error),
}

View File

@ -18,6 +18,9 @@ use std::io;
#[derive(Debug, Error)]
pub enum ManifestError {
#[error("{}: {}", _0, _1)]
Crate(&'static str, String),
#[error("`{}` creating: {}", _0, _1)]
Creating(&'static str, io::Error),
@ -36,3 +39,9 @@ pub enum ManifestError {
#[error("`{}` writing: {}", _0, _1)]
Writing(&'static str, io::Error),
}
impl From<crate::errors::PackageError> for ManifestError {
fn from(error: crate::errors::PackageError) -> Self {
ManifestError::Crate("leo-package", error.to_string())
}
}

View File

@ -37,6 +37,11 @@ impl LeoPackage {
package::Package::initialize(package_name, is_lib, path)
}
/// Returns `true` if the given Leo package name is valid.
pub fn is_package_name_valid(package_name: &str) -> bool {
package::Package::is_package_name_valid(package_name)
}
/// Removes an imported Leo package
pub fn remove_imported_package(package_name: &str, path: &Path) -> Result<(), PackageError> {
package::Package::remove_imported_package(package_name, path)

View File

@ -34,17 +34,79 @@ pub struct Package {
}
impl Package {
pub fn new(package_name: &str) -> Self {
Self {
pub fn new(package_name: &str) -> Result<Self, PackageError> {
// Check that the package name is valid.
if !Self::is_package_name_valid(package_name) {
return Err(PackageError::InvalidPackageName(package_name.to_string()));
}
Ok(Self {
name: package_name.to_owned(),
version: "0.1.0".to_owned(),
description: None,
license: None,
})
}
/// Returns `true` if the package name is valid.
///
/// Package names must be lowercase and composed solely
/// of ASCII alphanumeric characters, and may be word-separated
/// by a single dash '-'.
pub fn is_package_name_valid(package_name: &str) -> bool {
// Check that the package name is nonempty.
if package_name.is_empty() {
tracing::error!("Project names must be nonempty");
return false;
}
let mut previous = package_name.chars().next().unwrap();
// Check that the first character is not a dash.
if previous == '-' {
tracing::error!("Project names cannot begin with a dash");
return false;
}
// Iterate and check that the package name is valid.
for current in package_name.chars() {
// Check that the package name is lowercase.
if !current.is_ascii_lowercase() && current != '-' {
tracing::error!("Project names must be all lowercase");
return false;
}
// Check that the package name is only ASCII alphanumeric or a dash.
if !current.is_ascii_alphanumeric() && current != '-' {
tracing::error!("Project names must be ASCII alphanumeric, and may be word-separated with a dash");
return false;
}
// If the previous character was a dash, check that the current character is not a dash.
if previous == '-' && current == '-' {
tracing::error!("Project names may only be word-separated by one dash");
return false;
}
previous = current;
}
// Check that the last character is not a dash.
if previous == '-' {
tracing::error!("Project names cannot end with a dash");
return false;
}
true
}
/// Returns `true` if a package is can be initialized at a given path.
pub fn can_initialize(package_name: &str, is_lib: bool, path: &Path) -> bool {
// Check that the package name is valid.
if !Self::is_package_name_valid(package_name) {
return false;
}
let mut result = true;
let mut existing_files = vec![];
@ -91,6 +153,11 @@ impl Package {
/// Returns `true` if a package is initialized at the given path
pub fn is_initialized(package_name: &str, is_lib: bool, path: &Path) -> bool {
// Check that the package name is valid.
if !Self::is_package_name_valid(package_name) {
return false;
}
// Check if the manifest file exists.
if !Manifest::exists_at(&path) {
return false;
@ -137,7 +204,7 @@ impl Package {
// Next, initialize this directory as a Leo package.
{
// Create the manifest file.
Manifest::new(&package_name).write_to(&path)?;
Manifest::new(&package_name)?.write_to(&path)?;
// Verify that the .gitignore file does not exist.
if !Gitignore::exists_at(&path) {
@ -190,3 +257,27 @@ impl Package {
Ok(ImportsDirectory::remove_import(path, package_name)?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_package_name_valid() {
assert!(Package::is_package_name_valid("foo"));
assert!(Package::is_package_name_valid("foo-bar"));
assert!(Package::is_package_name_valid("foo-bar-baz"));
assert!(!Package::is_package_name_valid(""));
assert!(!Package::is_package_name_valid("-"));
assert!(!Package::is_package_name_valid("-foo"));
assert!(!Package::is_package_name_valid("-foo-"));
assert!(!Package::is_package_name_valid("foo--bar"));
assert!(!Package::is_package_name_valid("foo---bar"));
assert!(!Package::is_package_name_valid("foo--bar--baz"));
assert!(!Package::is_package_name_valid("foo---bar---baz"));
assert!(!Package::is_package_name_valid("foo*bar"));
assert!(!Package::is_package_name_valid("foo,bar"));
assert!(!Package::is_package_name_valid("foo_bar"));
}
}

View File

@ -39,11 +39,11 @@ pub struct Manifest {
}
impl Manifest {
pub fn new(package_name: &str) -> Self {
Self {
project: Package::new(package_name),
pub fn new(package_name: &str) -> Result<Self, ManifestError> {
Ok(Self {
project: Package::new(package_name)?,
remote: None,
}
})
}
pub fn filename() -> String {

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