Merge pull request #2630 from AleoHQ/deprecate/input-files

[Deprecate] Input files.
This commit is contained in:
d0cd 2024-01-16 09:33:04 +08:00 committed by GitHub
commit 58c1240857
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
187 changed files with 246 additions and 2022 deletions

View File

@ -4,7 +4,7 @@ ls -la
cd foo && ls -la
# Run `leo run`.
$LEO run || exit
$LEO run main 0u32 1u32 || exit
# Assert that the 'build' folder exists.
if [ "$(ls -A build)" ]; then

View File

@ -4,11 +4,10 @@
ls -la
cd lottery && ls -la
# Run the play function.
$LEO run play || exit
# Execute the play function.
$LEO execute play || exit
# Run the script.
chmod +x ./run.sh || exit
export -f leo
./run.sh || exit
)
(
@ -17,14 +16,10 @@
ls -la
cd tictactoe && ls -la
# Create a new game.
$LEO run new || exit
# Run the make_move function.
$LEO run make_move || exit
# Execute the make_move function.
$LEO execute make_move || exit
# Run the script.
chmod +x ./run.sh || exit
export -f leo
./run.sh || exit
)
(
@ -33,9 +28,8 @@
ls -la
cd token && ls -la
# Run the mint_public function.
$LEO run mint_public || exit
# Execute the mint_public function.
$LEO execute mint_public || exit
# Run the script.
chmod +x ./run.sh || exit
export -f leo
./run.sh || exit
)

View File

@ -20,7 +20,7 @@ do
done
# Try to run `leo run`.
$LEO run || exit
$LEO run main 0u32 1u32 || exit
# Remove the dummy program.
cd .. && rm -rf dummy

View File

