mirror of
https://github.com/ProvableHQ/leo.git
synced 2024-11-30 23:33:27 +03:00
Merge pull request #597 from AleoHQ/asg-compiler
[Feature] Abstract Semantic Graph (ASG) - Compiler Integration
This commit is contained in:
commit
2657c448a0
49
Cargo.lock
generated
49
Cargo.lock
generated
@ -1266,16 +1266,14 @@ dependencies = [
|
||||
"bincode",
|
||||
"hex",
|
||||
"indexmap",
|
||||
"leo-asg",
|
||||
"leo-ast",
|
||||
"leo-core",
|
||||
"leo-gadgets",
|
||||
"leo-grammar",
|
||||
"leo-imports",
|
||||
"leo-input",
|
||||
"leo-package",
|
||||
"leo-state",
|
||||
"leo-symbol-table",
|
||||
"leo-type-inference",
|
||||
"num-bigint",
|
||||
"pest",
|
||||
"rand",
|
||||
@ -1292,22 +1290,7 @@ dependencies = [
|
||||
"snarkvm-utilities",
|
||||
"thiserror",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "leo-core"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"leo-ast",
|
||||
"leo-gadgets",
|
||||
"rand",
|
||||
"rand_xorshift",
|
||||
"snarkvm-curves",
|
||||
"snarkvm-errors",
|
||||
"snarkvm-gadgets",
|
||||
"snarkvm-models",
|
||||
"snarkvm-utilities",
|
||||
"thiserror",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -1344,6 +1327,7 @@ name = "leo-imports"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"leo-asg",
|
||||
"leo-ast",
|
||||
"leo-grammar",
|
||||
"thiserror",
|
||||
@ -1438,33 +1422,6 @@ dependencies = [
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "leo-symbol-table"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"leo-ast",
|
||||
"leo-core",
|
||||
"leo-grammar",
|
||||
"leo-imports",
|
||||
"serde",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "leo-type-inference"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"leo-ast",
|
||||
"leo-grammar",
|
||||
"leo-imports",
|
||||
"leo-symbol-table",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.81"
|
||||
|
@ -28,7 +28,6 @@ path = "leo/main.rs"
|
||||
members = [
|
||||
"ast",
|
||||
"compiler",
|
||||
"core",
|
||||
"gadgets",
|
||||
"grammar",
|
||||
"imports",
|
||||
@ -37,8 +36,6 @@ members = [
|
||||
"package",
|
||||
"state",
|
||||
"asg",
|
||||
"symbol-table",
|
||||
"type-inference"
|
||||
]
|
||||
|
||||
[dependencies.leo-ast]
|
||||
|
@ -88,10 +88,6 @@ impl Identifier {
|
||||
pub fn is_self(&self) -> bool {
|
||||
self.is_self_type() || self.name == "self"
|
||||
}
|
||||
|
||||
pub fn is_core(&self) -> bool {
|
||||
self.name.starts_with('#')
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ast> From<GrammarIdentifier<'ast>> for Identifier {
|
||||
|
@ -21,10 +21,6 @@ edition = "2018"
|
||||
path = "../ast"
|
||||
version = "1.0.8"
|
||||
|
||||
[dependencies.leo-core]
|
||||
path = "../core"
|
||||
version = "1.0.8"
|
||||
|
||||
[dependencies.leo-gadgets]
|
||||
path = "../gadgets"
|
||||
version = "1.0.8"
|
||||
@ -49,12 +45,8 @@ version = "1.0.8"
|
||||
path = "../state"
|
||||
version = "1.0.8"
|
||||
|
||||
[dependencies.leo-symbol-table]
|
||||
path = "../symbol-table"
|
||||
version = "1.0.8"
|
||||
|
||||
[dependencies.leo-type-inference]
|
||||
path = "../type-inference"
|
||||
[dependencies.leo-asg]
|
||||
path = "../asg"
|
||||
version = "1.0.8"
|
||||
|
||||
[dependencies.snarkvm-curves]
|
||||
@ -116,6 +108,10 @@ version = "1.0"
|
||||
[dependencies.tracing]
|
||||
version = "0.1"
|
||||
|
||||
[dependencies.uuid]
|
||||
version = "0.8"
|
||||
features = ["v4", "serde"]
|
||||
|
||||
[dev-dependencies.num-bigint]
|
||||
version = "0.3"
|
||||
|
||||
|
@ -25,13 +25,11 @@ use crate::{
|
||||
};
|
||||
use leo_ast::{Ast, Input, MainInput, Program};
|
||||
use leo_grammar::Grammar;
|
||||
use leo_imports::ImportParser;
|
||||
use leo_input::LeoInputParser;
|
||||
use leo_package::inputs::InputPairs;
|
||||
use leo_state::verify_local_data_commitment;
|
||||
use leo_symbol_table::SymbolTable;
|
||||
use leo_type_inference::TypeInference;
|
||||
|
||||
use leo_asg::Program as AsgProgram;
|
||||
use snarkvm_dpc::{base_dpc::instantiated::Components, SystemParameters};
|
||||
use snarkvm_errors::gadgets::SynthesisError;
|
||||
use snarkvm_models::{
|
||||
@ -54,7 +52,7 @@ pub struct Compiler<F: Field + PrimeField, G: GroupType<F>> {
|
||||
output_directory: PathBuf,
|
||||
program: Program,
|
||||
program_input: Input,
|
||||
imported_programs: ImportParser,
|
||||
asg: Option<AsgProgram>,
|
||||
_engine: PhantomData<F>,
|
||||
_group: PhantomData<G>,
|
||||
}
|
||||
@ -70,7 +68,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> Compiler<F, G> {
|
||||
output_directory,
|
||||
program: Program::new(package_name),
|
||||
program_input: Input::new(),
|
||||
imported_programs: ImportParser::default(),
|
||||
asg: None,
|
||||
_engine: PhantomData,
|
||||
_group: PhantomData,
|
||||
}
|
||||
@ -162,9 +160,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> Compiler<F, G> {
|
||||
/// Runs program parser and type inference checker consecutively.
|
||||
///
|
||||
pub(crate) fn parse_and_check_program(&mut self) -> Result<(), CompilerError> {
|
||||
self.parse_program()?;
|
||||
|
||||
self.check_program()
|
||||
self.parse_program()
|
||||
}
|
||||
|
||||
///
|
||||
@ -189,38 +185,20 @@ impl<F: Field + PrimeField, G: GroupType<F>> Compiler<F, G> {
|
||||
// Store the main program file.
|
||||
self.program = core_ast.into_repr();
|
||||
|
||||
// Parse and store all programs imported by the main program file.
|
||||
self.imported_programs = ImportParser::parse(&self.program)?;
|
||||
|
||||
tracing::debug!("Program parsing complete\n{:#?}", self.program);
|
||||
|
||||
self.program_asg_generate()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
///
|
||||
/// Runs a type check on the program, imports, and input.
|
||||
///
|
||||
/// First, a symbol table of all user defined types is created.
|
||||
/// Second, a type inference check is run on the program - inferring a data type for all implicit types and
|
||||
/// catching type mismatch errors.
|
||||
///
|
||||
pub(crate) fn check_program(&self) -> Result<(), CompilerError> {
|
||||
pub(crate) fn program_asg_generate(&mut self) -> Result<(), CompilerError> {
|
||||
// Create a new symbol table from the program, imported_programs, and program_input.
|
||||
let symbol_table =
|
||||
SymbolTable::new(&self.program, &self.imported_programs, &self.program_input).map_err(|mut e| {
|
||||
e.set_path(&self.main_file_path);
|
||||
let asg = leo_asg::InnerProgram::new(&self.program, &mut leo_imports::ImportParser::default())?;
|
||||
|
||||
e
|
||||
})?;
|
||||
tracing::debug!("ASG generation complete");
|
||||
|
||||
// Run type inference check on program.
|
||||
TypeInference::new(&self.program, symbol_table).map_err(|mut e| {
|
||||
e.set_path(&self.main_file_path);
|
||||
|
||||
e
|
||||
})?;
|
||||
|
||||
tracing::debug!("Program checks complete");
|
||||
self.asg = Some(asg);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@ -246,17 +224,10 @@ impl<F: Field + PrimeField, G: GroupType<F>> Compiler<F, G> {
|
||||
// Store the main program file.
|
||||
self.program = core_ast.into_repr();
|
||||
|
||||
// Parse and store all programs imported by the main program file.
|
||||
self.imported_programs = ImportParser::parse(&self.program)?;
|
||||
|
||||
// Create a new symbol table from the program, imported programs, and program input.
|
||||
let symbol_table = SymbolTable::new(&self.program, &self.imported_programs, &self.program_input)?;
|
||||
|
||||
// Run type inference check on program.
|
||||
TypeInference::new(&self.program, symbol_table)?;
|
||||
|
||||
tracing::debug!("Program parsing complete\n{:#?}", self.program);
|
||||
|
||||
self.program_asg_generate()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@ -303,13 +274,11 @@ impl<F: Field + PrimeField, G: GroupType<F>> Compiler<F, G> {
|
||||
pub fn compile_constraints<CS: ConstraintSystem<F>>(self, cs: &mut CS) -> Result<OutputBytes, CompilerError> {
|
||||
let path = self.main_file_path;
|
||||
|
||||
generate_constraints::<F, G, CS>(cs, &self.program, &self.program_input, &self.imported_programs).map_err(
|
||||
|mut error| {
|
||||
error.set_path(&path);
|
||||
generate_constraints::<F, G, CS>(cs, self.asg.as_ref().unwrap(), &self.program_input).map_err(|mut error| {
|
||||
error.set_path(&path);
|
||||
|
||||
error
|
||||
},
|
||||
)
|
||||
error
|
||||
})
|
||||
}
|
||||
|
||||
///
|
||||
@ -317,9 +286,8 @@ impl<F: Field + PrimeField, G: GroupType<F>> Compiler<F, G> {
|
||||
///
|
||||
pub fn compile_test_constraints(self, input_pairs: InputPairs) -> Result<(u32, u32), CompilerError> {
|
||||
generate_test_constraints::<F, G>(
|
||||
self.program,
|
||||
self.asg.as_ref().unwrap(),
|
||||
input_pairs,
|
||||
&self.imported_programs,
|
||||
&self.main_file_path,
|
||||
&self.output_directory,
|
||||
)
|
||||
@ -333,12 +301,10 @@ impl<F: Field + PrimeField, G: GroupType<F>> Compiler<F, G> {
|
||||
cs: &mut CS,
|
||||
) -> Result<OutputBytes, CompilerError> {
|
||||
let path = &self.main_file_path;
|
||||
generate_constraints::<_, G, _>(cs, &self.program, &self.program_input, &self.imported_programs).map_err(
|
||||
|mut error| {
|
||||
error.set_path(&path);
|
||||
error
|
||||
},
|
||||
)
|
||||
generate_constraints::<_, G, _>(cs, self.asg.as_ref().unwrap(), &self.program_input).map_err(|mut error| {
|
||||
error.set_path(&path);
|
||||
error
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -23,7 +23,8 @@ use crate::{
|
||||
value::ConstrainedValue,
|
||||
GroupType,
|
||||
};
|
||||
use leo_ast::{Expression, Span, Type};
|
||||
use leo_asg::{Expression, Span};
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -34,17 +35,12 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn evaluate_console_assert<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
indicator: &Boolean,
|
||||
expression: Expression,
|
||||
expression: &Arc<Expression>,
|
||||
span: &Span,
|
||||
) -> Result<(), ConsoleError> {
|
||||
let expected_type = Some(Type::Boolean);
|
||||
let expression_string = expression.to_string();
|
||||
|
||||
// Evaluate assert expression
|
||||
let assert_expression = self.enforce_expression(cs, file_scope, function_scope, expected_type, expression)?;
|
||||
let assert_expression = self.enforce_expression(cs, expression)?;
|
||||
|
||||
// If the indicator bit is false, do not evaluate the assertion
|
||||
// This is okay since we are not enforcing any constraints
|
||||
@ -57,7 +53,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
ConstrainedValue::Boolean(boolean) => boolean.get_value(),
|
||||
_ => {
|
||||
return Err(ConsoleError::assertion_must_be_boolean(
|
||||
expression_string,
|
||||
span.text.clone(),
|
||||
span.to_owned(),
|
||||
));
|
||||
}
|
||||
@ -65,7 +61,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
let result_bool = result_option.ok_or_else(|| ConsoleError::assertion_depends_on_input(span.to_owned()))?;
|
||||
|
||||
if !result_bool {
|
||||
return Err(ConsoleError::assertion_failed(expression_string, span.to_owned()));
|
||||
return Err(ConsoleError::assertion_failed(span.text.clone(), span.to_owned()));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
@ -17,7 +17,7 @@
|
||||
//! Evaluates a macro in a compiled Leo program.
|
||||
|
||||
use crate::{errors::ConsoleError, program::ConstrainedProgram, statement::get_indicator_value, GroupType};
|
||||
use leo_ast::{ConsoleFunction, ConsoleStatement};
|
||||
use leo_asg::{ConsoleFunction, ConsoleStatement};
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -28,31 +28,29 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn evaluate_console_function_call<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
indicator: &Boolean,
|
||||
console: ConsoleStatement,
|
||||
console: &ConsoleStatement,
|
||||
) -> Result<(), ConsoleError> {
|
||||
match console.function {
|
||||
match &console.function {
|
||||
ConsoleFunction::Assert(expression) => {
|
||||
self.evaluate_console_assert(cs, file_scope, function_scope, indicator, expression, &console.span)?;
|
||||
self.evaluate_console_assert(cs, indicator, expression, &console.span.clone().unwrap_or_default())?;
|
||||
}
|
||||
ConsoleFunction::Debug(string) => {
|
||||
let string = self.format(cs, file_scope, function_scope, string)?;
|
||||
let string = self.format(cs, string)?;
|
||||
|
||||
if get_indicator_value(indicator) {
|
||||
tracing::debug!("{}", string);
|
||||
}
|
||||
}
|
||||
ConsoleFunction::Error(string) => {
|
||||
let string = self.format(cs, file_scope, function_scope, string)?;
|
||||
let string = self.format(cs, string)?;
|
||||
|
||||
if get_indicator_value(indicator) {
|
||||
tracing::error!("{}", string);
|
||||
}
|
||||
}
|
||||
ConsoleFunction::Log(string) => {
|
||||
let string = self.format(cs, file_scope, function_scope, string)?;
|
||||
let string = self.format(cs, string)?;
|
||||
|
||||
if get_indicator_value(indicator) {
|
||||
tracing::info!("{}", string);
|
||||
|
@ -17,7 +17,7 @@
|
||||
//! Evaluates a formatted string in a compiled Leo program.
|
||||
|
||||
use crate::{errors::ConsoleError, program::ConstrainedProgram, GroupType};
|
||||
use leo_ast::FormattedString;
|
||||
use leo_asg::FormattedString;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -28,16 +28,14 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn format<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
formatted: FormattedString,
|
||||
formatted: &FormattedString,
|
||||
) -> Result<String, ConsoleError> {
|
||||
// Check that containers and parameters match
|
||||
if formatted.containers.len() != formatted.parameters.len() {
|
||||
return Err(ConsoleError::length(
|
||||
formatted.containers.len(),
|
||||
formatted.parameters.len(),
|
||||
formatted.span,
|
||||
formatted.span.clone(),
|
||||
));
|
||||
}
|
||||
|
||||
@ -51,8 +49,8 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
// Insert the parameter for each container `{}`
|
||||
let mut result = string.to_string();
|
||||
|
||||
for parameter in formatted.parameters.into_iter() {
|
||||
let parameter_value = self.enforce_expression(cs, file_scope, function_scope, None, parameter)?;
|
||||
for parameter in formatted.parameters.iter() {
|
||||
let parameter_value = self.enforce_expression(cs, parameter)?;
|
||||
|
||||
result = result.replacen("{}", ¶meter_value.to_string(), 1);
|
||||
}
|
||||
|
@ -16,17 +16,9 @@
|
||||
|
||||
//! Generates R1CS constraints for a compiled Leo program.
|
||||
|
||||
use crate::{
|
||||
errors::CompilerError,
|
||||
new_scope,
|
||||
ConstrainedProgram,
|
||||
ConstrainedValue,
|
||||
GroupType,
|
||||
OutputBytes,
|
||||
OutputFile,
|
||||
};
|
||||
use leo_ast::{Input, Program};
|
||||
use leo_imports::ImportParser;
|
||||
use crate::{errors::CompilerError, ConstrainedProgram, GroupType, OutputBytes, OutputFile};
|
||||
use leo_asg::Program;
|
||||
use leo_ast::Input;
|
||||
use leo_input::LeoInputParser;
|
||||
use leo_package::inputs::InputPairs;
|
||||
|
||||
@ -40,19 +32,17 @@ pub fn generate_constraints<F: Field + PrimeField, G: GroupType<F>, CS: Constrai
|
||||
cs: &mut CS,
|
||||
program: &Program,
|
||||
input: &Input,
|
||||
imported_programs: &ImportParser,
|
||||
) -> Result<OutputBytes, CompilerError> {
|
||||
let mut resolved_program = ConstrainedProgram::<F, G>::new();
|
||||
let program_name = program.get_name();
|
||||
let main_function_name = new_scope(&program_name, "main");
|
||||
let mut resolved_program = ConstrainedProgram::<F, G>::new(program.clone());
|
||||
|
||||
resolved_program.store_definitions(program, imported_programs)?;
|
||||
let main = {
|
||||
let program = program.borrow();
|
||||
program.functions.get("main").cloned()
|
||||
};
|
||||
|
||||
let main = resolved_program.get(&main_function_name).ok_or(CompilerError::NoMain)?;
|
||||
|
||||
match main.clone() {
|
||||
ConstrainedValue::Function(_circuit_identifier, function) => {
|
||||
let result = resolved_program.enforce_main_function(cs, &program_name, *function, input)?;
|
||||
match main {
|
||||
Some(function) => {
|
||||
let result = resolved_program.enforce_main_function(cs, &function, input)?;
|
||||
Ok(result)
|
||||
}
|
||||
_ => Err(CompilerError::NoMainFunction),
|
||||
@ -60,38 +50,34 @@ pub fn generate_constraints<F: Field + PrimeField, G: GroupType<F>, CS: Constrai
|
||||
}
|
||||
|
||||
pub fn generate_test_constraints<F: Field + PrimeField, G: GroupType<F>>(
|
||||
program: Program,
|
||||
program: &Program,
|
||||
input: InputPairs,
|
||||
imported_programs: &ImportParser,
|
||||
main_file_path: &Path,
|
||||
output_directory: &Path,
|
||||
) -> Result<(u32, u32), CompilerError> {
|
||||
let mut resolved_program = ConstrainedProgram::<F, G>::new();
|
||||
let program_name = program.get_name();
|
||||
|
||||
let tests = program.tests.clone();
|
||||
|
||||
// Store definitions
|
||||
resolved_program.store_definitions(&program, imported_programs)?;
|
||||
let mut resolved_program = ConstrainedProgram::<F, G>::new(program.clone());
|
||||
let program_name = program.borrow().name.clone();
|
||||
|
||||
// Get default input
|
||||
let default = input.pairs.get(&program_name);
|
||||
|
||||
let program = program.borrow();
|
||||
let tests = &program.test_functions;
|
||||
tracing::info!("Running {} tests", tests.len());
|
||||
|
||||
// Count passed and failed tests
|
||||
let mut passed = 0;
|
||||
let mut failed = 0;
|
||||
|
||||
for (test_name, test) in tests.into_iter() {
|
||||
for (test_name, (function, input_file)) in tests.into_iter() {
|
||||
let cs = &mut TestConstraintSystem::<F>::new();
|
||||
let full_test_name = format!("{}::{}", program_name.clone(), test_name);
|
||||
let mut output_file_name = program_name.clone();
|
||||
|
||||
// get input file name from annotation or use test_name
|
||||
let input_pair = match test.input_file {
|
||||
let input_pair = match input_file {
|
||||
Some(file_id) => {
|
||||
let file_name = file_id.name;
|
||||
let file_name = file_id.name.clone();
|
||||
|
||||
output_file_name = file_name.clone();
|
||||
|
||||
@ -117,10 +103,7 @@ pub fn generate_test_constraints<F: Field + PrimeField, G: GroupType<F>>(
|
||||
|
||||
// run test function on new program with input
|
||||
let result = resolved_program.enforce_main_function(
|
||||
cs,
|
||||
&program_name,
|
||||
test.function,
|
||||
&input, // pass program input into every test
|
||||
cs, function, &input, // pass program input into every test
|
||||
);
|
||||
|
||||
match (result.is_ok(), cs.is_satisfied()) {
|
||||
|
@ -16,30 +16,19 @@
|
||||
|
||||
//! Stores all defined names in a compiled Leo program.
|
||||
|
||||
use crate::{
|
||||
program::{new_scope, ConstrainedProgram},
|
||||
value::ConstrainedValue,
|
||||
GroupType,
|
||||
};
|
||||
use leo_ast::Identifier;
|
||||
use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_asg::Variable;
|
||||
|
||||
use snarkvm_models::curves::{Field, PrimeField};
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn store_definition(
|
||||
&mut self,
|
||||
function_scope: &str,
|
||||
mutable: bool,
|
||||
identifier: Identifier,
|
||||
mut value: ConstrainedValue<F, G>,
|
||||
) {
|
||||
pub fn store_definition(&mut self, variable: &Variable, mut value: ConstrainedValue<F, G>) {
|
||||
let variable = variable.borrow();
|
||||
// Store with given mutability
|
||||
if mutable {
|
||||
if variable.mutable {
|
||||
value = ConstrainedValue::Mutable(Box::new(value));
|
||||
}
|
||||
|
||||
let variable_program_identifier = new_scope(function_scope, &identifier.name);
|
||||
|
||||
self.store(variable_program_identifier, value);
|
||||
self.store(variable.id, value);
|
||||
}
|
||||
}
|
||||
|
@ -1,65 +0,0 @@
|
||||
// Copyright (C) 2019-2021 Aleo Systems Inc.
|
||||
// This file is part of the Leo library.
|
||||
|
||||
// The Leo library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// The Leo library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
//! Stores all defined names in a compiled Leo program.
|
||||
|
||||
use crate::{
|
||||
errors::ImportError,
|
||||
program::{new_scope, ConstrainedProgram},
|
||||
value::ConstrainedValue,
|
||||
GroupType,
|
||||
};
|
||||
use leo_ast::Program;
|
||||
use leo_imports::ImportParser;
|
||||
|
||||
use snarkvm_models::curves::{Field, PrimeField};
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn store_definitions(
|
||||
&mut self,
|
||||
program: &Program,
|
||||
imported_programs: &ImportParser,
|
||||
) -> Result<(), ImportError> {
|
||||
let program_name = program.name.trim_end_matches(".leo");
|
||||
|
||||
// evaluate all import statements and store imported definitions
|
||||
program
|
||||
.imports
|
||||
.iter()
|
||||
.map(|import| self.store_import(&program_name, import, imported_programs))
|
||||
.collect::<Result<Vec<_>, ImportError>>()?;
|
||||
|
||||
// evaluate and store all circuit definitions
|
||||
program.circuits.iter().for_each(|(identifier, circuit)| {
|
||||
let resolved_circuit_name = new_scope(program_name, &identifier.name);
|
||||
self.store(
|
||||
resolved_circuit_name,
|
||||
ConstrainedValue::CircuitDefinition(circuit.clone()),
|
||||
);
|
||||
});
|
||||
|
||||
// evaluate and store all function definitions
|
||||
program.functions.iter().for_each(|(function_name, function)| {
|
||||
let resolved_function_name = new_scope(program_name, &function_name.name);
|
||||
self.store(
|
||||
resolved_function_name,
|
||||
ConstrainedValue::Function(None, Box::new(function.clone())),
|
||||
);
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
@ -16,6 +16,3 @@
|
||||
|
||||
pub mod definition;
|
||||
pub use self::definition::*;
|
||||
|
||||
pub mod definitions;
|
||||
pub use self::definitions::*;
|
||||
|
@ -15,13 +15,12 @@
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::errors::{FunctionError, ImportError, OutputBytesError, OutputFileError};
|
||||
use leo_asg::AsgConvertError;
|
||||
use leo_ast::AstError;
|
||||
use leo_grammar::ParserError;
|
||||
use leo_imports::ImportParserError;
|
||||
use leo_input::InputParserError;
|
||||
use leo_state::LocalDataVerificationError;
|
||||
use leo_symbol_table::SymbolTableError;
|
||||
use leo_type_inference::TypeInferenceError;
|
||||
|
||||
use bincode::Error as SerdeError;
|
||||
use std::path::{Path, PathBuf};
|
||||
@ -74,9 +73,7 @@ pub enum CompilerError {
|
||||
SerdeError(#[from] SerdeError),
|
||||
|
||||
#[error("{}", _0)]
|
||||
SymbolTableError(#[from] SymbolTableError),
|
||||
#[error("{}", _0)]
|
||||
TypeInferenceError(#[from] TypeInferenceError),
|
||||
AsgConvertError(#[from] AsgConvertError),
|
||||
}
|
||||
|
||||
impl CompilerError {
|
||||
@ -85,8 +82,6 @@ impl CompilerError {
|
||||
CompilerError::InputParserError(error) => error.set_path(path),
|
||||
CompilerError::FunctionError(error) => error.set_path(path),
|
||||
CompilerError::OutputStringError(error) => error.set_path(path),
|
||||
CompilerError::SymbolTableError(error) => error.set_path(path),
|
||||
CompilerError::TypeInferenceError(error) => error.set_path(path),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
@ -16,7 +16,6 @@
|
||||
|
||||
use crate::errors::{AddressError, BooleanError, FieldError, FunctionError, GroupError, IntegerError, ValueError};
|
||||
use leo_ast::{ArrayDimensions, Error as FormattedError, Identifier, PositiveNumber, Span};
|
||||
use leo_core::LeoCorePackageError;
|
||||
|
||||
use snarkvm_errors::gadgets::SynthesisError;
|
||||
use std::path::Path;
|
||||
@ -44,9 +43,6 @@ pub enum ExpressionError {
|
||||
#[error("{}", _0)]
|
||||
IntegerError(#[from] IntegerError),
|
||||
|
||||
#[error("{}", _0)]
|
||||
LeoCoreError(#[from] LeoCorePackageError),
|
||||
|
||||
#[error("{}", _0)]
|
||||
ValueError(#[from] ValueError),
|
||||
}
|
||||
@ -61,7 +57,6 @@ impl ExpressionError {
|
||||
ExpressionError::FunctionError(error) => error.set_path(path),
|
||||
ExpressionError::GroupError(error) => error.set_path(path),
|
||||
ExpressionError::IntegerError(error) => error.set_path(path),
|
||||
ExpressionError::LeoCoreError(error) => error.set_path(path),
|
||||
ExpressionError::ValueError(error) => error.set_path(path),
|
||||
}
|
||||
}
|
||||
|
@ -25,6 +25,7 @@ use crate::errors::{
|
||||
StatementError,
|
||||
ValueError,
|
||||
};
|
||||
use leo_asg::AsgConvertError;
|
||||
use leo_ast::{Error as FormattedError, Span};
|
||||
|
||||
use std::path::Path;
|
||||
@ -60,6 +61,9 @@ pub enum FunctionError {
|
||||
|
||||
#[error("{}", _0)]
|
||||
ValueError(#[from] ValueError),
|
||||
|
||||
#[error("{}", _0)]
|
||||
ImportASGError(#[from] AsgConvertError),
|
||||
}
|
||||
|
||||
impl FunctionError {
|
||||
@ -75,6 +79,7 @@ impl FunctionError {
|
||||
FunctionError::OutputStringError(error) => error.set_path(path),
|
||||
FunctionError::StatementError(error) => error.set_path(path),
|
||||
FunctionError::ValueError(error) => error.set_path(path),
|
||||
FunctionError::ImportASGError(_error) => (),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -15,15 +15,11 @@
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use leo_ast::{Error as FormattedError, Identifier, ImportSymbol, Span};
|
||||
use leo_core::LeoCorePackageError;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ImportError {
|
||||
#[error("{}", _0)]
|
||||
Error(#[from] FormattedError),
|
||||
|
||||
#[error("{}", _0)]
|
||||
LeoCoreError(#[from] LeoCorePackageError),
|
||||
}
|
||||
|
||||
impl ImportError {
|
||||
|
@ -15,7 +15,8 @@
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::errors::ValueError;
|
||||
use leo_ast::{Error as FormattedError, Span, Type};
|
||||
use leo_asg::{AsgConvertError, Type};
|
||||
use leo_ast::{Error as FormattedError, Span};
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
@ -26,6 +27,9 @@ pub enum OutputBytesError {
|
||||
|
||||
#[error("{}", _0)]
|
||||
ValueError(#[from] ValueError),
|
||||
|
||||
#[error("{}", _0)]
|
||||
AsgConvertError(#[from] AsgConvertError),
|
||||
}
|
||||
|
||||
impl OutputBytesError {
|
||||
@ -33,6 +37,7 @@ impl OutputBytesError {
|
||||
match self {
|
||||
OutputBytesError::Error(error) => error.set_path(path),
|
||||
OutputBytesError::ValueError(error) => error.set_path(path),
|
||||
OutputBytesError::AsgConvertError(_error) => (),
|
||||
}
|
||||
}
|
||||
|
||||
@ -46,7 +51,7 @@ impl OutputBytesError {
|
||||
Self::new_from_span(message, span)
|
||||
}
|
||||
|
||||
pub fn mismatched_output_types(left: Type, right: Type, span: Span) -> Self {
|
||||
pub fn mismatched_output_types(left: &Type, right: &Type, span: Span) -> Self {
|
||||
let message = format!(
|
||||
"Mismatched types. Expected register output type `{}`, found type `{}`.",
|
||||
left, right
|
||||
|
@ -15,7 +15,8 @@
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::errors::{AddressError, BooleanError, ConsoleError, ExpressionError, IntegerError, ValueError};
|
||||
use leo_ast::{Error as FormattedError, Span, Type};
|
||||
use leo_asg::Type;
|
||||
use leo_ast::{Error as FormattedError, Span};
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
@ -166,7 +167,7 @@ impl StatementError {
|
||||
Self::new_from_span(message, span)
|
||||
}
|
||||
|
||||
pub fn no_returns(expected: Type, span: Span) -> Self {
|
||||
pub fn no_returns(expected: &Type, span: Span) -> Self {
|
||||
let message = format!(
|
||||
"function expected `{}` return type but no valid branches returned a result",
|
||||
expected
|
||||
|
@ -40,14 +40,6 @@ pub fn enforce_add<F: Field + PrimeField, G: GroupType<F>, CS: ConstraintSystem<
|
||||
(ConstrainedValue::Group(point_1), ConstrainedValue::Group(point_2)) => {
|
||||
Ok(ConstrainedValue::Group(point_1.add(cs, &point_2, span)?))
|
||||
}
|
||||
(ConstrainedValue::Unresolved(string), val_2) => {
|
||||
let val_1 = ConstrainedValue::from_other(string, &val_2, span)?;
|
||||
enforce_add(cs, val_1, val_2, span)
|
||||
}
|
||||
(val_1, ConstrainedValue::Unresolved(string)) => {
|
||||
let val_2 = ConstrainedValue::from_other(string, &val_1, span)?;
|
||||
enforce_add(cs, val_1, val_2, span)
|
||||
}
|
||||
(val_1, val_2) => Err(ExpressionError::incompatible_types(
|
||||
format!("{} + {}", val_1, val_2),
|
||||
span.to_owned(),
|
||||
|
@ -37,14 +37,6 @@ pub fn enforce_div<F: Field + PrimeField, G: GroupType<F>, CS: ConstraintSystem<
|
||||
(ConstrainedValue::Field(field_1), ConstrainedValue::Field(field_2)) => {
|
||||
Ok(ConstrainedValue::Field(field_1.div(cs, &field_2, span)?))
|
||||
}
|
||||
(ConstrainedValue::Unresolved(string), val_2) => {
|
||||
let val_1 = ConstrainedValue::from_other(string, &val_2, span)?;
|
||||
enforce_div(cs, val_1, val_2, span)
|
||||
}
|
||||
(val_1, ConstrainedValue::Unresolved(string)) => {
|
||||
let val_2 = ConstrainedValue::from_other(string, &val_1, span)?;
|
||||
enforce_div(cs, val_1, val_2, span)
|
||||
}
|
||||
(val_1, val_2) => Err(ExpressionError::incompatible_types(
|
||||
format!("{} / {}", val_1, val_2,),
|
||||
span.to_owned(),
|
||||
|
@ -37,14 +37,6 @@ pub fn enforce_mul<F: Field + PrimeField, G: GroupType<F>, CS: ConstraintSystem<
|
||||
(ConstrainedValue::Field(field_1), ConstrainedValue::Field(field_2)) => {
|
||||
Ok(ConstrainedValue::Field(field_1.mul(cs, &field_2, span)?))
|
||||
}
|
||||
(ConstrainedValue::Unresolved(string), val_2) => {
|
||||
let val_1 = ConstrainedValue::from_other(string, &val_2, span)?;
|
||||
enforce_mul(cs, val_1, val_2, span)
|
||||
}
|
||||
(val_1, ConstrainedValue::Unresolved(string)) => {
|
||||
let val_2 = ConstrainedValue::from_other(string, &val_1, span)?;
|
||||
enforce_mul(cs, val_1, val_2, span)
|
||||
}
|
||||
(val_1, val_2) => Err(ExpressionError::incompatible_types(
|
||||
format!("{} * {}", val_1, val_2),
|
||||
span.to_owned(),
|
||||
|
@ -34,14 +34,6 @@ pub fn enforce_pow<F: Field + PrimeField, G: GroupType<F>, CS: ConstraintSystem<
|
||||
(ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => {
|
||||
Ok(ConstrainedValue::Integer(num_1.pow(cs, num_2, span)?))
|
||||
}
|
||||
(ConstrainedValue::Unresolved(string), val_2) => {
|
||||
let val_1 = ConstrainedValue::from_other(string, &val_2, span)?;
|
||||
enforce_pow(cs, val_1, val_2, span)
|
||||
}
|
||||
(val_1, ConstrainedValue::Unresolved(string)) => {
|
||||
let val_2 = ConstrainedValue::from_other(string, &val_1, span)?;
|
||||
enforce_pow(cs, val_1, val_2, span)
|
||||
}
|
||||
(val_1, val_2) => Err(ExpressionError::incompatible_types(
|
||||
format!("{} ** {}", val_1, val_2,),
|
||||
span.to_owned(),
|
||||
|
@ -40,14 +40,6 @@ pub fn enforce_sub<F: Field + PrimeField, G: GroupType<F>, CS: ConstraintSystem<
|
||||
(ConstrainedValue::Group(point_1), ConstrainedValue::Group(point_2)) => {
|
||||
Ok(ConstrainedValue::Group(point_1.sub(cs, &point_2, span)?))
|
||||
}
|
||||
(ConstrainedValue::Unresolved(string), val_2) => {
|
||||
let val_1 = ConstrainedValue::from_other(string, &val_2, &span)?;
|
||||
enforce_sub(cs, val_1, val_2, span)
|
||||
}
|
||||
(val_1, ConstrainedValue::Unresolved(string)) => {
|
||||
let val_2 = ConstrainedValue::from_other(string, &val_1, &span)?;
|
||||
enforce_sub(cs, val_1, val_2, span)
|
||||
}
|
||||
(val_1, val_2) => Err(ExpressionError::incompatible_types(
|
||||
format!("{} - {}", val_1, val_2),
|
||||
span.to_owned(),
|
||||
|
@ -17,7 +17,8 @@
|
||||
//! Enforces array access in a compiled Leo program.
|
||||
|
||||
use crate::{errors::ExpressionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::{Expression, Span, Type};
|
||||
use leo_asg::{Expression, Span};
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -29,19 +30,16 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_array_access<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
expected_type: Option<Type>,
|
||||
array: Expression,
|
||||
index: Expression,
|
||||
array: &Arc<Expression>,
|
||||
index: &Arc<Expression>,
|
||||
span: &Span,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
let array = match self.enforce_operand(cs, file_scope, function_scope, expected_type, array, span)? {
|
||||
let array = match self.enforce_operand(cs, array)? {
|
||||
ConstrainedValue::Array(array) => array,
|
||||
value => return Err(ExpressionError::undefined_array(value.to_string(), span.to_owned())),
|
||||
};
|
||||
|
||||
let index_resolved = self.enforce_index(cs, file_scope, function_scope, index, span)?;
|
||||
let index_resolved = self.enforce_index(cs, index, span)?;
|
||||
Ok(array[index_resolved].to_owned())
|
||||
}
|
||||
|
||||
@ -49,25 +47,22 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_array_range_access<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
expected_type: Option<Type>,
|
||||
array: Expression,
|
||||
left: Option<Expression>,
|
||||
right: Option<Expression>,
|
||||
array: &Arc<Expression>,
|
||||
left: Option<&Arc<Expression>>,
|
||||
right: Option<&Arc<Expression>>,
|
||||
span: &Span,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
let array = match self.enforce_operand(cs, file_scope, function_scope, expected_type, array, span)? {
|
||||
let array = match self.enforce_operand(cs, array)? {
|
||||
ConstrainedValue::Array(array) => array,
|
||||
value => return Err(ExpressionError::undefined_array(value.to_string(), span.to_owned())),
|
||||
};
|
||||
|
||||
let from_resolved = match left {
|
||||
Some(from_index) => self.enforce_index(cs, file_scope, function_scope, from_index, span)?,
|
||||
let from_resolved = match left.as_deref() {
|
||||
Some(from_index) => self.enforce_index(cs, from_index, span)?,
|
||||
None => 0usize, // Array slice starts at index 0
|
||||
};
|
||||
let to_resolved = match right {
|
||||
Some(to_index) => self.enforce_index(cs, file_scope, function_scope, to_index, span)?,
|
||||
let to_resolved = match right.as_deref() {
|
||||
Some(to_index) => self.enforce_index(cs, to_index, span)?,
|
||||
None => array.len(), // Array slice ends at array length
|
||||
};
|
||||
Ok(ConstrainedValue::Array(array[from_resolved..to_resolved].to_owned()))
|
||||
|
@ -16,13 +16,9 @@
|
||||
|
||||
//! Enforces an array expression in a compiled Leo program.
|
||||
|
||||
use crate::{
|
||||
errors::ExpressionError,
|
||||
program::{new_scope, ConstrainedProgram},
|
||||
value::ConstrainedValue,
|
||||
GroupType,
|
||||
};
|
||||
use leo_ast::{ArrayDimensions, Expression, PositiveNumber, Span, SpreadOrExpression, Type};
|
||||
use crate::{errors::ExpressionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_asg::{Expression, Span};
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -34,65 +30,21 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_array<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
mut expected_type: Option<Type>,
|
||||
array: Vec<SpreadOrExpression>,
|
||||
array: &[(Arc<Expression>, bool)],
|
||||
span: Span,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
let mut expected_dimension = None;
|
||||
|
||||
// Check explicit array type dimension if given
|
||||
if let Some(type_) = expected_type {
|
||||
match type_ {
|
||||
Type::Array(type_, mut dimensions) => {
|
||||
// Remove the first dimension of the array.
|
||||
let first = match dimensions.remove_first() {
|
||||
Some(number) => {
|
||||
// Parse the array dimension into a `usize`.
|
||||
parse_index(&number, &span)?
|
||||
}
|
||||
None => return Err(ExpressionError::unexpected_array(type_.to_string(), span)),
|
||||
};
|
||||
|
||||
// Update the expected dimension to the first dimension.
|
||||
expected_dimension = Some(first);
|
||||
|
||||
// Update the expected type to a new array type with the first dimension removed.
|
||||
expected_type = Some(inner_array_type(*type_, dimensions));
|
||||
}
|
||||
ref type_ => {
|
||||
// Return an error if the expected type is not an array.
|
||||
return Err(ExpressionError::unexpected_array(type_.to_string(), span));
|
||||
}
|
||||
}
|
||||
}
|
||||
let expected_dimension = None;
|
||||
|
||||
let mut result = vec![];
|
||||
for element in array.into_iter() {
|
||||
match element {
|
||||
SpreadOrExpression::Spread(spread) => match spread {
|
||||
Expression::Identifier(identifier) => {
|
||||
let array_name = new_scope(&function_scope, &identifier.name);
|
||||
match self.get(&array_name) {
|
||||
Some(value) => match value {
|
||||
ConstrainedValue::Array(array) => result.extend(array.clone()),
|
||||
value => return Err(ExpressionError::invalid_spread(value.to_string(), span)),
|
||||
},
|
||||
None => return Err(ExpressionError::undefined_array(identifier.name, span)),
|
||||
}
|
||||
}
|
||||
value => return Err(ExpressionError::invalid_spread(value.to_string(), span)),
|
||||
},
|
||||
SpreadOrExpression::Expression(expression) => {
|
||||
result.push(self.enforce_expression(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
expected_type.clone(),
|
||||
expression,
|
||||
)?);
|
||||
for (element, is_spread) in array.iter() {
|
||||
let element_value = self.enforce_expression(cs, element)?;
|
||||
if *is_spread {
|
||||
match element_value {
|
||||
ConstrainedValue::Array(array) => result.extend(array),
|
||||
_ => unimplemented!(), // type should already be checked
|
||||
}
|
||||
} else {
|
||||
result.push(element_value);
|
||||
}
|
||||
}
|
||||
|
||||
@ -114,144 +66,17 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_array_initializer<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
expected_type: Option<Type>,
|
||||
element_expression: Expression,
|
||||
mut actual_dimensions: ArrayDimensions,
|
||||
span: Span,
|
||||
element_expression: &Arc<Expression>,
|
||||
actual_size: usize,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
// Compare dimensions
|
||||
// Case 1: expected == actual => enforce expression with array element type
|
||||
// Case 2: expected first dimension == actual first dimension => enforce expression with updated array type
|
||||
// Case 3: expected first dimension != actual first dimension => return mismatched dimensions error
|
||||
let mut value = self.enforce_expression(cs, element_expression)?;
|
||||
|
||||
if let Some(Type::Array(type_, mut expected_dimensions)) = expected_type {
|
||||
if expected_dimensions == actual_dimensions {
|
||||
// Case 1 - enforce expression with array element type
|
||||
let mut value =
|
||||
self.enforce_expression(cs, file_scope, function_scope, Some(*type_), element_expression)?;
|
||||
// Allocate the array.
|
||||
let array = vec![value; actual_size];
|
||||
|
||||
// Allocate the array.
|
||||
while let Some(dimension) = actual_dimensions.remove_last() {
|
||||
// Parse the dimension into a `usize`.
|
||||
let dimension_usize = parse_index(&dimension, &span)?;
|
||||
// Set the array value.
|
||||
value = ConstrainedValue::Array(array);
|
||||
|
||||
// Allocate the array dimension.
|
||||
let array = vec![value; dimension_usize];
|
||||
|
||||
// Set the array value.
|
||||
value = ConstrainedValue::Array(array);
|
||||
}
|
||||
|
||||
Ok(value)
|
||||
} else if expected_dimensions.first() == actual_dimensions.first() {
|
||||
// Case 2 - enforce expression with updated array type.
|
||||
let dimension = match expected_dimensions.remove_first() {
|
||||
Some(number) => {
|
||||
// Parse the array dimension into a `usize`.
|
||||
parse_index(&number, &span)?
|
||||
}
|
||||
None => return Err(ExpressionError::unexpected_array(type_.to_string(), span)),
|
||||
};
|
||||
|
||||
// Update the actual array dimensions.
|
||||
let _first_dimension = actual_dimensions.remove_first();
|
||||
|
||||
// Update the expected type to a new array type with the first dimension removed.
|
||||
let expected_expression_type = Some(inner_array_type(*type_, expected_dimensions));
|
||||
|
||||
// If the expression has more dimensions.
|
||||
let element_value = match actual_dimensions.first() {
|
||||
Some(_dimension) => {
|
||||
// Get the value of the array element as an initializer.
|
||||
self.enforce_array_initializer(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
expected_expression_type,
|
||||
element_expression,
|
||||
actual_dimensions.clone(),
|
||||
span,
|
||||
)?
|
||||
}
|
||||
None => {
|
||||
// Get the value of the array element as an expression.
|
||||
self.enforce_expression(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
expected_expression_type,
|
||||
element_expression,
|
||||
)?
|
||||
}
|
||||
};
|
||||
|
||||
// Allocate the array of values.
|
||||
let array_values = vec![element_value; dimension];
|
||||
|
||||
// Create a new value with the expected dimension.
|
||||
Ok(ConstrainedValue::Array(array_values))
|
||||
} else {
|
||||
// Case 3 - return mismatched dimensions error.
|
||||
Err(ExpressionError::invalid_first_dimension(
|
||||
expected_dimensions
|
||||
.first()
|
||||
.ok_or_else(|| ExpressionError::undefined_first_dimension(span.clone()))?,
|
||||
actual_dimensions
|
||||
.first()
|
||||
.ok_or_else(|| ExpressionError::undefined_first_dimension(span.clone()))?,
|
||||
span,
|
||||
))
|
||||
}
|
||||
} else {
|
||||
// No explicit type given - evaluate array element expression.
|
||||
let mut value =
|
||||
self.enforce_expression(cs, file_scope, function_scope, expected_type, element_expression)?;
|
||||
|
||||
// Allocate the array.
|
||||
while let Some(dimension) = actual_dimensions.remove_last() {
|
||||
// Parse the dimension into a `usize`.
|
||||
let dimension_usize = parse_index(&dimension, &span)?;
|
||||
|
||||
// Allocate the array dimension.
|
||||
let array = vec![value; dimension_usize];
|
||||
|
||||
// Set the array value.
|
||||
value = ConstrainedValue::Array(array);
|
||||
}
|
||||
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// Returns the index as a usize.
|
||||
///
|
||||
pub fn parse_index(number: &PositiveNumber, span: &Span) -> Result<usize, ExpressionError> {
|
||||
number
|
||||
.value
|
||||
.parse::<usize>()
|
||||
.map_err(|_| ExpressionError::invalid_index(number.value.to_owned(), span))
|
||||
}
|
||||
|
||||
///
|
||||
/// Returns the type of the inner array given an array element and array dimensions.
|
||||
///
|
||||
/// If the array has no dimensions, then an inner array does not exist. Simply return the given
|
||||
/// element type.
|
||||
///
|
||||
/// If the array has dimensions, then an inner array exists. Create a new type for the
|
||||
/// inner array. The element type of the new array should be the same as the old array. The
|
||||
/// dimensions of the new array should be the old array dimensions with the first dimension removed.
|
||||
///
|
||||
pub fn inner_array_type(element_type: Type, dimensions: ArrayDimensions) -> Type {
|
||||
if dimensions.is_empty() {
|
||||
// The array has one dimension.
|
||||
element_type
|
||||
} else {
|
||||
// The array has multiple dimensions.
|
||||
Type::Array(Box::new(element_type), dimensions)
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
@ -17,7 +17,8 @@
|
||||
//! Enforces an array index expression in a compiled Leo program.
|
||||
|
||||
use crate::{errors::ExpressionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::{Expression, IntegerType, Span, Type};
|
||||
use leo_asg::{Expression, Span};
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -28,13 +29,10 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub(crate) fn enforce_index<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
index: Expression,
|
||||
index: &Arc<Expression>,
|
||||
span: &Span,
|
||||
) -> Result<usize, ExpressionError> {
|
||||
let expected_type = Some(Type::IntegerType(IntegerType::U32));
|
||||
match self.enforce_operand(cs, file_scope, function_scope, expected_type, index, &span)? {
|
||||
match self.enforce_operand(cs, index)? {
|
||||
ConstrainedValue::Integer(number) => Ok(number.to_usize(span)?),
|
||||
value => Err(ExpressionError::invalid_index(value.to_string(), span)),
|
||||
}
|
||||
|
@ -17,7 +17,8 @@
|
||||
//! Enforces a binary expression in a compiled Leo program.
|
||||
|
||||
use crate::{errors::ExpressionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::{Expression, Span, Type};
|
||||
use leo_asg::Expression;
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -31,19 +32,11 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_binary_expression<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
expected_type: Option<Type>,
|
||||
left: Expression,
|
||||
right: Expression,
|
||||
span: &Span,
|
||||
left: &Arc<Expression>,
|
||||
right: &Arc<Expression>,
|
||||
) -> Result<ConstrainedValuePair<F, G>, ExpressionError> {
|
||||
let mut resolved_left =
|
||||
self.enforce_operand(cs, file_scope, function_scope, expected_type.clone(), left, span)?;
|
||||
let mut resolved_right =
|
||||
self.enforce_operand(cs, file_scope, function_scope, expected_type.clone(), right, span)?;
|
||||
|
||||
resolved_left.resolve_types(&mut resolved_right, expected_type, span)?;
|
||||
let resolved_left = self.enforce_operand(cs, left)?;
|
||||
let resolved_right = self.enforce_operand(cs, right)?;
|
||||
|
||||
Ok((resolved_left, resolved_right))
|
||||
}
|
||||
|
@ -17,7 +17,8 @@
|
||||
//! Enforces one operand in a binary expression in a compiled Leo program.
|
||||
|
||||
use crate::{errors::ExpressionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::{Expression, Span, Type};
|
||||
use leo_asg::Expression;
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -31,16 +32,11 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_operand<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
expected_type: Option<Type>,
|
||||
expression: Expression,
|
||||
span: &Span,
|
||||
expression: &Arc<Expression>,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
let mut branch = self.enforce_expression(cs, file_scope, function_scope, expected_type.clone(), expression)?;
|
||||
let mut branch = self.enforce_expression(cs, expression)?;
|
||||
|
||||
branch.get_inner_mut();
|
||||
branch.resolve_type(expected_type, span)?;
|
||||
|
||||
Ok(branch)
|
||||
}
|
||||
|
@ -16,82 +16,47 @@
|
||||
|
||||
//! Enforces a circuit access expression in a compiled Leo program.
|
||||
|
||||
use crate::{
|
||||
errors::ExpressionError,
|
||||
program::{new_scope, ConstrainedProgram},
|
||||
value::ConstrainedValue,
|
||||
GroupType,
|
||||
};
|
||||
use leo_ast::{Expression, Identifier, Span, Type};
|
||||
use crate::{errors::ExpressionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_asg::{CircuitAccessExpression, Node};
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
gadgets::r1cs::ConstraintSystem,
|
||||
};
|
||||
|
||||
static SELF_KEYWORD: &str = "self";
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn enforce_circuit_access<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
expected_type: Option<Type>,
|
||||
circuit_identifier: Expression,
|
||||
circuit_member: Identifier,
|
||||
span: Span,
|
||||
expr: &CircuitAccessExpression,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
// access a circuit member using the `self` keyword
|
||||
if let Expression::Identifier(ref identifier) = circuit_identifier {
|
||||
if identifier.is_self() {
|
||||
let self_file_scope = new_scope(&file_scope, &identifier.name);
|
||||
let self_function_scope = new_scope(&self_file_scope, &identifier.name);
|
||||
|
||||
let member_value =
|
||||
self.evaluate_identifier(&self_file_scope, &self_function_scope, None, circuit_member)?;
|
||||
|
||||
return Ok(member_value);
|
||||
}
|
||||
}
|
||||
|
||||
let (circuit_name, members) =
|
||||
match self.enforce_operand(cs, file_scope, function_scope, expected_type, circuit_identifier, &span)? {
|
||||
ConstrainedValue::CircuitExpression(name, members) => (name, members),
|
||||
value => return Err(ExpressionError::undefined_circuit(value.to_string(), span)),
|
||||
};
|
||||
|
||||
let matched_member = members.clone().into_iter().find(|member| member.0 == circuit_member);
|
||||
|
||||
match matched_member {
|
||||
Some(member) => {
|
||||
match &member.1 {
|
||||
ConstrainedValue::Function(ref _circuit_identifier, ref function) => {
|
||||
// Check for function input `self` or `mut self`.
|
||||
if function.contains_self() {
|
||||
// Pass circuit members into function call by value
|
||||
for stored_member in members {
|
||||
let circuit_scope = new_scope(&file_scope, &circuit_name.name);
|
||||
let self_keyword = new_scope(&circuit_scope, SELF_KEYWORD);
|
||||
let variable = new_scope(&self_keyword, &stored_member.0.name);
|
||||
|
||||
self.store(variable, stored_member.1.clone());
|
||||
}
|
||||
}
|
||||
if let Some(target) = &expr.target {
|
||||
//todo: we can prob pass values by ref here to avoid copying the entire circuit on access
|
||||
let target_value = self.enforce_operand(cs, target)?;
|
||||
match target_value {
|
||||
ConstrainedValue::CircuitExpression(def, members) => {
|
||||
assert!(def.circuit == expr.circuit);
|
||||
if let Some(member) = members.into_iter().find(|x| x.0.name == expr.member.name) {
|
||||
Ok(member.1)
|
||||
} else {
|
||||
Err(ExpressionError::undefined_member_access(
|
||||
expr.circuit.name.borrow().to_string(),
|
||||
expr.member.to_string(),
|
||||
expr.member.span.clone(),
|
||||
))
|
||||
}
|
||||
ConstrainedValue::Static(value) => {
|
||||
return Err(ExpressionError::invalid_static_access(value.to_string(), span));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(member.1)
|
||||
value => Err(ExpressionError::undefined_circuit(
|
||||
value.to_string(),
|
||||
target.span().cloned().unwrap_or_default(),
|
||||
)),
|
||||
}
|
||||
None => Err(ExpressionError::undefined_member_access(
|
||||
circuit_name.to_string(),
|
||||
circuit_member.to_string(),
|
||||
span,
|
||||
)),
|
||||
} else {
|
||||
Err(ExpressionError::invalid_static_access(
|
||||
expr.member.to_string(),
|
||||
expr.member.span.clone(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -18,11 +18,11 @@
|
||||
|
||||
use crate::{
|
||||
errors::ExpressionError,
|
||||
program::{new_scope, ConstrainedProgram},
|
||||
program::ConstrainedProgram,
|
||||
value::{ConstrainedCircuitMember, ConstrainedValue},
|
||||
GroupType,
|
||||
};
|
||||
use leo_ast::{CircuitMember, CircuitVariableDefinition, Identifier, Span};
|
||||
use leo_asg::{CircuitInitExpression, CircuitMemberBody, Span};
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -33,65 +33,34 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_circuit<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
identifier: Identifier,
|
||||
members: Vec<CircuitVariableDefinition>,
|
||||
span: Span,
|
||||
expr: &CircuitInitExpression,
|
||||
span: &Span,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
// Circuit definitions are located at the minimum file scope
|
||||
let minimum_scope = file_scope.split('_').next().unwrap();
|
||||
let identifier_string = identifier.to_string();
|
||||
let mut program_identifier = new_scope(minimum_scope, &identifier_string);
|
||||
let circuit = expr
|
||||
.circuit
|
||||
.body
|
||||
.borrow()
|
||||
.upgrade()
|
||||
.expect("circuit init stale circuit ref");
|
||||
let members = circuit.members.borrow();
|
||||
|
||||
if identifier.is_self() {
|
||||
program_identifier = file_scope.to_string();
|
||||
let mut resolved_members = Vec::with_capacity(members.len());
|
||||
|
||||
// type checking is already done in asg
|
||||
for (name, inner) in expr.values.iter() {
|
||||
let target = members
|
||||
.get(&name.name)
|
||||
.expect("illegal name in asg circuit init expression");
|
||||
match target {
|
||||
CircuitMemberBody::Variable(_type_) => {
|
||||
let variable_value = self.enforce_expression(cs, inner)?;
|
||||
resolved_members.push(ConstrainedCircuitMember(name.clone(), variable_value));
|
||||
}
|
||||
_ => return Err(ExpressionError::expected_circuit_member(name.to_string(), span.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
let circuit = match self.get(&program_identifier) {
|
||||
Some(value) => value.clone().extract_circuit(&span)?,
|
||||
None => return Err(ExpressionError::undefined_circuit(identifier.to_string(), span)),
|
||||
};
|
||||
|
||||
let circuit_identifier = circuit.circuit_name.clone();
|
||||
let mut resolved_members = Vec::with_capacity(circuit.members.len());
|
||||
|
||||
for member in circuit.members.into_iter() {
|
||||
match member {
|
||||
CircuitMember::CircuitVariable(identifier, type_) => {
|
||||
let matched_variable = members
|
||||
.clone()
|
||||
.into_iter()
|
||||
.find(|variable| variable.identifier.eq(&identifier));
|
||||
match matched_variable {
|
||||
Some(variable) => {
|
||||
// Resolve and enforce circuit variable
|
||||
let variable_value = self.enforce_expression(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
Some(type_.clone()),
|
||||
variable.expression,
|
||||
)?;
|
||||
|
||||
resolved_members.push(ConstrainedCircuitMember(identifier, variable_value))
|
||||
}
|
||||
None => return Err(ExpressionError::expected_circuit_member(identifier.to_string(), span)),
|
||||
}
|
||||
}
|
||||
CircuitMember::CircuitFunction(function) => {
|
||||
let identifier = function.identifier.clone();
|
||||
let constrained_function_value =
|
||||
ConstrainedValue::Function(Some(circuit_identifier.clone()), Box::new(function));
|
||||
|
||||
resolved_members.push(ConstrainedCircuitMember(identifier, constrained_function_value));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Ok(ConstrainedValue::CircuitExpression(
|
||||
circuit_identifier,
|
||||
resolved_members,
|
||||
))
|
||||
let value = ConstrainedValue::CircuitExpression(circuit.clone(), resolved_members);
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
@ -21,6 +21,3 @@ pub use self::access::*;
|
||||
|
||||
pub mod circuit;
|
||||
pub use self::circuit::*;
|
||||
|
||||
pub mod static_access;
|
||||
pub use self::static_access::*;
|
||||
|
@ -1,80 +0,0 @@
|
||||
// Copyright (C) 2019-2021 Aleo Systems Inc.
|
||||
// This file is part of the Leo library.
|
||||
|
||||
// The Leo library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// The Leo library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
//! Enforces a circuit static access expression in a compiled Leo program.
|
||||
|
||||
use crate::{errors::ExpressionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::{CircuitMember, Expression, Identifier, Span, Type};
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
gadgets::r1cs::ConstraintSystem,
|
||||
};
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn enforce_circuit_static_access<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
expected_type: Option<Type>,
|
||||
circuit_identifier: Expression,
|
||||
circuit_member: Identifier,
|
||||
span: Span,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
// Get defined circuit
|
||||
let circuit = match circuit_identifier {
|
||||
Expression::Identifier(identifier) => {
|
||||
// Use the "Self" keyword to access a static circuit function
|
||||
if identifier.is_self() {
|
||||
let circuit = self
|
||||
.get(&file_scope)
|
||||
.ok_or_else(|| ExpressionError::self_keyword(identifier.span))?;
|
||||
|
||||
circuit.to_owned()
|
||||
} else {
|
||||
self.evaluate_identifier(&file_scope, &function_scope, expected_type, identifier)?
|
||||
}
|
||||
}
|
||||
expression => self.enforce_expression(cs, file_scope, function_scope, expected_type, expression)?,
|
||||
}
|
||||
.extract_circuit(&span)?;
|
||||
|
||||
// Find static circuit function
|
||||
let matched_function = circuit.members.into_iter().find(|member| match member {
|
||||
CircuitMember::CircuitFunction(function) => function.identifier == circuit_member,
|
||||
_ => false,
|
||||
});
|
||||
|
||||
// Return errors if no static function exists
|
||||
let function = match matched_function {
|
||||
Some(CircuitMember::CircuitFunction(function)) => function,
|
||||
_ => {
|
||||
return Err(ExpressionError::undefined_member_access(
|
||||
circuit.circuit_name.to_string(),
|
||||
circuit_member.to_string(),
|
||||
span,
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
Ok(ConstrainedValue::Function(
|
||||
Some(circuit.circuit_name),
|
||||
Box::new(function),
|
||||
))
|
||||
}
|
||||
}
|
@ -17,7 +17,8 @@
|
||||
//! Enforces a conditional expression in a compiled Leo program.
|
||||
|
||||
use crate::{errors::ExpressionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::{Expression, Span, Type};
|
||||
use leo_asg::{Expression, Span};
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -30,23 +31,19 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_conditional_expression<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
expected_type: Option<Type>,
|
||||
conditional: Expression,
|
||||
first: Expression,
|
||||
second: Expression,
|
||||
conditional: &Arc<Expression>,
|
||||
first: &Arc<Expression>,
|
||||
second: &Arc<Expression>,
|
||||
span: &Span,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
let conditional_value =
|
||||
match self.enforce_expression(cs, file_scope, function_scope, Some(Type::Boolean), conditional)? {
|
||||
ConstrainedValue::Boolean(resolved) => resolved,
|
||||
value => return Err(ExpressionError::conditional_boolean(value.to_string(), span.to_owned())),
|
||||
};
|
||||
let conditional_value = match self.enforce_expression(cs, conditional)? {
|
||||
ConstrainedValue::Boolean(resolved) => resolved,
|
||||
value => return Err(ExpressionError::conditional_boolean(value.to_string(), span.to_owned())),
|
||||
};
|
||||
|
||||
let first_value = self.enforce_operand(cs, file_scope, function_scope, expected_type.clone(), first, span)?;
|
||||
let first_value = self.enforce_operand(cs, first)?;
|
||||
|
||||
let second_value = self.enforce_operand(cs, file_scope, function_scope, expected_type, second, span)?;
|
||||
let second_value = self.enforce_operand(cs, second)?;
|
||||
|
||||
let unique_namespace = cs.ns(|| {
|
||||
format!(
|
||||
|
@ -22,71 +22,49 @@ use crate::{
|
||||
logical::*,
|
||||
program::ConstrainedProgram,
|
||||
relational::*,
|
||||
value::{boolean::input::new_bool_constant, implicit::*, ConstrainedValue},
|
||||
Address,
|
||||
resolve_core_circuit,
|
||||
value::{Address, ConstrainedValue, Integer},
|
||||
FieldType,
|
||||
GroupType,
|
||||
Integer,
|
||||
};
|
||||
use leo_ast::{expression::*, Expression, Type};
|
||||
use leo_asg::{expression::*, ConstValue, Expression, Node};
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
gadgets::r1cs::ConstraintSystem,
|
||||
gadgets::{r1cs::ConstraintSystem, utilities::boolean::Boolean},
|
||||
};
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub(crate) fn enforce_expression<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
expected_type: Option<Type>,
|
||||
expression: Expression,
|
||||
expression: &Arc<Expression>,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
match expression {
|
||||
let span = expression.span().cloned().unwrap_or_default();
|
||||
match &**expression {
|
||||
// Variables
|
||||
Expression::Identifier(unresolved_variable) => {
|
||||
self.evaluate_identifier(file_scope, function_scope, expected_type, unresolved_variable)
|
||||
}
|
||||
Expression::VariableRef(variable_ref) => self.evaluate_ref(variable_ref),
|
||||
|
||||
// Values
|
||||
Expression::Value(ValueExpression::Address(address, span)) => {
|
||||
Ok(ConstrainedValue::Address(Address::constant(address, &span)?))
|
||||
Expression::Constant(Constant { value, .. }) => {
|
||||
Ok(match value {
|
||||
ConstValue::Address(value) => ConstrainedValue::Address(Address::constant(value.clone(), &span)?),
|
||||
ConstValue::Boolean(value) => ConstrainedValue::Boolean(Boolean::Constant(*value)),
|
||||
ConstValue::Field(value) => ConstrainedValue::Field(FieldType::constant(value.to_string(), &span)?),
|
||||
ConstValue::Group(value) => ConstrainedValue::Group(G::constant(value, &span)?),
|
||||
ConstValue::Int(value) => ConstrainedValue::Integer(Integer::new(value)),
|
||||
ConstValue::Tuple(_) | ConstValue::Array(_) => unimplemented!(), // shouldnt be in the asg here
|
||||
})
|
||||
}
|
||||
Expression::Value(ValueExpression::Boolean(boolean, span)) => {
|
||||
Ok(ConstrainedValue::Boolean(new_bool_constant(boolean, &span)?))
|
||||
}
|
||||
Expression::Value(ValueExpression::Field(field, span)) => {
|
||||
Ok(ConstrainedValue::Field(FieldType::constant(field, &span)?))
|
||||
}
|
||||
Expression::Value(ValueExpression::Group(group_element)) => {
|
||||
Ok(ConstrainedValue::Group(G::constant(*group_element)?))
|
||||
}
|
||||
Expression::Value(ValueExpression::Implicit(value, span)) => {
|
||||
Ok(enforce_number_implicit(expected_type, value, &span)?)
|
||||
}
|
||||
Expression::Value(ValueExpression::Integer(type_, integer, span)) => Ok(ConstrainedValue::Integer(
|
||||
Integer::new(expected_type, &type_, integer, &span)?,
|
||||
)),
|
||||
|
||||
// Binary operations
|
||||
Expression::Binary(BinaryExpression { left, right, op, span }) => {
|
||||
let (resolved_left, resolved_right) = self.enforce_binary_expression(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
if op.class() == BinaryOperationClass::Numeric {
|
||||
expected_type
|
||||
} else {
|
||||
None
|
||||
},
|
||||
*left,
|
||||
*right,
|
||||
&span,
|
||||
)?;
|
||||
Expression::Binary(BinaryExpression {
|
||||
left, right, operation, ..
|
||||
}) => {
|
||||
let (resolved_left, resolved_right) = self.enforce_binary_expression(cs, left, right)?;
|
||||
|
||||
match op {
|
||||
match operation {
|
||||
BinaryOperation::Add => enforce_add(cs, resolved_left, resolved_right, &span),
|
||||
BinaryOperation::Sub => enforce_sub(cs, resolved_left, resolved_right, &span),
|
||||
BinaryOperation::Mul => enforce_mul(cs, resolved_left, resolved_right, &span),
|
||||
@ -99,7 +77,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
enforce_and(cs, resolved_left, resolved_right, &span).map_err(ExpressionError::BooleanError)
|
||||
}
|
||||
BinaryOperation::Eq => evaluate_eq(cs, resolved_left, resolved_right, &span),
|
||||
BinaryOperation::Ne => evaluate_not(evaluate_eq(cs, resolved_left, resolved_right, &span)?, span)
|
||||
BinaryOperation::Ne => evaluate_not(evaluate_eq(cs, resolved_left, resolved_right, &span)?, &span)
|
||||
.map_err(ExpressionError::BooleanError),
|
||||
BinaryOperation::Ge => evaluate_ge(cs, resolved_left, resolved_right, &span),
|
||||
BinaryOperation::Gt => evaluate_gt(cs, resolved_left, resolved_right, &span),
|
||||
@ -109,114 +87,71 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
}
|
||||
|
||||
// Unary operations
|
||||
Expression::Unary(UnaryExpression { inner, op, span }) => match op {
|
||||
Expression::Unary(UnaryExpression { inner, operation, .. }) => match operation {
|
||||
UnaryOperation::Negate => {
|
||||
let resolved_inner =
|
||||
self.enforce_expression(cs, file_scope, function_scope, expected_type, *inner)?;
|
||||
let resolved_inner = self.enforce_expression(cs, inner)?;
|
||||
enforce_negate(cs, resolved_inner, &span)
|
||||
}
|
||||
UnaryOperation::Not => Ok(evaluate_not(
|
||||
self.enforce_operand(cs, file_scope, function_scope, expected_type, *inner, &span)?,
|
||||
span,
|
||||
)?),
|
||||
UnaryOperation::Not => Ok(evaluate_not(self.enforce_operand(cs, inner)?, &span)?),
|
||||
},
|
||||
|
||||
Expression::Ternary(TernaryExpression {
|
||||
condition,
|
||||
if_true,
|
||||
if_false,
|
||||
span,
|
||||
}) => self.enforce_conditional_expression(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
expected_type,
|
||||
*condition,
|
||||
*if_true,
|
||||
*if_false,
|
||||
&span,
|
||||
),
|
||||
..
|
||||
}) => self.enforce_conditional_expression(cs, condition, if_true, if_false, &span),
|
||||
|
||||
// Arrays
|
||||
Expression::ArrayInline(ArrayInlineExpression { elements, span }) => {
|
||||
self.enforce_array(cs, file_scope, function_scope, expected_type, elements, span)
|
||||
Expression::ArrayInline(ArrayInlineExpression { elements, .. }) => self.enforce_array(cs, elements, span),
|
||||
Expression::ArrayInit(ArrayInitExpression { element, len, .. }) => {
|
||||
self.enforce_array_initializer(cs, element, *len)
|
||||
}
|
||||
Expression::ArrayInit(ArrayInitExpression {
|
||||
element,
|
||||
dimensions,
|
||||
span,
|
||||
}) => self.enforce_array_initializer(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
expected_type,
|
||||
*element,
|
||||
dimensions,
|
||||
span,
|
||||
),
|
||||
Expression::ArrayAccess(ArrayAccessExpression { array, index, span }) => {
|
||||
self.enforce_array_access(cs, file_scope, function_scope, expected_type, *array, *index, &span)
|
||||
Expression::ArrayAccess(ArrayAccessExpression { array, index, .. }) => {
|
||||
self.enforce_array_access(cs, array, index, &span)
|
||||
}
|
||||
Expression::ArrayRangeAccess(ArrayRangeAccessExpression { array, left, right, .. }) => {
|
||||
self.enforce_array_range_access(cs, array, left.as_ref(), right.as_ref(), &span)
|
||||
}
|
||||
Expression::ArrayRangeAccess(ArrayRangeAccessExpression {
|
||||
array,
|
||||
left,
|
||||
right,
|
||||
span,
|
||||
}) => self.enforce_array_range_access(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
expected_type,
|
||||
*array,
|
||||
left.map(|x| *x),
|
||||
right.map(|x| *x),
|
||||
&span,
|
||||
),
|
||||
|
||||
// Tuples
|
||||
Expression::TupleInit(TupleInitExpression { elements, span }) => {
|
||||
self.enforce_tuple(cs, file_scope, function_scope, expected_type, elements, span)
|
||||
}
|
||||
Expression::TupleAccess(TupleAccessExpression { tuple, index, span }) => {
|
||||
self.enforce_tuple_access(cs, file_scope, function_scope, expected_type, *tuple, index, &span)
|
||||
Expression::TupleInit(TupleInitExpression { elements, .. }) => self.enforce_tuple(cs, elements),
|
||||
Expression::TupleAccess(TupleAccessExpression { tuple_ref, index, .. }) => {
|
||||
self.enforce_tuple_access(cs, tuple_ref, *index, &span)
|
||||
}
|
||||
|
||||
// Circuits
|
||||
Expression::CircuitInit(CircuitInitExpression { name, members, span }) => {
|
||||
self.enforce_circuit(cs, file_scope, function_scope, name, members, span)
|
||||
}
|
||||
Expression::CircuitMemberAccess(CircuitMemberAccessExpression { circuit, name, span }) => {
|
||||
self.enforce_circuit_access(cs, file_scope, function_scope, expected_type, *circuit, name, span)
|
||||
}
|
||||
Expression::CircuitStaticFunctionAccess(CircuitStaticFunctionAccessExpression { circuit, name, span }) => {
|
||||
self.enforce_circuit_static_access(cs, file_scope, function_scope, expected_type, *circuit, name, span)
|
||||
}
|
||||
Expression::CircuitInit(expr) => self.enforce_circuit(cs, expr, &span),
|
||||
Expression::CircuitAccess(expr) => self.enforce_circuit_access(cs, expr),
|
||||
|
||||
// Functions
|
||||
Expression::Call(CallExpression {
|
||||
function,
|
||||
target,
|
||||
arguments,
|
||||
span,
|
||||
}) => match *function {
|
||||
Expression::Identifier(id) if id.is_core() => self.enforce_core_circuit_call_expression(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
expected_type,
|
||||
id.name,
|
||||
arguments,
|
||||
span,
|
||||
),
|
||||
function => self.enforce_function_call_expression(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
expected_type,
|
||||
function,
|
||||
arguments,
|
||||
span,
|
||||
),
|
||||
},
|
||||
..
|
||||
}) => {
|
||||
if let Some(circuit) = function
|
||||
.circuit
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.map(|x| x.upgrade().expect("stale circuit for member function"))
|
||||
{
|
||||
let core_mapping = circuit.core_mapping.borrow();
|
||||
if let Some(core_mapping) = core_mapping.as_deref() {
|
||||
let core_circuit = resolve_core_circuit::<F, G>(core_mapping);
|
||||
return self.enforce_core_circuit_call_expression(
|
||||
cs,
|
||||
&core_circuit,
|
||||
&function,
|
||||
target.as_ref(),
|
||||
arguments,
|
||||
&span,
|
||||
);
|
||||
}
|
||||
}
|
||||
self.enforce_function_call_expression(cs, &function, target.as_ref(), arguments, &span)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -13,61 +13,48 @@
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
use crate::{program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use crate::{program::ConstrainedProgram, value::ConstrainedValue, CoreCircuit, GroupType};
|
||||
|
||||
use crate::errors::{ExpressionError, FunctionError};
|
||||
use leo_ast::{Expression, Span, Type};
|
||||
use leo_core::call_core_circuit;
|
||||
use crate::errors::ExpressionError;
|
||||
use leo_asg::{Expression, Function, Span};
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
gadgets::r1cs::ConstraintSystem,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
/// Call a default core circuit function with arguments
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn enforce_core_circuit_call_expression<CS: ConstraintSystem<F>>(
|
||||
pub fn enforce_core_circuit_call_expression<CS: ConstraintSystem<F>, C: CoreCircuit<F, G>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
expected_type: Option<Type>,
|
||||
core_circuit: String,
|
||||
arguments: Vec<Expression>,
|
||||
span: Span,
|
||||
core_circuit: &C,
|
||||
function: &Arc<Function>,
|
||||
target: Option<&Arc<Expression>>,
|
||||
arguments: &[Arc<Expression>],
|
||||
span: &Span,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
// Get the value of each core function argument
|
||||
let mut argument_values = Vec::with_capacity(arguments.len());
|
||||
for argument in arguments.into_iter() {
|
||||
let argument_value = self.enforce_expression(cs, file_scope, function_scope, None, argument)?;
|
||||
let core_function_argument = argument_value.to_value();
|
||||
let function = function
|
||||
.body
|
||||
.borrow()
|
||||
.upgrade()
|
||||
.expect("stale function in call expression");
|
||||
|
||||
argument_values.push(core_function_argument);
|
||||
}
|
||||
|
||||
// Call the core function in `leo-core`
|
||||
let res = call_core_circuit(cs, core_circuit, argument_values, span.clone())?;
|
||||
|
||||
// Convert the core function returns into constrained values
|
||||
let returns = res.into_iter().map(ConstrainedValue::from).collect::<Vec<_>>();
|
||||
|
||||
let return_value = if returns.len() == 1 {
|
||||
// The function has a single return
|
||||
returns[0].clone()
|
||||
let target_value = if let Some(target) = target {
|
||||
Some(self.enforce_expression(cs, target)?)
|
||||
} else {
|
||||
// The function has multiple returns
|
||||
ConstrainedValue::Tuple(returns)
|
||||
None
|
||||
};
|
||||
|
||||
// Check that function returns expected type
|
||||
if let Some(expected) = expected_type {
|
||||
let actual = return_value.to_type(&span)?;
|
||||
if expected.ne(&actual) {
|
||||
return Err(ExpressionError::FunctionError(Box::new(
|
||||
FunctionError::return_argument_type(expected.to_string(), actual.to_string(), span),
|
||||
)));
|
||||
}
|
||||
}
|
||||
// Get the value of each core function argument
|
||||
let arguments = arguments
|
||||
.iter()
|
||||
.map(|argument| self.enforce_expression(cs, argument))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
// Call the core function
|
||||
let return_value = core_circuit.call_function(cs, function, span, target_value, arguments)?;
|
||||
|
||||
Ok(return_value)
|
||||
}
|
||||
|
@ -16,8 +16,9 @@
|
||||
|
||||
//! Enforce a function call expression in a compiled Leo program.
|
||||
|
||||
use crate::{errors::ExpressionError, new_scope, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::{expression::CircuitMemberAccessExpression, Expression, Span, Type};
|
||||
use crate::{errors::ExpressionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_asg::{Expression, Function, Span};
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -29,51 +30,29 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_function_call_expression<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
expected_type: Option<Type>,
|
||||
function: Expression,
|
||||
arguments: Vec<Expression>,
|
||||
span: Span,
|
||||
function: &Arc<Function>,
|
||||
target: Option<&Arc<Expression>>,
|
||||
arguments: &[Arc<Expression>],
|
||||
span: &Span,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
let (declared_circuit_reference, function_value) = match function {
|
||||
Expression::CircuitMemberAccess(CircuitMemberAccessExpression { circuit, name, span }) => {
|
||||
// Call a circuit function that can mutate self.
|
||||
|
||||
// Save a reference to the circuit we are mutating.
|
||||
let circuit_id_string = circuit.to_string();
|
||||
let declared_circuit_reference = new_scope(function_scope, &circuit_id_string);
|
||||
|
||||
(
|
||||
declared_circuit_reference,
|
||||
self.enforce_circuit_access(cs, file_scope, function_scope, expected_type, *circuit, name, span)?,
|
||||
)
|
||||
}
|
||||
function => (
|
||||
function_scope.to_string(),
|
||||
self.enforce_expression(cs, file_scope, function_scope, expected_type, function)?,
|
||||
),
|
||||
};
|
||||
|
||||
let (outer_scope, function_call) = function_value.extract_function(file_scope, &span)?;
|
||||
|
||||
let name_unique = || {
|
||||
format!(
|
||||
"function call {} {}:{}",
|
||||
function_call.get_name(),
|
||||
function.name.borrow().clone(),
|
||||
span.line,
|
||||
span.start,
|
||||
)
|
||||
};
|
||||
let function = function
|
||||
.body
|
||||
.borrow()
|
||||
.upgrade()
|
||||
.expect("stale function in call expression");
|
||||
|
||||
self.enforce_function(
|
||||
&mut cs.ns(name_unique),
|
||||
&outer_scope,
|
||||
function_scope,
|
||||
function_call,
|
||||
arguments,
|
||||
&declared_circuit_reference,
|
||||
)
|
||||
.map_err(|error| ExpressionError::from(Box::new(error)))
|
||||
let return_value = self
|
||||
.enforce_function(&mut cs.ns(name_unique), &function, target, arguments)
|
||||
.map_err(|error| ExpressionError::from(Box::new(error)))?;
|
||||
|
||||
Ok(return_value)
|
||||
}
|
||||
}
|
||||
|
@ -1,65 +0,0 @@
|
||||
// Copyright (C) 2019-2021 Aleo Systems Inc.
|
||||
// This file is part of the Leo library.
|
||||
|
||||
// The Leo library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// The Leo library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
//! Enforces an identifier expression in a compiled Leo program.
|
||||
|
||||
use crate::{
|
||||
errors::ExpressionError,
|
||||
program::{new_scope, ConstrainedProgram},
|
||||
value::ConstrainedValue,
|
||||
Address,
|
||||
GroupType,
|
||||
};
|
||||
use leo_ast::{Identifier, Type};
|
||||
|
||||
use snarkvm_models::curves::{Field, PrimeField};
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
/// Enforce a variable expression by getting the resolved value
|
||||
pub fn evaluate_identifier(
|
||||
&mut self,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
expected_type: Option<Type>,
|
||||
unresolved_identifier: Identifier,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
// Evaluate the identifier name in the current function scope
|
||||
let variable_name = new_scope(function_scope, &unresolved_identifier.name);
|
||||
let identifier_name = new_scope(file_scope, &unresolved_identifier.name);
|
||||
|
||||
let mut result_value = if let Some(value) = self.get(&variable_name) {
|
||||
// Reassigning variable to another variable
|
||||
value.clone()
|
||||
} else if let Some(value) = self.get(&identifier_name) {
|
||||
// Check global scope (function and circuit names)
|
||||
value.clone()
|
||||
} else if let Some(value) = self.get(&unresolved_identifier.name) {
|
||||
// Check imported file scope
|
||||
value.clone()
|
||||
} else if expected_type == Some(Type::Address) {
|
||||
// If we expect an address type, try to return an address
|
||||
let address = Address::constant(unresolved_identifier.name, &unresolved_identifier.span)?;
|
||||
|
||||
return Ok(ConstrainedValue::Address(address));
|
||||
} else {
|
||||
return Err(ExpressionError::undefined_identifier(unresolved_identifier));
|
||||
};
|
||||
|
||||
result_value.resolve_type(expected_type, &unresolved_identifier.span)?;
|
||||
|
||||
Ok(result_value)
|
||||
}
|
||||
}
|
@ -17,7 +17,7 @@
|
||||
//! Enforces a logical `&&` operator in a resolved Leo program.
|
||||
|
||||
use crate::{errors::BooleanError, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::Span;
|
||||
use leo_asg::Span;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
|
@ -17,16 +17,16 @@
|
||||
//! Enforces a logical `!` operator in a resolved Leo program.
|
||||
|
||||
use crate::{errors::BooleanError, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::Span;
|
||||
use leo_asg::Span;
|
||||
|
||||
use snarkvm_models::curves::{Field, PrimeField};
|
||||
|
||||
pub fn evaluate_not<F: Field + PrimeField, G: GroupType<F>>(
|
||||
value: ConstrainedValue<F, G>,
|
||||
span: Span,
|
||||
span: &Span,
|
||||
) -> Result<ConstrainedValue<F, G>, BooleanError> {
|
||||
match value {
|
||||
ConstrainedValue::Boolean(boolean) => Ok(ConstrainedValue::Boolean(boolean.not())),
|
||||
value => Err(BooleanError::cannot_evaluate(format!("!{}", value), span)),
|
||||
value => Err(BooleanError::cannot_evaluate(format!("!{}", value), span.clone())),
|
||||
}
|
||||
}
|
||||
|
@ -17,7 +17,7 @@
|
||||
//! Enforces a logical `||` operator in a resolved Leo program.
|
||||
|
||||
use crate::{errors::BooleanError, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::Span;
|
||||
use leo_asg::Span;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
|
@ -37,8 +37,8 @@ pub use self::expression::*;
|
||||
pub mod function;
|
||||
pub use self::function::*;
|
||||
|
||||
pub mod identifier;
|
||||
pub use self::identifier::*;
|
||||
pub mod variable_ref;
|
||||
pub use self::variable_ref::*;
|
||||
|
||||
pub mod logical;
|
||||
pub use self::logical::*;
|
||||
|
@ -17,7 +17,7 @@
|
||||
//! Enforces a relational `==` operator in a resolved Leo program.
|
||||
|
||||
use crate::{enforce_and, errors::ExpressionError, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::Span;
|
||||
use leo_asg::Span;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -74,16 +74,6 @@ pub fn evaluate_eq<F: Field + PrimeField, G: GroupType<F>, CS: ConstraintSystem<
|
||||
}
|
||||
return Ok(current);
|
||||
}
|
||||
(ConstrainedValue::Unresolved(string), val_2) => {
|
||||
let mut unique_namespace = cs.ns(|| namespace_string);
|
||||
let val_1 = ConstrainedValue::from_other(string, &val_2, span)?;
|
||||
return evaluate_eq(&mut unique_namespace, val_1, val_2, span);
|
||||
}
|
||||
(val_1, ConstrainedValue::Unresolved(string)) => {
|
||||
let mut unique_namespace = cs.ns(|| namespace_string);
|
||||
let val_2 = ConstrainedValue::from_other(string, &val_1, span)?;
|
||||
return evaluate_eq(&mut unique_namespace, val_1, val_2, span);
|
||||
}
|
||||
(val_1, val_2) => {
|
||||
return Err(ExpressionError::incompatible_types(
|
||||
format!("{} == {}", val_1, val_2,),
|
||||
|
@ -17,7 +17,7 @@
|
||||
//! Enforces a relational `>=` operator in a resolved Leo program.
|
||||
|
||||
use crate::{errors::ExpressionError, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::Span;
|
||||
use leo_asg::Span;
|
||||
use leo_gadgets::bits::ComparatorGadget;
|
||||
|
||||
use snarkvm_models::{
|
||||
@ -31,19 +31,11 @@ pub fn evaluate_ge<F: Field + PrimeField, G: GroupType<F>, CS: ConstraintSystem<
|
||||
right: ConstrainedValue<F, G>,
|
||||
span: &Span,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
let mut unique_namespace = cs.ns(|| format!("evaluate {} >= {} {}:{}", left, right, span.line, span.start));
|
||||
let unique_namespace = cs.ns(|| format!("evaluate {} >= {} {}:{}", left, right, span.line, span.start));
|
||||
let constraint_result = match (left, right) {
|
||||
(ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => {
|
||||
num_1.greater_than_or_equal(unique_namespace, &num_2)
|
||||
}
|
||||
(ConstrainedValue::Unresolved(string), val_2) => {
|
||||
let val_1 = ConstrainedValue::from_other(string, &val_2, span)?;
|
||||
return evaluate_ge(&mut unique_namespace, val_1, val_2, span);
|
||||
}
|
||||
(val_1, ConstrainedValue::Unresolved(string)) => {
|
||||
let val_2 = ConstrainedValue::from_other(string, &val_1, span)?;
|
||||
return evaluate_ge(&mut unique_namespace, val_1, val_2, span);
|
||||
}
|
||||
(val_1, val_2) => {
|
||||
return Err(ExpressionError::incompatible_types(
|
||||
format!("{} >= {}", val_1, val_2),
|
||||
|
@ -17,7 +17,7 @@
|
||||
//! Enforces a relational `>` operator in a resolved Leo program.
|
||||
|
||||
use crate::{errors::ExpressionError, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::Span;
|
||||
use leo_asg::Span;
|
||||
use leo_gadgets::bits::ComparatorGadget;
|
||||
|
||||
use snarkvm_models::{
|
||||
@ -31,19 +31,11 @@ pub fn evaluate_gt<F: Field + PrimeField, G: GroupType<F>, CS: ConstraintSystem<
|
||||
right: ConstrainedValue<F, G>,
|
||||
span: &Span,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
let mut unique_namespace = cs.ns(|| format!("evaluate {} > {} {}:{}", left, right, span.line, span.start));
|
||||
let unique_namespace = cs.ns(|| format!("evaluate {} > {} {}:{}", left, right, span.line, span.start));
|
||||
let constraint_result = match (left, right) {
|
||||
(ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => {
|
||||
num_1.greater_than(unique_namespace, &num_2)
|
||||
}
|
||||
(ConstrainedValue::Unresolved(string), val_2) => {
|
||||
let val_1 = ConstrainedValue::from_other(string, &val_2, span)?;
|
||||
return evaluate_gt(&mut unique_namespace, val_1, val_2, span);
|
||||
}
|
||||
(val_1, ConstrainedValue::Unresolved(string)) => {
|
||||
let val_2 = ConstrainedValue::from_other(string, &val_1, span)?;
|
||||
return evaluate_gt(&mut unique_namespace, val_1, val_2, span);
|
||||
}
|
||||
(val_1, val_2) => {
|
||||
return Err(ExpressionError::incompatible_types(
|
||||
format!("{} > {}", val_1, val_2),
|
||||
|
@ -17,7 +17,7 @@
|
||||
//! Enforces a relational `<=` operator in a resolved Leo program.
|
||||
|
||||
use crate::{errors::ExpressionError, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::Span;
|
||||
use leo_asg::Span;
|
||||
use leo_gadgets::bits::ComparatorGadget;
|
||||
|
||||
use snarkvm_models::{
|
||||
@ -31,19 +31,11 @@ pub fn evaluate_le<F: Field + PrimeField, G: GroupType<F>, CS: ConstraintSystem<
|
||||
right: ConstrainedValue<F, G>,
|
||||
span: &Span,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
let mut unique_namespace = cs.ns(|| format!("evaluate {} <= {} {}:{}", left, right, span.line, span.start));
|
||||
let unique_namespace = cs.ns(|| format!("evaluate {} <= {} {}:{}", left, right, span.line, span.start));
|
||||
let constraint_result = match (left, right) {
|
||||
(ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => {
|
||||
num_1.less_than_or_equal(unique_namespace, &num_2)
|
||||
}
|
||||
(ConstrainedValue::Unresolved(string), val_2) => {
|
||||
let val_1 = ConstrainedValue::from_other(string, &val_2, span)?;
|
||||
return evaluate_le(&mut unique_namespace, val_1, val_2, span);
|
||||
}
|
||||
(val_1, ConstrainedValue::Unresolved(string)) => {
|
||||
let val_2 = ConstrainedValue::from_other(string, &val_1, span)?;
|
||||
return evaluate_le(&mut unique_namespace, val_1, val_2, span);
|
||||
}
|
||||
(val_1, val_2) => {
|
||||
return Err(ExpressionError::incompatible_types(
|
||||
format!("{} <= {}", val_1, val_2),
|
||||
|
@ -17,7 +17,7 @@
|
||||
//! Enforces a relational `<` operator in a resolved Leo program.
|
||||
|
||||
use crate::{errors::ExpressionError, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::Span;
|
||||
use leo_asg::Span;
|
||||
use leo_gadgets::bits::comparator::EvaluateLtGadget;
|
||||
|
||||
use snarkvm_models::{
|
||||
@ -31,19 +31,11 @@ pub fn evaluate_lt<F: Field + PrimeField, G: GroupType<F>, CS: ConstraintSystem<
|
||||
right: ConstrainedValue<F, G>,
|
||||
span: &Span,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
let mut unique_namespace = cs.ns(|| format!("evaluate {} < {} {}:{}", left, right, span.line, span.start));
|
||||
let unique_namespace = cs.ns(|| format!("evaluate {} < {} {}:{}", left, right, span.line, span.start));
|
||||
let constraint_result = match (left, right) {
|
||||
(ConstrainedValue::Integer(num_1), ConstrainedValue::Integer(num_2)) => {
|
||||
num_1.less_than(unique_namespace, &num_2)
|
||||
}
|
||||
(ConstrainedValue::Unresolved(string), val_2) => {
|
||||
let val_1 = ConstrainedValue::from_other(string, &val_2, span)?;
|
||||
return evaluate_lt(&mut unique_namespace, val_1, val_2, span);
|
||||
}
|
||||
(val_1, ConstrainedValue::Unresolved(string)) => {
|
||||
let val_2 = ConstrainedValue::from_other(string, &val_1, span)?;
|
||||
return evaluate_lt(&mut unique_namespace, val_1, val_2, span);
|
||||
}
|
||||
(val_1, val_2) => {
|
||||
return Err(ExpressionError::incompatible_types(
|
||||
format!("{} < {}", val_1, val_2),
|
||||
|
@ -16,8 +16,9 @@
|
||||
|
||||
//! Enforces array access in a compiled Leo program.
|
||||
|
||||
use crate::{errors::ExpressionError, parse_index, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::{Expression, PositiveNumber, Span, Type};
|
||||
use crate::{errors::ExpressionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_asg::{Expression, Span};
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -29,27 +30,22 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_tuple_access<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
expected_type: Option<Type>,
|
||||
tuple: Expression,
|
||||
index: PositiveNumber,
|
||||
tuple: &Arc<Expression>,
|
||||
index: usize,
|
||||
span: &Span,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
// Get the tuple values.
|
||||
let tuple = match self.enforce_operand(cs, file_scope, function_scope, expected_type, tuple, &span)? {
|
||||
let tuple = match self.enforce_operand(cs, tuple)? {
|
||||
ConstrainedValue::Tuple(tuple) => tuple,
|
||||
value => return Err(ExpressionError::undefined_array(value.to_string(), span.to_owned())),
|
||||
};
|
||||
|
||||
// Parse the tuple index.
|
||||
let index_usize = parse_index(&index, &span)?;
|
||||
|
||||
// Check for out of bounds access.
|
||||
if index_usize > tuple.len() - 1 {
|
||||
return Err(ExpressionError::index_out_of_bounds(index_usize, span.to_owned()));
|
||||
if index > tuple.len() - 1 {
|
||||
// probably safe to be a panic here
|
||||
return Err(ExpressionError::index_out_of_bounds(index, span.to_owned()));
|
||||
}
|
||||
|
||||
Ok(tuple[index_usize].to_owned())
|
||||
Ok(tuple[index].to_owned())
|
||||
}
|
||||
}
|
||||
|
@ -17,7 +17,8 @@
|
||||
//! Enforces an tuple expression in a compiled Leo program.
|
||||
|
||||
use crate::{errors::ExpressionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::{Expression, Span, Type};
|
||||
use leo_asg::Expression;
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -29,38 +30,11 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_tuple<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
expected_type: Option<Type>,
|
||||
tuple: Vec<Expression>,
|
||||
span: Span,
|
||||
tuple: &[Arc<Expression>],
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
// Check explicit tuple type dimension if given
|
||||
let mut expected_types = vec![];
|
||||
|
||||
match expected_type {
|
||||
Some(Type::Tuple(ref types)) => {
|
||||
expected_types = types.clone();
|
||||
}
|
||||
Some(ref type_) => {
|
||||
return Err(ExpressionError::unexpected_tuple(
|
||||
type_.to_string(),
|
||||
format!("{:?}", tuple),
|
||||
span,
|
||||
));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
let mut result = Vec::with_capacity(tuple.len());
|
||||
for (i, expression) in tuple.into_iter().enumerate() {
|
||||
let type_ = if expected_types.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(expected_types[i].clone())
|
||||
};
|
||||
|
||||
result.push(self.enforce_expression(cs, file_scope, function_scope, type_, expression)?);
|
||||
for expression in tuple.iter() {
|
||||
result.push(self.enforce_expression(cs, expression)?);
|
||||
}
|
||||
|
||||
Ok(ConstrainedValue::Tuple(result))
|
||||
|
@ -16,5 +16,5 @@
|
||||
|
||||
//! Methods to enforce identifier expressions in a compiled Leo program.
|
||||
|
||||
pub mod identifier;
|
||||
pub use self::identifier::*;
|
||||
pub mod variable_ref;
|
||||
pub use self::variable_ref::*;
|
@ -14,27 +14,24 @@
|
||||
// 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::{new_scope, ConstrainedProgram, ConstrainedValue, GroupType};
|
||||
use leo_ast::Package;
|
||||
//! Enforces an identifier expression in a compiled Leo program.
|
||||
|
||||
use crate::{errors::ExpressionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_asg::VariableRef;
|
||||
|
||||
use leo_core::{CorePackageList, LeoCorePackageError};
|
||||
use snarkvm_models::curves::{Field, PrimeField};
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub(crate) fn store_core_package(&mut self, scope: &str, package: Package) -> Result<(), LeoCorePackageError> {
|
||||
// Create list of imported core packages.
|
||||
let list = CorePackageList::from_package_access(package.access)?;
|
||||
/// Enforce a variable expression by getting the resolved value
|
||||
pub fn evaluate_ref(&mut self, variable_ref: &VariableRef) -> Result<ConstrainedValue<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) {
|
||||
value.clone()
|
||||
} else {
|
||||
return Err(ExpressionError::undefined_identifier(variable.name.clone())); // todo: probably can be a panic here instead
|
||||
};
|
||||
|
||||
// Fetch core packages from `leo-core`.
|
||||
let symbol_list = list.to_symbols()?;
|
||||
|
||||
for (symbol, circuit) in symbol_list.symbols() {
|
||||
let symbol_name = new_scope(scope, symbol);
|
||||
|
||||
// store packages
|
||||
self.store(symbol_name, ConstrainedValue::CircuitDefinition(circuit.to_owned()))
|
||||
}
|
||||
|
||||
Ok(())
|
||||
Ok(result_value)
|
||||
}
|
||||
}
|
@ -16,14 +16,10 @@
|
||||
|
||||
//! Enforces constraints on a function in a compiled Leo program.
|
||||
|
||||
use crate::{
|
||||
errors::FunctionError,
|
||||
program::{new_scope, ConstrainedProgram},
|
||||
value::ConstrainedValue,
|
||||
GroupType,
|
||||
};
|
||||
use crate::{errors::FunctionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
|
||||
use leo_ast::{Expression, Function, FunctionInput};
|
||||
use leo_asg::{Expression, FunctionBody, FunctionQualifier};
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -34,83 +30,77 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub(crate) fn enforce_function<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
scope: &str,
|
||||
caller_scope: &str,
|
||||
function: Function,
|
||||
input: Vec<Expression>,
|
||||
declared_circuit_reference: &str,
|
||||
function: &Arc<FunctionBody>,
|
||||
target: Option<&Arc<Expression>>,
|
||||
arguments: &[Arc<Expression>],
|
||||
) -> Result<ConstrainedValue<F, G>, FunctionError> {
|
||||
let function_name = new_scope(scope, function.get_name());
|
||||
let target_value = if let Some(target) = target {
|
||||
Some(self.enforce_expression(cs, target)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Store if function contains input `mut self`.
|
||||
let mut_self = function.contains_mut_self();
|
||||
let self_var = if let Some(target) = &target_value {
|
||||
let self_var = function
|
||||
.scope
|
||||
.borrow()
|
||||
.resolve_variable("self")
|
||||
.expect("attempted to call static function from non-static context");
|
||||
self.store(self_var.borrow().id, target.clone());
|
||||
Some(self_var)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if function.arguments.len() != arguments.len() {
|
||||
return Err(FunctionError::input_not_found(
|
||||
"arguments length invalid".to_string(),
|
||||
function.span.clone().unwrap_or_default(),
|
||||
));
|
||||
}
|
||||
|
||||
// Store input values as new variables in resolved program
|
||||
for (input_model, input_expression) in function.filter_self_inputs().zip(input.into_iter()) {
|
||||
let (name, value) = match input_model {
|
||||
FunctionInput::InputKeyword(keyword) => {
|
||||
let value =
|
||||
self.enforce_function_input(cs, scope, caller_scope, &function_name, None, input_expression)?;
|
||||
for (variable, input_expression) in function.arguments.iter().zip(arguments.iter()) {
|
||||
let mut input_value = self.enforce_expression(cs, input_expression)?;
|
||||
let variable = variable.borrow();
|
||||
|
||||
(keyword.to_string(), value)
|
||||
}
|
||||
FunctionInput::SelfKeyword(keyword) => {
|
||||
let value =
|
||||
self.enforce_function_input(cs, scope, caller_scope, &function_name, None, input_expression)?;
|
||||
if variable.mutable {
|
||||
input_value = ConstrainedValue::Mutable(Box::new(input_value))
|
||||
}
|
||||
|
||||
(keyword.to_string(), value)
|
||||
}
|
||||
FunctionInput::MutSelfKeyword(keyword) => {
|
||||
let value =
|
||||
self.enforce_function_input(cs, scope, caller_scope, &function_name, None, input_expression)?;
|
||||
|
||||
(keyword.to_string(), value)
|
||||
}
|
||||
FunctionInput::Variable(input_model) => {
|
||||
// First evaluate input expression
|
||||
let mut input_value = self.enforce_function_input(
|
||||
cs,
|
||||
scope,
|
||||
caller_scope,
|
||||
&function_name,
|
||||
Some(input_model.type_.clone()),
|
||||
input_expression,
|
||||
)?;
|
||||
|
||||
if input_model.mutable {
|
||||
input_value = ConstrainedValue::Mutable(Box::new(input_value))
|
||||
}
|
||||
|
||||
(input_model.identifier.name.clone(), input_value)
|
||||
}
|
||||
};
|
||||
|
||||
// Store input as variable with {function_name}_{input_name}
|
||||
let input_program_identifier = new_scope(&function_name, &name);
|
||||
self.store(input_program_identifier, value);
|
||||
self.store(variable.id, input_value);
|
||||
}
|
||||
|
||||
// Evaluate every statement in the function and save all potential results
|
||||
let mut results = vec![];
|
||||
let indicator = Boolean::constant(true);
|
||||
|
||||
for statement in function.block.statements.iter() {
|
||||
let mut result = self.enforce_statement(
|
||||
cs,
|
||||
scope,
|
||||
&function_name,
|
||||
&indicator,
|
||||
statement.clone(),
|
||||
function.output.clone(),
|
||||
declared_circuit_reference,
|
||||
mut_self,
|
||||
)?;
|
||||
let output = function.function.output.clone().strong();
|
||||
|
||||
results.append(&mut result);
|
||||
let mut result = self.enforce_statement(cs, &indicator, &function.body)?;
|
||||
|
||||
results.append(&mut result);
|
||||
|
||||
if function.function.qualifier == FunctionQualifier::MutSelfRef {
|
||||
if let (Some(self_var), Some(target)) = (self_var, target) {
|
||||
let new_self = self
|
||||
.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)? {
|
||||
if assignable_target.len() != 1 {
|
||||
panic!("found tuple as a self assignment target");
|
||||
}
|
||||
let assignable_target = assignable_target.into_iter().next().unwrap();
|
||||
*assignable_target = new_self;
|
||||
} else {
|
||||
// todo: we should report a warning for calling a mutable function on an effectively copied self (i.e. wasn't assignable `tempStruct {x: 5}.myMutSelfFunction()`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Conditionally select a result based on returned indicators
|
||||
Self::conditionally_select_result(cs, function.output, results, &function.span)
|
||||
Self::conditionally_select_result(cs, &output, results, &function.span.clone().unwrap_or_default())
|
||||
.map_err(FunctionError::StatementError)
|
||||
}
|
||||
}
|
||||
|
@ -16,18 +16,11 @@
|
||||
|
||||
//! Allocates an array as a main function input parameter in a compiled Leo program.
|
||||
|
||||
use crate::{
|
||||
errors::FunctionError,
|
||||
inner_array_type,
|
||||
parse_index,
|
||||
program::{new_scope, ConstrainedProgram},
|
||||
value::ConstrainedValue,
|
||||
GroupType,
|
||||
};
|
||||
use crate::{errors::FunctionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
|
||||
use leo_ast::{ArrayDimensions, InputValue, Span, Type};
|
||||
use leo_asg::Type;
|
||||
use leo_ast::{InputValue, Span};
|
||||
|
||||
use crate::errors::ExpressionError;
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
gadgets::r1cs::ConstraintSystem,
|
||||
@ -38,27 +31,11 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
name: &str,
|
||||
array_type: Type,
|
||||
mut array_dimensions: ArrayDimensions,
|
||||
array_type: &Type,
|
||||
array_len: usize,
|
||||
input_value: Option<InputValue>,
|
||||
span: &Span,
|
||||
) -> Result<ConstrainedValue<F, G>, FunctionError> {
|
||||
let expected_length = match array_dimensions.remove_first() {
|
||||
Some(number) => {
|
||||
// Parse the array dimension into a `usize`.
|
||||
parse_index(&number, &span)?
|
||||
}
|
||||
None => {
|
||||
return Err(FunctionError::ExpressionError(ExpressionError::unexpected_array(
|
||||
array_type.to_string(),
|
||||
span.to_owned(),
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
// Get the expected type for each array element.
|
||||
let inner_array_type = inner_array_type(array_type, array_dimensions);
|
||||
|
||||
// Build the array value using the expected types.
|
||||
let mut array_value = vec![];
|
||||
|
||||
@ -66,11 +43,11 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
Some(InputValue::Array(arr)) => {
|
||||
// Allocate each value in the current row
|
||||
for (i, value) in arr.into_iter().enumerate() {
|
||||
let value_name = new_scope(&name, &i.to_string());
|
||||
let value_name = format!("{}_{}", &name, &i.to_string());
|
||||
|
||||
array_value.push(self.allocate_main_function_input(
|
||||
cs,
|
||||
inner_array_type.clone(),
|
||||
array_type,
|
||||
&value_name,
|
||||
Some(value),
|
||||
span,
|
||||
@ -79,16 +56,10 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
}
|
||||
None => {
|
||||
// Allocate all row values as none
|
||||
for i in 0..expected_length {
|
||||
let value_name = new_scope(&name, &i.to_string());
|
||||
for i in 0..array_len {
|
||||
let value_name = format!("{}_{}", &name, &i.to_string());
|
||||
|
||||
array_value.push(self.allocate_main_function_input(
|
||||
cs,
|
||||
inner_array_type.clone(),
|
||||
&value_name,
|
||||
None,
|
||||
span,
|
||||
)?);
|
||||
array_value.push(self.allocate_main_function_input(cs, array_type, &value_name, None, span)?);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
|
@ -1,47 +0,0 @@
|
||||
// Copyright (C) 2019-2021 Aleo Systems Inc.
|
||||
// This file is part of the Leo library.
|
||||
|
||||
// The Leo library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// The Leo library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
//! Enforces a function input parameter in a compiled Leo program.
|
||||
|
||||
use crate::{errors::FunctionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
|
||||
use leo_ast::{Expression, Type};
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
gadgets::r1cs::ConstraintSystem,
|
||||
};
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_function_input<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
scope: &str,
|
||||
caller_scope: &str,
|
||||
function_name: &str,
|
||||
expected_type: Option<Type>,
|
||||
input: Expression,
|
||||
) -> Result<ConstrainedValue<F, G>, FunctionError> {
|
||||
// Evaluate the function input value as pass by value from the caller or
|
||||
// evaluate as an expression in the current function scope
|
||||
match input {
|
||||
Expression::Identifier(identifier) => {
|
||||
Ok(self.evaluate_identifier(caller_scope, function_name, expected_type, identifier)?)
|
||||
}
|
||||
expression => Ok(self.enforce_expression(cs, scope, function_name, expected_type, expression)?),
|
||||
}
|
||||
}
|
||||
}
|
@ -15,7 +15,9 @@
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::{errors::FunctionError, ConstrainedCircuitMember, ConstrainedProgram, ConstrainedValue, GroupType};
|
||||
use leo_ast::{Identifier, Input, InputKeyword};
|
||||
use leo_asg::{CircuitBody, CircuitMemberBody, Type};
|
||||
use leo_ast::{Identifier, Input, Span};
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -31,26 +33,27 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn allocate_input_keyword<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
keyword: InputKeyword,
|
||||
span: Span,
|
||||
expected_type: &Arc<CircuitBody>,
|
||||
input: &Input,
|
||||
) -> Result<ConstrainedValue<F, G>, FunctionError> {
|
||||
// Create an identifier for each input variable
|
||||
|
||||
let registers_name = Identifier {
|
||||
name: REGISTERS_VARIABLE_NAME.to_string(),
|
||||
span: keyword.span.clone(),
|
||||
span: span.clone(),
|
||||
};
|
||||
let record_name = Identifier {
|
||||
name: RECORD_VARIABLE_NAME.to_string(),
|
||||
span: keyword.span.clone(),
|
||||
span: span.clone(),
|
||||
};
|
||||
let state_name = Identifier {
|
||||
name: STATE_VARIABLE_NAME.to_string(),
|
||||
span: keyword.span.clone(),
|
||||
span: span.clone(),
|
||||
};
|
||||
let state_leaf_name = Identifier {
|
||||
name: STATE_LEAF_VARIABLE_NAME.to_string(),
|
||||
span: keyword.span.clone(),
|
||||
span,
|
||||
};
|
||||
|
||||
// Fetch each input variable's definitions
|
||||
@ -72,8 +75,17 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
let mut members = Vec::with_capacity(sections.len());
|
||||
|
||||
for (name, values) in sections {
|
||||
let sub_circuit = match expected_type.members.borrow().get(&name.name) {
|
||||
Some(CircuitMemberBody::Variable(Type::Circuit(circuit))) => circuit
|
||||
.body
|
||||
.borrow()
|
||||
.upgrade()
|
||||
.expect("stale circuit body for input subtype"),
|
||||
_ => panic!("illegal input type definition from asg"),
|
||||
};
|
||||
|
||||
let member_name = name.clone();
|
||||
let member_value = self.allocate_input_section(cs, name, values)?;
|
||||
let member_value = self.allocate_input_section(cs, name, sub_circuit, values)?;
|
||||
|
||||
let member = ConstrainedCircuitMember(member_name, member_value);
|
||||
|
||||
@ -82,6 +94,6 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
|
||||
// Return input variable keyword as circuit expression
|
||||
|
||||
Ok(ConstrainedValue::CircuitExpression(Identifier::from(keyword), members))
|
||||
Ok(ConstrainedValue::CircuitExpression(expected_type.clone(), members))
|
||||
}
|
||||
}
|
||||
|
@ -15,7 +15,9 @@
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::{errors::FunctionError, ConstrainedCircuitMember, ConstrainedProgram, ConstrainedValue, GroupType};
|
||||
use leo_asg::{AsgConvertError, CircuitBody, CircuitMemberBody};
|
||||
use leo_ast::{Identifier, InputValue, Parameter};
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -29,6 +31,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
identifier: Identifier,
|
||||
expected_type: Arc<CircuitBody>,
|
||||
section: IndexMap<Parameter, Option<InputValue>>,
|
||||
) -> Result<ConstrainedValue<F, G>, FunctionError> {
|
||||
let mut members = Vec::with_capacity(section.len());
|
||||
@ -36,10 +39,24 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
// Allocate each section definition as a circuit member value
|
||||
|
||||
for (parameter, option) in section.into_iter() {
|
||||
let section_members = expected_type.members.borrow();
|
||||
let expected_type = match section_members.get(¶meter.variable.name) {
|
||||
Some(CircuitMemberBody::Variable(inner)) => inner,
|
||||
_ => continue, // present, but unused
|
||||
};
|
||||
let declared_type = self.asg.borrow().scope.borrow().resolve_ast_type(¶meter.type_)?;
|
||||
if !expected_type.is_assignable_from(&declared_type) {
|
||||
return Err(AsgConvertError::unexpected_type(
|
||||
&expected_type.to_string(),
|
||||
Some(&declared_type.to_string()),
|
||||
&identifier.span,
|
||||
)
|
||||
.into());
|
||||
}
|
||||
let member_name = parameter.variable.clone();
|
||||
let member_value = self.allocate_main_function_input(
|
||||
cs,
|
||||
parameter.type_,
|
||||
&declared_type,
|
||||
¶meter.variable.name,
|
||||
option,
|
||||
¶meter.span,
|
||||
@ -51,6 +68,6 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
|
||||
// Return section as circuit expression
|
||||
|
||||
Ok(ConstrainedValue::CircuitExpression(identifier, members))
|
||||
Ok(ConstrainedValue::CircuitExpression(expected_type, members))
|
||||
}
|
||||
}
|
||||
|
@ -30,8 +30,8 @@ use crate::{
|
||||
Integer,
|
||||
};
|
||||
|
||||
use leo_ast::{InputValue, Span, Type};
|
||||
|
||||
use leo_asg::Type;
|
||||
use leo_ast::{InputValue, Span};
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
gadgets::r1cs::ConstraintSystem,
|
||||
@ -41,7 +41,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn allocate_main_function_input<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
type_: Type,
|
||||
type_: &Type,
|
||||
name: &str,
|
||||
input_option: Option<InputValue>,
|
||||
span: &Span,
|
||||
@ -51,14 +51,14 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
Type::Boolean => Ok(bool_from_input(cs, name, input_option, span)?),
|
||||
Type::Field => Ok(field_from_input(cs, name, input_option, span)?),
|
||||
Type::Group => Ok(group_from_input(cs, name, input_option, span)?),
|
||||
Type::IntegerType(integer_type) => Ok(ConstrainedValue::Integer(Integer::from_input(
|
||||
Type::Integer(integer_type) => Ok(ConstrainedValue::Integer(Integer::from_input(
|
||||
cs,
|
||||
integer_type,
|
||||
name,
|
||||
input_option,
|
||||
span,
|
||||
)?)),
|
||||
Type::Array(type_, dimensions) => self.allocate_array(cs, name, *type_, dimensions, input_option, span),
|
||||
Type::Array(type_, len) => self.allocate_array(cs, name, &*type_, *len, input_option, span),
|
||||
Type::Tuple(types) => self.allocate_tuple(cs, &name, types, input_option, span),
|
||||
_ => unimplemented!("main function input not implemented for type"),
|
||||
}
|
||||
|
@ -19,9 +19,6 @@
|
||||
pub mod array;
|
||||
pub use self::array::*;
|
||||
|
||||
pub mod function_input;
|
||||
pub use self::function_input::*;
|
||||
|
||||
pub mod main_function_input;
|
||||
pub use self::main_function_input::*;
|
||||
|
||||
|
@ -16,14 +16,10 @@
|
||||
|
||||
//! Allocates an array as a main function input parameter in a compiled Leo program.
|
||||
|
||||
use crate::{
|
||||
errors::FunctionError,
|
||||
program::{new_scope, ConstrainedProgram},
|
||||
value::ConstrainedValue,
|
||||
GroupType,
|
||||
};
|
||||
use crate::{errors::FunctionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
|
||||
use leo_ast::{InputValue, Span, Type};
|
||||
use leo_asg::Type;
|
||||
use leo_ast::{InputValue, Span};
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -35,7 +31,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
name: &str,
|
||||
types: Vec<Type>,
|
||||
types: &[Type],
|
||||
input_value: Option<InputValue>,
|
||||
span: &Span,
|
||||
) -> Result<ConstrainedValue<F, G>, FunctionError> {
|
||||
@ -44,16 +40,16 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
match input_value {
|
||||
Some(InputValue::Tuple(values)) => {
|
||||
// Allocate each value in the tuple
|
||||
for (i, (value, type_)) in values.into_iter().zip(types.into_iter()).enumerate() {
|
||||
let value_name = new_scope(name, &i.to_string());
|
||||
for (i, (value, type_)) in values.into_iter().zip(types.iter()).enumerate() {
|
||||
let value_name = format!("{}_{}", &name, &i.to_string());
|
||||
|
||||
tuple_values.push(self.allocate_main_function_input(cs, type_, &value_name, Some(value), span)?)
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// Allocate all tuple values as none
|
||||
for (i, type_) in types.into_iter().enumerate() {
|
||||
let value_name = new_scope(name, &i.to_string());
|
||||
for (i, type_) in types.iter().enumerate() {
|
||||
let value_name = format!("{}_{}", &name, &i.to_string());
|
||||
|
||||
tuple_values.push(self.allocate_main_function_input(cs, type_, &value_name, None, span)?);
|
||||
}
|
||||
|
@ -16,14 +16,11 @@
|
||||
|
||||
//! Enforces constraints on the main function of a compiled Leo program.
|
||||
|
||||
use crate::{
|
||||
errors::FunctionError,
|
||||
program::{new_scope, ConstrainedProgram},
|
||||
GroupType,
|
||||
OutputBytes,
|
||||
};
|
||||
use crate::{errors::FunctionError, program::ConstrainedProgram, GroupType, OutputBytes};
|
||||
|
||||
use leo_ast::{Expression, Function, FunctionInput, Identifier, Input};
|
||||
use leo_asg::{Expression, FunctionBody, FunctionQualifier};
|
||||
use leo_ast::Input;
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -34,49 +31,67 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_main_function<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
scope: &str,
|
||||
function: Function,
|
||||
function: &Arc<FunctionBody>,
|
||||
input: &Input,
|
||||
) -> Result<OutputBytes, FunctionError> {
|
||||
let function_name = new_scope(scope, function.get_name());
|
||||
let registers = input.get_registers();
|
||||
|
||||
// Iterate over main function input variables and allocate new values
|
||||
let mut input_variables = Vec::with_capacity(function.input.len());
|
||||
for input_model in function.input.clone().into_iter() {
|
||||
let (input_id, value) = match input_model {
|
||||
FunctionInput::InputKeyword(keyword) => {
|
||||
let input_id = Identifier::new_with_span(&keyword.to_string(), &keyword.span);
|
||||
let value = self.allocate_input_keyword(cs, keyword, input)?;
|
||||
if function.function.has_input {
|
||||
// let input_var = function.scope.
|
||||
let asg_input = function
|
||||
.scope
|
||||
.borrow()
|
||||
.resolve_input()
|
||||
.expect("no input variable in scope when function is qualified");
|
||||
|
||||
(input_id, value)
|
||||
}
|
||||
FunctionInput::SelfKeyword(_) => unimplemented!("cannot access self keyword in main function"),
|
||||
FunctionInput::MutSelfKeyword(_) => unimplemented!("cannot access mut self keyword in main function"),
|
||||
FunctionInput::Variable(input_model) => {
|
||||
let name = input_model.identifier.name.clone();
|
||||
let input_option = input
|
||||
.get(&name)
|
||||
.ok_or_else(|| FunctionError::input_not_found(name.clone(), function.span.clone()))?;
|
||||
let input_value =
|
||||
self.allocate_main_function_input(cs, input_model.type_, &name, input_option, &function.span)?;
|
||||
let value = self.allocate_input_keyword(
|
||||
cs,
|
||||
function.function.name.borrow().span.clone(),
|
||||
&asg_input.container_circuit,
|
||||
input,
|
||||
)?;
|
||||
|
||||
(input_model.identifier, input_value)
|
||||
}
|
||||
};
|
||||
|
||||
// Store input as variable with {function_name}_{identifier_name}
|
||||
let input_name = new_scope(&function_name, &input_id.to_string());
|
||||
|
||||
// Store a new variable for every allocated main function input
|
||||
self.store(input_name, value);
|
||||
|
||||
input_variables.push(Expression::Identifier(input_id));
|
||||
self.store(asg_input.container.borrow().id, value);
|
||||
}
|
||||
|
||||
let span = function.span.clone();
|
||||
let result_value = self.enforce_function(cs, scope, &function_name, function, input_variables, "")?;
|
||||
let output_bytes = OutputBytes::new_from_constrained_value(registers, result_value, span)?;
|
||||
match function.function.qualifier {
|
||||
FunctionQualifier::SelfRef | FunctionQualifier::MutSelfRef => {
|
||||
unimplemented!("cannot access self variable in main function")
|
||||
}
|
||||
FunctionQualifier::Static => (),
|
||||
}
|
||||
|
||||
let mut arguments = vec![];
|
||||
|
||||
for input_variable in function.arguments.iter() {
|
||||
{
|
||||
let input_variable = input_variable.borrow();
|
||||
let name = input_variable.name.name.clone();
|
||||
let input_option = input.get(&name).ok_or_else(|| {
|
||||
FunctionError::input_not_found(name.clone(), function.span.clone().unwrap_or_default())
|
||||
})?;
|
||||
let input_value = self.allocate_main_function_input(
|
||||
cs,
|
||||
&input_variable.type_,
|
||||
&name,
|
||||
input_option,
|
||||
&function.span.clone().unwrap_or_default(),
|
||||
)?;
|
||||
|
||||
// Store a new variable for every allocated main function input
|
||||
self.store(input_variable.id, input_value);
|
||||
}
|
||||
arguments.push(Arc::new(Expression::VariableRef(leo_asg::VariableRef {
|
||||
parent: std::cell::RefCell::new(None),
|
||||
span: Some(input_variable.borrow().name.span.clone()),
|
||||
variable: input_variable.clone(),
|
||||
})));
|
||||
}
|
||||
|
||||
let span = function.span.clone().unwrap_or_default();
|
||||
let result_value = self.enforce_function(cs, function, None, &arguments)?;
|
||||
let output_bytes = OutputBytes::new_from_constrained_value(&self.asg, registers, result_value, span)?;
|
||||
|
||||
Ok(output_bytes)
|
||||
}
|
||||
|
@ -27,3 +27,6 @@ pub use self::main_function::*;
|
||||
|
||||
pub mod result;
|
||||
pub use self::result::*;
|
||||
|
||||
pub mod mut_target;
|
||||
pub use self::mut_target::*;
|
||||
|
124
compiler/src/function/mut_target.rs
Normal file
124
compiler/src/function/mut_target.rs
Normal file
@ -0,0 +1,124 @@
|
||||
// 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/>.
|
||||
|
||||
//! Resolves assignees in a compiled Leo program.
|
||||
|
||||
use crate::{
|
||||
errors::StatementError,
|
||||
program::ConstrainedProgram,
|
||||
value::ConstrainedValue,
|
||||
GroupType,
|
||||
ResolvedAssigneeAccess,
|
||||
};
|
||||
use leo_asg::{
|
||||
ArrayAccessExpression,
|
||||
ArrayRangeAccessExpression,
|
||||
CircuitAccessExpression,
|
||||
Expression,
|
||||
Node,
|
||||
Span,
|
||||
TupleAccessExpression,
|
||||
Variable,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
gadgets::r1cs::ConstraintSystem,
|
||||
};
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
fn prepare_mut_access<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
expr: &Arc<Expression>,
|
||||
span: &Span,
|
||||
output: &mut Vec<ResolvedAssigneeAccess>,
|
||||
) -> Result<Option<Variable>, StatementError> {
|
||||
match &**expr {
|
||||
Expression::ArrayRangeAccess(ArrayRangeAccessExpression { array, left, right, .. }) => {
|
||||
let inner = self.prepare_mut_access(cs, array, span, output)?;
|
||||
let start_index = left
|
||||
.as_ref()
|
||||
.map(|start| self.enforce_index(cs, start, &span))
|
||||
.transpose()?;
|
||||
let stop_index = right
|
||||
.as_ref()
|
||||
.map(|stop| self.enforce_index(cs, stop, &span))
|
||||
.transpose()?;
|
||||
|
||||
output.push(ResolvedAssigneeAccess::ArrayRange(start_index, stop_index));
|
||||
Ok(inner)
|
||||
}
|
||||
Expression::ArrayAccess(ArrayAccessExpression { array, index, .. }) => {
|
||||
let inner = self.prepare_mut_access(cs, array, span, output)?;
|
||||
let index = self.enforce_index(cs, index, &span)?;
|
||||
|
||||
output.push(ResolvedAssigneeAccess::ArrayIndex(index));
|
||||
Ok(inner)
|
||||
}
|
||||
Expression::TupleAccess(TupleAccessExpression { tuple_ref, index, .. }) => {
|
||||
let inner = self.prepare_mut_access(cs, tuple_ref, span, output)?;
|
||||
|
||||
output.push(ResolvedAssigneeAccess::Tuple(*index, span.clone()));
|
||||
Ok(inner)
|
||||
}
|
||||
Expression::CircuitAccess(CircuitAccessExpression {
|
||||
target: Some(target),
|
||||
member,
|
||||
..
|
||||
}) => {
|
||||
let inner = self.prepare_mut_access(cs, target, span, output)?;
|
||||
|
||||
output.push(ResolvedAssigneeAccess::Member(member.clone()));
|
||||
Ok(inner)
|
||||
}
|
||||
Expression::VariableRef(variable_ref) => Ok(Some(variable_ref.variable.clone())),
|
||||
_ => Ok(None), // not a valid reference to mutable variable, we copy
|
||||
}
|
||||
}
|
||||
|
||||
// resolve a mutable reference from an expression
|
||||
// return Ok(None) if no valid mutable reference, or Err(_) on more critical error
|
||||
pub fn resolve_mut_ref<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
assignee: &Arc<Expression>,
|
||||
) -> Result<Option<Vec<&mut ConstrainedValue<F, G>>>, StatementError> {
|
||||
let span = assignee.span().cloned().unwrap_or_default();
|
||||
|
||||
let mut accesses = vec![];
|
||||
let target = self.prepare_mut_access(cs, assignee, &span, &mut accesses)?;
|
||||
if target.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let variable = target.unwrap();
|
||||
let variable = variable.borrow();
|
||||
|
||||
let mut result = vec![match self.get_mut(&variable.id) {
|
||||
Some(value) => match value {
|
||||
ConstrainedValue::Mutable(mutable) => &mut **mutable,
|
||||
_ => return Err(StatementError::immutable_assign(variable.name.to_string(), span)),
|
||||
},
|
||||
None => return Err(StatementError::undefined_variable(variable.name.to_string(), span)),
|
||||
}];
|
||||
|
||||
for access in accesses {
|
||||
result = Self::resolve_assignee_access(access, &span, result)?;
|
||||
}
|
||||
Ok(Some(result))
|
||||
}
|
||||
}
|
@ -17,7 +17,6 @@
|
||||
//! Enforces that one return value is produced in a compiled Leo program.
|
||||
|
||||
use crate::{
|
||||
check_return_type,
|
||||
errors::StatementError,
|
||||
get_indicator_value,
|
||||
program::ConstrainedProgram,
|
||||
@ -25,7 +24,7 @@ use crate::{
|
||||
GroupType,
|
||||
};
|
||||
|
||||
use leo_ast::{Span, Type};
|
||||
use leo_asg::{Span, Type};
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -42,37 +41,21 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
///
|
||||
pub fn conditionally_select_result<CS: ConstraintSystem<F>>(
|
||||
cs: &mut CS,
|
||||
expected_return: Option<Type>,
|
||||
expected_return: &Type,
|
||||
results: Vec<(Boolean, ConstrainedValue<F, G>)>,
|
||||
span: &Span,
|
||||
) -> Result<ConstrainedValue<F, G>, StatementError> {
|
||||
// Initialize empty return value.
|
||||
let mut return_value = ConstrainedValue::Tuple(vec![]);
|
||||
|
||||
// If the function does not expect a return type, then make sure there are no returned results.
|
||||
let return_type = match expected_return {
|
||||
Some(return_type) => return_type,
|
||||
None => {
|
||||
if results.is_empty() {
|
||||
// If the function has no returns, then return an empty tuple.
|
||||
return Ok(return_value);
|
||||
} else {
|
||||
return Err(StatementError::invalid_number_of_returns(
|
||||
0,
|
||||
results.len(),
|
||||
span.to_owned(),
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Error if the function or one of its branches does not return.
|
||||
if results
|
||||
.iter()
|
||||
.find(|(indicator, _res)| get_indicator_value(indicator))
|
||||
.is_none()
|
||||
if !expected_return.is_unit()
|
||||
&& results
|
||||
.iter()
|
||||
.find(|(indicator, _res)| get_indicator_value(indicator))
|
||||
.is_none()
|
||||
{
|
||||
return Err(StatementError::no_returns(return_type, span.to_owned()));
|
||||
return Err(StatementError::no_returns(&expected_return, span.to_owned()));
|
||||
}
|
||||
|
||||
// Find the return value
|
||||
@ -81,7 +64,13 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
for (indicator, result) in results.into_iter() {
|
||||
// Error if a statement returned a result with an incorrect type
|
||||
let result_type = result.to_type(span)?;
|
||||
check_return_type(&return_type, &result_type, span)?;
|
||||
if !expected_return.is_assignable_from(&result_type) {
|
||||
panic!(
|
||||
"failed type resolution for function return: expected '{}', got '{}'",
|
||||
expected_return.to_string(),
|
||||
result_type.to_string()
|
||||
);
|
||||
}
|
||||
|
||||
if get_indicator_value(&indicator) {
|
||||
// Error if we already have a return value.
|
||||
|
@ -1,18 +0,0 @@
|
||||
// Copyright (C) 2019-2021 Aleo Systems Inc.
|
||||
// This file is part of the Leo library.
|
||||
|
||||
// The Leo library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// The Leo library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
/// The import store brings an imported symbol into the main program from an import program struct
|
||||
pub mod store;
|
||||
pub use self::store::*;
|
@ -1,58 +0,0 @@
|
||||
// Copyright (C) 2019-2021 Aleo Systems Inc.
|
||||
// This file is part of the Leo library.
|
||||
|
||||
// The Leo library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// The Leo library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::{errors::ImportError, ConstrainedProgram, GroupType};
|
||||
use leo_ast::ImportStatement;
|
||||
use leo_imports::ImportParser;
|
||||
use leo_symbol_table::imported_symbols::ImportedSymbols;
|
||||
|
||||
use snarkvm_models::curves::{Field, PrimeField};
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub(crate) fn store_import(
|
||||
&mut self,
|
||||
scope: &str,
|
||||
import: &ImportStatement,
|
||||
imported_programs: &ImportParser,
|
||||
) -> Result<(), ImportError> {
|
||||
// Fetch core packages.
|
||||
let core_package = imported_programs.get_core_package(&import.package);
|
||||
|
||||
if let Some(package) = core_package {
|
||||
self.store_core_package(scope, package.clone())?;
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Fetch dependencies for the current import
|
||||
let imported_symbols = ImportedSymbols::new(import);
|
||||
|
||||
for (name, symbol) in imported_symbols.symbols {
|
||||
// Find imported program
|
||||
let program = imported_programs
|
||||
.get_import(&name)
|
||||
.ok_or_else(|| ImportError::unknown_package(import.package.name.clone()))?;
|
||||
|
||||
// Parse imported program
|
||||
self.store_definitions(program, imported_programs)?;
|
||||
|
||||
// Store the imported symbol
|
||||
self.store_symbol(scope, &name, &symbol, program)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
// Copyright (C) 2019-2021 Aleo Systems Inc.
|
||||
// This file is part of the Leo library.
|
||||
|
||||
// The Leo library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// The Leo library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
/// The import store brings an imported symbol into the main program from an import program struct
|
||||
pub mod core_package;
|
||||
pub use self::core_package::*;
|
||||
|
||||
pub mod import;
|
||||
pub use self::import::*;
|
||||
|
||||
pub mod symbol;
|
||||
pub use self::symbol::*;
|
@ -1,92 +0,0 @@
|
||||
// Copyright (C) 2019-2021 Aleo Systems Inc.
|
||||
// This file is part of the Leo library.
|
||||
|
||||
// The Leo library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// The Leo library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::{errors::ImportError, new_scope, ConstrainedProgram, ConstrainedValue, GroupType};
|
||||
use leo_ast::{ImportSymbol, Program};
|
||||
|
||||
use snarkvm_models::curves::{Field, PrimeField};
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub(crate) fn store_symbol(
|
||||
&mut self,
|
||||
scope: &str,
|
||||
program_name: &str,
|
||||
symbol: &ImportSymbol,
|
||||
program: &Program,
|
||||
) -> Result<(), ImportError> {
|
||||
// Store the symbol that was imported by another file
|
||||
if symbol.is_star() {
|
||||
// evaluate and store all circuit definitions
|
||||
program.circuits.iter().for_each(|(identifier, circuit)| {
|
||||
let name = new_scope(scope, &identifier.name);
|
||||
let value = ConstrainedValue::Import(
|
||||
program_name.to_owned(),
|
||||
Box::new(ConstrainedValue::CircuitDefinition(circuit.clone())),
|
||||
);
|
||||
|
||||
self.store(name, value);
|
||||
});
|
||||
|
||||
// evaluate and store all function definitions
|
||||
program.functions.iter().for_each(|(identifier, function)| {
|
||||
let name = new_scope(scope, &identifier.name);
|
||||
let value = ConstrainedValue::Import(
|
||||
program_name.to_owned(),
|
||||
Box::new(ConstrainedValue::Function(None, Box::new(function.clone()))),
|
||||
);
|
||||
|
||||
self.store(name, value);
|
||||
});
|
||||
} else {
|
||||
// see if the imported symbol is a circuit
|
||||
let matched_circuit = program
|
||||
.circuits
|
||||
.iter()
|
||||
.find(|(circuit_name, _circuit_def)| symbol.symbol == **circuit_name);
|
||||
|
||||
let value = match matched_circuit {
|
||||
Some((_circuit_name, circuit)) => ConstrainedValue::Import(
|
||||
program_name.to_owned(),
|
||||
Box::new(ConstrainedValue::CircuitDefinition(circuit.clone())),
|
||||
),
|
||||
None => {
|
||||
// see if the imported symbol is a function
|
||||
let matched_function = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|(function_name, _function)| symbol.symbol == **function_name);
|
||||
|
||||
match matched_function {
|
||||
Some((_function_name, function)) => ConstrainedValue::Import(
|
||||
program_name.to_owned(),
|
||||
Box::new(ConstrainedValue::Function(None, Box::new(function.clone()))),
|
||||
),
|
||||
None => return Err(ImportError::unknown_symbol(symbol.to_owned(), program_name.to_owned())),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// take the alias if it is present
|
||||
let id = symbol.alias.clone().unwrap_or_else(|| symbol.symbol.clone());
|
||||
let name = new_scope(scope, &id.name);
|
||||
|
||||
// store imported circuit under imported name
|
||||
self.store(name, value);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
@ -41,9 +41,6 @@ pub use self::expression::*;
|
||||
pub mod function;
|
||||
pub use self::function::*;
|
||||
|
||||
pub mod import;
|
||||
pub use self::import::*;
|
||||
|
||||
pub mod output;
|
||||
pub use self::output::*;
|
||||
|
||||
@ -53,5 +50,11 @@ pub use self::program::*;
|
||||
pub mod statement;
|
||||
pub use self::statement::*;
|
||||
|
||||
pub mod prelude;
|
||||
pub use self::prelude::*;
|
||||
|
||||
pub mod value;
|
||||
pub use self::value::*;
|
||||
|
||||
pub mod stage;
|
||||
pub use self::stage::*;
|
||||
|
@ -15,6 +15,7 @@
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::{errors::OutputBytesError, ConstrainedValue, GroupType, REGISTERS_VARIABLE_NAME};
|
||||
use leo_asg::Program;
|
||||
use leo_ast::{Parameter, Registers, Span};
|
||||
|
||||
use snarkvm_models::curves::{Field, PrimeField};
|
||||
@ -31,6 +32,7 @@ impl OutputBytes {
|
||||
}
|
||||
|
||||
pub fn new_from_constrained_value<F: Field + PrimeField, G: GroupType<F>>(
|
||||
program: &Program,
|
||||
registers: &Registers,
|
||||
value: ConstrainedValue<F, G>,
|
||||
span: Span,
|
||||
@ -65,13 +67,13 @@ impl OutputBytes {
|
||||
let name = parameter.variable.name;
|
||||
|
||||
// Check register type == return value type.
|
||||
let register_type = parameter.type_;
|
||||
let register_type = program.borrow().scope.borrow().resolve_ast_type(¶meter.type_)?;
|
||||
let return_value_type = value.to_type(&span)?;
|
||||
|
||||
if !register_type.eq_flat(&return_value_type) {
|
||||
if !register_type.is_assignable_from(&return_value_type) {
|
||||
return Err(OutputBytesError::mismatched_output_types(
|
||||
register_type,
|
||||
return_value_type,
|
||||
®ister_type,
|
||||
&return_value_type,
|
||||
span,
|
||||
));
|
||||
}
|
||||
|
82
compiler/src/prelude/blake2s.rs
Normal file
82
compiler/src/prelude/blake2s.rs
Normal file
@ -0,0 +1,82 @@
|
||||
// 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::sync::Arc;
|
||||
|
||||
use super::CoreCircuit;
|
||||
use crate::{errors::ExpressionError, ConstrainedValue, GroupType, Integer};
|
||||
use leo_asg::{FunctionBody, Span};
|
||||
use snarkvm_gadgets::algorithms::prf::Blake2sGadget;
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
gadgets::{
|
||||
algorithms::PRFGadget,
|
||||
r1cs::ConstraintSystem,
|
||||
utilities::{uint::UInt8, ToBytesGadget},
|
||||
},
|
||||
};
|
||||
|
||||
pub struct Blake2s;
|
||||
|
||||
fn unwrap_argument<F: Field + PrimeField, G: GroupType<F>>(mut arg: ConstrainedValue<F, G>) -> Vec<UInt8> {
|
||||
arg.get_inner_mut();
|
||||
if let ConstrainedValue::Array(args) = arg {
|
||||
assert_eq!(args.len(), 32); // asg enforced
|
||||
args.into_iter()
|
||||
.map(|item| {
|
||||
if let ConstrainedValue::Integer(Integer::U8(item)) = item {
|
||||
item
|
||||
} else {
|
||||
panic!("illegal non-u8 type in blake2s call");
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
panic!("illegal non-array type in blake2s call");
|
||||
}
|
||||
}
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> CoreCircuit<F, G> for Blake2s {
|
||||
fn call_function<CS: ConstraintSystem<F>>(
|
||||
&self,
|
||||
cs: &mut CS,
|
||||
function: Arc<FunctionBody>,
|
||||
span: &Span,
|
||||
target: Option<ConstrainedValue<F, G>>,
|
||||
mut arguments: Vec<ConstrainedValue<F, G>>,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
|
||||
assert_eq!(arguments.len(), 2); // asg enforced
|
||||
assert!(function.function.name.borrow().name == "hash"); // asg enforced
|
||||
assert!(target.is_none()); // asg enforced
|
||||
let input = unwrap_argument(arguments.remove(1));
|
||||
let seed = unwrap_argument(arguments.remove(0));
|
||||
|
||||
let digest =
|
||||
Blake2sGadget::check_evaluation_gadget(cs.ns(|| "blake2s hash"), &seed[..], &input[..]).map_err(|e| {
|
||||
ExpressionError::cannot_enforce("Blake2s check evaluation gadget".to_owned(), e, span.clone())
|
||||
})?;
|
||||
|
||||
Ok(ConstrainedValue::Array(
|
||||
digest
|
||||
.to_bytes(cs)
|
||||
.map_err(|e| ExpressionError::cannot_enforce("Vec<UInt8> ToBytes".to_owned(), e, span.clone()))?
|
||||
.into_iter()
|
||||
.map(Integer::U8)
|
||||
.map(ConstrainedValue::Integer)
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
}
|
@ -14,28 +14,32 @@
|
||||
// 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::{CoreCircuitError, Value};
|
||||
use leo_ast::{Circuit, Identifier, Span};
|
||||
pub mod blake2s;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use blake2s::*;
|
||||
|
||||
use crate::{errors::ExpressionError, ConstrainedValue, GroupType};
|
||||
use leo_asg::{FunctionBody, Span};
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
gadgets::r1cs::ConstraintSystem,
|
||||
};
|
||||
|
||||
/// A core circuit type, accessible to all Leo programs by default.
|
||||
/// To access a `CoreCircuit`, import its symbol from a `CorePackage`.
|
||||
pub trait CoreCircuit {
|
||||
/// The name of the core circuit function
|
||||
fn name() -> String;
|
||||
|
||||
/// Return the abstract syntax tree representation of the core circuit for compiler parsing.
|
||||
fn ast(circuit_name: Identifier, span: Span) -> Circuit;
|
||||
|
||||
/// Call the gadget associated with this core circuit with arguments.
|
||||
/// Generate constraints on the given `ConstraintSystem`.
|
||||
fn call<F: Field + PrimeField, CS: ConstraintSystem<F>>(
|
||||
cs: CS,
|
||||
arguments: Vec<Value>,
|
||||
span: Span,
|
||||
) -> Result<Vec<Value>, CoreCircuitError>;
|
||||
pub trait CoreCircuit<F: Field + PrimeField, G: GroupType<F>>: Send + Sync {
|
||||
fn call_function<CS: ConstraintSystem<F>>(
|
||||
&self,
|
||||
cs: &mut CS,
|
||||
function: Arc<FunctionBody>,
|
||||
span: &Span,
|
||||
target: Option<ConstrainedValue<F, G>>,
|
||||
arguments: Vec<ConstrainedValue<F, G>>,
|
||||
) -> Result<ConstrainedValue<F, G>, ExpressionError>;
|
||||
}
|
||||
|
||||
pub fn resolve_core_circuit<F: Field + PrimeField, G: GroupType<F>>(name: &str) -> impl CoreCircuit<F, G> {
|
||||
match name {
|
||||
"blake2s" => Blake2s,
|
||||
_ => unimplemented!("invalid core circuit: {}", name),
|
||||
}
|
||||
}
|
@ -18,44 +18,34 @@
|
||||
|
||||
use crate::{value::ConstrainedValue, GroupType};
|
||||
|
||||
use leo_asg::Program;
|
||||
use snarkvm_models::curves::{Field, PrimeField};
|
||||
|
||||
use indexmap::IndexMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct ConstrainedProgram<F: Field + PrimeField, G: GroupType<F>> {
|
||||
pub identifiers: IndexMap<String, ConstrainedValue<F, G>>,
|
||||
}
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> Default for ConstrainedProgram<F, G> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
identifiers: IndexMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_scope(outer: &str, inner: &str) -> String {
|
||||
format!("{}_{}", outer, inner)
|
||||
}
|
||||
|
||||
pub fn is_in_scope(current_scope: &str, desired_scope: &str) -> bool {
|
||||
current_scope.ends_with(desired_scope)
|
||||
pub asg: Program,
|
||||
identifiers: IndexMap<Uuid, ConstrainedValue<F, G>>,
|
||||
}
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
pub fn new(asg: Program) -> Self {
|
||||
Self {
|
||||
asg,
|
||||
identifiers: IndexMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn store(&mut self, name: String, value: ConstrainedValue<F, G>) {
|
||||
pub(crate) fn store(&mut self, name: Uuid, value: ConstrainedValue<F, G>) {
|
||||
self.identifiers.insert(name, value);
|
||||
}
|
||||
|
||||
pub(crate) fn get(&self, name: &str) -> Option<&ConstrainedValue<F, G>> {
|
||||
pub(crate) fn get(&self, name: &Uuid) -> Option<&ConstrainedValue<F, G>> {
|
||||
self.identifiers.get(name)
|
||||
}
|
||||
|
||||
pub(crate) fn get_mut(&mut self, name: &str) -> Option<&mut ConstrainedValue<F, G>> {
|
||||
pub(crate) fn get_mut(&mut self, name: &Uuid) -> Option<&mut ConstrainedValue<F, G>> {
|
||||
self.identifiers.get_mut(name)
|
||||
}
|
||||
}
|
||||
|
@ -14,5 +14,8 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
pub mod blake2s;
|
||||
pub use self::blake2s::*;
|
||||
use leo_asg::Program;
|
||||
|
||||
pub trait ASGStage {
|
||||
fn apply(asg: &mut Program);
|
||||
}
|
@ -16,15 +16,8 @@
|
||||
|
||||
//! Enforces an assign statement in a compiled Leo program.
|
||||
|
||||
use crate::{
|
||||
arithmetic::*,
|
||||
errors::StatementError,
|
||||
new_scope,
|
||||
program::ConstrainedProgram,
|
||||
value::ConstrainedValue,
|
||||
GroupType,
|
||||
};
|
||||
use leo_ast::{AssignOperation, AssignStatement, AssigneeAccess, Span};
|
||||
use crate::{arithmetic::*, errors::StatementError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_asg::{AssignOperation, AssignStatement, Span};
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -39,28 +32,15 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_assign_statement<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
declared_circuit_reference: &str,
|
||||
indicator: &Boolean,
|
||||
mut_self: bool,
|
||||
statement: AssignStatement,
|
||||
statement: &AssignStatement,
|
||||
) -> Result<(), StatementError> {
|
||||
// Get the name of the variable we are assigning to
|
||||
let mut new_value = self.enforce_expression(cs, file_scope, function_scope, None, statement.value)?;
|
||||
let mut resolved_assignee = self.resolve_assignee(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
declared_circuit_reference,
|
||||
mut_self,
|
||||
statement.assignee.clone(),
|
||||
)?;
|
||||
let new_value = self.enforce_expression(cs, &statement.value)?;
|
||||
let mut resolved_assignee = self.resolve_assign(cs, statement)?;
|
||||
|
||||
if resolved_assignee.len() == 1 {
|
||||
new_value.resolve_type(Some(resolved_assignee[0].to_type(&statement.span)?), &statement.span)?;
|
||||
|
||||
let span = statement.span.clone();
|
||||
let span = statement.span.clone().unwrap_or_default();
|
||||
|
||||
Self::enforce_assign_operation(
|
||||
cs,
|
||||
@ -74,7 +54,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
} else {
|
||||
match new_value {
|
||||
ConstrainedValue::Array(new_values) => {
|
||||
let span = statement.span.clone();
|
||||
let span = statement.span.clone().unwrap_or_default();
|
||||
|
||||
for (i, (old_ref, new_value)) in
|
||||
resolved_assignee.into_iter().zip(new_values.into_iter()).enumerate()
|
||||
@ -90,35 +70,12 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
)?;
|
||||
}
|
||||
}
|
||||
_ => return Err(StatementError::array_assign_range(statement.span)),
|
||||
};
|
||||
}
|
||||
|
||||
// self re-store logic -- structure is already checked by enforce_assign_operation
|
||||
if statement.assignee.identifier.is_self() && mut_self {
|
||||
if let Some(AssigneeAccess::Member(member_name)) = statement.assignee.accesses.get(0) {
|
||||
let self_circuit_variable_name = new_scope(&statement.assignee.identifier.name, &member_name.name);
|
||||
let self_variable_name = new_scope(file_scope, &self_circuit_variable_name);
|
||||
// get circuit ref
|
||||
let target = match self.get(declared_circuit_reference) {
|
||||
Some(ConstrainedValue::Mutable(value)) => &**value,
|
||||
_ => unimplemented!(),
|
||||
};
|
||||
// get freshly assigned member ref, and clone it
|
||||
let source = match target {
|
||||
ConstrainedValue::CircuitExpression(_circuit_name, members) => {
|
||||
let matched_variable = members.iter().find(|member| &member.0 == member_name);
|
||||
|
||||
match matched_variable {
|
||||
Some(member) => &member.1,
|
||||
None => unimplemented!(),
|
||||
}
|
||||
}
|
||||
_ => unimplemented!(),
|
||||
_ => {
|
||||
return Err(StatementError::array_assign_range(
|
||||
statement.span.clone().unwrap_or_default(),
|
||||
));
|
||||
}
|
||||
.clone();
|
||||
self.store(self_variable_name, source);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@ -130,11 +87,9 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
scope: String,
|
||||
operation: &AssignOperation,
|
||||
target: &mut ConstrainedValue<F, G>,
|
||||
mut new_value: ConstrainedValue<F, G>,
|
||||
new_value: ConstrainedValue<F, G>,
|
||||
span: &Span,
|
||||
) -> Result<(), StatementError> {
|
||||
new_value.resolve_type(Some(target.to_type(span)?), span)?;
|
||||
|
||||
let new_value = match operation {
|
||||
AssignOperation::Assign => new_value,
|
||||
AssignOperation::Add => enforce_add(cs, target.clone(), new_value, span)?,
|
||||
|
@ -16,79 +16,62 @@
|
||||
|
||||
//! Resolves assignees in a compiled Leo program.
|
||||
|
||||
use crate::{
|
||||
errors::StatementError,
|
||||
new_scope,
|
||||
parse_index,
|
||||
program::ConstrainedProgram,
|
||||
value::ConstrainedValue,
|
||||
GroupType,
|
||||
};
|
||||
use leo_ast::{Assignee, AssigneeAccess, Identifier, PositiveNumber, Span};
|
||||
use crate::{errors::StatementError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_asg::{AssignAccess, AssignStatement, Identifier, Span};
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
gadgets::r1cs::ConstraintSystem,
|
||||
};
|
||||
|
||||
enum ResolvedAssigneeAccess {
|
||||
pub(crate) enum ResolvedAssigneeAccess {
|
||||
ArrayRange(Option<usize>, Option<usize>),
|
||||
ArrayIndex(usize),
|
||||
Tuple(PositiveNumber, Span),
|
||||
Tuple(usize, Span),
|
||||
Member(Identifier),
|
||||
}
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn resolve_assignee<CS: ConstraintSystem<F>>(
|
||||
pub fn resolve_assign<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
declared_circuit_reference: &str,
|
||||
mut_self: bool,
|
||||
assignee: Assignee,
|
||||
assignee: &AssignStatement,
|
||||
) -> Result<Vec<&mut ConstrainedValue<F, G>>, StatementError> {
|
||||
let value_ref = if assignee.identifier.is_self() {
|
||||
if !mut_self {
|
||||
return Err(StatementError::immutable_assign("self".to_string(), assignee.span));
|
||||
}
|
||||
declared_circuit_reference.to_string()
|
||||
} else {
|
||||
new_scope(&function_scope, &assignee.identifier().to_string())
|
||||
};
|
||||
|
||||
let span = assignee.span.clone();
|
||||
let identifier_string = assignee.identifier.to_string();
|
||||
let span = assignee.span.clone().unwrap_or_default();
|
||||
|
||||
let resolved_accesses = assignee
|
||||
.accesses
|
||||
.into_iter()
|
||||
.target_accesses
|
||||
.iter()
|
||||
.map(|access| match access {
|
||||
AssigneeAccess::ArrayRange(start, stop) => {
|
||||
AssignAccess::ArrayRange(start, stop) => {
|
||||
let start_index = start
|
||||
.map(|start| self.enforce_index(cs, file_scope, function_scope, start, &span))
|
||||
.as_ref()
|
||||
.map(|start| self.enforce_index(cs, start, &span))
|
||||
.transpose()?;
|
||||
let stop_index = stop
|
||||
.map(|stop| self.enforce_index(cs, file_scope, function_scope, stop, &span))
|
||||
.as_ref()
|
||||
.map(|stop| self.enforce_index(cs, stop, &span))
|
||||
.transpose()?;
|
||||
Ok(ResolvedAssigneeAccess::ArrayRange(start_index, stop_index))
|
||||
}
|
||||
AssigneeAccess::ArrayIndex(index) => {
|
||||
let index = self.enforce_index(cs, file_scope, function_scope, index, &span)?;
|
||||
AssignAccess::ArrayIndex(index) => {
|
||||
let index = self.enforce_index(cs, index, &span)?;
|
||||
|
||||
Ok(ResolvedAssigneeAccess::ArrayIndex(index))
|
||||
}
|
||||
AssigneeAccess::Tuple(index, span) => Ok(ResolvedAssigneeAccess::Tuple(index, span)),
|
||||
AssigneeAccess::Member(identifier) => Ok(ResolvedAssigneeAccess::Member(identifier)),
|
||||
AssignAccess::Tuple(index) => Ok(ResolvedAssigneeAccess::Tuple(*index, span.clone())),
|
||||
AssignAccess::Member(identifier) => Ok(ResolvedAssigneeAccess::Member(identifier.clone())),
|
||||
})
|
||||
.collect::<Result<Vec<_>, crate::errors::ExpressionError>>()?;
|
||||
|
||||
let mut result = vec![match self.get_mut(&value_ref) {
|
||||
let variable = assignee.target_variable.borrow();
|
||||
|
||||
let mut result = vec![match self.get_mut(&variable.id) {
|
||||
Some(value) => match value {
|
||||
ConstrainedValue::Mutable(mutable) => &mut **mutable,
|
||||
_ => return Err(StatementError::immutable_assign(identifier_string, span)),
|
||||
_ => return Err(StatementError::immutable_assign(variable.name.to_string(), span)),
|
||||
},
|
||||
None => return Err(StatementError::undefined_variable(identifier_string, span)),
|
||||
None => return Err(StatementError::undefined_variable(variable.name.to_string(), span)),
|
||||
}];
|
||||
|
||||
for access in resolved_accesses {
|
||||
@ -121,12 +104,13 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
// discards unnecessary mutable wrappers
|
||||
fn unwrap_mutable(input: &mut ConstrainedValue<F, G>) -> &mut ConstrainedValue<F, G> {
|
||||
match input {
|
||||
ConstrainedValue::Mutable(x) => &mut **x,
|
||||
ConstrainedValue::Mutable(x) => Self::unwrap_mutable(&mut **x),
|
||||
x => x,
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_assignee_access<'a>(
|
||||
// todo: this can prob have most of its error checking removed
|
||||
pub(crate) fn resolve_assignee_access<'a>(
|
||||
access: ResolvedAssigneeAccess,
|
||||
span: &Span,
|
||||
mut value: Vec<&'a mut ConstrainedValue<F, G>>,
|
||||
@ -174,8 +158,6 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
}
|
||||
}
|
||||
ResolvedAssigneeAccess::Tuple(index, span) => {
|
||||
let index = parse_index(&index, &span)?;
|
||||
|
||||
if value.len() != 1 {
|
||||
return Err(StatementError::array_assign_interior_index(span));
|
||||
}
|
||||
@ -200,23 +182,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
let matched_variable = members.iter_mut().find(|member| member.0 == name);
|
||||
|
||||
match matched_variable {
|
||||
Some(member) => match &mut member.1 {
|
||||
ConstrainedValue::Function(_circuit_identifier, function) => {
|
||||
// Throw an error if we try to mutate a circuit function
|
||||
Err(StatementError::immutable_circuit_function(
|
||||
function.identifier.to_string(),
|
||||
span.to_owned(),
|
||||
))
|
||||
}
|
||||
ConstrainedValue::Static(_circuit_function) => {
|
||||
// Throw an error if we try to mutate a static circuit function
|
||||
Err(StatementError::immutable_circuit_function(
|
||||
"static".into(),
|
||||
span.to_owned(),
|
||||
))
|
||||
}
|
||||
value => Ok(vec![value]),
|
||||
},
|
||||
Some(member) => Ok(vec![&mut member.1]),
|
||||
None => {
|
||||
// Throw an error if the circuit variable does not exist in the circuit
|
||||
Err(StatementError::undefined_circuit_variable(
|
||||
@ -227,30 +193,9 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
}
|
||||
}
|
||||
// Throw an error if the circuit definition does not exist in the file
|
||||
_ => Err(StatementError::undefined_circuit(name.to_string(), span.to_owned())),
|
||||
x => Err(StatementError::undefined_circuit(x.to_string(), span.to_owned())),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_mutable_assignee(
|
||||
&mut self,
|
||||
name: &str,
|
||||
span: &Span,
|
||||
) -> Result<&mut ConstrainedValue<F, G>, StatementError> {
|
||||
// Check that assignee exists and is mutable
|
||||
Ok(match self.get_mut(name) {
|
||||
Some(value) => match value {
|
||||
ConstrainedValue::Mutable(mutable_value) => {
|
||||
// Get the mutable value.
|
||||
mutable_value.get_inner_mut();
|
||||
|
||||
// Return the mutable value.
|
||||
mutable_value
|
||||
}
|
||||
_ => return Err(StatementError::immutable_assign(name.to_owned(), span.to_owned())),
|
||||
},
|
||||
None => return Err(StatementError::undefined_variable(name.to_owned(), span.to_owned())),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -20,4 +20,4 @@ pub mod assign;
|
||||
pub use self::assign::*;
|
||||
|
||||
pub mod assignee;
|
||||
pub use self::assignee::*;
|
||||
pub(crate) use self::assignee::*;
|
||||
|
@ -17,7 +17,7 @@
|
||||
//! Enforces a branch of a conditional or iteration statement in a compiled Leo program.
|
||||
|
||||
use crate::{program::ConstrainedProgram, GroupType, IndicatorAndConstrainedValue, StatementResult};
|
||||
use leo_ast::{Block, Type};
|
||||
use leo_asg::BlockStatement;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -31,27 +31,13 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn evaluate_block<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
indicator: &Boolean,
|
||||
block: Block,
|
||||
return_type: Option<Type>,
|
||||
declared_circuit_reference: &str,
|
||||
mut_self: bool,
|
||||
block: &BlockStatement,
|
||||
) -> StatementResult<Vec<IndicatorAndConstrainedValue<F, G>>> {
|
||||
let mut results = Vec::with_capacity(block.statements.len());
|
||||
// Evaluate statements. Only allow a single return argument to be returned.
|
||||
for statement in block.statements.into_iter() {
|
||||
let value = self.enforce_statement(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
indicator,
|
||||
statement,
|
||||
return_type.clone(),
|
||||
declared_circuit_reference,
|
||||
mut_self,
|
||||
)?;
|
||||
for statement in block.statements.iter() {
|
||||
let value = self.enforce_statement(cs, indicator, statement)?;
|
||||
|
||||
results.extend(value);
|
||||
}
|
||||
|
@ -24,7 +24,7 @@ use crate::{
|
||||
IndicatorAndConstrainedValue,
|
||||
StatementResult,
|
||||
};
|
||||
use leo_ast::{ConditionalStatement, Type};
|
||||
use leo_asg::ConditionalStatement;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -47,33 +47,18 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_conditional_statement<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
indicator: &Boolean,
|
||||
return_type: Option<Type>,
|
||||
declared_circuit_reference: &str,
|
||||
mut_self: bool,
|
||||
statement: ConditionalStatement,
|
||||
statement: &ConditionalStatement,
|
||||
) -> StatementResult<Vec<IndicatorAndConstrainedValue<F, G>>> {
|
||||
let statement_string = statement.to_string();
|
||||
|
||||
let span = statement.span.clone().unwrap_or_default();
|
||||
// Inherit an indicator from a previous statement.
|
||||
let outer_indicator = indicator;
|
||||
|
||||
// Evaluate the conditional boolean as the inner indicator
|
||||
let inner_indicator = match self.enforce_expression(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
Some(Type::Boolean),
|
||||
statement.condition.clone(),
|
||||
)? {
|
||||
let inner_indicator = match self.enforce_expression(cs, &statement.condition)? {
|
||||
ConstrainedValue::Boolean(resolved) => resolved,
|
||||
value => {
|
||||
return Err(StatementError::conditional_boolean(
|
||||
value.to_string(),
|
||||
statement.span.clone(),
|
||||
));
|
||||
return Err(StatementError::conditional_boolean(value.to_string(), span));
|
||||
}
|
||||
};
|
||||
|
||||
@ -85,30 +70,16 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
outer_indicator_string, inner_indicator_string
|
||||
);
|
||||
let branch_1_indicator = Boolean::and(
|
||||
&mut cs.ns(|| {
|
||||
format!(
|
||||
"branch 1 {} {}:{}",
|
||||
statement_string, &statement.span.line, &statement.span.start
|
||||
)
|
||||
}),
|
||||
&mut cs.ns(|| format!("branch 1 {} {}:{}", span.text, &span.line, &span.start)),
|
||||
outer_indicator,
|
||||
&inner_indicator,
|
||||
)
|
||||
.map_err(|_| StatementError::indicator_calculation(branch_1_name, statement.span.clone()))?;
|
||||
.map_err(|_| StatementError::indicator_calculation(branch_1_name, span.clone()))?;
|
||||
|
||||
let mut results = vec![];
|
||||
|
||||
// Evaluate branch 1
|
||||
let mut branch_1_result = self.evaluate_block(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
&branch_1_indicator,
|
||||
statement.block,
|
||||
return_type.clone(),
|
||||
declared_circuit_reference,
|
||||
mut_self,
|
||||
)?;
|
||||
let mut branch_1_result = self.enforce_statement(cs, &branch_1_indicator, &statement.result)?;
|
||||
|
||||
results.append(&mut branch_1_result);
|
||||
|
||||
@ -119,26 +90,16 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
"branch indicator 2 {} && {}",
|
||||
outer_indicator_string, inner_indicator_string
|
||||
);
|
||||
let span = statement.span.clone();
|
||||
let branch_2_indicator = Boolean::and(
|
||||
&mut cs.ns(|| format!("branch 2 {} {}:{}", statement_string, &span.line, &span.start)),
|
||||
&mut cs.ns(|| format!("branch 2 {} {}:{}", span.text, &span.line, &span.start)),
|
||||
&outer_indicator,
|
||||
&inner_indicator,
|
||||
)
|
||||
.map_err(|_| StatementError::indicator_calculation(branch_2_name, span.clone()))?;
|
||||
|
||||
// Evaluate branch 2
|
||||
let mut branch_2_result = match statement.next {
|
||||
Some(next) => self.enforce_statement(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
&branch_2_indicator,
|
||||
*next,
|
||||
return_type,
|
||||
declared_circuit_reference,
|
||||
mut_self,
|
||||
)?,
|
||||
let mut branch_2_result = match &statement.next {
|
||||
Some(next) => self.enforce_statement(cs, &branch_2_indicator, next)?,
|
||||
None => vec![],
|
||||
};
|
||||
|
||||
|
@ -17,7 +17,7 @@
|
||||
//! Enforces a definition statement in a compiled Leo program.
|
||||
|
||||
use crate::{errors::StatementError, program::ConstrainedProgram, ConstrainedValue, GroupType};
|
||||
use leo_ast::{Declare, DefinitionStatement, Span, VariableName};
|
||||
use leo_asg::{DefinitionStatement, Span, Variable};
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -25,35 +25,9 @@ use snarkvm_models::{
|
||||
};
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
fn enforce_single_definition<CS: ConstraintSystem<F>>(
|
||||
fn enforce_multiple_definition(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
function_scope: &str,
|
||||
is_constant: bool,
|
||||
variable_name: VariableName,
|
||||
mut value: ConstrainedValue<F, G>,
|
||||
span: &Span,
|
||||
) -> Result<(), StatementError> {
|
||||
if is_constant && variable_name.mutable {
|
||||
return Err(StatementError::immutable_assign(
|
||||
variable_name.to_string(),
|
||||
span.to_owned(),
|
||||
));
|
||||
} else {
|
||||
value.allocate_value(cs, span)?
|
||||
}
|
||||
|
||||
self.store_definition(function_scope, variable_name.mutable, variable_name.identifier, value);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn enforce_multiple_definition<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
function_scope: &str,
|
||||
is_constant: bool,
|
||||
variable_names: Vec<VariableName>,
|
||||
variable_names: &[Variable],
|
||||
values: Vec<ConstrainedValue<F, G>>,
|
||||
span: &Span,
|
||||
) -> Result<(), StatementError> {
|
||||
@ -65,8 +39,8 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
));
|
||||
}
|
||||
|
||||
for (variable, value) in variable_names.into_iter().zip(values.into_iter()) {
|
||||
self.enforce_single_definition(cs, function_scope, is_constant, variable, value, span)?;
|
||||
for (variable, value) in variable_names.iter().zip(values.into_iter()) {
|
||||
self.store_definition(variable, value);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@ -76,39 +50,25 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_definition_statement<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
statement: DefinitionStatement,
|
||||
statement: &DefinitionStatement,
|
||||
) -> Result<(), StatementError> {
|
||||
let num_variables = statement.variable_names.len();
|
||||
let is_constant = match statement.declaration_type {
|
||||
Declare::Let => false,
|
||||
Declare::Const => true,
|
||||
};
|
||||
let expression =
|
||||
self.enforce_expression(cs, file_scope, function_scope, statement.type_.clone(), statement.value)?;
|
||||
let num_variables = statement.variables.len();
|
||||
let expression = self.enforce_expression(cs, &statement.value)?;
|
||||
|
||||
let span = statement.span.clone().unwrap_or_default();
|
||||
if num_variables == 1 {
|
||||
// Define a single variable with a single value
|
||||
let variable = statement.variable_names[0].clone();
|
||||
|
||||
self.enforce_single_definition(cs, function_scope, is_constant, variable, expression, &statement.span)
|
||||
self.store_definition(statement.variables.get(0).unwrap(), expression);
|
||||
Ok(())
|
||||
} else {
|
||||
// Define multiple variables for an expression that returns multiple results (multiple definition)
|
||||
let values = match expression {
|
||||
// ConstrainedValue::Return(values) => values,
|
||||
ConstrainedValue::Tuple(values) => values,
|
||||
value => return Err(StatementError::multiple_definition(value.to_string(), statement.span)),
|
||||
value => return Err(StatementError::multiple_definition(value.to_string(), span)),
|
||||
};
|
||||
|
||||
self.enforce_multiple_definition(
|
||||
cs,
|
||||
function_scope,
|
||||
is_constant,
|
||||
statement.variable_names,
|
||||
values,
|
||||
&statement.span,
|
||||
)
|
||||
self.enforce_multiple_definition(&statement.variables, values, &span)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -17,7 +17,6 @@
|
||||
//! Enforces an iteration statement in a compiled Leo program.
|
||||
|
||||
use crate::{
|
||||
new_scope,
|
||||
program::ConstrainedProgram,
|
||||
value::ConstrainedValue,
|
||||
GroupType,
|
||||
@ -25,7 +24,7 @@ use crate::{
|
||||
Integer,
|
||||
StatementResult,
|
||||
};
|
||||
use leo_ast::{IterationStatement, Type};
|
||||
use leo_asg::IterationStatement;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -40,41 +39,32 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_iteration_statement<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
indicator: &Boolean,
|
||||
return_type: Option<Type>,
|
||||
declared_circuit_reference: &str,
|
||||
mut_self: bool,
|
||||
statement: IterationStatement,
|
||||
statement: &IterationStatement,
|
||||
) -> StatementResult<Vec<IndicatorAndConstrainedValue<F, G>>> {
|
||||
let mut results = vec![];
|
||||
|
||||
let from = self.enforce_index(cs, file_scope, function_scope, statement.start, &statement.span)?;
|
||||
let to = self.enforce_index(cs, file_scope, function_scope, statement.stop, &statement.span)?;
|
||||
let span = statement.span.clone().unwrap_or_default();
|
||||
|
||||
let from = self.enforce_index(cs, &statement.start, &span)?;
|
||||
let to = self.enforce_index(cs, &statement.stop, &span)?;
|
||||
|
||||
let span = statement.span.clone();
|
||||
for i in from..to {
|
||||
// Store index in current function scope.
|
||||
// For loop scope is not implemented.
|
||||
let variable = statement.variable.borrow();
|
||||
|
||||
let index_name = new_scope(function_scope, &statement.variable.name);
|
||||
|
||||
// todo: replace definition with var typed
|
||||
self.store(
|
||||
index_name,
|
||||
variable.id,
|
||||
ConstrainedValue::Integer(Integer::U32(UInt32::constant(i as u32))),
|
||||
);
|
||||
|
||||
// Evaluate statements and possibly return early
|
||||
let result = self.evaluate_block(
|
||||
let result = self.enforce_statement(
|
||||
&mut cs.ns(|| format!("for loop iteration {} {}:{}", i, &span.line, &span.start)),
|
||||
file_scope,
|
||||
function_scope,
|
||||
indicator,
|
||||
statement.block.clone(),
|
||||
return_type.clone(),
|
||||
declared_circuit_reference,
|
||||
mut_self,
|
||||
&statement.body,
|
||||
)?;
|
||||
|
||||
results.extend(result);
|
||||
|
@ -17,49 +17,20 @@
|
||||
//! Enforces a return statement in a compiled Leo program.
|
||||
|
||||
use crate::{errors::StatementError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::{ReturnStatement, Span, Type};
|
||||
use leo_asg::ReturnStatement;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
gadgets::r1cs::ConstraintSystem,
|
||||
};
|
||||
|
||||
/// Returns `Ok` if the expected type == actual type, returns `Err` otherwise.
|
||||
pub fn check_return_type(expected: &Type, actual: &Type, span: &Span) -> Result<(), StatementError> {
|
||||
if expected.ne(&actual) {
|
||||
// If the return type is `SelfType` returning the circuit type is okay.
|
||||
return if (expected.is_self() && actual.is_circuit()) || expected.eq_flat(&actual) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StatementError::arguments_type(&expected, &actual, span.to_owned()))
|
||||
};
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_return_statement<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
return_type: Option<Type>,
|
||||
statement: ReturnStatement,
|
||||
statement: &ReturnStatement,
|
||||
) -> Result<ConstrainedValue<F, G>, StatementError> {
|
||||
let result = self.enforce_operand(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
return_type.clone(),
|
||||
statement.expression,
|
||||
&statement.span,
|
||||
)?;
|
||||
|
||||
// Make sure we return the correct type.
|
||||
if let Some(expected) = return_type {
|
||||
check_return_type(&expected, &result.to_type(&statement.span)?, &statement.span)?;
|
||||
}
|
||||
|
||||
let result = self.enforce_operand(cs, &statement.expression)?;
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
@ -17,7 +17,8 @@
|
||||
//! Enforces a statement in a compiled Leo program.
|
||||
|
||||
use crate::{errors::StatementError, program::ConstrainedProgram, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::{Statement, Type};
|
||||
use leo_asg::Statement;
|
||||
use std::sync::Arc;
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, PrimeField},
|
||||
@ -39,73 +40,38 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
pub fn enforce_statement<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
cs: &mut CS,
|
||||
file_scope: &str,
|
||||
function_scope: &str,
|
||||
indicator: &Boolean,
|
||||
statement: Statement,
|
||||
return_type: Option<Type>,
|
||||
declared_circuit_reference: &str,
|
||||
mut_self: bool,
|
||||
statement: &Arc<Statement>,
|
||||
) -> StatementResult<Vec<IndicatorAndConstrainedValue<F, G>>> {
|
||||
let mut results = vec![];
|
||||
|
||||
match statement {
|
||||
match &**statement {
|
||||
Statement::Return(statement) => {
|
||||
let return_value = (
|
||||
*indicator,
|
||||
self.enforce_return_statement(cs, file_scope, function_scope, return_type, statement)?,
|
||||
);
|
||||
let return_value = (*indicator, self.enforce_return_statement(cs, statement)?);
|
||||
|
||||
results.push(return_value);
|
||||
}
|
||||
Statement::Definition(statement) => {
|
||||
self.enforce_definition_statement(cs, file_scope, function_scope, statement)?;
|
||||
self.enforce_definition_statement(cs, statement)?;
|
||||
}
|
||||
Statement::Assign(statement) => {
|
||||
self.enforce_assign_statement(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
declared_circuit_reference,
|
||||
indicator,
|
||||
mut_self,
|
||||
statement,
|
||||
)?;
|
||||
self.enforce_assign_statement(cs, indicator, statement)?;
|
||||
}
|
||||
Statement::Conditional(statement) => {
|
||||
let result = self.enforce_conditional_statement(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
indicator,
|
||||
return_type,
|
||||
declared_circuit_reference,
|
||||
mut_self,
|
||||
statement,
|
||||
)?;
|
||||
let result = self.enforce_conditional_statement(cs, indicator, statement)?;
|
||||
|
||||
results.extend(result);
|
||||
}
|
||||
Statement::Iteration(statement) => {
|
||||
let result = self.enforce_iteration_statement(
|
||||
cs,
|
||||
file_scope,
|
||||
function_scope,
|
||||
indicator,
|
||||
return_type,
|
||||
declared_circuit_reference,
|
||||
mut_self,
|
||||
statement,
|
||||
)?;
|
||||
let result = self.enforce_iteration_statement(cs, indicator, statement)?;
|
||||
|
||||
results.extend(result);
|
||||
}
|
||||
Statement::Console(statement) => {
|
||||
self.evaluate_console_function_call(cs, file_scope, function_scope, indicator, statement)?;
|
||||
self.evaluate_console_function_call(cs, indicator, statement)?;
|
||||
}
|
||||
Statement::Expression(statement) => {
|
||||
let expression_string = statement.expression.to_string();
|
||||
let value = self.enforce_expression(cs, file_scope, function_scope, None, statement.expression)?;
|
||||
let value = self.enforce_expression(cs, &statement.expression)?;
|
||||
// handle empty return value cases
|
||||
match &value {
|
||||
ConstrainedValue::Tuple(values) => {
|
||||
@ -113,20 +79,20 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
|
||||
results.push((*indicator, value));
|
||||
}
|
||||
}
|
||||
_ => return Err(StatementError::unassigned(expression_string, statement.span)),
|
||||
_ => {
|
||||
return Err(StatementError::unassigned(
|
||||
statement.span.as_ref().map(|x| x.text.clone()).unwrap_or_default(),
|
||||
statement.span.clone().unwrap_or_default(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Statement::Block(statement) => {
|
||||
let span = statement.span.clone();
|
||||
let span = statement.span.clone().unwrap_or_default();
|
||||
let result = self.evaluate_block(
|
||||
&mut cs.ns(|| format!("block {}:{}", &span.line, &span.start)),
|
||||
file_scope,
|
||||
function_scope,
|
||||
indicator,
|
||||
statement,
|
||||
return_type,
|
||||
declared_circuit_reference,
|
||||
mut_self,
|
||||
)?;
|
||||
|
||||
results.extend(result);
|
||||
|
@ -28,14 +28,6 @@ use snarkvm_models::{
|
||||
},
|
||||
};
|
||||
|
||||
pub(crate) fn new_bool_constant(string: String, span: &Span) -> Result<Boolean, BooleanError> {
|
||||
let boolean = string
|
||||
.parse::<bool>()
|
||||
.map_err(|_| BooleanError::invalid_boolean(string, span.to_owned()))?;
|
||||
|
||||
Ok(Boolean::constant(boolean))
|
||||
}
|
||||
|
||||
pub(crate) fn allocate_bool<F: Field + PrimeField, CS: ConstraintSystem<F>>(
|
||||
cs: &mut CS,
|
||||
name: &str,
|
||||
|
@ -17,7 +17,7 @@
|
||||
//! A data type that represents members in the group formed by the set of affine points on a curve.
|
||||
|
||||
use crate::errors::GroupError;
|
||||
use leo_ast::{GroupValue, Span};
|
||||
use leo_asg::{GroupValue, Span};
|
||||
|
||||
use snarkvm_models::{
|
||||
curves::{Field, One},
|
||||
@ -48,7 +48,7 @@ pub trait GroupType<F: Field>:
|
||||
+ ToBitsGadget<F>
|
||||
+ ToBytesGadget<F>
|
||||
{
|
||||
fn constant(value: GroupValue) -> Result<Self, GroupError>;
|
||||
fn constant(value: &GroupValue, span: &Span) -> Result<Self, GroupError>;
|
||||
|
||||
fn to_allocated<CS: ConstraintSystem<F>>(&self, cs: CS, span: &Span) -> Result<Self, GroupError>;
|
||||
|
||||
|
@ -17,7 +17,8 @@
|
||||
//! Methods to enforce constraints on input group values in a Leo program.
|
||||
|
||||
use crate::{errors::GroupError, ConstrainedValue, GroupType};
|
||||
use leo_ast::{GroupValue, InputValue, Span};
|
||||
use leo_asg::{GroupValue, Span};
|
||||
use leo_ast::InputValue;
|
||||
|
||||
use snarkvm_errors::gadgets::SynthesisError;
|
||||
use snarkvm_models::{
|
||||
@ -56,7 +57,15 @@ pub(crate) fn group_from_input<F: Field + PrimeField, G: GroupType<F>, CS: Const
|
||||
None => None,
|
||||
};
|
||||
|
||||
let group = allocate_group(cs, name, option, span)?;
|
||||
let group = allocate_group(
|
||||
cs,
|
||||
name,
|
||||
option.map(|x| match x {
|
||||
leo_ast::GroupValue::Single(s, _) => GroupValue::Single(s),
|
||||
leo_ast::GroupValue::Tuple(leo_ast::GroupTuple { x, y, .. }) => GroupValue::Tuple((&x).into(), (&y).into()),
|
||||
}),
|
||||
span,
|
||||
)?;
|
||||
|
||||
Ok(ConstrainedValue::Group(group))
|
||||
}
|
||||
|
@ -15,7 +15,7 @@
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::{errors::GroupError, GroupType};
|
||||
use leo_ast::{GroupCoordinate, GroupTuple, GroupValue, Span};
|
||||
use leo_asg::{GroupCoordinate, GroupValue, Span};
|
||||
|
||||
use snarkvm_curves::{
|
||||
edwards_bls12::{EdwardsAffine, EdwardsParameters, Fq},
|
||||
@ -52,8 +52,8 @@ pub enum EdwardsGroupType {
|
||||
}
|
||||
|
||||
impl GroupType<Fq> for EdwardsGroupType {
|
||||
fn constant(group: GroupValue) -> Result<Self, GroupError> {
|
||||
let value = Self::edwards_affine_from_value(group)?;
|
||||
fn constant(group: &GroupValue, span: &Span) -> Result<Self, GroupError> {
|
||||
let value = Self::edwards_affine_from_value(group, span)?;
|
||||
|
||||
Ok(EdwardsGroupType::Constant(value))
|
||||
}
|
||||
@ -134,75 +134,79 @@ impl GroupType<Fq> for EdwardsGroupType {
|
||||
}
|
||||
|
||||
impl EdwardsGroupType {
|
||||
pub fn edwards_affine_from_value(value: GroupValue) -> Result<EdwardsAffine, GroupError> {
|
||||
pub fn edwards_affine_from_value(value: &GroupValue, span: &Span) -> Result<EdwardsAffine, GroupError> {
|
||||
match value {
|
||||
GroupValue::Single(number, span) => Self::edwards_affine_from_single(number, span),
|
||||
GroupValue::Tuple(tuple) => Self::edwards_affine_from_tuple(tuple),
|
||||
GroupValue::Single(number, ..) => Self::edwards_affine_from_single(number, span),
|
||||
GroupValue::Tuple(x, y) => Self::edwards_affine_from_tuple(x, y, span),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn edwards_affine_from_single(number: String, span: Span) -> Result<EdwardsAffine, GroupError> {
|
||||
pub fn edwards_affine_from_single(number: &str, span: &Span) -> Result<EdwardsAffine, GroupError> {
|
||||
if number.eq("0") {
|
||||
Ok(EdwardsAffine::zero())
|
||||
} else {
|
||||
let one = edwards_affine_one();
|
||||
let number_value = Fp256::from_str(&number).map_err(|_| GroupError::n_group(number, span))?;
|
||||
let number_value =
|
||||
Fp256::from_str(&number).map_err(|_| GroupError::n_group(number.to_string(), span.clone()))?;
|
||||
let result: EdwardsAffine = one.mul(&number_value);
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn edwards_affine_from_tuple(group: GroupTuple) -> Result<EdwardsAffine, GroupError> {
|
||||
let span = group.span;
|
||||
let x = group.x;
|
||||
let y = group.y;
|
||||
pub fn edwards_affine_from_tuple(
|
||||
x: &GroupCoordinate,
|
||||
y: &GroupCoordinate,
|
||||
span: &Span,
|
||||
) -> Result<EdwardsAffine, GroupError> {
|
||||
let x = x.clone();
|
||||
let y = y.clone();
|
||||
|
||||
match (x, y) {
|
||||
// (x, y)
|
||||
(GroupCoordinate::Number(x_string, x_span), GroupCoordinate::Number(y_string, y_span)) => {
|
||||
Self::edwards_affine_from_pair(x_string, y_string, x_span, y_span, span)
|
||||
(GroupCoordinate::Number(x_string), GroupCoordinate::Number(y_string)) => {
|
||||
Self::edwards_affine_from_pair(x_string, y_string, span, span, span)
|
||||
}
|
||||
// (x, +)
|
||||
(GroupCoordinate::Number(x_string, x_span), GroupCoordinate::SignHigh) => {
|
||||
Self::edwards_affine_from_x_str(x_string, x_span, Some(true), span)
|
||||
(GroupCoordinate::Number(x_string), GroupCoordinate::SignHigh) => {
|
||||
Self::edwards_affine_from_x_str(x_string, span, Some(true), span)
|
||||
}
|
||||
// (x, -)
|
||||
(GroupCoordinate::Number(x_string, x_span), GroupCoordinate::SignLow) => {
|
||||
Self::edwards_affine_from_x_str(x_string, x_span, Some(false), span)
|
||||
(GroupCoordinate::Number(x_string), GroupCoordinate::SignLow) => {
|
||||
Self::edwards_affine_from_x_str(x_string, span, Some(false), span)
|
||||
}
|
||||
// (x, _)
|
||||
(GroupCoordinate::Number(x_string, x_span), GroupCoordinate::Inferred) => {
|
||||
Self::edwards_affine_from_x_str(x_string, x_span, None, span)
|
||||
(GroupCoordinate::Number(x_string), GroupCoordinate::Inferred) => {
|
||||
Self::edwards_affine_from_x_str(x_string, span, None, span)
|
||||
}
|
||||
// (+, y)
|
||||
(GroupCoordinate::SignHigh, GroupCoordinate::Number(y_string, y_span)) => {
|
||||
Self::edwards_affine_from_y_str(y_string, y_span, Some(true), span)
|
||||
(GroupCoordinate::SignHigh, GroupCoordinate::Number(y_string)) => {
|
||||
Self::edwards_affine_from_y_str(y_string, span, Some(true), span)
|
||||
}
|
||||
// (-, y)
|
||||
(GroupCoordinate::SignLow, GroupCoordinate::Number(y_string, y_span)) => {
|
||||
Self::edwards_affine_from_y_str(y_string, y_span, Some(false), span)
|
||||
(GroupCoordinate::SignLow, GroupCoordinate::Number(y_string)) => {
|
||||
Self::edwards_affine_from_y_str(y_string, span, Some(false), span)
|
||||
}
|
||||
// (_, y)
|
||||
(GroupCoordinate::Inferred, GroupCoordinate::Number(y_string, y_span)) => {
|
||||
Self::edwards_affine_from_y_str(y_string, y_span, None, span)
|
||||
(GroupCoordinate::Inferred, GroupCoordinate::Number(y_string)) => {
|
||||
Self::edwards_affine_from_y_str(y_string, span, None, span)
|
||||
}
|
||||
// Invalid
|
||||
(x, y) => Err(GroupError::invalid_group(format!("({}, {})", x, y), span)),
|
||||
(x, y) => Err(GroupError::invalid_group(format!("({}, {})", x, y), span.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn edwards_affine_from_x_str(
|
||||
x_string: String,
|
||||
x_span: Span,
|
||||
x_span: &Span,
|
||||
greatest: Option<bool>,
|
||||
element_span: Span,
|
||||
element_span: &Span,
|
||||
) -> Result<EdwardsAffine, GroupError> {
|
||||
let x = Fq::from_str(&x_string).map_err(|_| GroupError::x_invalid(x_string, x_span))?;
|
||||
let x = Fq::from_str(&x_string).map_err(|_| GroupError::x_invalid(x_string, x_span.clone()))?;
|
||||
match greatest {
|
||||
// Sign provided
|
||||
Some(greatest) => {
|
||||
EdwardsAffine::from_x_coordinate(x, greatest).ok_or_else(|| GroupError::x_recover(element_span))
|
||||
EdwardsAffine::from_x_coordinate(x, greatest).ok_or_else(|| GroupError::x_recover(element_span.clone()))
|
||||
}
|
||||
// Sign inferred
|
||||
None => {
|
||||
@ -217,23 +221,23 @@ impl EdwardsGroupType {
|
||||
}
|
||||
|
||||
// Otherwise return error.
|
||||
Err(GroupError::x_recover(element_span))
|
||||
Err(GroupError::x_recover(element_span.clone()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn edwards_affine_from_y_str(
|
||||
y_string: String,
|
||||
y_span: Span,
|
||||
y_span: &Span,
|
||||
greatest: Option<bool>,
|
||||
element_span: Span,
|
||||
element_span: &Span,
|
||||
) -> Result<EdwardsAffine, GroupError> {
|
||||
let y = Fq::from_str(&y_string).map_err(|_| GroupError::y_invalid(y_string, y_span))?;
|
||||
let y = Fq::from_str(&y_string).map_err(|_| GroupError::y_invalid(y_string, y_span.clone()))?;
|
||||
|
||||
match greatest {
|
||||
// Sign provided
|
||||
Some(greatest) => {
|
||||
EdwardsAffine::from_y_coordinate(y, greatest).ok_or_else(|| GroupError::y_recover(element_span))
|
||||
EdwardsAffine::from_y_coordinate(y, greatest).ok_or_else(|| GroupError::y_recover(element_span.clone()))
|
||||
}
|
||||
// Sign inferred
|
||||
None => {
|
||||
@ -248,7 +252,7 @@ impl EdwardsGroupType {
|
||||
}
|
||||
|
||||
// Otherwise return error.
|
||||
Err(GroupError::y_recover(element_span))
|
||||
Err(GroupError::y_recover(element_span.clone()))
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -256,19 +260,19 @@ impl EdwardsGroupType {
|
||||
pub fn edwards_affine_from_pair(
|
||||
x_string: String,
|
||||
y_string: String,
|
||||
x_span: Span,
|
||||
y_span: Span,
|
||||
element_span: Span,
|
||||
x_span: &Span,
|
||||
y_span: &Span,
|
||||
element_span: &Span,
|
||||
) -> Result<EdwardsAffine, GroupError> {
|
||||
let x = Fq::from_str(&x_string).map_err(|_| GroupError::x_invalid(x_string, x_span))?;
|
||||
let y = Fq::from_str(&y_string).map_err(|_| GroupError::y_invalid(y_string, y_span))?;
|
||||
let x = Fq::from_str(&x_string).map_err(|_| GroupError::x_invalid(x_string, x_span.clone()))?;
|
||||
let y = Fq::from_str(&y_string).map_err(|_| GroupError::y_invalid(y_string, y_span.clone()))?;
|
||||
|
||||
let element = EdwardsAffine::new(x, y);
|
||||
|
||||
if element.is_on_curve() {
|
||||
Ok(element)
|
||||
} else {
|
||||
Err(GroupError::not_on_curve(element.to_string(), element_span))
|
||||
Err(GroupError::not_on_curve(element.to_string(), element_span.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
@ -283,7 +287,7 @@ impl EdwardsGroupType {
|
||||
_ => Err(SynthesisError::AssignmentMissing),
|
||||
}?;
|
||||
|
||||
Self::edwards_affine_from_value(group_value).map_err(|_| SynthesisError::AssignmentMissing)
|
||||
Self::edwards_affine_from_value(&group_value, &Span::default()).map_err(|_| SynthesisError::AssignmentMissing)
|
||||
}
|
||||
|
||||
pub fn allocated<CS: ConstraintSystem<Fq>>(&self, mut cs: CS) -> Result<EdwardsBlsGadget, SynthesisError> {
|
||||
|
@ -1,33 +0,0 @@
|
||||
// Copyright (C) 2019-2021 Aleo Systems Inc.
|
||||
// This file is part of the Leo library.
|
||||
|
||||
// The Leo library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// The Leo library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
//! Enforces constraints on an implicit number in a compiled Leo program.
|
||||
|
||||
use crate::{errors::ValueError, value::ConstrainedValue, GroupType};
|
||||
use leo_ast::{Span, Type};
|
||||
|
||||
use snarkvm_models::curves::{Field, PrimeField};
|
||||
|
||||
pub fn enforce_number_implicit<F: Field + PrimeField, G: GroupType<F>>(
|
||||
expected_type: Option<Type>,
|
||||
value: String,
|
||||
span: &Span,
|
||||
) -> Result<ConstrainedValue<F, G>, ValueError> {
|
||||
match expected_type {
|
||||
Some(type_) => Ok(ConstrainedValue::from_type(value, &type_, span)?),
|
||||
None => Ok(ConstrainedValue::Unresolved(value)),
|
||||
}
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
// Copyright (C) 2019-2021 Aleo Systems Inc.
|
||||
// This file is part of the Leo library.
|
||||
|
||||
// The Leo library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// The Leo library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
pub mod implicit;
|
||||
pub use self::implicit::*;
|
@ -16,7 +16,8 @@
|
||||
|
||||
//! Conversion of integer declarations to constraints in Leo.
|
||||
use crate::{errors::IntegerError, IntegerTrait};
|
||||
use leo_ast::{InputValue, IntegerType, Span, Type};
|
||||
use leo_asg::{ConstInt, IntegerType, Span};
|
||||
use leo_ast::InputValue;
|
||||
use leo_gadgets::{
|
||||
arithmetic::*,
|
||||
bits::comparator::{ComparatorGadget, EvaluateLtGadget},
|
||||
@ -72,112 +73,18 @@ impl Integer {
|
||||
///
|
||||
/// Checks that the expression is equal to the expected type if given.
|
||||
///
|
||||
pub fn new(
|
||||
expected_type: Option<Type>,
|
||||
actual_integer_type: &IntegerType,
|
||||
string: String,
|
||||
span: &Span,
|
||||
) -> Result<Self, IntegerError> {
|
||||
// Check expected type if given.
|
||||
if let Some(type_) = expected_type {
|
||||
// Check expected type is an integer.
|
||||
match type_ {
|
||||
Type::IntegerType(expected_integer_type) => {
|
||||
// Check expected integer type == actual integer type
|
||||
if expected_integer_type.ne(actual_integer_type) {
|
||||
return Err(IntegerError::invalid_integer_type(
|
||||
&expected_integer_type,
|
||||
actual_integer_type,
|
||||
span.to_owned(),
|
||||
));
|
||||
}
|
||||
}
|
||||
type_ => return Err(IntegerError::invalid_type(&type_, span.to_owned())),
|
||||
}
|
||||
}
|
||||
|
||||
// Return a new constant integer.
|
||||
Self::new_constant(actual_integer_type, string, span)
|
||||
}
|
||||
|
||||
///
|
||||
/// Returns a new integer value from an expression.
|
||||
///
|
||||
/// The returned integer value is "constant" and is not allocated in the constraint system.
|
||||
///
|
||||
pub fn new_constant(integer_type: &IntegerType, string: String, span: &Span) -> Result<Self, IntegerError> {
|
||||
match integer_type {
|
||||
IntegerType::U8 => {
|
||||
let number = string
|
||||
.parse::<u8>()
|
||||
.map_err(|_| IntegerError::invalid_integer(string, span.to_owned()))?;
|
||||
|
||||
Ok(Integer::U8(UInt8::constant(number)))
|
||||
}
|
||||
IntegerType::U16 => {
|
||||
let number = string
|
||||
.parse::<u16>()
|
||||
.map_err(|_| IntegerError::invalid_integer(string, span.to_owned()))?;
|
||||
|
||||
Ok(Integer::U16(UInt16::constant(number)))
|
||||
}
|
||||
IntegerType::U32 => {
|
||||
let number = string
|
||||
.parse::<u32>()
|
||||
.map_err(|_| IntegerError::invalid_integer(string, span.to_owned()))?;
|
||||
|
||||
Ok(Integer::U32(UInt32::constant(number)))
|
||||
}
|
||||
IntegerType::U64 => {
|
||||
let number = string
|
||||
.parse::<u64>()
|
||||
.map_err(|_| IntegerError::invalid_integer(string, span.to_owned()))?;
|
||||
|
||||
Ok(Integer::U64(UInt64::constant(number)))
|
||||
}
|
||||
IntegerType::U128 => {
|
||||
let number = string
|
||||
.parse::<u128>()
|
||||
.map_err(|_| IntegerError::invalid_integer(string, span.to_owned()))?;
|
||||
|
||||
Ok(Integer::U128(UInt128::constant(number)))
|
||||
}
|
||||
|
||||
IntegerType::I8 => {
|
||||
let number = string
|
||||
.parse::<i8>()
|
||||
.map_err(|_| IntegerError::invalid_integer(string, span.to_owned()))?;
|
||||
|
||||
Ok(Integer::I8(Int8::constant(number)))
|
||||
}
|
||||
IntegerType::I16 => {
|
||||
let number = string
|
||||
.parse::<i16>()
|
||||
.map_err(|_| IntegerError::invalid_integer(string, span.to_owned()))?;
|
||||
|
||||
Ok(Integer::I16(Int16::constant(number)))
|
||||
}
|
||||
IntegerType::I32 => {
|
||||
let number = string
|
||||
.parse::<i32>()
|
||||
.map_err(|_| IntegerError::invalid_integer(string, span.to_owned()))?;
|
||||
|
||||
Ok(Integer::I32(Int32::constant(number)))
|
||||
}
|
||||
IntegerType::I64 => {
|
||||
let number = string
|
||||
.parse::<i64>()
|
||||
.map_err(|_| IntegerError::invalid_integer(string, span.to_owned()))?;
|
||||
|
||||
Ok(Integer::I64(Int64::constant(number)))
|
||||
}
|
||||
IntegerType::I128 => {
|
||||
let number = string
|
||||
.parse::<i128>()
|
||||
.map_err(|_| IntegerError::invalid_integer(string, span.to_owned()))?;
|
||||
|
||||
Ok(Integer::I128(Int128::constant(number)))
|
||||
}
|
||||
pub fn new(value: &ConstInt) -> Self {
|
||||
match value {
|
||||
ConstInt::U8(i) => Integer::U8(UInt8::constant(*i)),
|
||||
ConstInt::U16(i) => Integer::U16(UInt16::constant(*i)),
|
||||
ConstInt::U32(i) => Integer::U32(UInt32::constant(*i)),
|
||||
ConstInt::U64(i) => Integer::U64(UInt64::constant(*i)),
|
||||
ConstInt::U128(i) => Integer::U128(UInt128::constant(*i)),
|
||||
ConstInt::I8(i) => Integer::I8(Int8::constant(*i)),
|
||||
ConstInt::I16(i) => Integer::I16(Int16::constant(*i)),
|
||||
ConstInt::I32(i) => Integer::I32(Int32::constant(*i)),
|
||||
ConstInt::I64(i) => Integer::I64(Int64::constant(*i)),
|
||||
ConstInt::I128(i) => Integer::I128(Int128::constant(*i)),
|
||||
}
|
||||
}
|
||||
|
||||
@ -220,7 +127,7 @@ impl Integer {
|
||||
|
||||
pub fn allocate_type<F: Field, CS: ConstraintSystem<F>>(
|
||||
cs: &mut CS,
|
||||
integer_type: IntegerType,
|
||||
integer_type: &IntegerType,
|
||||
name: &str,
|
||||
option: Option<String>,
|
||||
span: &Span,
|
||||
@ -371,7 +278,7 @@ impl Integer {
|
||||
|
||||
pub fn from_input<F: Field, CS: ConstraintSystem<F>>(
|
||||
cs: &mut CS,
|
||||
integer_type: IntegerType,
|
||||
integer_type: &IntegerType,
|
||||
name: &str,
|
||||
integer_value: Option<InputValue>,
|
||||
span: &Span,
|
||||
|
@ -27,9 +27,6 @@ pub use self::field::*;
|
||||
pub mod group;
|
||||
pub use self::group::*;
|
||||
|
||||
pub mod implicit;
|
||||
pub use self::implicit::*;
|
||||
|
||||
pub mod integer;
|
||||
pub use self::integer::*;
|
||||
|
||||
|
@ -16,18 +16,8 @@
|
||||
|
||||
//! The in memory stored value for a defined name in a compiled Leo program.
|
||||
|
||||
use crate::{
|
||||
boolean::input::{allocate_bool, new_bool_constant},
|
||||
errors::{ExpressionError, FieldError, ValueError},
|
||||
is_in_scope,
|
||||
new_scope,
|
||||
Address,
|
||||
FieldType,
|
||||
GroupType,
|
||||
Integer,
|
||||
};
|
||||
use leo_ast::{ArrayDimensions, Circuit, Function, GroupValue, Identifier, Span, Type};
|
||||
use leo_core::Value;
|
||||
use crate::{errors::ValueError, Address, FieldType, GroupType, Integer};
|
||||
use leo_asg::{CircuitBody, Identifier, Span, Type};
|
||||
|
||||
use snarkvm_errors::gadgets::SynthesisError;
|
||||
use snarkvm_models::{
|
||||
@ -37,7 +27,7 @@ use snarkvm_models::{
|
||||
utilities::{boolean::Boolean, eq::ConditionalEqGadget, select::CondSelectGadget},
|
||||
},
|
||||
};
|
||||
use std::fmt;
|
||||
use std::{fmt, sync::Arc};
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct ConstrainedCircuitMember<F: Field + PrimeField, G: GroupType<F>>(pub Identifier, pub ConstrainedValue<F, G>);
|
||||
@ -58,50 +48,13 @@ pub enum ConstrainedValue<F: Field + PrimeField, G: GroupType<F>> {
|
||||
Tuple(Vec<ConstrainedValue<F, G>>),
|
||||
|
||||
// Circuits
|
||||
CircuitDefinition(Circuit),
|
||||
CircuitExpression(Identifier, Vec<ConstrainedCircuitMember<F, G>>),
|
||||
|
||||
// Functions
|
||||
Function(Option<Identifier>, Box<Function>), // (optional circuit identifier, function definition)
|
||||
CircuitExpression(Arc<CircuitBody>, Vec<ConstrainedCircuitMember<F, G>>),
|
||||
|
||||
// Modifiers
|
||||
Mutable(Box<ConstrainedValue<F, G>>),
|
||||
Static(Box<ConstrainedValue<F, G>>),
|
||||
Unresolved(String),
|
||||
|
||||
// Imports
|
||||
Import(String, Box<ConstrainedValue<F, G>>),
|
||||
}
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedValue<F, G> {
|
||||
pub(crate) fn from_other(value: String, other: &ConstrainedValue<F, G>, span: &Span) -> Result<Self, ValueError> {
|
||||
let other_type = other.to_type(span)?;
|
||||
|
||||
ConstrainedValue::from_type(value, &other_type, span)
|
||||
}
|
||||
|
||||
pub(crate) fn from_type(value: String, type_: &Type, span: &Span) -> Result<Self, ValueError> {
|
||||
match type_ {
|
||||
// Data types
|
||||
Type::Address => Ok(ConstrainedValue::Address(Address::constant(value, span)?)),
|
||||
Type::Boolean => Ok(ConstrainedValue::Boolean(new_bool_constant(value, span)?)),
|
||||
Type::Field => Ok(ConstrainedValue::Field(FieldType::constant(value, span)?)),
|
||||
Type::Group => Ok(ConstrainedValue::Group(G::constant(GroupValue::Single(
|
||||
value,
|
||||
span.to_owned(),
|
||||
))?)),
|
||||
Type::IntegerType(integer_type) => Ok(ConstrainedValue::Integer(Integer::new_constant(
|
||||
integer_type,
|
||||
value,
|
||||
span,
|
||||
)?)),
|
||||
|
||||
// Data type wrappers
|
||||
Type::Array(ref type_, _dimensions) => ConstrainedValue::from_type(value, type_, span),
|
||||
_ => Ok(ConstrainedValue::Unresolved(value)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn to_type(&self, span: &Span) -> Result<Type, ValueError> {
|
||||
Ok(match self {
|
||||
// Data types
|
||||
@ -109,21 +62,13 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedValue<F, G> {
|
||||
ConstrainedValue::Boolean(_bool) => Type::Boolean,
|
||||
ConstrainedValue::Field(_field) => Type::Field,
|
||||
ConstrainedValue::Group(_group) => Type::Group,
|
||||
ConstrainedValue::Integer(integer) => Type::IntegerType(integer.get_type()),
|
||||
ConstrainedValue::Integer(integer) => Type::Integer(integer.get_type()),
|
||||
|
||||
// Data type wrappers
|
||||
ConstrainedValue::Array(array) => {
|
||||
let array_type = array[0].to_type(span)?;
|
||||
let mut dimensions = ArrayDimensions::default();
|
||||
dimensions.push_usize(array.len());
|
||||
|
||||
// Nested array type
|
||||
if let Type::Array(inner_type, inner_dimensions) = &array_type {
|
||||
dimensions.append(&mut inner_dimensions.clone());
|
||||
return Ok(Type::Array(inner_type.clone(), dimensions));
|
||||
}
|
||||
|
||||
Type::Array(Box::new(array_type), dimensions)
|
||||
Type::Array(Box::new(array_type), array.len())
|
||||
}
|
||||
ConstrainedValue::Tuple(tuple) => {
|
||||
let mut types = Vec::with_capacity(tuple.len());
|
||||
@ -135,100 +80,11 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedValue<F, G> {
|
||||
|
||||
Type::Tuple(types)
|
||||
}
|
||||
ConstrainedValue::CircuitExpression(id, _members) => Type::Circuit(id.clone()),
|
||||
ConstrainedValue::CircuitExpression(id, _members) => Type::Circuit(id.circuit.clone()),
|
||||
ConstrainedValue::Mutable(value) => return value.to_type(span),
|
||||
value => return Err(ValueError::implicit(value.to_string(), span.to_owned())),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the `ConstrainedValue` in intermediate `Value` format (for core circuits)
|
||||
pub(crate) fn to_value(&self) -> Value {
|
||||
match self.clone() {
|
||||
ConstrainedValue::Boolean(boolean) => Value::Boolean(boolean),
|
||||
ConstrainedValue::Integer(integer) => match integer {
|
||||
Integer::U8(u8) => Value::U8(u8),
|
||||
Integer::U16(u16) => Value::U16(u16),
|
||||
Integer::U32(u32) => Value::U32(u32),
|
||||
Integer::U64(u64) => Value::U64(u64),
|
||||
Integer::U128(u128) => Value::U128(u128),
|
||||
|
||||
Integer::I8(i8) => Value::I8(i8),
|
||||
Integer::I16(i16) => Value::I16(i16),
|
||||
Integer::I32(i32) => Value::I32(i32),
|
||||
Integer::I64(i64) => Value::I64(i64),
|
||||
Integer::I128(i128) => Value::I128(i128),
|
||||
},
|
||||
ConstrainedValue::Array(array) => {
|
||||
let array_value = array.into_iter().map(|element| element.to_value()).collect();
|
||||
|
||||
Value::Array(array_value)
|
||||
}
|
||||
ConstrainedValue::Tuple(tuple) => {
|
||||
let tuple_value = tuple.into_iter().map(|element| element.to_value()).collect();
|
||||
|
||||
Value::Tuple(tuple_value)
|
||||
}
|
||||
_ => unimplemented!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_type(&mut self, type_: Option<Type>, span: &Span) -> Result<(), ValueError> {
|
||||
if let ConstrainedValue::Unresolved(ref string) = self {
|
||||
if type_.is_some() {
|
||||
*self = ConstrainedValue::from_type(string.clone(), &type_.unwrap(), span)?
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Expect both `self` and `other` to resolve to the same type
|
||||
pub(crate) fn resolve_types(
|
||||
&mut self,
|
||||
other: &mut Self,
|
||||
type_: Option<Type>,
|
||||
span: &Span,
|
||||
) -> Result<(), ValueError> {
|
||||
if type_.is_some() {
|
||||
self.resolve_type(type_.clone(), span)?;
|
||||
return other.resolve_type(type_, span);
|
||||
}
|
||||
|
||||
match (&self, &other) {
|
||||
(ConstrainedValue::Unresolved(_), ConstrainedValue::Unresolved(_)) => Ok(()),
|
||||
(ConstrainedValue::Unresolved(_), _) => self.resolve_type(Some(other.to_type(span)?), span),
|
||||
(_, ConstrainedValue::Unresolved(_)) => other.resolve_type(Some(self.to_type(span)?), span),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn extract_function(self, scope: &str, span: &Span) -> Result<(String, Function), ExpressionError> {
|
||||
match self {
|
||||
ConstrainedValue::Function(circuit_identifier, function) => {
|
||||
let mut outer_scope = scope.to_string();
|
||||
// If this is a circuit function, evaluate inside the circuit scope
|
||||
if let Some(identifier) = circuit_identifier {
|
||||
// avoid creating recursive scope
|
||||
if !is_in_scope(&scope, &identifier.name) {
|
||||
outer_scope = new_scope(scope, &identifier.name);
|
||||
}
|
||||
}
|
||||
|
||||
Ok((outer_scope, *function))
|
||||
}
|
||||
ConstrainedValue::Import(import_scope, function) => function.extract_function(&import_scope, span),
|
||||
value => Err(ExpressionError::undefined_function(value.to_string(), span.to_owned())),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn extract_circuit(self, span: &Span) -> Result<Circuit, ExpressionError> {
|
||||
match self {
|
||||
ConstrainedValue::CircuitDefinition(circuit) => Ok(circuit),
|
||||
ConstrainedValue::Import(_import_scope, circuit) => circuit.extract_circuit(span),
|
||||
value => Err(ExpressionError::undefined_circuit(value.to_string(), span.to_owned())),
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// Modifies the `self` [ConstrainedValue] so there are no `mut` keywords wrapping the `self` value.
|
||||
///
|
||||
@ -241,85 +97,6 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedValue<F, G> {
|
||||
*self = *inner.clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn allocate_value<CS: ConstraintSystem<F>>(
|
||||
&mut self,
|
||||
mut cs: CS,
|
||||
span: &Span,
|
||||
) -> Result<(), ValueError> {
|
||||
match self {
|
||||
// Data types
|
||||
ConstrainedValue::Address(_address) => {
|
||||
// allow `let address()` even though addresses are constant
|
||||
}
|
||||
ConstrainedValue::Boolean(boolean) => {
|
||||
let option = boolean.get_value();
|
||||
let name = option
|
||||
.map(|b| b.to_string())
|
||||
.unwrap_or_else(|| "[allocated]".to_string());
|
||||
|
||||
*boolean = allocate_bool(&mut cs, &name, option, span)?;
|
||||
}
|
||||
ConstrainedValue::Field(field) => {
|
||||
let gadget = field
|
||||
.allocated(cs.ns(|| format!("allocate field {}:{}", span.line, span.start)))
|
||||
.map_err(|error| ValueError::FieldError(FieldError::synthesis_error(error, span.to_owned())))?;
|
||||
|
||||
*field = FieldType::Allocated(gadget)
|
||||
}
|
||||
ConstrainedValue::Group(group) => {
|
||||
*group = group.to_allocated(cs, span)?;
|
||||
}
|
||||
ConstrainedValue::Integer(integer) => {
|
||||
let integer_type = integer.get_type();
|
||||
let option = integer.get_value();
|
||||
let name = option.clone().unwrap_or_else(|| "[allocated]".to_string());
|
||||
|
||||
*integer = Integer::allocate_type(&mut cs, integer_type, &name, option, span)?;
|
||||
}
|
||||
|
||||
// Data type wrappers
|
||||
ConstrainedValue::Array(array) => {
|
||||
array.iter_mut().enumerate().try_for_each(|(i, value)| {
|
||||
let unique_name = format!("allocate array member {} {}:{}", i, span.line, span.start);
|
||||
|
||||
value.allocate_value(cs.ns(|| unique_name), span)
|
||||
})?;
|
||||
}
|
||||
ConstrainedValue::Tuple(tuple) => {
|
||||
tuple.iter_mut().enumerate().try_for_each(|(i, value)| {
|
||||
let unique_name = format!("allocate tuple member {} {}:{}", i, span.line, span.start);
|
||||
|
||||
value.allocate_value(cs.ns(|| unique_name), span)
|
||||
})?;
|
||||
}
|
||||
ConstrainedValue::CircuitExpression(_id, members) => {
|
||||
members.iter_mut().enumerate().try_for_each(|(i, member)| {
|
||||
let unique_name = format!("allocate circuit member {} {}:{}", i, span.line, span.start);
|
||||
|
||||
member.1.allocate_value(cs.ns(|| unique_name), span)
|
||||
})?;
|
||||
}
|
||||
ConstrainedValue::Mutable(value) => {
|
||||
value.allocate_value(cs, span)?;
|
||||
}
|
||||
ConstrainedValue::Static(value) => {
|
||||
value.allocate_value(cs, span)?;
|
||||
}
|
||||
|
||||
// Empty wrappers that are unreachable
|
||||
ConstrainedValue::CircuitDefinition(_) => {}
|
||||
ConstrainedValue::Function(_, _) => {}
|
||||
ConstrainedValue::Import(_, _) => {}
|
||||
|
||||
// Cannot allocate an unresolved value
|
||||
ConstrainedValue::Unresolved(value) => {
|
||||
return Err(ValueError::implicit(value.to_string(), span.to_owned()));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> fmt::Display for ConstrainedValue<F, G> {
|
||||
@ -355,8 +132,8 @@ impl<F: Field + PrimeField, G: GroupType<F>> fmt::Display for ConstrainedValue<F
|
||||
|
||||
write!(f, "({})", values)
|
||||
}
|
||||
ConstrainedValue::CircuitExpression(ref identifier, ref members) => {
|
||||
write!(f, "{} {{", identifier)?;
|
||||
ConstrainedValue::CircuitExpression(ref circuit, ref members) => {
|
||||
write!(f, "{} {{", circuit.circuit.name.borrow())?;
|
||||
for (i, member) in members.iter().enumerate() {
|
||||
write!(f, "{}: {}", member.0, member.1)?;
|
||||
if i < members.len() - 1 {
|
||||
@ -365,14 +142,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> fmt::Display for ConstrainedValue<F
|
||||
}
|
||||
write!(f, "}}")
|
||||
}
|
||||
ConstrainedValue::CircuitDefinition(ref circuit) => write!(f, "circuit {{ {} }}", circuit.circuit_name),
|
||||
ConstrainedValue::Function(ref _circuit_option, ref function) => {
|
||||
write!(f, "function {{ {}() }}", function.identifier)
|
||||
}
|
||||
ConstrainedValue::Import(_, ref value) => write!(f, "{}", value),
|
||||
ConstrainedValue::Mutable(ref value) => write!(f, "{}", value),
|
||||
ConstrainedValue::Static(ref value) => write!(f, "{}", value),
|
||||
ConstrainedValue::Unresolved(ref value) => write!(f, "{}", value),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -478,11 +248,6 @@ impl<F: Field + PrimeField, G: GroupType<F>> CondSelectGadget<F> for Constrained
|
||||
|
||||
ConstrainedValue::Tuple(array)
|
||||
}
|
||||
(ConstrainedValue::Function(identifier_1, function_1), ConstrainedValue::Function(_, _)) => {
|
||||
// This is a no-op. functions cannot hold circuit values
|
||||
// However, we must return a result here
|
||||
ConstrainedValue::Function(identifier_1.clone(), function_1.clone())
|
||||
}
|
||||
(
|
||||
ConstrainedValue::CircuitExpression(identifier, members_1),
|
||||
ConstrainedValue::CircuitExpression(_identifier, members_2),
|
||||
@ -500,11 +265,6 @@ impl<F: Field + PrimeField, G: GroupType<F>> CondSelectGadget<F> for Constrained
|
||||
|
||||
ConstrainedValue::CircuitExpression(identifier.clone(), members)
|
||||
}
|
||||
(ConstrainedValue::Static(first), ConstrainedValue::Static(second)) => {
|
||||
let value = Self::conditionally_select(cs, cond, first, second)?;
|
||||
|
||||
ConstrainedValue::Static(Box::new(value))
|
||||
}
|
||||
(ConstrainedValue::Mutable(first), _) => Self::conditionally_select(cs, cond, first, second)?,
|
||||
(_, ConstrainedValue::Mutable(second)) => Self::conditionally_select(cs, cond, first, second)?,
|
||||
(_, _) => return Err(SynthesisError::Unsatisfiable),
|
||||
@ -533,25 +293,3 @@ impl<F: Field + PrimeField, G: GroupType<F>> CondSelectGadget<F> for Constrained
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
impl<F: Field + PrimeField, G: GroupType<F>> From<Value> for ConstrainedValue<F, G> {
|
||||
fn from(v: Value) -> Self {
|
||||
match v {
|
||||
Value::Boolean(boolean) => ConstrainedValue::Boolean(boolean),
|
||||
Value::U8(u8) => ConstrainedValue::Integer(Integer::U8(u8)),
|
||||
Value::U16(u16) => ConstrainedValue::Integer(Integer::U16(u16)),
|
||||
Value::U32(u32) => ConstrainedValue::Integer(Integer::U32(u32)),
|
||||
Value::U64(u64) => ConstrainedValue::Integer(Integer::U64(u64)),
|
||||
Value::U128(u128) => ConstrainedValue::Integer(Integer::U128(u128)),
|
||||
|
||||
Value::I8(i8) => ConstrainedValue::Integer(Integer::I8(i8)),
|
||||
Value::I16(i16) => ConstrainedValue::Integer(Integer::I16(i16)),
|
||||
Value::I32(i32) => ConstrainedValue::Integer(Integer::I32(i32)),
|
||||
Value::I64(i64) => ConstrainedValue::Integer(Integer::I64(i64)),
|
||||
Value::I128(i128) => ConstrainedValue::Integer(Integer::I128(i128)),
|
||||
|
||||
Value::Array(array) => ConstrainedValue::Array(array.into_iter().map(ConstrainedValue::from).collect()),
|
||||
Value::Tuple(tuple) => ConstrainedValue::Tuple(tuple.into_iter().map(ConstrainedValue::from).collect()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -14,7 +14,7 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::{assert_satisfied, expect_compiler_error, generate_main_input, parse_program};
|
||||
use crate::{assert_satisfied, expect_asg_error, expect_compiler_error, generate_main_input, parse_program};
|
||||
use leo_ast::InputValue;
|
||||
|
||||
static TEST_ADDRESS_1: &str = "aleo1qnr4dkkvkgfqph0vzc3y6z2eu975wnpz2925ntjccd5cfqxtyu8sta57j8";
|
||||
@ -63,9 +63,9 @@ fn test_implicit_valid() {
|
||||
#[test]
|
||||
fn test_implicit_invalid() {
|
||||
let program_string = include_str!("implicit_invalid.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
let _output = expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -16,6 +16,7 @@
|
||||
|
||||
use crate::{
|
||||
assert_satisfied,
|
||||
expect_asg_error,
|
||||
expect_compiler_error,
|
||||
get_output,
|
||||
parse_program,
|
||||
@ -67,6 +68,14 @@ fn test_inline() {
|
||||
assert_satisfied(program);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nested() {
|
||||
let program_string = include_str!("nested.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
|
||||
assert_satisfied(program);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inline_fail() {
|
||||
let program_string = include_str!("inline.leo");
|
||||
@ -150,17 +159,17 @@ fn test_input_tuple_3x2_fail() {
|
||||
#[test]
|
||||
fn test_multi_fail_initializer() {
|
||||
let program_string = include_str!("multi_fail_initializer.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
let _err = expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multi_inline_fail() {
|
||||
let program_string = include_str!("multi_fail_inline.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
let _err = expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -174,9 +183,9 @@ fn test_multi_initializer() {
|
||||
#[test]
|
||||
fn test_multi_initializer_fail() {
|
||||
let program_string = include_str!("multi_initializer_fail.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
let _err = expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -190,9 +199,9 @@ fn test_nested_3x2_value() {
|
||||
#[test]
|
||||
fn test_nested_3x2_value_fail() {
|
||||
let program_string = include_str!("nested_3x2_value_fail.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
let _err = expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -206,9 +215,9 @@ fn test_tuple_3x2_value() {
|
||||
#[test]
|
||||
fn test_tuple_3x2_value_fail() {
|
||||
let program_string = include_str!("tuple_3x2_value_fail.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
let _err = expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -258,9 +267,9 @@ fn test_type_nested_value_nested_3x2() {
|
||||
#[test]
|
||||
fn test_type_nested_value_nested_3x2_fail() {
|
||||
let program_string = include_str!("type_nested_value_nested_3x2_fail.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
let _err = expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -274,9 +283,9 @@ fn test_type_nested_value_nested_4x3x2() {
|
||||
#[test]
|
||||
fn test_type_nested_value_nested_4x3x2_fail() {
|
||||
let program_string = include_str!("type_nested_value_nested_4x3x2_fail.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
let _err = expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -290,9 +299,9 @@ fn test_type_nested_value_tuple_3x2() {
|
||||
#[test]
|
||||
fn test_type_nested_value_tuple_3x2_fail() {
|
||||
let program_string = include_str!("type_nested_value_tuple_3x2_fail.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
let _err = expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -306,9 +315,9 @@ fn test_type_nested_value_tuple_4x3x2() {
|
||||
#[test]
|
||||
fn test_type_nested_value_tuple_4x3x2_fail() {
|
||||
let program_string = include_str!("type_nested_value_tuple_4x3x2_fail.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
let _err = expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -322,9 +331,9 @@ fn test_type_tuple_value_nested_3x2() {
|
||||
#[test]
|
||||
fn test_type_tuple_value_nested_3x2_fail() {
|
||||
let program_string = include_str!("type_tuple_value_nested_3x2_fail.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
let _err = expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -338,9 +347,9 @@ fn test_type_tuple_value_nested_4x3x2() {
|
||||
#[test]
|
||||
fn test_type_tuple_value_nested_4x3x2_fail() {
|
||||
let program_string = include_str!("type_tuple_value_nested_4x3x2_fail.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
let _err = expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -354,9 +363,9 @@ fn test_type_tuple_value_tuple_3x2() {
|
||||
#[test]
|
||||
fn test_type_tuple_value_tuple_3x2_fail() {
|
||||
let program_string = include_str!("type_tuple_value_tuple_3x2_fail.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
let _err = expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -370,9 +379,9 @@ fn test_type_tuple_value_tuple_4x3x2() {
|
||||
#[test]
|
||||
fn test_type_tuple_value_tuple_4x3x2_fail() {
|
||||
let program_string = include_str!("type_tuple_value_tuple_4x3x2_fail.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
let _err = expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
// Tests for nested multi-dimensional arrays as input to the program
|
||||
@ -522,3 +531,11 @@ fn test_input_type_tuple_value_tuple_4x3x2_fail() {
|
||||
|
||||
assert!(syntax_error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_variable_slice_fail() {
|
||||
let program_string = include_str!("variable_slice_fail.leo");
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
4
compiler/tests/array/nested.leo
Normal file
4
compiler/tests/array/nested.leo
Normal file
@ -0,0 +1,4 @@
|
||||
function main () {
|
||||
let x = [false; (2, 2)];
|
||||
let y: bool = x[0][0];
|
||||
}
|
@ -1,7 +1,7 @@
|
||||
function main() {
|
||||
const a = [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]]; // inline
|
||||
|
||||
const b: [u8; (2, 3)] = [[0; 3]; 2]; // initializer
|
||||
const b: [u8; (3, 2)] = [[0; 2]; 3]; // initializer
|
||||
|
||||
console.assert(a == b);
|
||||
}
|
@ -1,7 +1,7 @@
|
||||
function main() {
|
||||
const a = [[0u8, 0u8], [0u8, 0u8], [0u8, 0u8]]; // inline
|
||||
|
||||
const b: [u8; (2, 3)] = [0; (2, 3)]; // initializer
|
||||
const b: [u8; (3, 2)] = [0; (3, 2)]; // initializer
|
||||
|
||||
console.assert(a == b);
|
||||
}
|
7
compiler/tests/array/variable_slice_fail.leo
Normal file
7
compiler/tests/array/variable_slice_fail.leo
Normal file
@ -0,0 +1,7 @@
|
||||
function main() {
|
||||
let a = [1u8; 10];
|
||||
for i in 0..10 {
|
||||
let x = a[i..10];
|
||||
console.debug("{}", x);
|
||||
}
|
||||
}
|
@ -16,8 +16,8 @@
|
||||
|
||||
use crate::{
|
||||
assert_satisfied,
|
||||
expect_asg_error,
|
||||
expect_compiler_error,
|
||||
expect_type_inference_error,
|
||||
get_output,
|
||||
parse_program,
|
||||
parse_program_with_input,
|
||||
@ -104,9 +104,9 @@ fn test_not_mutable() {
|
||||
#[test]
|
||||
fn test_not_u32() {
|
||||
let program_string = include_str!("not_u32.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
// Boolean or ||
|
||||
@ -140,7 +140,7 @@ fn test_true_or_u32() {
|
||||
let program_string = include_str!("true_or_u32.leo");
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_type_inference_error(error);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
// Boolean and &&
|
||||
@ -174,7 +174,7 @@ fn test_true_and_u32() {
|
||||
let program_string = include_str!("true_and_u32.leo");
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_type_inference_error(error);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
// All
|
||||
|
@ -1,11 +1,13 @@
|
||||
circuit Foo {
|
||||
function echo(x: u32) -> u32 {
|
||||
return x
|
||||
x: u32,
|
||||
|
||||
function echo(self) -> u32 {
|
||||
return self.x
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
let a = Foo { };
|
||||
let a = Foo { x: 1u32 };
|
||||
|
||||
console.assert(a.echo(1u32) == 1u32);
|
||||
console.assert(a.echo() == 1u32);
|
||||
}
|
@ -14,7 +14,7 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::{assert_satisfied, expect_compiler_error, expect_type_inference_error, parse_program};
|
||||
use crate::{assert_satisfied, expect_asg_error, parse_program};
|
||||
|
||||
// Expressions
|
||||
|
||||
@ -29,9 +29,9 @@ fn test_inline() {
|
||||
#[test]
|
||||
fn test_inline_fail() {
|
||||
let program_string = include_str!("inline_fail.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -39,7 +39,7 @@ fn test_inline_undefined() {
|
||||
let program_string = include_str!("inline_undefined.leo");
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_type_inference_error(error);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
// Members
|
||||
@ -57,7 +57,7 @@ fn test_member_variable_fail() {
|
||||
let program_string = include_str!("member_variable_fail.leo");
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_type_inference_error(error);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -81,7 +81,7 @@ fn test_member_function_fail() {
|
||||
let program_string = include_str!("member_function_fail.leo");
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_type_inference_error(error);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -89,7 +89,7 @@ fn test_member_function_invalid() {
|
||||
let program_string = include_str!("member_function_invalid.leo");
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_type_inference_error(error);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -121,7 +121,7 @@ fn test_member_static_function_invalid() {
|
||||
let program_string = include_str!("member_static_function_invalid.leo");
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_type_inference_error(error)
|
||||
expect_asg_error(error)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -129,7 +129,7 @@ fn test_member_static_function_undefined() {
|
||||
let program_string = include_str!("member_static_function_undefined.leo");
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_type_inference_error(error)
|
||||
expect_asg_error(error)
|
||||
}
|
||||
|
||||
// Mutability
|
||||
@ -139,7 +139,7 @@ fn test_mutate_function_fail() {
|
||||
let program_string = include_str!("mut_function_fail.leo");
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_type_inference_error(error);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -150,6 +150,14 @@ fn test_mutate_self_variable() {
|
||||
assert_satisfied(program);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mutate_self_variable_branch() {
|
||||
let program_string = include_str!("mut_self_variable_branch.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
|
||||
assert_satisfied(program);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mutate_self_variable_conditional() {
|
||||
let program_string = include_str!("mut_self_variable_conditional.leo");
|
||||
@ -161,9 +169,9 @@ fn test_mutate_self_variable_conditional() {
|
||||
#[test]
|
||||
fn test_mutate_self_variable_fail() {
|
||||
let program_string = include_str!("mut_self_variable_fail.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -171,7 +179,7 @@ fn test_mutate_self_function_fail() {
|
||||
let program_string = include_str!("mut_self_function_fail.leo");
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_type_inference_error(error);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -179,7 +187,7 @@ fn test_mutate_self_static_function_fail() {
|
||||
let program_string = include_str!("mut_self_static_function_fail.leo");
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_type_inference_error(error);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -187,7 +195,7 @@ fn test_mutate_static_function_fail() {
|
||||
let program_string = include_str!("mut_static_function_fail.leo");
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_type_inference_error(error);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -201,9 +209,9 @@ fn test_mutate_variable() {
|
||||
#[test]
|
||||
fn test_mutate_variable_fail() {
|
||||
let program_string = include_str!("mut_variable_fail.leo");
|
||||
let program = parse_program(program_string).unwrap();
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_compiler_error(program);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
// Self
|
||||
@ -213,7 +221,7 @@ fn test_self_fail() {
|
||||
let program_string = include_str!("self_fail.leo");
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_type_inference_error(error);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -229,7 +237,7 @@ fn test_self_member_invalid() {
|
||||
let program_string = include_str!("self_member_invalid.leo");
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_type_inference_error(error);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -237,7 +245,7 @@ fn test_self_member_undefined() {
|
||||
let program_string = include_str!("self_member_undefined.leo");
|
||||
let error = parse_program(program_string).err().unwrap();
|
||||
|
||||
expect_type_inference_error(error);
|
||||
expect_asg_error(error);
|
||||
}
|
||||
|
||||
// All
|
||||
|
32
compiler/tests/circuits/mut_self_variable_branch.leo
Normal file
32
compiler/tests/circuits/mut_self_variable_branch.leo
Normal file
@ -0,0 +1,32 @@
|
||||
circuit Foo {
|
||||
a: u8,
|
||||
|
||||
function set_a(mut self, condition: bool, new: u8) {
|
||||
if condition {
|
||||
self.a = new;
|
||||
console.assert(self.a == new);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
let mut f = Foo { a: 0u8 };
|
||||
|
||||
console.assert(f.a == 0u8);
|
||||
|
||||
f.set_a(false, 1u8);
|
||||
|
||||
console.assert(f.a == 0u8);
|
||||
|
||||
f.set_a(true, 1u8);
|
||||
|
||||
console.assert(f.a == 1u8);
|
||||
|
||||
f.set_a(false, 2u8);
|
||||
|
||||
console.assert(f.a == 1u8);
|
||||
|
||||
f.set_a(true, 2u8);
|
||||
|
||||
console.assert(f.a == 2u8);
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user