@ -8,9 +8,6 @@ leo() {
echo "Building and running the \`auction\` program..."
(
cd $EXAMPLES/auction || exit
$LEO run place_bid || exit
$LEO run resolve || exit
$LEO run finish || exit
chmod +x $EXAMPLES/auction/run.sh || exit
export -f leo || exit
@ -27,9 +24,6 @@ fi
echo "Building and running the \`basic_bank\` program..."
(
cd $EXAMPLES/basic_bank || exit
$LEO run issue || exit
$LEO run deposit || exit
$LEO run withdraw || exit
chmod +x $EXAMPLES/basic_bank/run.sh || exit
export -f leo || exit
@ -63,7 +57,7 @@ fi
echo "Building and running the \`bubblesort\` program..."
(
cd $EXAMPLES/bubblesort || exit
$LEO run bubble_sort || exit
$LEO run bubble_sort --file $EXAMPLES/bubblesort/inputs/bubblesort.in || exit
)
# Check that the bubblesort program ran successfully.
EXITCODE=$?
@ -76,7 +70,7 @@ fi
echo "Building and running the \`core\` program..."
(
cd $EXAMPLES/core || exit
$LEO run main || exit
$LEO run main --file $EXAMPLES/core/inputs/core.in || exit
)
# Check that the core program ran successfully.
EXITCODE=$?
@ -89,7 +83,7 @@ fi
echo "Building and running the \`groups\` program..."
(
cd $EXAMPLES/groups || exit
$LEO run main || exit
$LEO run main --file $EXAMPLES/groups/inputs/groups.in || exit
)
# Check that the groups program ran successfully.
EXITCODE=$?
@ -102,7 +96,7 @@ fi
echo "Building and running the \`hackers-delight/ntzdebruijn\` program..."
(
cd $EXAMPLES/hackers-delight/ntzdebruijn || exit
$LEO run || exit
$LEO run main --file $EXAMPLES/hackers-delight/ntzdebruijn/inputs/ntzdebruijn.in || exit
)
# Check that the hackers-delight/ntzdebruijn program ran successfully.
EXITCODE=$?
@ -115,7 +109,7 @@ fi
echo "Building and running the \`hackers-delight/ntzgaudet\` program..."
(
cd $EXAMPLES/hackers-delight/ntzgaudet || exit
$LEO run || exit
$LEO run main --file $EXAMPLES/hackers-delight/ntzgaudet/inputs/ntzgaudet.in || exit
)
# Check that the hackers-delight/ntzgaudet program ran successfully.
EXITCODE=$?
@ -128,7 +122,7 @@ fi
echo "Building and running the \`hackers-delight/ntzloops\` program..."
(
cd $EXAMPLES/hackers-delight/ntzloops || exit
$LEO run || exit
$LEO run main --file $EXAMPLES/hackers-delight/ntzloops/inputs/ntzloops.in || exit
)
# Check that the hackers-delight/ntzloops program ran successfully.
EXITCODE=$?
@ -141,7 +135,7 @@ fi
echo "Building and running the \`hackers-delight/ntzmasks\` program..."
(
cd $EXAMPLES/hackers-delight/ntzmasks || exit
$LEO run || exit
$LEO run main --file $EXAMPLES/hackers-delight/ntzmasks/inputs/ntzmasks.in || exit
)
# Check that the hackers-delight/ntzmasks program ran successfully.
EXITCODE=$?
@ -154,7 +148,7 @@ fi
echo "Building and running the \`hackers-delight/ntzreisers\` program..."
(
cd $EXAMPLES/hackers-delight/ntzreisers || exit
$LEO run || exit
$LEO run main --file $EXAMPLES/hackers-delight/ntzreisers/inputs/ntzreisers.in || exit
)
# Check that the hackers-delight/ntzreisers program ran successfully.
EXITCODE=$?
@ -167,7 +161,7 @@ fi
echo "Building and running the \`hackers-delight/ntzseals\` program..."
(
cd $EXAMPLES/hackers-delight/ntzseals || exit
$LEO run || exit
$LEO run main --file $EXAMPLES/hackers-delight/ntzseals/inputs/ntzseals.in || exit
)
# Check that the hackers-delight/ntzseals program ran successfully.
EXITCODE=$?
@ -180,7 +174,7 @@ fi
echo "Building and running the \`hackers-delight/ntzsearchtree\` program..."
(
cd $EXAMPLES/hackers-delight/ntzsearchtree || exit
$LEO run || exit
$LEO run main --file $EXAMPLES/hackers-delight/ntzsearchtree/inputs/ntzsearchtree.in || exit
)
# Check that the hackers-delight/ntzsearchtree program ran successfully.
EXITCODE=$?
@ -193,7 +187,7 @@ fi
echo "Building and running the \`hackers-delight/ntzsmallvals\` program..."
(
cd $EXAMPLES/hackers-delight/ntzsmallvals || exit
$LEO run || exit
$LEO run main --file $EXAMPLES/hackers-delight/ntzsmallvals/inputs/ntzsmallvals.in || exit
)
# Check that the hackers-delight/ntzsmallvals program ran successfully.
EXITCODE=$?
@ -206,7 +200,7 @@ fi
echo "Building and running the \`helloworld\` program..."
(
cd $EXAMPLES/helloworld || exit
$LEO run main || exit
$LEO run main --file $EXAMPLES/helloworld/inputs/helloworld.in || exit
)
# Check that the helloworld program ran successfully.
EXITCODE=$?
@ -222,10 +216,10 @@ echo "Building and running the \`interest\` programs..."
cd $EXAMPLES/interest || exit
# Run the fixed period interest program.
$LEO run fixed_iteration_interest || exit
$LEO run fixed_iteration_interest --file $EXAMPLES/interest/inputs/fixed.in || exit
# Run the bounded period interest program.
$LEO run bounded_iteration_interest || exit
$LEO run bounded_iteration_interest --file $EXAMPLES/interest/inputs/bounded.in || exit
)
# Check that the interest programs ran successfully.
EXITCODE=$?
@ -238,7 +232,7 @@ fi
echo "Building and running the \`message\` program..."
(
cd $EXAMPLES/message || exit
$LEO run main || exit
$LEO run main --file $EXAMPLES/message/inputs/message.in || exit
)
# Check that the message program ran successfully.
EXITCODE=$?
@ -252,7 +246,7 @@ echo "Building and running the \`tictactoe\` program..."
(
cd $EXAMPLES/tictactoe || exit
$LEO run new || exit
$LEO run make_move || exit
$LEO run make_move --file $EXAMPLES/tictactoe/inputs/tictactoe.in || exit
chmod +x $EXAMPLES/tictactoe/run.sh || exit
export -f leo
@ -271,10 +265,10 @@ echo "Building and running the \`simple_token\` programs..."
cd $EXAMPLES/simple_token || exit
# Run the mint program.
$LEO run mint
$LEO run mint --file $EXAMPLES/simple_token/inputs/mint.in || exit
# Run the transfer program.
$LEO run transfer
$LEO run transfer --file $EXAMPLES/simple_token/inputs/transfer.in || exit
)
# Check that the simple token programs ran successfully.
EXITCODE=$?
@ -288,23 +282,9 @@ echo "Building and running the \`token\` program..."
(
cd $EXAMPLES/token || exit
# Run the mint_public function.
$LEO run mint_public || exit
# Run the mint_private function.
$LEO run mint_private || exit
# Run the transfer_public function.
$LEO run transfer_public || exit
# Run the transfer_private function.
$LEO run transfer_private || exit
# Run the transfer_private_to_public function.
$LEO run transfer_private_to_public || exit
# Run the transfer_public_to_private function.
$LEO run transfer_public_to_private || exit
chmod +x $EXAMPLES/token/run.sh || exit
export -f leo
$EXAMPLES/token/run.sh || exit
)
# Check that the token program ran successfully.
EXITCODE=$?
@ -317,7 +297,7 @@ fi
echo "Building and running the \`twoadicity\` program..."
(
cd $EXAMPLES/twoadicity || exit
$LEO run main || exit
$LEO run main --file $EXAMPLES/twoadicity/inputs/twoadicity.in || exit
)
# Check that the two-adicity program ran successfully.
EXITCODE=$?
@ -332,7 +312,7 @@ echo "Building and running the \`vote\` program..."
cd $EXAMPLES/vote || exit
chmod +x $EXAMPLES/vote/run.sh || exit
export -f leo
export -f leo || exit
$EXAMPLES/vote/run.sh || exit
)
# Check that the vote program ran successfully.
@ -356,4 +336,4 @@ EXITCODE=$?
if [ $EXITCODE -ne 0 ]; then
echo "The \`lottery\` program failed to run successfully."
exit $EXITCODE
fi
fi

View File

@ -18,13 +18,10 @@ include = [
"leo",
"README.md",
"LICENSE.md",
"examples/lottery/inputs/lottery.in",
"examples/lottery/src/main.leo",
"examples/lottery/run.sh",
"examples/tictactoe/inputs/tictactoe.in",
"examples/tictactoe/src/main.leo",
"examples/tictactoe/run.sh",
"examples/token/inputs/token.in",
"examples/token/src/main.leo",
"examples/token/run.sh"
]

View File

@ -87,7 +87,7 @@ leo new helloworld
cd helloworld
# build & setup & prove & verify
leo run
leo run main 0u32 1u32
```
The `leo new` command creates a new Leo project with a given name.

View File

@ -1,29 +0,0 @@
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use super::*;
use crate::{Expression, Identifier, Mode, Type};
/// A single definition inside a section in a state or an input file.
/// Definitions should be structured as: `<name>: <type_> = <value>;`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Definition {
pub mode: Mode,
pub type_: Type,
pub name: Identifier,
pub value: Expression,
pub span: Span,
}

View File

@ -1,108 +0,0 @@
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{normalize_json_value, remove_key_from_json, Expression, Struct, Type};
use super::*;
use leo_errors::{AstError, Result};
/// Input data which includes [`ProgramInput`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct InputData {
pub program_input: ProgramInput,
}
impl InputData {
/// Serializes the ast into a JSON string.
pub fn to_json_string(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(&self).map_err(|e| AstError::failed_to_convert_ast_to_json_string(&e))?)
}
}
/// A raw unprocessed input or state file data. Used for future conversion
/// into [`ProgramInput`].
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct InputAst {
pub sections: Vec<Section>,
}
impl InputAst {
/// Returns all values of the input AST for execution with `leo run`.
pub fn program_inputs(&self, program_name: &str, structs: IndexMap<Symbol, Struct>) -> Vec<String> {
self.sections
.iter()
.filter(|section| section.name() == program_name)
.flat_map(|section| {
section.definitions.iter().map(|definition| match &definition.type_ {
// Handle case where the input may be record.
Type::Identifier(identifier) => {
match structs.get(&identifier.name) {
// TODO: Better error handling.
None => panic!(
"Input error: A struct or record declaration does not exist for {}.",
identifier.name
),
Some(struct_) => match struct_.is_record {
false => definition.value.to_string(),
true => match &definition.value {
// Print out the record interface with visibility.
Expression::Struct(struct_expression) => struct_expression.to_record_string(),
_ => panic!("Input error: Expected a struct expression."),
},
},
}
}
_ => definition.value.to_string(),
})
})
.collect::<Vec<_>>()
}
/// Serializes the `Input` into a JSON Value.
pub fn to_json_value(&self) -> Result<serde_json::Value> {
Ok(serde_json::to_value(self).map_err(|e| AstError::failed_to_convert_ast_to_json_value(&e))?)
}
/// Serializes the input into a JSON file.
pub fn to_json_file(&self, mut path: std::path::PathBuf, file_name: &str) -> Result<()> {
path.push(file_name);
let file = std::fs::File::create(&path).map_err(|e| AstError::failed_to_create_ast_json_file(&path, &e))?;
let writer = std::io::BufWriter::new(file);
Ok(serde_json::to_writer_pretty(writer, &self)
.map_err(|e| AstError::failed_to_write_ast_to_json_file(&path, &e))?)
}
/// Serializes the `Input` into a JSON value and removes keys from object mappings before writing to a file.
pub fn to_json_file_without_keys(
&self,
mut path: std::path::PathBuf,
file_name: &str,
excluded_keys: &[&str],
) -> Result<()> {
path.push(file_name);
let file = std::fs::File::create(&path).map_err(|e| AstError::failed_to_create_ast_json_file(&path, &e))?;
let writer = std::io::BufWriter::new(file);
let mut value = self.to_json_value().unwrap();
for key in excluded_keys {
value = remove_key_from_json(value, key);
}
value = normalize_json_value(value);
Ok(serde_json::to_writer_pretty(writer, &value)
.map_err(|e| AstError::failed_to_write_ast_to_json_file(&path, &e))?)
}
}

View File

@ -1,71 +0,0 @@
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{Expression, GroupLiteral, IntegerType, Literal, Node, Type, UnaryOperation};
use leo_errors::{InputError, LeoError, Result};
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum InputValue {
Address(String),
Boolean(bool),
Field(String),
Group(GroupLiteral),
Integer(IntegerType, String),
}
impl TryFrom<(Type, Expression)> for InputValue {
type Error = LeoError;
fn try_from(value: (Type, Expression)) -> Result<Self> {
Ok(match value {
(type_, Expression::Literal(lit)) => match (type_, lit) {
(Type::Address, Literal::Address(value, _, _)) => Self::Address(value),
(Type::Boolean, Literal::Boolean(value, _, _)) => Self::Boolean(value),
(Type::Field, Literal::Field(value, _, _)) => Self::Field(value),
(Type::Group, Literal::Group(value)) => Self::Group(*value),
(Type::Integer(expected), Literal::Integer(actual, value, span, _)) => {
if expected == actual {
Self::Integer(expected, value)
} else {
return Err(InputError::unexpected_type(expected.to_string(), actual, span).into());
}
}
(x, y) => {
return Err(InputError::unexpected_type(x, &y, y.span()).into());
}
},
(type_, Expression::Unary(unary)) if unary.op == UnaryOperation::Negate => {
InputValue::try_from((type_, *unary.receiver))?
}
(_type_, expr) => return Err(InputError::illegal_expression(&expr, expr.span()).into()),
})
}
}
impl fmt::Display for InputValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
InputValue::Address(ref address) => write!(f, "{address}"),
InputValue::Boolean(ref boolean) => write!(f, "{boolean}"),
InputValue::Group(ref group) => write!(f, "{group}"),
InputValue::Field(ref field) => write!(f, "{field}"),
InputValue::Integer(ref type_, ref number) => write!(f, "{number}{type_:?}"),
}
}
}

View File

@ -1,37 +0,0 @@
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
pub mod definition;
pub use definition::*;
pub mod input_ast;
pub use input_ast::*;
pub mod input_value;
pub use input_value::*;
pub mod program_input;
pub use program_input::*;
pub mod section;
pub use section::*;
use indexmap::IndexMap;
use leo_errors::{InputError, LeoError, Result};
use leo_span::{sym, Span, Symbol};
use serde::{Deserialize, Serialize};
type Definitions = IndexMap<Symbol, InputValue>;

View File

@ -1,44 +0,0 @@
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use super::*;
/// Processed Program input.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProgramInput {
pub main: Definitions,
}
impl TryFrom<InputAst> for ProgramInput {
type Error = LeoError;
fn try_from(input: InputAst) -> Result<Self> {
let mut main = IndexMap::new();
for section in input.sections {
let target = match section.name {
sym::main => &mut main,
_ => return Err(InputError::unexpected_section(&["main"], section.name, section.span).into()),
};
for definition in section.definitions {
target.insert(definition.name.name, InputValue::try_from((definition.type_, definition.value))?);
}
}
Ok(ProgramInput { main })
}
}

View File

@ -1,32 +0,0 @@
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use super::*;
/// A single section in an input or a state file.
/// An example of a section would be: `[main]`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Section {
pub name: Symbol,
pub definitions: Vec<Definition>,
pub span: Span,
}
impl Section {
pub fn name(&self) -> String {
self.name.to_string()
}
}

View File

@ -40,9 +40,6 @@ pub use self::functions::*;
pub mod groups;
pub use self::groups::*;
pub mod input;
pub use self::input::*;
pub mod mapping;
pub use self::mapping::*;

View File

@ -17,7 +17,7 @@
//! The compiler for Leo programs.
//!
//! The [`Compiler`] type compiles Leo programs into R1CS circuits.
pub use leo_ast::{Ast, InputAst};
pub use leo_ast::Ast;
use leo_ast::{NodeBuilder, Program, Stub};
use leo_errors::{emitter::Handler, CompilerError, Result};
pub use leo_passes::SymbolTable;
@ -45,8 +45,6 @@ pub struct Compiler<'a> {
pub network: String,
/// The AST for the program.
pub ast: Ast,
/// The input ast for the program if it exists.
pub input_ast: Option<InputAst>,
/// Options configuring compilation.
compiler_options: CompilerOptions,
/// The `NodeCounter` used to generate sequentially increasing `NodeID`s.
@ -80,7 +78,6 @@ impl<'a> Compiler<'a> {
program_name,
network,
ast: Ast::new(Program::default()),
input_ast: None,
compiler_options: compiler_options.unwrap_or_default(),
node_builder,
assigner,
@ -141,37 +138,6 @@ impl<'a> Compiler<'a> {
self.parse_program_from_string(&program_string, FileName::Real(self.main_file_path.clone()))
}
/// Parses and stores the input file, constructs a syntax tree, and generates a program input.
pub fn parse_input(&mut self, input_file_path: PathBuf) -> Result<()> {
if input_file_path.exists() {
// Load the input file into the source map.
let input_sf = with_session_globals(|s| s.source_map.load_file(&input_file_path))
.map_err(|e| CompilerError::file_read_error(&input_file_path, e))?;
// Parse and serialize it.
let input_ast =
leo_parser::parse_input(self.handler, &self.node_builder, &input_sf.src, input_sf.start_pos)?;
if self.compiler_options.output.initial_ast {
// Write the input AST snapshot post parsing.
if self.compiler_options.output.ast_spans_enabled {
input_ast.to_json_file(
self.output_directory.clone(),
&format!("{}.initial_input_ast.json", self.program_name),
)?;
} else {
input_ast.to_json_file_without_keys(
self.output_directory.clone(),
&format!("{}.initial_input_ast.json", self.program_name),
&["span"],
)?;
}
}
self.input_ast = Some(input_ast);
}
Ok(())
}
/// Runs the symbol table pass.
pub fn symbol_table_pass(&self) -> Result<SymbolTable> {
let symbol_table = SymbolTableCreator::do_pass((&self.ast, self.handler))?;
@ -326,7 +292,7 @@ impl<'a> Compiler<'a> {
}
/// Returns a compiled Leo program.
pub fn compile(&mut self) -> Result<(SymbolTable, String)> {
pub fn compile(&mut self) -> Result<String> {
// Parse the program.
self.parse_program()?;
// Copy the dependencies specified in `program.json` into the AST.
@ -335,7 +301,7 @@ impl<'a> Compiler<'a> {
let (symbol_table, struct_graph, call_graph) = self.compiler_stages()?;
// Run code generation.
let bytecode = self.code_generation_pass(&symbol_table, &struct_graph, &call_graph)?;
Ok((symbol_table, bytecode))
Ok(bytecode)
}
/// Writes the AST to a JSON file.

View File

@ -44,8 +44,6 @@ pub struct OutputOptions {
pub ast_spans_enabled: bool,
/// If enabled writes the AST after parsing.
pub initial_ast: bool,
/// If enabled writes the input AST after parsing.
pub initial_input_ast: bool,
/// If enabled writes the AST after loop unrolling.
pub unrolled_ast: bool,
/// If enabled writes the AST after static single assignment.

View File

@ -91,7 +91,6 @@ fn run_test(test: Test, handler: &Handler, buf: &BufferEmitter) -> Result<Value,
type_checked_symbol_table: true,
unrolled_symbol_table: true,
ast_spans_enabled: false,
initial_input_ast: true,
initial_ast: true,
unrolled_ast: true,
ssa_ast: true,

View File

@ -105,7 +105,6 @@ fn run_test(test: Test, handler: &Handler, err_buf: &BufferEmitter) -> Result<Va
type_checked_symbol_table: true,
unrolled_symbol_table: true,
ast_spans_enabled: false,
initial_input_ast: true,
initial_ast: true,
unrolled_ast: true,
ssa_ast: true,

View File

@ -1,70 +0,0 @@
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public 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/>.
#![forbid(unsafe_code)]
use leo_ast::NodeBuilder;
use leo_errors::{emitter::Handler, Result};
use leo_span::symbol::create_session_if_not_set_then;
use clap::Parser;
use std::{
fs,
path::{Path, PathBuf},
};
#[derive(Debug, Parser)]
#[clap(name = "input parser", about = "Parse an Input file and save its JSON representation")]
struct Opt {
/// Path to the input file.
input_path: PathBuf,
/// Optional path to the output directory.
out_dir_path: Option<PathBuf>,
/// Whether to print result to STDOUT.
#[clap(short, long)]
print_stdout: bool,
}
fn main() -> Result<(), String> {
let opt = Opt::parse();
let input_tree = create_session_if_not_set_then(|s| {
let input_string = s.source_map.load_file(&opt.input_path).expect("failed to open an input file");
Handler::with(|handler| {
let node_builder = NodeBuilder::default();
let input =
leo_parser::parse_program_inputs(handler, &node_builder, &input_string.src, input_string.start_pos)?;
input.to_json_string()
})
.map_err(|e| e.to_string())
})?;
if opt.print_stdout {
println!("{input_tree}");
}
let out_path = if let Some(out_dir) = opt.out_dir_path {
format!("{}/{}.json", out_dir.as_path().display(), opt.input_path.file_stem().unwrap().to_str().unwrap())
} else {
format!("./{}.json", opt.input_path.file_stem().unwrap().to_str().unwrap())
};
fs::write(Path::new(&out_path), input_tree).expect("failed to write output");
Ok(())
}

View File

@ -31,7 +31,7 @@ pub(crate) use tokenizer::*;
pub mod parser;
pub use parser::*;
use leo_ast::{input::InputData, Ast, NodeBuilder, ProgramInput};
use leo_ast::{Ast, NodeBuilder};
use leo_errors::{emitter::Handler, Result};
#[cfg(test)]
@ -41,16 +41,3 @@ mod test;
pub fn parse_ast(handler: &Handler, node_builder: &NodeBuilder, source: &str, start_pos: BytePos) -> Result<Ast> {
Ok(Ast::new(parser::parse(handler, node_builder, source, start_pos)?))
}
/// Parses program inputs from the input file path
pub fn parse_program_inputs(
handler: &Handler,
node_builder: &NodeBuilder,
input_string: &str,
start_pos: BytePos,
) -> Result<InputData> {
let program_input: ProgramInput =
parser::parse_input(handler, node_builder, input_string, start_pos)?.try_into()?;
Ok(InputData { program_input })
}

View File

@ -39,8 +39,6 @@ pub(crate) struct ParserContext<'a> {
pub(crate) prev_token: SpannedToken,
/// true if parsing an expression for if and loop statements -- means struct inits are not legal
pub(crate) disallow_struct_construction: bool,
/// true if parsing an identifier inside an input file.
pub(crate) allow_identifier_underscores: bool,
}
/// Dummy span used to appease borrow checker.
@ -59,7 +57,6 @@ impl<'a> ParserContext<'a> {
handler,
node_builder,
disallow_struct_construction: false,
allow_identifier_underscores: false,
prev_token: token.clone(),
token,
tokens,

View File

@ -17,7 +17,7 @@
use super::*;
use leo_errors::{ParserError, Result};
use leo_span::{sym, Symbol};
use leo_span::sym;
use snarkvm::console::{account::Address, network::Testnet3};
const INT_TYPES: &[Token] = &[
@ -623,16 +623,7 @@ impl ParserContext<'_> {
}
fn parse_struct_member(&mut self) -> Result<StructVariableInitializer> {
let identifier = if self.allow_identifier_underscores && self.eat(&Token::Underscore) {
// Allow `_nonce` for struct records.
let identifier_without_underscore = self.expect_identifier()?;
Identifier::new(
Symbol::intern(&format!("_{}", identifier_without_underscore.name)),
self.node_builder.next_id(),
)
} else {
self.expect_identifier()?
};
let identifier = self.expect_identifier()?;
let (expression, span) = if self.eat(&Token::Colon) {
// Parse individual struct variable declarations.

View File

@ -1,76 +0,0 @@
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use super::*;
use leo_errors::{ParserError, Result};
impl ParserContext<'_> {
/// Returns a [`ParsedInputFile`] struct filled with the data acquired in the file.
pub(crate) fn parse_input_file(&mut self) -> Result<InputAst> {
// Allow underscores in identifiers for input record declarations.
self.allow_identifier_underscores = true;
let mut sections = Vec::new();
while self.has_next() {
if self.check(&Token::LeftSquare) {
sections.push(self.parse_section()?);
} else {
return Err(ParserError::unexpected_token(self.token.token.clone(), self.token.span).into());
}
}
// Do not allow underscores in identifiers outside of input files.
self.allow_identifier_underscores = false;
Ok(InputAst { sections })
}
/// Parses particular section in the Input or State file.
/// `
/// [<identifier>]
/// <...definition>
/// `
/// Returns [`Section`].
fn parse_section(&mut self) -> Result<Section> {
self.expect(&Token::LeftSquare)?;
let section = self.expect_identifier()?;
self.expect(&Token::RightSquare)?;
let mut definitions = Vec::new();
while let Token::Constant | Token::Public | Token::Identifier(_) = self.token.token {
definitions.push(self.parse_input_definition()?);
}
Ok(Section { name: section.name, span: section.span, definitions })
}
/// Parses a single parameter definition:
/// `<identifier> : <type> = <expression>;`
/// Returns [`Definition`].
fn parse_input_definition(&mut self) -> Result<Definition> {
let mode = self.parse_mode()?;
let name = self.expect_identifier()?;
self.expect(&Token::Colon)?;
let (type_, span) = self.parse_type()?;
self.expect(&Token::Assign)?;
let value = self.parse_unary_expression()?;
self.expect(&Token::Semicolon)?;
Ok(Definition { mode, name, type_, value, span })
}
}

View File

@ -34,7 +34,6 @@ pub(super) use context::ParserContext;
mod expression;
mod file;
mod input;
mod statement;
pub(super) mod type_;
@ -44,15 +43,3 @@ pub fn parse(handler: &Handler, node_builder: &NodeBuilder, source: &str, start_
tokens.parse_program()
}
/// Parses an input file at the given file `path` and `source` code text.
pub fn parse_input(
handler: &Handler,
node_builder: &NodeBuilder,
source: &str,
start_pos: BytePos,
) -> Result<InputAst> {
let mut tokens = ParserContext::new(handler, node_builder, crate::tokenize(source, start_pos)?);
tokens.parse_input_file()
}

View File

@ -202,18 +202,6 @@ impl Namespace for SerializeNamespace {
}
}
struct InputNamespace;
impl Namespace for InputNamespace {
fn parse_type(&self) -> ParseType {
ParseType::Whole
}
fn run_test(&self, test: Test) -> Result<Value, String> {
create_session_if_not_set_then(|s| with_handler(tokenize(test, s)?, |p| p.parse_input_file()).map(yaml_or_fail))
}
}
struct TestRunner;
impl Runner for TestRunner {
@ -223,7 +211,6 @@ impl Runner for TestRunner {
"ParseExpression" => Box::new(ParseExpressionNamespace),
"ParseStatement" => Box::new(ParseStatementNamespace),
"Serialize" => Box::new(SerializeNamespace),
"Input" => Box::new(InputNamespace),
"Token" => Box::new(TokenNamespace),
_ => return None,
})

View File

@ -2,8 +2,6 @@
## Parser Errors: Error Code Range 370_000 - 370_999
## State Errors: Error Code Range 371_000 - 371_999
## AST Errors: Error Code Range 372_000 - 372_999
## ASG Errors: Error Code Range 373_000 - 373_999

View File

@ -49,10 +49,6 @@ The errors for the `leo-compiler` crate. Its error codes will range from 6_000-6
The errors for the `leo-imports` crate. Its error codes will range from 4_000-4_999 and be prefixed with the characters `IMP`.
### Input
The errors for the `leo-ast` crate. Its error codes will range from 8_000-8_999 and be prefixed with the characters `INP`.
### Loop Unrolling
The errors for loop unrolling in the `leo-passes` crate. Its error codes will range from 9_000-9_999 and be prefixed with the characters `LUN`.
@ -70,10 +66,6 @@ The errors for the `leo-parser` crate. Its error codes will range from 0-999 and
The errors from SnarkVM that bubble up into Leo in some situations. For right now, they have an exit code of 1.
When SnarkVM implements better error codes and messages, we can bubble them up.
### State
The errors for the `leo-state` crate. Its error codes will range from 1_000-1_999 and be prefixed with the characters `STA`.
### Utils
The errors related to dependency retrieval in the `utils` crate. Its error codes will range from 10_000-10_999 and be prefixed with the characters `DEP`.

View File

@ -1,58 +0,0 @@
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::create_messages;
use std::fmt::{Debug, Display};
create_messages!(
/// InputError enum that represents all the errors for the inputs part of `leo-ast` crate.
InputError,
code_mask: 1000i32,
code_prefix: "INP",
/// For when declared variable type mismatches actual type.
@formatted
unexpected_type {
args: (expected: impl Display, received: impl Display),
msg: format!(
"unexpected type, expected: '{expected}', received: '{received}'",
),
help: None,
}
/// For when the expression is not allowed in an input file.
@formatted
illegal_expression {
args: (expr: impl Display),
msg: format!("expression '{expr}' is not allowed in inputs"),
help: None,
}
/// For when section name is not an allowed one.
@formatted
unexpected_section {
args: (expected: &[impl Display], received: impl Display),
msg: format!(
"unexpected section: expected {} -- got '{received}'",
expected
.iter()
.map(|x| format!("'{x}'"))
.collect::<Vec<_>>()
.join(", ")
),
help: None,
}
);

View File

@ -1,19 +0,0 @@
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public 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/>.
/// This module contains the Input error definitions.
pub mod input_errors;
pub use self::input_errors::*;

View File

@ -33,10 +33,7 @@ pub use self::compiler::*;
pub mod flattener;
pub use self::flattener::*;
/// Contains the Input error definitions.
pub mod input;
pub use self::input::*;
/// Contains the Loop Unroller error definitions.
pub mod loop_unroller;
pub use self::loop_unroller::*;
@ -69,9 +66,6 @@ pub enum LeoError {
/// Represents an Compiler Error in a Leo Error.
#[error(transparent)]
CompilerError(#[from] CompilerError),
/// Represents an Input Error in a Leo Error.
#[error(transparent)]
InputError(#[from] InputError),
/// Represents an Package Error in a Leo Error.
#[error(transparent)]
PackageError(#[from] PackageError),
@ -108,7 +102,6 @@ impl LeoError {
AstError(error) => error.error_code(),
CompilerError(error) => error.error_code(),
CliError(error) => error.error_code(),
InputError(error) => error.error_code(),
ParserError(error) => error.error_code(),
PackageError(error) => error.error_code(),
TypeCheckerError(error) => error.error_code(),
@ -128,7 +121,6 @@ impl LeoError {
AstError(error) => error.exit_code(),
CompilerError(error) => error.exit_code(),
CliError(error) => error.exit_code(),
InputError(error) => error.exit_code(),
ParserError(error) => error.exit_code(),
PackageError(error) => error.exit_code(),
TypeCheckerError(error) => error.exit_code(),

View File

@ -1,19 +0,0 @@
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public 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/>.
/// This module contains the State error definitions.
pub mod state_errors;
pub use self::state_errors::*;

View File

@ -1,29 +0,0 @@
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::create_errors;
use std::{
error::Error as ErrorArg,
fmt::{Debug, Display},
};
create_errors!(
/// StateError enum that represents all the errors for the `leo-state` crate.
StateError,
exit_code_mask: 1000i32,
error_code_prefix: "STA",
);

View File

@ -1,26 +1,26 @@
# Leo Examples
This directory includes the following Leo code examples:
This directory includes the following Leo code including:
1. Hello World -> Basic Sum of two u32
2. Groups -> Basic operations over groups
3. Core -> Core functions over a field type
4. Bubblesort -> Sorting algorithms over a tuple
5. Import point -> Import code from another file
6. Message -> Initialization of a struct
7. Token -> Record example
5. Message -> Initialization of a struct
6. Token -> Record example
along with many more.
## Run Guide
To run each program, run:
```bash
leo run main
leo run main <inputs>
```
This command will look in the input file inputs/*.in where should find a section [main] and use the variables as inputs to the program.
## Execute Guide
To execute each program call, run:
```bash
leo execute main <inputs> --endpoint <endpoint>
```
leo execute main <inputs>
```

View File

@ -36,7 +36,6 @@ The auction is conducted in a series of stages.
## Running the Program
Leo provides users with a command line interface for compiling and running Leo programs.
Users may either specify input values via the command line or provide an input file in `inputs/`.
### Configuring Accounts
The `.env` file contains a private key.
@ -50,16 +49,9 @@ To generate a new account, navigate to [aleo.tools](https://aleo.tools).
### Providing inputs via the command line.
1. Run
```bash
leo run <function_name> <input_1> <input_2> ...
```
See `./run.sh` for an example.
### Using an input file.
1. Modify `inputs/auction.in` with the desired inputs.
2. Run
```bash
leo run <function_name>
```

View File

@ -1,39 +0,0 @@
// The program input for auction/src/main.leo
[place_bid]
// Note that `bidder` must have the same address as the caller (refer to `program.json`).
// Swapping the below lines, will result in an error.
// bidder: address = aleo1y7065c2jxkra5yzu9jfxq55klweqev0zas89lt9nxmfrqrafmq9qw2ktdg;
bidder: address = aleo1fxs9s0w97lmkwlcmgn0z3nuxufdee5yck9wqrs0umevp7qs0sg9q5xxxzh;
amount: u64 = 90u64;
[resolve]
first: Bid = Bid {
owner: aleo1fxs9s0w97lmkwlcmgn0z3nuxufdee5yck9wqrs0umevp7qs0sg9q5xxxzh,
bidder: aleo1fxs9s0w97lmkwlcmgn0z3nuxufdee5yck9wqrs0umevp7qs0sg9q5xxxzh,
amount: 10u64,
is_winner: false,
_nonce: 6480683131255842390406647532838179519970794442201387718334686863304493823461group,
};
second: Bid = Bid {
owner: aleo1fxs9s0w97lmkwlcmgn0z3nuxufdee5yck9wqrs0umevp7qs0sg9q5xxxzh,
bidder: aleo1fxs9s0w97lmkwlcmgn0z3nuxufdee5yck9wqrs0umevp7qs0sg9q5xxxzh,
amount: 90u64,
is_winner: false,
_nonce: 1511010328912449299156978046557700301564153667442988008615502964863620401388group,
};
[finish]
bid: Bid = Bid {
owner: aleo1fxs9s0w97lmkwlcmgn0z3nuxufdee5yck9wqrs0umevp7qs0sg9q5xxxzh,
bidder: aleo1fxs9s0w97lmkwlcmgn0z3nuxufdee5yck9wqrs0umevp7qs0sg9q5xxxzh,
amount: 90u64,
is_winner: false,
_nonce: 4195536711021629817871261453343069023119119274215827022954896024118351555272group,
};

View File

@ -37,7 +37,6 @@ Can you find any others?
## Running the Program
Leo provides users with a command line interface for compiling and running Leo programs.
Users may either specify input values via the command line or provide an input file in `inputs/`.
### Configuring Accounts
The `.env` file contains a private key.
@ -50,22 +49,7 @@ The [Aleo SDK](https://github.com/AleoHQ/leo/tree/testnet3) provides an interfac
To generate a new account, navigate to [aleo.tools](https://aleo.tools).
### Providing inputs via the command line.
1. Run
```bash
leo run <function_name> <input_1> <input_2> ...
```
See `./run.sh` for an example.
### Using an input file.
1. Modify `inputs/auction.in` with the desired inputs.
2. Run
```bash
leo run <function_name>
```
For example,
```bash
leo run issue
leo run deposit
leo run withdraw
```

View File

@ -1,21 +0,0 @@
// Inputs for the `issue` function.
[issue]
owner: address = aleo1t0uer3jgtsgmx5tq6x6f9ecu8tr57rzzfnc2dgmcqldceal0ls9qf6st7a;
amount: u64 = 1234u64;
// Inputs for the `deposit` function.
[deposit]
token: Token = Token {
owner: aleo1t0uer3jgtsgmx5tq6x6f9ecu8tr57rzzfnc2dgmcqldceal0ls9qf6st7a,
amount: 1234u64,
_nonce: 0group,
};
amount: u64 = 321u64;
// Inputs for the `withdraw` function.
[withdraw]
recipient: address = aleo1t0uer3jgtsgmx5tq6x6f9ecu8tr57rzzfnc2dgmcqldceal0ls9qf6st7a;
amount: u64 = 321u64;
rate: u64 = 1500u64;
periods: u64 = 10u64;

View File

@ -1,4 +0,0 @@
// The program input for battleship/src/main.leo
[main]
public a: u32 = 1u32;
b: u32 = 2u32;

View File

@ -4,14 +4,14 @@
To run this program, run:
```bash
leo run bubble_sort
leo run bubble_sort <inputs>
```
## Execute Guide
To execute this program, run:
```bash
leo execute bubble_sort
leo execute bubble_sort <inputs>
```
## Overview

View File

@ -1,12 +1 @@
// The program input for bubblesort_tuple/src/main.leo
[bubble_sort]
arr0: u32 = 13u32;
arr1: u32 = 2u32;
arr2: u32 = 4u32;
arr3: u32 = 3u32;
arr4: u32 = 5u32;
arr5: u32 = 10u32;
arr6: u32 = 7u32;
arr7: u32 = 1u32;
13u32 2u32 4u32 3u32 5u32 10u32 7u32 1u32

View File

@ -4,12 +4,12 @@
To run this program, run:
```bash
leo run main
leo run main <inputs>
```
## Execute Guide
To execute this program, run:
```bash
leo execute main
leo execute main <inputs>
```

View File

@ -1,4 +1,2 @@
// The program input for core/src/main.leo
[main]
public a: field = 1field;
1field

View File

@ -4,17 +4,17 @@
To run this program, run:
```bash
leo run fibonacci
leo run fibonacci <inputs>
```
## Execute Guide
To execute this program, run:
```bash
leo execute fibonacci
leo execute fibonacci <inputs>
```
## Overview
This example shows how to calculate Fibonacci number using the [fast-doubling method](https://math.stackexchange.com/questions/1124590/need-help-understanding-fibonacci-fast-doubling-proof).
It takes the input data from `inputs/fibonacci.in`
It takes the input data from `inputs/fibonacci.in`

View File

@ -1,3 +1 @@
// The program input for fibonacci/src/main.leo
[fibonacci]
public n: u8 = 63u8;
63u8

View File

@ -4,14 +4,14 @@
To run this program, run:
```bash
leo run main
leo run main <inputs>
```
## Execute Guide
To execute this program, run:
```bash
leo execute main
leo execute main <inputs>
```
## Overview

View File

@ -1,4 +1 @@
// The program input for groups/src/main.leo
// Leo will use provided string as the x coordinate and attempt to recover the y coordinate to form a group.
[main]
a: group = 1817767092074430972953743941103352519057913259183777531581123188265134806220group;
1817767092074430972953743941103352519057913259183777531581123188265134806220group

View File

@ -4,7 +4,7 @@
To compile and run this Leo program, run:
```bash
leo run
leo run <function-name> <inputs>
```
## The Algorithm

View File

@ -1,3 +1 @@
// The program input for ntzdebruijn/src/main.leo
[main]
public x: u32 = 2147483648u32;
2147483648u32

View File

@ -4,7 +4,7 @@
To compile and run this Leo program, run:
```bash
leo run
leo run <function-name> <inputs>
```
## The Algorithm

View File

@ -1,3 +1 @@
// The program input for ntzgaudet/src/main.leo
[main]
public x: u32 = 2147483648u32;
2147483648u32

View File

@ -4,7 +4,7 @@
To compile and run this Leo program, run:
```bash
leo run
leo run <function-name> <inputs>
```
## The Algorithm

View File

@ -1,3 +1 @@
// The program input for ntzloops/src/main.leo
[main]
public x: u32 = 2147483648u32;
2147483648u32

View File

@ -4,7 +4,7 @@
To compile and run this Leo program, run:
```bash
leo run
leo run <function-name> <inputs>
```
## The Algorithm

View File

@ -1,3 +1 @@
// The program input for ntzmasks/src/main.leo
[main]
public x: u32 = 1073741824u32;
1073741824u32

View File

@ -4,7 +4,7 @@
To compile and run this Leo program, run:
```bash
leo run
leo run <function-name> <inputs>
```
## The Algorithm

View File

@ -1,3 +1 @@
// The program input for ntzreisers/src/main.leo
[main]
public x: u32 = 2147483648u32;
2147483648u32

View File

@ -4,7 +4,7 @@
To compile and run this Leo program, run:
```bash
leo run
leo run <function-name> <inputs>
```
## The Algorithm

View File

@ -1,3 +1 @@
// The program input for nztseals/src/main.leo
[main]
public x: u32 = 2147483648u32;
2147483648u32

View File

@ -4,7 +4,7 @@
To compile and run this Leo program, run:
```bash
leo run
leo run <function-name> <inputs>
```
## The Algorithm

View File

@ -1,3 +1 @@
// The program input for ntzsearchtree/src/main.leo
[main]
public z: u32 = 2147483648u32;
2147483648u32

View File

@ -4,7 +4,7 @@
To compile and run this Leo program, run:
```bash
leo run
leo run <function-name> <inputs>
```
## The Algorithm

View File

@ -1,3 +1 @@
// The program input for ntzsmallvals/src/main.leo
[main]
public x: u32 = 2147483648u32;
2147483648u32

View File

@ -4,7 +4,7 @@
To run this program, run:
```bash
leo run main
leo run <function-name> <inputs>
```
## Execute Guide
@ -18,4 +18,4 @@ leo execute main
This example shows how to sum two u32 numbers.
It takes the input data from inputs/helloworld.in
It takes the input data from inputs/helloworld.in

View File

@ -1,4 +1 @@
// The program input for helloworld/src/main.leo
[main]
public a: u32 = 1u32;
b: u32 = 2u32; // Input variable `b` is private by default.
1u32 2u32

View File

@ -6,7 +6,7 @@ This program provides utilities for calculating interest over a fixed or bounded
To run this program, run:
```bash
leo run <function_name>
leo run <function-name> <inputs>
```
where `<function_name>` is one of the following:
* `fixed_iteration_interest`
@ -18,10 +18,10 @@ Be sure to update `inputs/interest.in` with the desired inputs.
To execute this program, run:
```bash
leo execute <function_name>
leo execute <function_name> <inputs>
```
where `<function_name>` is one of the following:
* `fixed_iteration_interest`
* `bounded_iteration_interest`
Be sure to update `inputs/interest.in` with the desired inputs.
Be sure to update `inputs/interest.in` with the desired inputs.

View File

@ -0,0 +1 @@
80u32 5u32 10u8

View File

@ -0,0 +1 @@
80u32 5u32

View File

@ -1,9 +0,0 @@
// The program input for interest/src/main.leo
[fixed_iteration_interest]
capital: u32 = 80u32;
rate: u32 = 5u32; // 5%
[bounded_iteration_interest]
capital: u32 = 80u32;
rate: u32 = 5u32; // 5%
iterations: u8 = 10u8;

View File

@ -4,7 +4,7 @@
To run this program, run:
```bash
leo run play
leo run play <inputs>
or
@ -15,5 +15,5 @@ or
To execute this program, run:
```bash
leo execute play
leo execute play <inputs>
```

View File

@ -1,2 +0,0 @@
// The program input for lottery/src/main.leo
[play]

View File

@ -5,12 +5,12 @@ A basic example showing how to declare a struct in the Leo language.
To run this program, run:
```bash
leo run main
leo run main <inputs>
```
## Execute Guide
To execute this program, run:
```bash
leo execute main
leo execute main <inputs>
```

View File

@ -1,7 +1,4 @@
// The program input for message/src/main.leo
// To pass "m" into the "main" function we
// 1. Define the "Message" type.
// 2. Use brackets `{ }` to enclose the struct members.
// 3. Define each struct member `name : value`.
[main]
m: Message = Message { first: 2field, second: 3field };
{
first: 2field,
second: 3field
}

View File

@ -4,14 +4,14 @@
To run this program, run:
```bash
leo run mint
leo run transfer # update private key first
leo run mint <mint-inputs>
leo run transfer <transfer-inputs> # update private key first
```
## Execute Guide
To execute this program, run:
```bash
leo execute mint
leo execute transfer # update private key first
leo execute mint <mint-inputs>
leo execute transfer <transfer-inputs> # update private key first
```

View File

@ -0,0 +1 @@
aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau 100u64

View File

@ -1,13 +0,0 @@
// The program input for simple_token/src/main.leo
[mint]
owner: address = aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau;
amount: u64 = 100u64;
[transfer]
token: Token = Token {
owner: aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau,
amount: 100u64,
_nonce: 0group,
};
to: address = aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau;
amount: u64 = 50u64;

View File

@ -0,0 +1,7 @@
{
owner: aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau.private,
amount: 100u64.private,
_nonce: 0group.public
}
aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau
50u64

View File

@ -27,23 +27,13 @@ An alternative representation would be to use an array, however, these are not y
## Running the Program
Leo provides users with a command line interface for compiling and running Leo programs.
Users may either specify input values via the command line or provide an input file in `inputs/`.
### Providing inputs via the command line.
1. Run
```bash
leo run <function_name> <input_1> <input_2> ...
```
See `./run.sh` for an example.
### Using an input file.
1. Modify `inputs/tictactoe.in` with the desired inputs.
2. Run
```bash
leo run <function_name>
```
## Executing the Program
```bash
leo execute <function_name> <input_1> <input_2> ...

View File

@ -1,18 +1,8 @@
// The `new` function does not take any inputs.
[new]
// Inputs for the `make_move` function.
// - `player` : A u8 representing the player making the move. 1 for player 1, 2 for player 2.
// - `row` : A u8 representing the row to make the move in.
// - `column` : A u8 representing the column to make the move in.
// - `board` : A representation of the board state.
[make_move]
player: u8 = 1u8;
row: u8 = 1u8;
col: u8 = 1u8;
board: Board = Board {
r1: Row { c1: 0u8, c2: 0u8, c3: 0u8 },
r2: Row { c1: 0u8, c2: 0u8, c3: 0u8 },
r3: Row { c1: 0u8, c2: 0u8, c3: 0u8 },
};
1u8
1u8
1u8
{
r1: { c1: 0u8, c2: 0u8, c3: 0u8 },
r2: { c1: 0u8, c2: 0u8, c3: 0u8 },
r3: { c1: 0u8, c2: 0u8, c3: 0u8 }
}

View File

@ -1,2 +1,4 @@
NETWORK=testnet3
PRIVATE_KEY=APrivateKey1zkpGZsYM8WQJMDDrzeAhB2SB3N9WcGt9Ks6NLBKCWyiMKv8
PRIVATE_KEY=APrivateKey1zkp1w8PTxrRgGfAtfKUSq43iQyVbdQHfhGbiNPEg2LVSEXR

View File

@ -1,34 +0,0 @@
// The program input for token/src/main.leo
[mint_public]
receiver: address = aleo1ptqvxu4gjfge8tuhgq2pqap0u5pms4p97gwhu7dwngxshpfzcszsswzpzd;
amount: u64 = 100u64;
[mint_private]
receiver: address = aleo1ptqvxu4gjfge8tuhgq2pqap0u5pms4p97gwhu7dwngxshpfzcszsswzpzd;
amount: u64 = 100u64;
[transfer_public]
receiver: address = aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau;
amount: u64 = 50u64;
[transfer_private]
sender: token = token {
owner: aleo1ptqvxu4gjfge8tuhgq2pqap0u5pms4p97gwhu7dwngxshpfzcszsswzpzd,
amount: 100u64,
_nonce: 0group,
};
receiver: address = aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau;
amount: u64 = 50u64;
[transfer_private_to_public]
sender: token = token {
owner: aleo1ptqvxu4gjfge8tuhgq2pqap0u5pms4p97gwhu7dwngxshpfzcszsswzpzd,
amount: 100u64,
_nonce: 0group,
};
receiver: address = aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau;
amount: u64 = 50u64;
[transfer_public_to_private]
receiver: address = aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau;
amount: u64 = 50u64;

View File

@ -4,12 +4,12 @@
To run this program, run:
```bash
leo run main
leo run main <inputs>
```
## Execute Guide
To execute this program, run:
```bash
leo execute main
leo execute main <inputs>
```

View File

@ -1,11 +1 @@
// The program input for twoadicity/src/main.leo
[main]
// Here is a made-up example.
// public a: field = 391995973843653359517682711560178397928211734490775552field;
// (comes from: 2field.pow(41) * 178259130663561045147472537592047227885001field)
// This example is (maxfield - 1).
// The output for this can be seen in the Pratt certificate
// for bls12-377-scalar-field-prime
// as the number of factors of 2 in (bls12-377-scalar-field-prime - 1).
public a: field = 8444461749428370424248824938781546531375899335154063827935233455917409239040field;
8444461749428370424248824938781546531375899335154063827935233455917409239040field

View File

@ -33,7 +33,7 @@ Anyone can issue a new proposal publicly by calling `propose` function.
Run `propose`:
```
leo run propose
leo run propose <inputs>
```
Output sample:
@ -62,7 +62,7 @@ and can only be used(voted) by the ticket `owner`.
Run `new_ticket`:
```
leo run new_ticket
leo run new_ticket <inputs>
```
Output sample:
@ -84,11 +84,11 @@ Since the ticket record can be used as an input privately, the voter's privacy i
Run `agree`:
```
leo run agree
leo run agree <inputs>
```
Run `disagree`:
```
leo run disagree
leo run disagree <inputs>
```

View File

@ -39,8 +39,7 @@ function propose:
assert.eq self.caller r0.proposer;
hash.bhp256 r0.title into r1 as field;
cast self.caller r1 r0 into r2 as Proposal.record;
async propose r1 into r3;
output r2 as Proposal.record;
async propose r1 into r3; output r2 as Proposal.record;
output r3 as vote.aleo/propose.future;
finalize propose:
@ -52,8 +51,7 @@ function new_ticket:
input r0 as field.public;
input r1 as address.public;
cast r1 r0 into r2 as Ticket.record;
async new_ticket r0 into r3;
output r2 as Ticket.record;
async new_ticket r0 into r3; output r2 as Ticket.record;
output r3 as vote.aleo/new_ticket.future;
finalize new_ticket:
@ -65,8 +63,7 @@ finalize new_ticket:
function agree:
input r0 as Ticket.record;
async agree r0.pid into r1;
output r1 as vote.aleo/agree.future;
async agree r0.pid into r1; output r1 as vote.aleo/agree.future;
finalize agree:
input r0 as field.public;
@ -77,8 +74,7 @@ finalize agree:
function disagree:
input r0 as Ticket.record;
async disagree r0.pid into r1;
output r1 as vote.aleo/disagree.future;
async disagree r0.pid into r1; output r1 as vote.aleo/disagree.future;
finalize disagree:
input r0 as field.public;

View File

@ -0,0 +1,5 @@
{
owner: aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau.private,
pid: 2264670486490520844857553240576860973319410481267184439818180411609250173817field.private,
_nonce: 1637267040221574073903539416642641433705357302885235345311606754421919550724group.public
}

View File

@ -0,0 +1,5 @@
{
owner: aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau.private,
pid: 2264670486490520844857553240576860973319410481267184439818180411609250173817field.private,
_nonce: 1637267040221574073903539416642641433705357302885235345311606754421919550724group.public
}

View File

@ -0,0 +1 @@
2264670486490520844857553240576860973319410481267184439818180411609250173817field aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau

View File

@ -0,0 +1,5 @@
{
title: 2077160157502449938194577302446444field,
content: 1452374294790018907888397545906607852827800436field,
proposer: aleo1kkk52quhnxgn2nfrcd9jqk7c9x27c23f2wvw7fyzcze56yahvcgszgttu2
}

View File

@ -1,25 +0,0 @@
// The program input for vote/src/main.leo
[propose]
info: ProposalInfo = ProposalInfo {
title: 2077160157502449938194577302446444field,
content: 1452374294790018907888397545906607852827800436field,
proposer: aleo1kkk52quhnxgn2nfrcd9jqk7c9x27c23f2wvw7fyzcze56yahvcgszgttu2,
};
[new_ticket]
pid: field = 2264670486490520844857553240576860973319410481267184439818180411609250173817field;
voter: address = aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau;
[agree]
ticket: Ticket = Ticket {
owner: aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau,
pid: 2264670486490520844857553240576860973319410481267184439818180411609250173817field,
_nonce: 1637267040221574073903539416642641433705357302885235345311606754421919550724group
};
[disagree]
ticket: Ticket = Ticket {
owner: aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau,
pid: 2264670486490520844857553240576860973319410481267184439818180411609250173817field,
_nonce: 1637267040221574073903539416642641433705357302885235345311606754421919550724group
};

View File

@ -20,9 +20,11 @@ echo "
###############################################################################
"
# Run the `propose` program function
(
leo run propose || exit
)
leo run propose "{
title: 2077160157502449938194577302446444field,
content: 1452374294790018907888397545906607852827800436field,
proposer: aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau
}" || exit
echo "
###############################################################################
@ -38,9 +40,7 @@ echo "
###############################################################################
"
# Run the `new_ticket` program function
(
leo run new_ticket || exit
)
leo run new_ticket 2264670486490520844857553240576860973319410481267184439818180411609250173817field aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau || exit
echo "
###############################################################################
@ -56,7 +56,9 @@ echo "
###############################################################################
"
# Run the `agree` or `disagree` program function
(
leo run agree || exit
# leo run disagree || exit
)
leo run agree "{
owner: aleo1mgfq6g40l6zkhsm063n3uhr43qk5e0zsua5aszeq5080dsvlcvxsn0rrau.private,
pid: 2264670486490520844857553240576860973319410481267184439818180411609250173817field.private,
_nonce: 1637267040221574073903539416642641433705357302885235345311606754421919550724group.public
}" || exit
#cat ./inputs/disagree.in | xargs leo run disagree || exit

View File

@ -170,6 +170,7 @@ mod tests {
command: crate::cli::commands::Run {
name: "example".to_string(),
inputs: vec!["1u32".to_string(), "2u32".to_string()],
file: None,
compiler_options: Default::default(),
},
},
@ -214,6 +215,7 @@ mod tests {
"aleo13tngrq7506zwdxj0cxjtvp28pk937jejhne0rt4zp0z370uezuysjz2prs".to_string(),
"2u32".to_string(),
],
file: None,
compiler_options: Default::default(),
},
},

View File

@ -16,10 +16,12 @@
use super::*;
use leo_ast::{NodeBuilder, Struct, Stub};
use leo_compiler::{Compiler, CompilerOptions, InputAst, OutputOptions};
use leo_package::{build::BuildDirectory, inputs::InputFile, outputs::OutputsDirectory, source::SourceDirectory};
use leo_span::{symbol::with_session_globals, Symbol};
use leo_ast::Stub;
use leo_compiler::{Compiler, CompilerOptions, OutputOptions};
use leo_errors::UtilError;
use leo_package::{build::BuildDirectory, outputs::OutputsDirectory, source::SourceDirectory};
use leo_span::Symbol;
use retriever::Retriever;
use snarkvm::{
package::Package,
@ -27,15 +29,11 @@ use snarkvm::{
};
use indexmap::IndexMap;
use leo_errors::UtilError;
use std::{
io::Write,
path::{Path, PathBuf},
};
use retriever::Retriever;
type CurrentNetwork = Testnet3;
impl From<BuildOptions> for CompilerOptions {
@ -48,7 +46,6 @@ impl From<BuildOptions> for CompilerOptions {
type_checked_symbol_table: options.enable_type_checked_symbol_table_snapshot,
unrolled_symbol_table: options.enable_unrolled_symbol_table_snapshot,
ast_spans_enabled: options.enable_ast_spans,
initial_input_ast: options.enable_initial_input_ast_snapshot,
initial_ast: options.enable_initial_ast_snapshot,
unrolled_ast: options.enable_unrolled_ast_snapshot,
ssa_ast: options.enable_ssa_ast_snapshot,
@ -59,7 +56,6 @@ impl From<BuildOptions> for CompilerOptions {
},
};
if options.enable_all_ast_snapshots {
out_options.output.initial_input_ast = true;
out_options.output.initial_ast = true;
out_options.output.unrolled_ast = true;
out_options.output.ssa_ast = true;
@ -82,7 +78,7 @@ pub struct Build {
impl Command for Build {
type Input = ();
type Output = (Option<InputAst>, IndexMap<Symbol, Struct>);
type Output = ();
fn log_span(&self) -> Span {
tracing::span!(tracing::Level::INFO, "Leo")
@ -107,12 +103,6 @@ impl Command for Build {
// Initialize error handler
let handler = Handler::default();
// Initialize a node counter.
let node_builder = NodeBuilder::default();
// Store all struct declarations made in the source files.
let mut structs = IndexMap::new();
// Retrieve all local dependencies in post order
let main_sym = Symbol::intern(&program_id.name().to_string());
let mut retriever = Retriever::new(main_sym, &package_path, &home_path)
@ -142,7 +132,7 @@ impl Command for Build {
// Compile all .leo files into .aleo files.
for file_path in local_source_files {
structs.extend(compile_leo_file(
compile_leo_file(
file_path,
&ProgramID::<Testnet3>::try_from(format!("{}.aleo", dependency))
.map_err(|_| UtilError::snarkvm_error_building_program_id(Default::default()))?,
@ -151,30 +141,13 @@ impl Command for Build {
&handler,
self.options.clone(),
stubs.clone(),
)?);
)?;
}
// Writes `leo.lock` as well as caches objects (when target is an intermediate dependency)
retriever.process_local(dependency)?;
}
// Load the input file at `package_name.in`
let input_file_path = InputFile::new(&manifest.program_id().name().to_string()).setup_file_path(&package_path);
// Parse the input file.
let input_ast = if input_file_path.exists() {
// Load the input file into the source map.
let input_sf = with_session_globals(|s| s.source_map.load_file(&input_file_path))
.map_err(|e| CompilerError::file_read_error(&input_file_path, e))?;
// TODO: This is a hack to notify the user that something is wrong with the input file. Redesign.
leo_parser::parse_input(&handler, &node_builder, &input_sf.src, input_sf.start_pos)
.map_err(|_e| println!("Warning: Failed to parse input file"))
.ok()
} else {
None
};
// `Package::open` checks that the build directory and that `main.aleo` and all imported files are well-formed.
Package::<CurrentNetwork>::open(&build_directory).map_err(CliError::failed_to_execute_build)?;
@ -196,7 +169,7 @@ impl Command for Build {
// // Log the result of the build
// tracing::info!("{}", result);
Ok((input_ast, structs))
Ok(())
}
}
@ -210,7 +183,7 @@ fn compile_leo_file(
handler: &Handler,
options: BuildOptions,
stubs: IndexMap<Symbol, Stub>,
) -> Result<IndexMap<Symbol, Struct>> {
) -> Result<()> {
// Construct the Leo file name with extension `foo.leo`.
let file_name =
file_path.file_name().and_then(|name| name.to_str()).ok_or_else(PackageError::failed_to_get_file_name)?;
@ -234,7 +207,7 @@ fn compile_leo_file(
);
// Compile the Leo program into Aleo instructions.
let (symbol_table, instructions) = compiler.compile()?;
let instructions = compiler.compile()?;
// Write the instructions.
std::fs::File::create(&aleo_file_path)
@ -243,5 +216,5 @@ fn compile_leo_file(
.map_err(CliError::failed_to_load_instructions)?;
tracing::info!("✅ Compiled '{}' into Aleo instructions", file_name);
Ok(symbol_table.structs)
Ok(())
}

View File

@ -48,10 +48,6 @@ impl Command for Example {
let main_file_path = package_dir.join("src").join("main.leo");
fs::write(main_file_path, self.main_file_string()).map_err(CliError::failed_to_write_file)?;
// Write the input file.
let input_file_path = package_dir.join("inputs").join(format!("{}.in", self.name()));
fs::write(input_file_path, self.input_file_string()).map_err(CliError::failed_to_write_file)?;
// Write the README file.
let readme_file_path = package_dir.join("README.md");
let readme_file_path_string = readme_file_path.display().to_string();
@ -94,20 +90,6 @@ impl Example {
}
}
fn input_file_string(&self) -> String {
match self {
Self::Lottery => {
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/examples/lottery/inputs/lottery.in")).to_string()
}
Self::TicTacToe => {
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/examples/tictactoe/inputs/tictactoe.in")).to_string()
}
Self::Token => {
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/examples/token/inputs/token.in")).to_string()
}
}
}
fn readme_file_string(&self) -> String {
match self {
Self::Lottery => {

View File

@ -16,7 +16,7 @@
use super::*;
use snarkvm::cli::Execute as SnarkVMExecute;
use snarkvm::{cli::Execute as SnarkVMExecute, prelude::Parser as SnarkVMParser};
/// Build, Prove and Run Leo program with inputs
#[derive(Parser, Debug)]
@ -24,7 +24,7 @@ pub struct Execute {
#[clap(name = "NAME", help = "The name of the program to execute.", default_value = "main")]
name: String,
#[clap(name = "INPUTS", help = "The inputs to the program. If none are provided, the input file is used.")]
#[clap(name = "INPUTS", help = "The inputs to the program.")]
inputs: Vec<String>,
#[clap(
@ -35,6 +35,9 @@ pub struct Execute {
)]
endpoint: String,
#[arg(short, long, help = "The inputs to the program, from a file. Overrides the INPUTS argument.")]
file: Option<String>,
#[clap(flatten)]
pub(crate) compiler_options: BuildOptions,
}
@ -51,22 +54,37 @@ impl Command for Execute {
(Build { options: self.compiler_options.clone() }).execute(context)
}
fn apply(self, context: Context, input: Self::Input) -> Result<Self::Output> {
// If input values are provided, then run the program with those inputs.
// Otherwise, use the input file.
let mut inputs = match self.inputs.is_empty() {
true => match input {
(Some(input_ast), circuits) => input_ast.program_inputs(&self.name, circuits),
_ => Vec::new(),
},
false => self.inputs,
};
fn apply(self, context: Context, _: Self::Input) -> Result<Self::Output> {
let mut inputs = self.inputs;
// Compose the `execute` command.
let mut arguments = vec![SNARKVM_COMMAND.to_string(), self.name];
// Add the program inputs to the arguments.
arguments.append(&mut inputs);
// Add the inputs to the arguments.
match self.file {
Some(file) => {
// Get the contents from the file.
let path = context.dir()?.join(file);
let raw_content = std::fs::read_to_string(&path)
.map_err(|err| PackageError::failed_to_read_file(path.display(), err))?;
// Parse the values from the file.
let mut content = raw_content.as_str();
let mut values = vec![];
while let Ok((remaining, value)) = snarkvm::prelude::Value::<CurrentNetwork>::parse(content) {
content = remaining;
values.push(value);
}
// Check that the remaining content is empty.
if !content.trim().is_empty() {
return Err(PackageError::failed_to_read_input_file(path.display()).into());
}
// Convert the values to strings.
let mut inputs_from_file = values.into_iter().map(|value| value.to_string()).collect::<Vec<String>>();
// Add the inputs from the file to the arguments.
arguments.append(&mut inputs_from_file);
}
None => arguments.append(&mut inputs),
}
// Add the compiler options to the arguments.
if self.compiler_options.offline {

View File

@ -49,7 +49,7 @@ pub use update::Update;
use super::*;
use crate::cli::helpers::context::*;
use leo_errors::{emitter::Handler, CliError, CompilerError, PackageError, Result};
use leo_errors::{emitter::Handler, CliError, PackageError, Result};
use leo_package::{build::*, outputs::OutputsDirectory, package::*};
use clap::Parser;
@ -138,8 +138,6 @@ pub struct BuildOptions {
pub enable_dce: bool,
#[clap(long, help = "Writes all AST snapshots for the different compiler phases.")]
pub enable_all_ast_snapshots: bool,
#[clap(long, help = "Writes Input AST snapshot of the initial parse.")]
pub enable_initial_input_ast_snapshot: bool,
#[clap(long, help = "Writes AST snapshot of the initial parse.")]
pub enable_initial_ast_snapshot: bool,
#[clap(long, help = "Writes AST snapshot of the unrolled AST.")]

View File

@ -16,7 +16,7 @@
use super::*;
use snarkvm::cli::Run as SnarkVMRun;
use snarkvm::{cli::Run as SnarkVMRun, prelude::Parser as SnarkVMParser};
/// Build, Prove and Run Leo program with inputs
#[derive(Parser, Debug)]
@ -24,9 +24,12 @@ pub struct Run {
#[clap(name = "NAME", help = "The name of the program to run.", default_value = "main")]
pub(crate) name: String,
#[clap(name = "INPUTS", help = "The inputs to the program. If none are provided, the input file is used.")]
#[clap(name = "INPUTS", help = "The inputs to the program.")]
pub(crate) inputs: Vec<String>,
#[arg(short, long, help = "The inputs to the program, from a file. Overrides the INPUTS argument.")]
pub(crate) file: Option<String>,
#[clap(flatten)]
pub(crate) compiler_options: BuildOptions,
}
@ -43,22 +46,37 @@ impl Command for Run {
(Build { options: self.compiler_options.clone() }).execute(context)
}
fn apply(self, context: Context, input: Self::Input) -> Result<Self::Output> {
// If input values are provided, then run the program with those inputs.
// Otherwise, use the input file.
let mut inputs = match self.inputs.is_empty() {
true => match input {
(Some(input_ast), circuits) => input_ast.program_inputs(&self.name, circuits),
_ => Vec::new(),
},
false => self.inputs,
};
fn apply(self, context: Context, _: Self::Input) -> Result<Self::Output> {
let mut inputs = self.inputs;
// Compose the `run` command.
let mut arguments = vec![SNARKVM_COMMAND.to_string(), self.name];
// Add the program inputs to the arguments.
arguments.append(&mut inputs);
// Add the inputs to the arguments.
match self.file {
Some(file) => {
// Get the contents from the file.
let path = context.dir()?.join(file);
let raw_content = std::fs::read_to_string(&path)
.map_err(|err| PackageError::failed_to_read_file(path.display(), err))?;
// Parse the values from the file.
let mut content = raw_content.as_str();
let mut values = vec![];
while let Ok((remaining, value)) = snarkvm::prelude::Value::<CurrentNetwork>::parse(content) {
content = remaining;
values.push(value);
}
// Check that the remaining content is empty.
if !content.trim().is_empty() {
return Err(PackageError::failed_to_read_input_file(path.display()).into());
}
// Convert the values to strings.
let mut inputs_from_file = values.into_iter().map(|value| value.to_string()).collect::<Vec<String>>();
// Add the inputs from the file to the arguments.
arguments.append(&mut inputs_from_file);
}
None => arguments.append(&mut inputs),
}
// Open the Leo build/ directory
let path = context.dir()?;

View File

@ -1,94 +0,0 @@
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public 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/>.
//! The `program.in` file.
use crate::inputs::INPUTS_DIRECTORY_NAME;
use leo_errors::{PackageError, Result};
use serde::Deserialize;
use std::{
borrow::Cow,
fs::{
File,
{self},
},
io::Write,
path::Path,
};
pub static INPUT_FILE_EXTENSION: &str = ".in";
#[derive(Deserialize)]
pub struct InputFile {
pub package_name: String,
}
impl InputFile {
pub fn new(package_name: &str) -> Self {
Self { package_name: package_name.to_string() }
}
pub fn filename(&self) -> String {
format!("{INPUTS_DIRECTORY_NAME}{}{INPUT_FILE_EXTENSION}", self.package_name)
}
pub fn exists_at(&self, path: &Path) -> bool {
let path = self.setup_file_path(path);
path.exists()
}
/// Reads the program input variables from the given file path if it exists.
pub fn read_from<'a>(&self, path: &'a Path) -> Result<(String, Cow<'a, Path>)> {
let path = self.setup_file_path(path);
let input = fs::read_to_string(&path)
.map_err(|_| PackageError::failed_to_read_input_file(path.clone().into_owned()))?;
Ok((input, path))
}
/// Writes the standard input format to a file.
pub fn write_to(self, path: &Path) -> Result<()> {
let path = self.setup_file_path(path);
let mut file = File::create(path).map_err(PackageError::io_error_input_file)?;
file.write_all(self.template().as_bytes()).map_err(PackageError::io_error_input_file)?;
Ok(())
}
fn template(&self) -> String {
format!(
r#"// The program input for {}/src/main.leo
[main]
public a: u32 = 1u32;
b: u32 = 2u32;
"#,
self.package_name
)
}
pub fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
let mut path = Cow::from(path);
if path.is_dir() {
if !path.ends_with(INPUTS_DIRECTORY_NAME) {
path.to_mut().push(INPUTS_DIRECTORY_NAME);
}
path.to_mut().push(format!("{}{INPUT_FILE_EXTENSION}", self.package_name));
}
path
}
}

View File

@ -16,6 +16,3 @@
pub mod directory;
pub use directory::*;
pub mod input;
pub use input::*;

View File

@ -16,7 +16,7 @@
use crate::{
build::BuildDirectory,
inputs::{InputFile, InputsDirectory},
inputs::InputsDirectory,
root::{Env, Gitignore},
source::{MainFile, SourceDirectory},
};
@ -97,13 +97,6 @@ impl<N: Network> Package<N> {
let mut result = true;
let mut existing_files = vec![];
// Check if the input file already exists.
let input_file = InputFile::new(package_name);
if input_file.exists_at(path) {
existing_files.push(input_file.filename());
result = false;
}
// Check if the main file already exists.
if MainFile::exists_at(path) {
existing_files.push(MainFile::filename());
@ -124,12 +117,6 @@ impl<N: Network> Package<N> {
return false;
}
// Check if the input file exists.
let input_file = InputFile::new(package_name);
if !input_file.exists_at(path) {
return false;
}
// Check if the main file exists.
if !MainFile::exists_at(path) {
return false;
@ -161,9 +148,6 @@ impl<N: Network> Package<N> {
// Create the Leo build/ directory
BuildDirectory::create(path)?;
// Create the input file in the inputs directory.
InputFile::new(package_name).write_to(path)?;
// Create the main file in the source directory.
MainFile::new(package_name).write_to(path)?;

View File

@ -61,45 +61,9 @@ Parser Directory namespaces:
- `ParseExpression` - Test a file line by line to check that each line is a valid Leo expression.
- `ParseStatement` - Test a file consuming multiple lines till a blank line to check that it contains a valid Leo statement.
- `Serialize` - Test a file to check that it can be serialized to JSON.
- `Input` - Test an input file to check that it is a valid Leo input file.
- `Token` - Test a file line by line to check that it contains zero or more valid Leo parser tokens.
Compiler Directory namespaces:
- `Compiler` - Test a file to check that it is a valid Leo program, and it can be compiled without errors.
### expectation
```yaml
- Mandatory: yes
- Namespace: all
- Values: Pass / Fail
```
This setting indicates whether the tested code is supposed to succeed or to fail.
If the test was marked as `Pass` but it actually failed,
you'll know that something went wrong and the test or the compiler/parser needs fixing.
### input_file (Compile)
```yaml
- Mandatory: no
- Namespace: Compile
- Values: <input file path>, ...
```
This setting allows using one or more input files for the Leo program.
The program will be run with every provided input.
See this example:
```yaml
/*
namespace: Compile
expectation: Pass
input_file:
- inputs/a_0.in
- inputs/a_1.in
*/
function main(a: u32) {}
```
- `Execute` - Test a file to check that it is a valid Leo program, and it can be compiled and executed without errors.

View File

@ -97,7 +97,6 @@ fn new_compiler(handler: &Handler) -> Compiler<'_> {
unrolled_symbol_table: false,
ast_spans_enabled: false,
initial_ast: false,
initial_input_ast: false,
unrolled_ast: false,
ssa_ast: false,
flattened_ast: false,

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