diff --git a/changelogs/unreleased/1016-schaeff b/changelogs/unreleased/1016-schaeff new file mode 100644 index 00000000..d944de96 --- /dev/null +++ b/changelogs/unreleased/1016-schaeff @@ -0,0 +1 @@ +Fix false positives and false negatives in struct generic inference diff --git a/changelogs/unreleased/982-dark64 b/changelogs/unreleased/982-dark64 new file mode 100644 index 00000000..68919800 --- /dev/null +++ b/changelogs/unreleased/982-dark64 @@ -0,0 +1 @@ +Implement type aliasing \ No newline at end of file diff --git a/zokrates_abi/src/lib.rs b/zokrates_abi/src/lib.rs index 6c07891e..16cdca31 100644 --- a/zokrates_abi/src/lib.rs +++ b/zokrates_abi/src/lib.rs @@ -413,11 +413,8 @@ mod tests { fn array() { let s = "[[true, false]]"; assert_eq!( - parse_strict::( - s, - vec![ConcreteType::array((ConcreteType::Boolean, 2usize))] - ) - .unwrap(), + parse_strict::(s, vec![ConcreteType::array((ConcreteType::Boolean, 2u32))]) + .unwrap(), Values(vec![Value::Array(vec![ Value::Boolean(true), Value::Boolean(false) diff --git a/zokrates_book/src/language/types.md b/zokrates_book/src/language/types.md index b97c1913..8d4bbee2 100644 --- a/zokrates_book/src/language/types.md +++ b/zokrates_book/src/language/types.md @@ -128,6 +128,8 @@ struct Point { } ``` +Note that two struct definitions with the same members still introduce two entirely different types. For example, they cannot be compared with each other. + #### Declaration and Initialization Initialization of a variable of a struct type always needs to happen in the same statement as a declaration, unless the struct-typed variable is declared within a function's signature. @@ -144,3 +146,13 @@ The variables within a struct instance, the so called members, can be accessed t ```zokrates {{#include ../../../zokrates_cli/examples/book/struct_assign.zok}} ``` + +### Type aliases + +Type aliases can be defined for any existing type. This can be useful for readability, or to specialize generic types. + +Note that type aliases are just syntactic sugar: in the type system, a type and its alias are exactly equivalent. For example, they can be compared. + +```zokrates +{{#include ../../../zokrates_cli/examples/book/type_aliases.zok}} +``` diff --git a/zokrates_cli/examples/alias/basic_aliasing.zok b/zokrates_cli/examples/alias/basic_aliasing.zok new file mode 100644 index 00000000..c12362e5 --- /dev/null +++ b/zokrates_cli/examples/alias/basic_aliasing.zok @@ -0,0 +1,13 @@ +type byte = u8 +type uint32 = u32 +type UInt32Array = uint32[N] + +type matrix = field[R][C] + +def fill(field v) -> matrix: + return [[v; C]; R] + +def main(uint32 a, uint32 b) -> (UInt32Array<2>, matrix<2, 4>): + UInt32Array<2> res = [a, b] + matrix<2, 4> m = fill(1) + return res, m \ No newline at end of file diff --git a/zokrates_cli/examples/alias/import_alias.zok b/zokrates_cli/examples/alias/import_alias.zok new file mode 100644 index 00000000..6e7e54e4 --- /dev/null +++ b/zokrates_cli/examples/alias/import_alias.zok @@ -0,0 +1,14 @@ +from "./basic_aliasing.zok" import matrix +from "./struct_aliasing.zok" import Buzz + +const u32 R = 2 +const u32 C = 4 + +type matrix_2x4 = matrix + +def buzz() -> Buzz: + return Buzz { a: [0; N], b: [0; N] } + +def main(matrix_2x4 m) -> (Buzz<2>, matrix_2x4): + Buzz<2> b = buzz::<2>() + return b, m \ No newline at end of file diff --git a/zokrates_cli/examples/alias/struct_aliasing.zok b/zokrates_cli/examples/alias/struct_aliasing.zok new file mode 100644 index 00000000..932587b6 --- /dev/null +++ b/zokrates_cli/examples/alias/struct_aliasing.zok @@ -0,0 +1,15 @@ +type FieldArray = field[N] + +struct Foo { + FieldArray a + FieldArray b +} + +type Bar = Foo<2, 2> +type Buzz = Foo + +def main(Bar a) -> Buzz<2>: + Bar bar = Bar { a: [1, 2], b: [1, 2] } + Buzz<2> buzz = Buzz { a: [1, 2], b: [1, 2] } + assert(bar == buzz) + return buzz \ No newline at end of file diff --git a/zokrates_cli/examples/book/type_aliases.zok b/zokrates_cli/examples/book/type_aliases.zok new file mode 100644 index 00000000..fd500a4e --- /dev/null +++ b/zokrates_cli/examples/book/type_aliases.zok @@ -0,0 +1,11 @@ +type MyField = field + +type Rectangle = bool[L][W] + +type Square = Rectangle + +def main(): + MyField f = 42 + Rectangle<2, 2> r = [[true; 2]; 2] + Square<2> s = r + return \ No newline at end of file diff --git a/zokrates_cli/examples/compile_errors/variable_constant_lt.zok b/zokrates_cli/examples/compile_errors/variable_constant_lt.zok index 062d8295..86c3979c 100644 --- a/zokrates_cli/examples/compile_errors/variable_constant_lt.zok +++ b/zokrates_cli/examples/compile_errors/variable_constant_lt.zok @@ -2,4 +2,4 @@ from "EMBED" import bit_array_le // Calling the `bit_array_le` embed on a non-constant second argument should fail at compile-time def main(bool[1] a, bool[1] b) -> bool: - return bit_array_le::<1>(a, b) \ No newline at end of file + return bit_array_le(a, b) \ No newline at end of file diff --git a/zokrates_cli/examples/sudoku/prime_sudoku_checker.zok b/zokrates_cli/examples/sudoku/prime_sudoku_checker.zok index a5cd37d6..aec77917 100644 --- a/zokrates_cli/examples/sudoku/prime_sudoku_checker.zok +++ b/zokrates_cli/examples/sudoku/prime_sudoku_checker.zok @@ -8,6 +8,9 @@ // -------------------------- // | c21 | c22 || d21 | d22 | +type Grid = field[N][N] +const field[4] PRIMES = [2, 3, 5, 7] + // We encode values in the following way: // 1 -> 2 // 2 -> 3 @@ -18,16 +21,22 @@ // assumption: `a, b, c, d` are all in `{ 2, 3, 5, 7 }` def checkNoDuplicates(field a, field b, field c, field d) -> bool: // as `{ 2, 3, 5, 7 }` are primes, the set `{ a, b, c, d }` is equal to the set `{ 2, 3, 5, 7}` if and only if the products match - return a * b * c * d == 2 * 3 * 5 * 7 + return a * b * c * d == PRIMES[0] * PRIMES[1] * PRIMES[2] * PRIMES[3] -// returns `0` if and only if `x` in `{ 2, 3, 5, 7 }` +// returns true if and only if `x` is one of the `4` primes def validateInput(field x) -> bool: - return (x-2) * (x-3) * (x-5) * (x-7) == 0 + field res = 1 + + for u32 i in 0..4 do + res = res * (x - PRIMES[i]) + endfor + + return res == 0 // variables naming: box'row''column' def main(field a21, field b11, field b22, field c11, field c22, field d21, private field a11, private field a12, private field a22, private field b12, private field b21, private field c12, private field c21, private field d11, private field d12, private field d22) -> bool: - field[4][4] a = [[a11, a12, b11, b12], [a21, a22, b21, b22], [c11, c12, d11, d12], [c21, c22, d21, d22]] + Grid<4> a = [[a11, a12, b11, b12], [a21, a22, b21, b22], [c11, c12, d11, d12], [c21, c22, d21, d22]] bool res = true diff --git a/zokrates_core/src/absy/from_ast.rs b/zokrates_core/src/absy/from_ast.rs index 81f0b903..b488807d 100644 --- a/zokrates_core/src/absy/from_ast.rs +++ b/zokrates_core/src/absy/from_ast.rs @@ -1,5 +1,6 @@ use crate::absy; +use crate::absy::SymbolDefinition; use num_bigint::BigUint; use std::path::Path; use zokrates_pest_ast as pest; @@ -10,6 +11,7 @@ impl<'ast> From> for absy::Module<'ast> { pest::SymbolDeclaration::Import(i) => import_directive_to_symbol_vec(i), pest::SymbolDeclaration::Constant(c) => vec![c.into()], pest::SymbolDeclaration::Struct(s) => vec![s.into()], + pest::SymbolDeclaration::Type(t) => vec![t.into()], pest::SymbolDeclaration::Function(f) => vec![f.into()], })) } @@ -135,6 +137,31 @@ impl<'ast> From> for absy::SymbolDeclarationNode< } } +impl<'ast> From> for absy::SymbolDeclarationNode<'ast> { + fn from(definition: pest::TypeDefinition<'ast>) -> absy::SymbolDeclarationNode<'ast> { + use crate::absy::NodeValue; + + let span = definition.span; + let id = definition.id.span.as_str(); + + let ty = absy::TypeDefinition { + generics: definition + .generics + .into_iter() + .map(absy::ConstantGenericNode::from) + .collect(), + ty: definition.ty.into(), + } + .span(span.clone()); + + absy::SymbolDeclaration { + id, + symbol: absy::Symbol::Here(SymbolDefinition::Type(ty)), + } + .span(span) + } +} + impl<'ast> From> for absy::SymbolDeclarationNode<'ast> { fn from(function: pest::FunctionDefinition<'ast>) -> absy::SymbolDeclarationNode<'ast> { use crate::absy::NodeValue; diff --git a/zokrates_core/src/absy/mod.rs b/zokrates_core/src/absy/mod.rs index e6c8ec69..3983a3e8 100644 --- a/zokrates_core/src/absy/mod.rs +++ b/zokrates_core/src/absy/mod.rs @@ -133,6 +133,7 @@ pub enum SymbolDefinition<'ast> { Import(CanonicalImportNode<'ast>), Struct(StructDefinitionNode<'ast>), Constant(ConstantDefinitionNode<'ast>), + Type(TypeDefinitionNode<'ast>), Function(FunctionNode<'ast>), } @@ -153,12 +154,28 @@ impl<'ast> fmt::Display for SymbolDeclaration<'ast> { i.value.source.display(), i.value.id ), - SymbolDefinition::Struct(ref t) => write!(f, "struct {}{}", self.id, t), + SymbolDefinition::Struct(ref s) => write!(f, "struct {}{}", self.id, s), SymbolDefinition::Constant(ref c) => write!( f, "const {} {} = {}", c.value.ty, self.id, c.value.expression ), + SymbolDefinition::Type(ref t) => { + write!(f, "type {}", self.id)?; + if !t.value.generics.is_empty() { + write!( + f, + "<{}>", + t.value + .generics + .iter() + .map(|g| g.to_string()) + .collect::>() + .join(", ") + )?; + } + write!(f, " = {}", t.value.ty) + } SymbolDefinition::Function(ref func) => { write!(f, "def {}{}", self.id, func) } @@ -205,15 +222,18 @@ pub struct StructDefinition<'ast> { impl<'ast> fmt::Display for StructDefinition<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - writeln!( - f, - "<{}> {{", - self.generics - .iter() - .map(|g| g.to_string()) - .collect::>() - .join(", "), - )?; + if !self.generics.is_empty() { + write!( + f, + "<{}> ", + self.generics + .iter() + .map(|g| g.to_string()) + .collect::>() + .join(", ") + )?; + } + writeln!(f, "{{")?; for field in &self.fields { writeln!(f, " {}", field)?; } @@ -248,7 +268,34 @@ pub type ConstantDefinitionNode<'ast> = Node>; impl<'ast> fmt::Display for ConstantDefinition<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "const {}({})", self.ty, self.expression) + write!(f, "const {} _ = {}", self.ty, self.expression) + } +} + +/// A type definition +#[derive(Debug, Clone, PartialEq)] +pub struct TypeDefinition<'ast> { + pub generics: Vec>, + pub ty: UnresolvedTypeNode<'ast>, +} + +pub type TypeDefinitionNode<'ast> = Node>; + +impl<'ast> fmt::Display for TypeDefinition<'ast> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "type _")?; + if !self.generics.is_empty() { + write!( + f, + "<{}>", + self.generics + .iter() + .map(|g| g.to_string()) + .collect::>() + .join(", ") + )?; + } + write!(f, " = {}", self.ty) } } diff --git a/zokrates_core/src/absy/node.rs b/zokrates_core/src/absy/node.rs index e8325d6d..0332ad57 100644 --- a/zokrates_core/src/absy/node.rs +++ b/zokrates_core/src/absy/node.rs @@ -93,6 +93,7 @@ impl<'ast> NodeValue for UnresolvedType<'ast> {} impl<'ast> NodeValue for StructDefinition<'ast> {} impl<'ast> NodeValue for StructDefinitionField<'ast> {} impl<'ast> NodeValue for ConstantDefinition<'ast> {} +impl<'ast> NodeValue for TypeDefinition<'ast> {} impl<'ast> NodeValue for Function<'ast> {} impl<'ast> NodeValue for Module<'ast> {} impl<'ast> NodeValue for CanonicalImport<'ast> {} diff --git a/zokrates_core/src/embed.rs b/zokrates_core/src/embed.rs index 75d6f6cc..6a3c6eed 100644 --- a/zokrates_core/src/embed.rs +++ b/zokrates_core/src/embed.rs @@ -177,128 +177,105 @@ impl FlatEmbed { match self { FlatEmbed::BitArrayLe => DeclarationSignature::new() .generics(vec![Some(DeclarationConstant::Generic( - GenericIdentifier { - name: "N", - index: 0, - }, + GenericIdentifier::with_name("N").with_index(0), ))]) .inputs(vec![ DeclarationType::array(( DeclarationType::Boolean, - GenericIdentifier { - name: "N", - index: 0, - }, + GenericIdentifier::with_name("N").with_index(0), )), DeclarationType::array(( DeclarationType::Boolean, - GenericIdentifier { - name: "N", - index: 0, - }, + GenericIdentifier::with_name("N").with_index(0), )), ]) .outputs(vec![DeclarationType::Boolean]), FlatEmbed::Unpack => DeclarationSignature::new() .generics(vec![Some(DeclarationConstant::Generic( - GenericIdentifier { - name: "N", - index: 0, - }, + GenericIdentifier::with_name("N").with_index(0), ))]) .inputs(vec![DeclarationType::FieldElement]) .outputs(vec![DeclarationType::array(( DeclarationType::Boolean, - GenericIdentifier { - name: "N", - index: 0, - }, + GenericIdentifier::with_name("N").with_index(0), ))]), FlatEmbed::U8ToBits => DeclarationSignature::new() .inputs(vec![DeclarationType::uint(8)]) .outputs(vec![DeclarationType::array(( DeclarationType::Boolean, - 8usize, + 8u32, ))]), FlatEmbed::U16ToBits => DeclarationSignature::new() .inputs(vec![DeclarationType::uint(16)]) .outputs(vec![DeclarationType::array(( DeclarationType::Boolean, - 16usize, + 16u32, ))]), FlatEmbed::U32ToBits => DeclarationSignature::new() .inputs(vec![DeclarationType::uint(32)]) .outputs(vec![DeclarationType::array(( DeclarationType::Boolean, - 32usize, + 32u32, ))]), FlatEmbed::U64ToBits => DeclarationSignature::new() .inputs(vec![DeclarationType::uint(64)]) .outputs(vec![DeclarationType::array(( DeclarationType::Boolean, - 64usize, + 64u32, ))]), FlatEmbed::U8FromBits => DeclarationSignature::new() .outputs(vec![DeclarationType::uint(8)]) .inputs(vec![DeclarationType::array(( DeclarationType::Boolean, - 8usize, + 8u32, ))]), FlatEmbed::U16FromBits => DeclarationSignature::new() .outputs(vec![DeclarationType::uint(16)]) .inputs(vec![DeclarationType::array(( DeclarationType::Boolean, - 16usize, + 16u32, ))]), FlatEmbed::U32FromBits => DeclarationSignature::new() .outputs(vec![DeclarationType::uint(32)]) .inputs(vec![DeclarationType::array(( DeclarationType::Boolean, - 32usize, + 32u32, ))]), FlatEmbed::U64FromBits => DeclarationSignature::new() .outputs(vec![DeclarationType::uint(64)]) .inputs(vec![DeclarationType::array(( DeclarationType::Boolean, - 64usize, + 64u32, ))]), #[cfg(feature = "bellman")] FlatEmbed::Sha256Round => DeclarationSignature::new() .inputs(vec![ - DeclarationType::array((DeclarationType::Boolean, 512usize)), - DeclarationType::array((DeclarationType::Boolean, 256usize)), + DeclarationType::array((DeclarationType::Boolean, 512u32)), + DeclarationType::array((DeclarationType::Boolean, 256u32)), ]) .outputs(vec![DeclarationType::array(( DeclarationType::Boolean, - 256usize, + 256u32, ))]), #[cfg(feature = "ark")] FlatEmbed::SnarkVerifyBls12377 => DeclarationSignature::new() .generics(vec![ - Some(DeclarationConstant::Generic(GenericIdentifier { - name: "N", - index: 0, - })), - Some(DeclarationConstant::Generic(GenericIdentifier { - name: "V", - index: 1, - })), + Some(DeclarationConstant::Generic( + GenericIdentifier::with_name("N").with_index(0), + )), + Some(DeclarationConstant::Generic( + GenericIdentifier::with_name("V").with_index(1), + )), ]) .inputs(vec![ DeclarationType::array(( DeclarationType::FieldElement, - GenericIdentifier { - name: "N", - index: 0, - }, + GenericIdentifier::with_name("N").with_index(0), )), // inputs - DeclarationType::array((DeclarationType::FieldElement, 8usize)), // proof + DeclarationType::array((DeclarationType::FieldElement, 8u32)), // proof DeclarationType::array(( DeclarationType::FieldElement, - GenericIdentifier { - name: "V", - index: 1, - }, + GenericIdentifier::with_name("V").with_index(1), )), // 18 + (2 * n) // vk ]) .outputs(vec![DeclarationType::Boolean]), diff --git a/zokrates_core/src/semantics.rs b/zokrates_core/src/semantics.rs index b0041ef0..388b73ea 100644 --- a/zokrates_core/src/semantics.rs +++ b/zokrates_core/src/semantics.rs @@ -6,7 +6,7 @@ use crate::absy::Identifier; use crate::absy::*; -use crate::typed_absy::types::GGenericsAssignment; +use crate::typed_absy::types::{GGenericsAssignment, GenericsAssignment}; use crate::typed_absy::*; use crate::typed_absy::{DeclarationParameter, DeclarationVariable, Variable}; use num_bigint::BigUint; @@ -55,7 +55,33 @@ impl ErrorInner { } } -type TypeMap<'ast, T> = BTreeMap>>; +// a single struct to cover all cases of user-defined types +#[derive(Debug, Clone)] +struct UserDeclarationType<'ast, T> { + generics: Vec>, + ty: DeclarationType<'ast, T>, +} + +impl<'ast, T> UserDeclarationType<'ast, T> { + // returns the declared generics for this user type + // for alias of basic types this is empty + // for structs this is the same as the used generics + // for aliases of structs this is the names of the generics declared on the left side of the type declaration + fn declaration_generics(&self) -> Vec<&'ast str> { + self.generics + .iter() + .filter_map(|g| match g { + DeclarationConstant::Generic(g) => Some(g), + _ => None, + }) + .collect::>() // we collect into a BTreeSet because draining it after yields the element in the right order defined by Ord + .into_iter() + .map(|g| g.name()) + .collect() + } +} + +type TypeMap<'ast, T> = BTreeMap>>; type ConstantMap<'ast, T> = BTreeMap, DeclarationType<'ast, T>>>; @@ -366,6 +392,84 @@ impl<'ast, T: Field> Checker<'ast, T> { }) } + fn check_type_definition( + &mut self, + ty: TypeDefinitionNode<'ast>, + module_id: &ModuleId, + state: &State<'ast, T>, + ) -> Result, Vec> { + let pos = ty.pos(); + let ty = ty.value; + + let mut errors = vec![]; + + let mut generics = vec![]; + let mut generics_map = BTreeMap::new(); + + for (index, g) in ty.generics.iter().enumerate() { + if state + .constants + .get(module_id) + .and_then(|m| m.get(g.value)) + .is_some() + { + errors.push(ErrorInner { + pos: Some(g.pos()), + message: format!( + "Generic parameter {p} conflicts with constant symbol {p}", + p = g.value + ), + }); + } else { + match generics_map.insert(g.value, index).is_none() { + true => { + generics.push(DeclarationConstant::Generic( + GenericIdentifier::with_name(g.value).with_index(index), + )); + } + false => { + errors.push(ErrorInner { + pos: Some(g.pos()), + message: format!("Generic parameter {} is already declared", g.value), + }); + } + } + } + } + + let mut used_generics = HashSet::new(); + + match self.check_declaration_type( + ty.ty, + module_id, + state, + &generics_map, + &mut used_generics, + ) { + Ok(ty) => { + // check that all declared generics were used + for declared_generic in generics_map.keys() { + if !used_generics.contains(declared_generic) { + errors.push(ErrorInner { + pos: Some(pos), + message: format!("Generic parameter {} must be used", declared_generic), + }); + } + } + + if !errors.is_empty() { + return Err(errors); + } + + Ok(UserDeclarationType { generics, ty }) + } + Err(e) => { + errors.push(e); + Err(errors) + } + } + } + fn check_constant_definition( &mut self, id: ConstantIdentifier<'ast>, @@ -422,7 +526,7 @@ impl<'ast, T: Field> Checker<'ast, T> { s: StructDefinitionNode<'ast>, module_id: &ModuleId, state: &State<'ast, T>, - ) -> Result, Vec> { + ) -> Result, Vec> { let pos = s.pos(); let s = s.value; @@ -450,10 +554,9 @@ impl<'ast, T: Field> Checker<'ast, T> { } else { match generics_map.insert(g.value, index).is_none() { true => { - generics.push(Some(DeclarationConstant::Generic(GenericIdentifier { - name: g.value, - index, - }))); + generics.push(Some(DeclarationConstant::Generic( + GenericIdentifier::with_name(g.value).with_index(index), + ))); } false => { errors.push(ErrorInner { @@ -506,7 +609,7 @@ impl<'ast, T: Field> Checker<'ast, T> { return Err(errors); } - Ok(DeclarationType::Struct(DeclarationStructType::new( + Ok(DeclarationStructType::new( module_id.to_path_buf(), id, generics, @@ -514,7 +617,7 @@ impl<'ast, T: Field> Checker<'ast, T> { .iter() .map(|f| DeclarationStructMember::new(f.0.clone(), f.1.clone())) .collect(), - ))) + )) } fn check_symbol_declaration( @@ -556,7 +659,18 @@ impl<'ast, T: Field> Checker<'ast, T> { .types .entry(module_id.to_path_buf()) .or_default() - .insert(declaration.id.to_string(), ty) + .insert( + declaration.id.to_string(), + UserDeclarationType { + generics: ty + .generics + .clone() + .into_iter() + .map(|g| g.unwrap()) + .collect(), + ty: DeclarationType::Struct(ty) + } + ) .is_none()); } }; @@ -613,6 +727,35 @@ impl<'ast, T: Field> Checker<'ast, T> { } } } + Symbol::Here(SymbolDefinition::Type(t)) => { + match self.check_type_definition(t, module_id, state) { + Ok(ty) => { + match symbol_unifier.insert_type(declaration.id) { + false => errors.push( + ErrorInner { + pos: Some(pos), + message: format!( + "{} conflicts with another symbol", + declaration.id, + ), + } + .in_file(module_id), + ), + true => { + assert!(state + .types + .entry(module_id.to_path_buf()) + .or_default() + .insert(declaration.id.to_string(), ty) + .is_none()); + } + }; + } + Err(e) => { + errors.extend(e.into_iter().map(|inner| inner.in_file(module_id))); + } + } + } Symbol::Here(SymbolDefinition::Function(f)) => { match self.check_function(f, module_id, state) { Ok(funct) => { @@ -696,17 +839,19 @@ impl<'ast, T: Field> Checker<'ast, T> { match (function_candidates.len(), type_candidate, const_candidate) { (0, Some(t), None) => { - // rename the type to the declared symbol - let t = match t { - DeclarationType::Struct(t) => DeclarationType::Struct(DeclarationStructType { - location: Some(StructLocation { - name: declaration.id.into(), - module: module_id.to_path_buf() + let t = UserDeclarationType { + ty: match t.ty { + DeclarationType::Struct(t) => DeclarationType::Struct(DeclarationStructType { + location: Some(StructLocation { + name: declaration.id.into(), + module: module_id.to_path_buf() + }), + ..t }), - ..t - }), - _ => unreachable!() + _ => t.ty // all other cases + }, + ..t }; // we imported a type, so the symbol it gets bound to should not already exist @@ -954,17 +1099,26 @@ impl<'ast, T: Field> Checker<'ast, T> { match self.check_signature(funct.signature, module_id, state) { Ok(s) => { + // initialise generics map + let mut generics: GenericsAssignment<'ast, T> = GGenericsAssignment::default(); + // define variables for the constants for generic in &s.generics { - let generic = generic.clone().unwrap(); // for declaration signatures, generics cannot be ignored + let generic = match generic.clone().unwrap() { + DeclarationConstant::Generic(g) => g, + _ => unreachable!(), + }; - let v = Variable::with_id_and_type( - match generic { - DeclarationConstant::Generic(g) => g.name, - _ => unreachable!(), - }, - Type::Uint(UBitwidth::B32), + // for declaration signatures, generics cannot be ignored + + let v = Variable::with_id_and_type(generic.name(), Type::Uint(UBitwidth::B32)); + + generics.0.insert( + generic.clone(), + UExpressionInner::Identifier(generic.name().into()) + .annotate(UBitwidth::B32), ); + // we don't have to check for conflicts here, because this was done when checking the signature self.insert_into_scope(v.clone()); } @@ -977,9 +1131,12 @@ impl<'ast, T: Field> Checker<'ast, T> { let decl_v = DeclarationVariable::with_id_and_type(arg.id.value.id, decl_ty.clone()); - match self.insert_into_scope( - crate::typed_absy::variable::try_from_g_variable(decl_v.clone()).unwrap(), - ) { + let ty = specialize_declaration_type(decl_v.clone()._type, &generics).unwrap(); + + match self.insert_into_scope(crate::typed_absy::variable::Variable { + id: decl_v.clone().id, + _type: ty, + }) { true => {} false => { errors.push(ErrorInner { @@ -1103,10 +1260,9 @@ impl<'ast, T: Field> Checker<'ast, T> { } else { match generics_map.insert(g.value, index).is_none() { true => { - generics.push(Some(DeclarationConstant::Generic(GenericIdentifier { - name: g.value, - index, - }))); + generics.push(Some(DeclarationConstant::Generic( + GenericIdentifier::with_name(g.value).with_index(index), + ))); } false => { errors.push(ErrorInner { @@ -1220,7 +1376,7 @@ impl<'ast, T: Field> Checker<'ast, T> { ))) } UnresolvedType::User(id, generics) => { - let declaration_type = + let declared_ty = types .get(module_id) .unwrap() @@ -1231,72 +1387,60 @@ impl<'ast, T: Field> Checker<'ast, T> { message: format!("Undefined type {}", id), })?; + let generic_identifiers = declared_ty.declaration_generics(); + + let declaration_type = declared_ty.ty; + // absence of generics is treated as 0 generics, as we do not provide inference for now let generics = generics.unwrap_or_default(); // check generics - match declaration_type { - DeclarationType::Struct(struct_type) => { - match struct_type.generics.len() == generics.len() { - true => { - // downcast the generics to identifiers, as this is the only possibility here - let generic_identifiers = struct_type.generics.iter().map(|c| { - match c.as_ref().unwrap() { - DeclarationConstant::Generic(g) => g.clone(), - _ => unreachable!(), - } - }); - - // build the generic assignment for this type - let assignment = GGenericsAssignment(generics - .into_iter() - .zip(generic_identifiers) - .map(|(e, g)| match e { - Some(e) => { - self - .check_expression(e, module_id, types) - .and_then(|e| { - UExpression::try_from_typed(e, &UBitwidth::B32) - .map(|e| (g, e)) - .map_err(|e| ErrorInner { - pos: Some(pos), - message: format!("Expected u32 expression, but got expression of type {}", e.get_type()), - }) + match generic_identifiers.len() == generics.len() { + true => { + // build the generic assignment for this type + let assignment = GGenericsAssignment(generics + .into_iter() + .zip(generic_identifiers) + .enumerate() + .map(|(i, (e, g))| match e { + Some(e) => { + self + .check_expression(e, module_id, types) + .and_then(|e| { + UExpression::try_from_typed(e, &UBitwidth::B32) + .map(|e| (GenericIdentifier::with_name(g).with_index(i), e)) + .map_err(|e| ErrorInner { + pos: Some(pos), + message: format!("Expected u32 expression, but got expression of type {}", e.get_type()), }) - }, - None => Err(ErrorInner { - pos: Some(pos), - message: - "Expected u32 constant or identifier, but found `_`. Generic inference is not supported yet." - .into(), }) - }) - .collect::>()?); + }, + None => Err(ErrorInner { + pos: Some(pos), + message: + "Expected u32 constant or identifier, but found `_`. Generic inference is not supported yet." + .into(), + }) + }) + .collect::>()?); - // specialize the declared type using the generic assignment - Ok(specialize_declaration_type( - DeclarationType::Struct(struct_type), - &assignment, - ) - .unwrap()) - } - false => Err(ErrorInner { - pos: Some(pos), - message: format!( - "Expected {} generic argument{} on type {}, but got {}", - struct_type.generics.len(), - if struct_type.generics.len() == 1 { - "" - } else { - "s" - }, - id, - generics.len() - ), - }), - } + // specialize the declared type using the generic assignment + Ok(specialize_declaration_type(declaration_type, &assignment).unwrap()) } - _ => unreachable!("user defined types should always be structs"), + false => Err(ErrorInner { + pos: Some(pos), + message: format!( + "Expected {} generic argument{} on type {}, but got {}", + generic_identifiers.len(), + if generic_identifiers.len() == 1 { + "" + } else { + "s" + }, + id, + generics.len() + ), + }), } } } @@ -1344,7 +1488,7 @@ impl<'ast, T: Field> Checker<'ast, T> { }) } } - (None, Some(index)) => Ok(DeclarationConstant::Generic(GenericIdentifier { name, index: *index })), + (None, Some(index)) => Ok(DeclarationConstant::Generic(GenericIdentifier::with_name(name).with_index(*index))), _ => Err(ErrorInner { pos: Some(pos), message: format!("Undeclared symbol `{}`", name) @@ -1391,7 +1535,7 @@ impl<'ast, T: Field> Checker<'ast, T> { ))) } UnresolvedType::User(id, generics) => { - let declared_ty = state + let ty = state .types .get(module_id) .unwrap() @@ -1402,79 +1546,63 @@ impl<'ast, T: Field> Checker<'ast, T> { message: format!("Undefined type {}", id), })?; - match declared_ty { - DeclarationType::Struct(declared_struct_ty) => { - let generics = generics.unwrap_or_default(); - match declared_struct_ty.generics.len() == generics.len() { - true => { - let checked_generics: Vec<_> = generics - .into_iter() - .map(|e| match e { - Some(e) => self - .check_generic_expression( - e, - module_id, - state - .constants - .get(module_id) - .unwrap_or(&BTreeMap::new()), - generics_map, - used_generics, - ) - .map(Some), - None => Err(ErrorInner { - pos: Some(pos), - message: - "Expected u32 constant or identifier, but found `_`" - .into(), - }), - }) - .collect::>()?; + let generics = generics.unwrap_or_default(); + let checked_generics: Vec<_> = generics + .into_iter() + .map(|e| match e { + Some(e) => self + .check_generic_expression( + e, + module_id, + state.constants.get(module_id).unwrap_or(&BTreeMap::new()), + generics_map, + used_generics, + ) + .map(Some), + None => Err(ErrorInner { + pos: Some(pos), + message: "Expected u32 constant or identifier, but found `_`".into(), + }), + }) + .collect::>()?; - let mut assignment = GGenericsAssignment::default(); + match ty.generics.len() == checked_generics.len() { + true => { + let mut assignment = GGenericsAssignment::default(); - assignment.0.extend(declared_struct_ty.generics.iter().zip(checked_generics.iter()).map(|(decl_g, g_val)| match decl_g.clone().unwrap() { - DeclarationConstant::Generic(g) => (g, g_val.clone().unwrap()), - _ => unreachable!("generic on declaration struct types must be generic identifiers") - })); + assignment.0.extend(ty.generics.iter().zip(checked_generics.iter()).map(|(decl_g, g_val)| match decl_g.clone() { + DeclarationConstant::Generic(g) => (g, g_val.clone().unwrap()), + _ => unreachable!("generic on declaration struct types must be generic identifiers") + })); - // generate actual type based on generic type and concrete generics - let members = declared_struct_ty - .members - .into_iter() - .map(|m| { - Ok(DeclarationStructMember { - ty: box specialize_declaration_type(*m.ty, &assignment) - .unwrap(), - ..m - }) - }) - .collect::, _>>()?; - - Ok(DeclarationType::Struct(DeclarationStructType { - canonical_location: declared_struct_ty.canonical_location, - location: declared_struct_ty.location, - generics: checked_generics, - members, - })) + let res = match ty.ty { + // if the type is a struct, we do not specialize in the members. + // we only remap the generics + DeclarationType::Struct(declared_struct_ty) => { + DeclarationType::Struct(DeclarationStructType { + generics: declared_struct_ty + .generics + .into_iter() + .map(|g| g.map(|g| g.map(&assignment).unwrap())) + .collect(), + ..declared_struct_ty + }) } - false => Err(ErrorInner { - pos: Some(pos), - message: format!( - "Expected {} generic argument{} on type {}, but got {}", - declared_struct_ty.generics.len(), - if declared_struct_ty.generics.len() == 1 { - "" - } else { - "s" - }, - id, - generics.len() - ), - }), - } + ty => specialize_declaration_type(ty, &assignment).unwrap(), + }; + + Ok(res) } - _ => Ok(declared_ty), + false => Err(ErrorInner { + pos: Some(pos), + message: format!( + "Expected {} generic argument{} on type {}, but got {}", + ty.generics.len(), + if ty.generics.len() == 1 { "" } else { "s" }, + id, + checked_generics.len() + ), + }), } } } @@ -2995,11 +3123,19 @@ impl<'ast, T: Field> Checker<'ast, T> { Some(ty) => Ok(ty), }?; - let declared_struct_type = match ty { + let mut declared_struct_type = match ty.ty { DeclarationType::Struct(struct_type) => struct_type, _ => unreachable!(), }; + declared_struct_type.generics = (0..declared_struct_type.generics.len()) + .map(|index| { + Some(DeclarationConstant::Generic( + GenericIdentifier::without_name().with_index(index), + )) + }) + .collect(); + // check that we provided the required number of values if declared_struct_type.members_count() != inline_members.len() { return Err(ErrorInner { @@ -3560,7 +3696,7 @@ mod tests { "bar", DeclarationSignature::new() .generics(vec![Some( - GenericIdentifier::with_name("K").index(0).into() + GenericIdentifier::with_name("K").with_index(0).into() )]) .inputs(vec![DeclarationType::FieldElement]) )); @@ -3569,11 +3705,11 @@ mod tests { "bar", DeclarationSignature::new() .generics(vec![Some( - GenericIdentifier::with_name("K").index(0).into() + GenericIdentifier::with_name("K").with_index(0).into() )]) .inputs(vec![DeclarationType::array(( DeclarationType::FieldElement, - GenericIdentifier::with_name("K").index(0) + GenericIdentifier::with_name("K").with_index(0) ))]) )); // a `bar` function with an equivalent signature, just renaming generic parameters @@ -3581,11 +3717,11 @@ mod tests { "bar", DeclarationSignature::new() .generics(vec![Some( - GenericIdentifier::with_name("L").index(0).into() + GenericIdentifier::with_name("L").with_index(0).into() )]) .inputs(vec![DeclarationType::array(( DeclarationType::FieldElement, - GenericIdentifier::with_name("L").index(0) + GenericIdentifier::with_name("L").with_index(0) ))]) )); // a `bar` type isn't allowed as the name is already taken by at least one function @@ -4149,16 +4285,16 @@ mod tests { .inputs(vec![DeclarationType::array(( DeclarationType::array(( DeclarationType::FieldElement, - GenericIdentifier::with_name("K").index(0) + GenericIdentifier::with_name("K").with_index(0) )), - GenericIdentifier::with_name("L").index(1) + GenericIdentifier::with_name("L").with_index(1) ))]) .outputs(vec![DeclarationType::array(( DeclarationType::array(( DeclarationType::FieldElement, - GenericIdentifier::with_name("L").index(1) + GenericIdentifier::with_name("L").with_index(1) )), - GenericIdentifier::with_name("K").index(0) + GenericIdentifier::with_name("K").with_index(0) ))])) ); } @@ -5442,12 +5578,8 @@ mod tests { } .mock(); - let expected_type = DeclarationType::Struct(DeclarationStructType::new( - "".into(), - "Foo".into(), - vec![], - vec![], - )); + let expected_type = + DeclarationStructType::new("".into(), "Foo".into(), vec![], vec![]); assert_eq!( Checker::::default().check_struct_type_declaration( @@ -5483,7 +5615,7 @@ mod tests { } .mock(); - let expected_type = DeclarationType::Struct(DeclarationStructType::new( + let expected_type = DeclarationStructType::new( "".into(), "Foo".into(), vec![], @@ -5491,7 +5623,7 @@ mod tests { DeclarationStructMember::new("foo".into(), DeclarationType::FieldElement), DeclarationStructMember::new("bar".into(), DeclarationType::Boolean), ], - )); + ); assert_eq!( Checker::::default().check_struct_type_declaration( @@ -5596,6 +5728,7 @@ mod tests { .get(&*MODULE_ID) .unwrap() .get(&"Bar".to_string()) + .map(|ty| &ty.ty) .unwrap(), &DeclarationType::Struct(DeclarationStructType::new( (*MODULE_ID).clone(), diff --git a/zokrates_core/src/static_analysis/constant_inliner.rs b/zokrates_core/src/static_analysis/constant_inliner.rs new file mode 100644 index 00000000..d2b803e8 --- /dev/null +++ b/zokrates_core/src/static_analysis/constant_inliner.rs @@ -0,0 +1,973 @@ +use crate::static_analysis::Propagator; +use crate::typed_absy::result_folder::*; +use crate::typed_absy::types::DeclarationConstant; +use crate::typed_absy::*; +use std::collections::HashMap; +use std::convert::TryInto; +use std::fmt; +use zokrates_field::Field; + +type ProgramConstants<'ast, T> = + HashMap, TypedExpression<'ast, T>>>; + +#[derive(Debug, PartialEq)] +pub enum Error { + Type(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Error::Type(s) => write!(f, "{}", s), + } + } +} +pub struct ConstantInliner<'ast, T> { + modules: TypedModules<'ast, T>, + location: OwnedTypedModuleId, + constants: ProgramConstants<'ast, T>, +} + +impl<'ast, 'a, T: Field> ConstantInliner<'ast, T> { + pub fn new( + modules: TypedModules<'ast, T>, + location: OwnedTypedModuleId, + constants: ProgramConstants<'ast, T>, + ) -> Self { + ConstantInliner { + modules, + location, + constants, + } + } + pub fn inline(p: TypedProgram<'ast, T>) -> Result, Error> { + let constants = ProgramConstants::new(); + let mut inliner = ConstantInliner::new(p.modules.clone(), p.main.clone(), constants); + inliner.fold_program(p) + } + + fn change_location(&mut self, location: OwnedTypedModuleId) -> OwnedTypedModuleId { + let prev = self.location.clone(); + self.location = location; + self.constants.entry(self.location.clone()).or_default(); + prev + } + + fn treated(&self, id: &TypedModuleId) -> bool { + self.constants.contains_key(id) + } + + fn get_constant( + &self, + id: &CanonicalConstantIdentifier<'ast>, + ) -> Option> { + self.constants + .get(&id.module) + .and_then(|constants| constants.get(&id.id.into())) + .cloned() + } + + fn get_constant_for_identifier( + &self, + id: &Identifier<'ast>, + ) -> Option> { + self.constants + .get(&self.location) + .and_then(|constants| constants.get(&id)) + .cloned() + } +} + +impl<'ast, T: Field> ResultFolder<'ast, T> for ConstantInliner<'ast, T> { + type Error = Error; + + fn fold_program( + &mut self, + p: TypedProgram<'ast, T>, + ) -> Result, Self::Error> { + self.fold_module_id(p.main.clone())?; + + Ok(TypedProgram { + modules: std::mem::take(&mut self.modules), + ..p + }) + } + + fn fold_module_id( + &mut self, + id: OwnedTypedModuleId, + ) -> Result { + // anytime we encounter a module id, visit the corresponding module if it hasn't been done yet + if !self.treated(&id) { + let current_m_id = self.change_location(id.clone()); + let m = self.modules.remove(&id).unwrap(); + let m = self.fold_module(m)?; + self.modules.insert(id.clone(), m); + self.change_location(current_m_id); + } + Ok(id) + } + + fn fold_module( + &mut self, + m: TypedModule<'ast, T>, + ) -> Result, Self::Error> { + Ok(TypedModule { + constants: m + .constants + .into_iter() + .map(|(id, tc)| { + + let id = self.fold_canonical_constant_identifier(id)?; + + let constant = match tc { + TypedConstantSymbol::There(imported_id) => { + // visit the imported symbol. This triggers visiting the corresponding module if needed + let imported_id = self.fold_canonical_constant_identifier(imported_id)?; + // after that, the constant must have been defined defined in the global map. It is already reduced + // to a literal, so running propagation isn't required + self.get_constant(&imported_id).unwrap() + } + TypedConstantSymbol::Here(c) => { + let non_propagated_constant = fold_constant(self, c)?.expression; + // folding the constant above only reduces it to an expression containing only literals, not to a single literal. + // propagating with an empty map of constants reduces it to a single literal + Propagator::with_constants(&mut HashMap::default()) + .fold_expression(non_propagated_constant) + .unwrap() + } + }; + + if crate::typed_absy::types::try_from_g_type::<_, UExpression<'ast, T>>(*id.ty.clone()).unwrap() == constant.get_type() { + // add to the constant map. The value added is always a single litteral + self.constants + .get_mut(&self.location) + .unwrap() + .insert(id.id.into(), constant.clone()); + + Ok(( + id, + TypedConstantSymbol::Here(TypedConstant { + expression: constant, + }), + )) + } else { + Err(Error::Type(format!("Expression of type `{}` cannot be assigned to constant `{}` of type `{}`", constant.get_type(), id.id, id.ty))) + } + }) + .collect::, _>>()?, + functions: m + .functions + .into_iter() + .map::, _>(|(key, fun)| { + Ok(( + self.fold_declaration_function_key(key)?, + self.fold_function_symbol(fun)?, + )) + }) + .collect::, _>>() + .into_iter() + .flatten() + .collect(), + }) + } + + fn fold_declaration_constant( + &mut self, + c: DeclarationConstant<'ast>, + ) -> Result, Self::Error> { + match c { + // replace constants by their concrete value in declaration types + DeclarationConstant::Constant(id) => { + let id = CanonicalConstantIdentifier { + module: self.fold_module_id(id.module)?, + ..id + }; + + Ok(DeclarationConstant::Concrete(match self.get_constant(&id).unwrap() { + TypedExpression::Uint(UExpression { + inner: UExpressionInner::Value(v), + .. + }) => v as u32, + _ => unreachable!("all constants found in declaration types should be reduceable to u32 literals"), + })) + } + c => Ok(c), + } + } + + fn fold_field_expression( + &mut self, + e: FieldElementExpression<'ast, T>, + ) -> Result, Self::Error> { + match e { + FieldElementExpression::Identifier(ref id) => { + match self.get_constant_for_identifier(id) { + Some(c) => Ok(c.try_into().unwrap()), + None => fold_field_expression(self, e), + } + } + e => fold_field_expression(self, e), + } + } + + fn fold_boolean_expression( + &mut self, + e: BooleanExpression<'ast, T>, + ) -> Result, Self::Error> { + match e { + BooleanExpression::Identifier(ref id) => match self.get_constant_for_identifier(id) { + Some(c) => Ok(c.try_into().unwrap()), + None => fold_boolean_expression(self, e), + }, + e => fold_boolean_expression(self, e), + } + } + + fn fold_uint_expression_inner( + &mut self, + size: UBitwidth, + e: UExpressionInner<'ast, T>, + ) -> Result, Self::Error> { + match e { + UExpressionInner::Identifier(ref id) => match self.get_constant_for_identifier(id) { + Some(c) => { + let e: UExpression<'ast, T> = c.try_into().unwrap(); + Ok(e.into_inner()) + } + None => fold_uint_expression_inner(self, size, e), + }, + e => fold_uint_expression_inner(self, size, e), + } + } + + fn fold_array_expression_inner( + &mut self, + ty: &ArrayType<'ast, T>, + e: ArrayExpressionInner<'ast, T>, + ) -> Result, Self::Error> { + match e { + ArrayExpressionInner::Identifier(ref id) => { + match self.get_constant_for_identifier(id) { + Some(c) => { + let e: ArrayExpression<'ast, T> = c.try_into().unwrap(); + Ok(e.into_inner()) + } + None => fold_array_expression_inner(self, ty, e), + } + } + e => fold_array_expression_inner(self, ty, e), + } + } + + fn fold_struct_expression_inner( + &mut self, + ty: &StructType<'ast, T>, + e: StructExpressionInner<'ast, T>, + ) -> Result, Self::Error> { + match e { + StructExpressionInner::Identifier(ref id) => match self.get_constant_for_identifier(id) + { + Some(c) => { + let e: StructExpression<'ast, T> = c.try_into().unwrap(); + Ok(e.into_inner()) + } + None => fold_struct_expression_inner(self, ty, e), + }, + e => fold_struct_expression_inner(self, ty, e), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::typed_absy::types::DeclarationSignature; + use crate::typed_absy::{ + DeclarationArrayType, DeclarationFunctionKey, DeclarationType, FieldElementExpression, + GType, Identifier, TypedConstant, TypedExpression, TypedFunction, TypedFunctionSymbol, + TypedStatement, + }; + use zokrates_field::Bn128Field; + + #[test] + fn inline_const_field() { + // const field a = 1 + // + // def main() -> field: + // return a + + let const_id = "a"; + let main: TypedFunction = TypedFunction { + arguments: vec![], + statements: vec![TypedStatement::Return(vec![ + FieldElementExpression::Identifier(Identifier::from(const_id)).into(), + ])], + signature: DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::FieldElement]), + }; + + let constants: TypedConstantSymbols<_> = vec![( + CanonicalConstantIdentifier::new( + const_id, + "main".into(), + DeclarationType::FieldElement, + ), + TypedConstantSymbol::Here(TypedConstant::new(TypedExpression::FieldElement( + FieldElementExpression::Number(Bn128Field::from(1)), + ))), + )] + .into_iter() + .collect(); + + let program = TypedProgram { + main: "main".into(), + modules: vec![( + "main".into(), + TypedModule { + functions: vec![( + DeclarationFunctionKey::with_location("main", "main").signature( + DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::FieldElement]), + ), + TypedFunctionSymbol::Here(main), + )] + .into_iter() + .collect(), + constants: constants.clone(), + }, + )] + .into_iter() + .collect(), + }; + + let program = ConstantInliner::inline(program); + + let expected_main = TypedFunction { + arguments: vec![], + statements: vec![TypedStatement::Return(vec![ + FieldElementExpression::Number(Bn128Field::from(1)).into(), + ])], + signature: DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::FieldElement]), + }; + + let expected_program: TypedProgram = TypedProgram { + main: "main".into(), + modules: vec![( + "main".into(), + TypedModule { + functions: vec![( + DeclarationFunctionKey::with_location("main", "main").signature( + DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::FieldElement]), + ), + TypedFunctionSymbol::Here(expected_main), + )] + .into_iter() + .collect(), + constants, + }, + )] + .into_iter() + .collect(), + }; + + assert_eq!(program, Ok(expected_program)) + } + + #[test] + fn inline_const_boolean() { + // const bool a = true + // + // def main() -> bool: + // return a + + let const_id = "a"; + let main: TypedFunction = TypedFunction { + arguments: vec![], + statements: vec![TypedStatement::Return(vec![BooleanExpression::Identifier( + Identifier::from(const_id), + ) + .into()])], + signature: DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::Boolean]), + }; + + let constants: TypedConstantSymbols<_> = vec![( + CanonicalConstantIdentifier::new(const_id, "main".into(), DeclarationType::Boolean), + TypedConstantSymbol::Here(TypedConstant::new(TypedExpression::Boolean( + BooleanExpression::Value(true), + ))), + )] + .into_iter() + .collect(); + + let program = TypedProgram { + main: "main".into(), + modules: vec![( + "main".into(), + TypedModule { + functions: vec![( + DeclarationFunctionKey::with_location("main", "main").signature( + DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::Boolean]), + ), + TypedFunctionSymbol::Here(main), + )] + .into_iter() + .collect(), + constants: constants.clone(), + }, + )] + .into_iter() + .collect(), + }; + + let program = ConstantInliner::inline(program); + + let expected_main = TypedFunction { + arguments: vec![], + statements: vec![TypedStatement::Return(vec![ + BooleanExpression::Value(true).into() + ])], + signature: DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::Boolean]), + }; + + let expected_program: TypedProgram = TypedProgram { + main: "main".into(), + modules: vec![( + "main".into(), + TypedModule { + functions: vec![( + DeclarationFunctionKey::with_location("main", "main").signature( + DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::Boolean]), + ), + TypedFunctionSymbol::Here(expected_main), + )] + .into_iter() + .collect(), + constants, + }, + )] + .into_iter() + .collect(), + }; + + assert_eq!(program, Ok(expected_program)) + } + + #[test] + fn inline_const_uint() { + // const u32 a = 0x00000001 + // + // def main() -> u32: + // return a + + let const_id = "a"; + let main: TypedFunction = TypedFunction { + arguments: vec![], + statements: vec![TypedStatement::Return(vec![UExpressionInner::Identifier( + Identifier::from(const_id), + ) + .annotate(UBitwidth::B32) + .into()])], + signature: DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::Uint(UBitwidth::B32)]), + }; + + let constants: TypedConstantSymbols<_> = vec![( + CanonicalConstantIdentifier::new( + const_id, + "main".into(), + DeclarationType::Uint(UBitwidth::B32), + ), + TypedConstantSymbol::Here(TypedConstant::new( + UExpressionInner::Value(1u128) + .annotate(UBitwidth::B32) + .into(), + )), + )] + .into_iter() + .collect(); + + let program = TypedProgram { + main: "main".into(), + modules: vec![( + "main".into(), + TypedModule { + functions: vec![( + DeclarationFunctionKey::with_location("main", "main").signature( + DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::Uint(UBitwidth::B32)]), + ), + TypedFunctionSymbol::Here(main), + )] + .into_iter() + .collect(), + constants: constants.clone(), + }, + )] + .into_iter() + .collect(), + }; + + let program = ConstantInliner::inline(program); + + let expected_main = TypedFunction { + arguments: vec![], + statements: vec![TypedStatement::Return(vec![UExpressionInner::Value(1u128) + .annotate(UBitwidth::B32) + .into()])], + signature: DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::Uint(UBitwidth::B32)]), + }; + + let expected_program: TypedProgram = TypedProgram { + main: "main".into(), + modules: vec![( + "main".into(), + TypedModule { + functions: vec![( + DeclarationFunctionKey::with_location("main", "main").signature( + DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::Uint(UBitwidth::B32)]), + ), + TypedFunctionSymbol::Here(expected_main), + )] + .into_iter() + .collect(), + constants, + }, + )] + .into_iter() + .collect(), + }; + + assert_eq!(program, Ok(expected_program)) + } + + #[test] + fn inline_const_field_array() { + // const field[2] a = [2, 2] + // + // def main() -> field: + // return a[0] + a[1] + + let const_id = "a"; + let main: TypedFunction = TypedFunction { + arguments: vec![], + statements: vec![TypedStatement::Return(vec![FieldElementExpression::Add( + FieldElementExpression::select( + ArrayExpressionInner::Identifier(Identifier::from(const_id)) + .annotate(GType::FieldElement, 2u32), + UExpressionInner::Value(0u128).annotate(UBitwidth::B32), + ) + .into(), + FieldElementExpression::select( + ArrayExpressionInner::Identifier(Identifier::from(const_id)) + .annotate(GType::FieldElement, 2u32), + UExpressionInner::Value(1u128).annotate(UBitwidth::B32), + ) + .into(), + ) + .into()])], + signature: DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::FieldElement]), + }; + + let constants: TypedConstantSymbols<_> = vec![( + CanonicalConstantIdentifier::new( + const_id, + "main".into(), + DeclarationType::Array(DeclarationArrayType::new( + DeclarationType::FieldElement, + 2u32, + )), + ), + TypedConstantSymbol::Here(TypedConstant::new(TypedExpression::Array( + ArrayExpressionInner::Value( + vec![ + FieldElementExpression::Number(Bn128Field::from(2)).into(), + FieldElementExpression::Number(Bn128Field::from(2)).into(), + ] + .into(), + ) + .annotate(GType::FieldElement, 2u32), + ))), + )] + .into_iter() + .collect(); + + let program = TypedProgram { + main: "main".into(), + modules: vec![( + "main".into(), + TypedModule { + functions: vec![( + DeclarationFunctionKey::with_location("main", "main").signature( + DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::FieldElement]), + ), + TypedFunctionSymbol::Here(main), + )] + .into_iter() + .collect(), + constants: constants.clone(), + }, + )] + .into_iter() + .collect(), + }; + + let program = ConstantInliner::inline(program); + + let expected_main = TypedFunction { + arguments: vec![], + statements: vec![TypedStatement::Return(vec![FieldElementExpression::Add( + FieldElementExpression::select( + ArrayExpressionInner::Value( + vec![ + FieldElementExpression::Number(Bn128Field::from(2)).into(), + FieldElementExpression::Number(Bn128Field::from(2)).into(), + ] + .into(), + ) + .annotate(GType::FieldElement, 2u32), + UExpressionInner::Value(0u128).annotate(UBitwidth::B32), + ) + .into(), + FieldElementExpression::select( + ArrayExpressionInner::Value( + vec![ + FieldElementExpression::Number(Bn128Field::from(2)).into(), + FieldElementExpression::Number(Bn128Field::from(2)).into(), + ] + .into(), + ) + .annotate(GType::FieldElement, 2u32), + UExpressionInner::Value(1u128).annotate(UBitwidth::B32), + ) + .into(), + ) + .into()])], + signature: DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::FieldElement]), + }; + + let expected_program: TypedProgram = TypedProgram { + main: "main".into(), + modules: vec![( + "main".into(), + TypedModule { + functions: vec![( + DeclarationFunctionKey::with_location("main", "main").signature( + DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::FieldElement]), + ), + TypedFunctionSymbol::Here(expected_main), + )] + .into_iter() + .collect(), + constants, + }, + )] + .into_iter() + .collect(), + }; + + assert_eq!(program, Ok(expected_program)) + } + + #[test] + fn inline_nested_const_field() { + // const field a = 1 + // const field b = a + 1 + // + // def main() -> field: + // return b + + let const_a_id = "a"; + let const_b_id = "b"; + + let main: TypedFunction = TypedFunction { + arguments: vec![], + statements: vec![TypedStatement::Return(vec![ + FieldElementExpression::Identifier(Identifier::from(const_b_id)).into(), + ])], + signature: DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::FieldElement]), + }; + + let program = TypedProgram { + main: "main".into(), + modules: vec![( + "main".into(), + TypedModule { + functions: vec![( + DeclarationFunctionKey::with_location("main", "main").signature( + DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::FieldElement]), + ), + TypedFunctionSymbol::Here(main), + )] + .into_iter() + .collect(), + constants: vec![ + ( + CanonicalConstantIdentifier::new( + const_a_id, + "main".into(), + DeclarationType::FieldElement, + ), + TypedConstantSymbol::Here(TypedConstant::new( + TypedExpression::FieldElement(FieldElementExpression::Number( + Bn128Field::from(1), + )), + )), + ), + ( + CanonicalConstantIdentifier::new( + const_b_id, + "main".into(), + DeclarationType::FieldElement, + ), + TypedConstantSymbol::Here(TypedConstant::new( + TypedExpression::FieldElement(FieldElementExpression::Add( + box FieldElementExpression::Identifier(Identifier::from( + const_a_id, + )), + box FieldElementExpression::Number(Bn128Field::from(1)), + )), + )), + ), + ] + .into_iter() + .collect(), + }, + )] + .into_iter() + .collect(), + }; + + let program = ConstantInliner::inline(program); + + let expected_main = TypedFunction { + arguments: vec![], + statements: vec![TypedStatement::Return(vec![ + FieldElementExpression::Number(Bn128Field::from(2)).into(), + ])], + signature: DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::FieldElement]), + }; + + let expected_program: TypedProgram = TypedProgram { + main: "main".into(), + modules: vec![( + "main".into(), + TypedModule { + functions: vec![( + DeclarationFunctionKey::with_location("main", "main").signature( + DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::FieldElement]), + ), + TypedFunctionSymbol::Here(expected_main), + )] + .into_iter() + .collect(), + constants: vec![ + ( + CanonicalConstantIdentifier::new( + const_a_id, + "main".into(), + DeclarationType::FieldElement, + ), + TypedConstantSymbol::Here(TypedConstant::new( + TypedExpression::FieldElement(FieldElementExpression::Number( + Bn128Field::from(1), + )), + )), + ), + ( + CanonicalConstantIdentifier::new( + const_b_id, + "main".into(), + DeclarationType::FieldElement, + ), + TypedConstantSymbol::Here(TypedConstant::new( + TypedExpression::FieldElement(FieldElementExpression::Number( + Bn128Field::from(2), + )), + )), + ), + ] + .into_iter() + .collect(), + }, + )] + .into_iter() + .collect(), + }; + + assert_eq!(program, Ok(expected_program)) + } + + #[test] + fn inline_imported_constant() { + // --------------------- + // module `foo` + // -------------------- + // const field FOO = 42 + // + // def main(): + // return + // + // --------------------- + // module `main` + // --------------------- + // from "foo" import FOO + // + // def main() -> field: + // return FOO + + let foo_const_id = "FOO"; + let foo_module = TypedModule { + functions: vec![( + DeclarationFunctionKey::with_location("main", "main") + .signature(DeclarationSignature::new().inputs(vec![]).outputs(vec![])), + TypedFunctionSymbol::Here(TypedFunction { + arguments: vec![], + statements: vec![], + signature: DeclarationSignature::new().inputs(vec![]).outputs(vec![]), + }), + )] + .into_iter() + .collect(), + constants: vec![( + CanonicalConstantIdentifier::new( + foo_const_id, + "foo".into(), + DeclarationType::FieldElement, + ), + TypedConstantSymbol::Here(TypedConstant::new(TypedExpression::FieldElement( + FieldElementExpression::Number(Bn128Field::from(42)), + ))), + )] + .into_iter() + .collect(), + }; + + let main_module = TypedModule { + functions: vec![( + DeclarationFunctionKey::with_location("main", "main").signature( + DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::FieldElement]), + ), + TypedFunctionSymbol::Here(TypedFunction { + arguments: vec![], + statements: vec![TypedStatement::Return(vec![ + FieldElementExpression::Identifier(Identifier::from(foo_const_id)).into(), + ])], + signature: DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::FieldElement]), + }), + )] + .into_iter() + .collect(), + constants: vec![( + CanonicalConstantIdentifier::new( + foo_const_id, + "main".into(), + DeclarationType::FieldElement, + ), + TypedConstantSymbol::There(CanonicalConstantIdentifier::new( + foo_const_id, + "foo".into(), + DeclarationType::FieldElement, + )), + )] + .into_iter() + .collect(), + }; + + let program = TypedProgram { + main: "main".into(), + modules: vec![ + ("main".into(), main_module), + ("foo".into(), foo_module.clone()), + ] + .into_iter() + .collect(), + }; + + let program = ConstantInliner::inline(program); + let expected_main_module = TypedModule { + functions: vec![( + DeclarationFunctionKey::with_location("main", "main").signature( + DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::FieldElement]), + ), + TypedFunctionSymbol::Here(TypedFunction { + arguments: vec![], + statements: vec![TypedStatement::Return(vec![ + FieldElementExpression::Number(Bn128Field::from(42)).into(), + ])], + signature: DeclarationSignature::new() + .inputs(vec![]) + .outputs(vec![DeclarationType::FieldElement]), + }), + )] + .into_iter() + .collect(), + constants: vec![( + CanonicalConstantIdentifier::new( + foo_const_id, + "main".into(), + DeclarationType::FieldElement, + ), + TypedConstantSymbol::Here(TypedConstant::new(TypedExpression::FieldElement( + FieldElementExpression::Number(Bn128Field::from(42)), + ))), + )] + .into_iter() + .collect(), + }; + + let expected_program: TypedProgram = TypedProgram { + main: "main".into(), + modules: vec![ + ("main".into(), expected_main_module), + ("foo".into(), foo_module), + ] + .into_iter() + .collect(), + }; + + assert_eq!(program, Ok(expected_program)) + } +} diff --git a/zokrates_core/src/static_analysis/constant_resolver.rs b/zokrates_core/src/static_analysis/constant_resolver.rs index 9f9ed5d2..546b9b56 100644 --- a/zokrates_core/src/static_analysis/constant_resolver.rs +++ b/zokrates_core/src/static_analysis/constant_resolver.rs @@ -310,13 +310,13 @@ mod tests { statements: vec![TypedStatement::Return(vec![FieldElementExpression::Add( FieldElementExpression::select( ArrayExpressionInner::Identifier(Identifier::from(const_id.clone())) - .annotate(GType::FieldElement, 2usize), + .annotate(GType::FieldElement, 2u32), UExpressionInner::Value(0u128).annotate(UBitwidth::B32), ) .into(), FieldElementExpression::select( ArrayExpressionInner::Identifier(Identifier::from(const_id.clone())) - .annotate(GType::FieldElement, 2usize), + .annotate(GType::FieldElement, 2u32), UExpressionInner::Value(1u128).annotate(UBitwidth::B32), ) .into(), @@ -346,7 +346,7 @@ mod tests { ] .into(), ) - .annotate(GType::FieldElement, 2usize), + .annotate(GType::FieldElement, 2u32), ), DeclarationType::Array(DeclarationArrayType::new( DeclarationType::FieldElement, diff --git a/zokrates_core/src/static_analysis/flatten_complex_types.rs b/zokrates_core/src/static_analysis/flatten_complex_types.rs index 7709fbb6..d0e4ba1c 100644 --- a/zokrates_core/src/static_analysis/flatten_complex_types.rs +++ b/zokrates_core/src/static_analysis/flatten_complex_types.rs @@ -340,7 +340,7 @@ impl<'ast, T: Field> Flattener { &mut self, statements_buffer: &mut Vec>, ty: &typed_absy::types::ConcreteType, - size: usize, + size: u32, e: typed_absy::ArrayExpressionInner<'ast, T>, ) -> Vec> { fold_array_expression_inner(self, statements_buffer, ty, size, e) @@ -410,7 +410,7 @@ fn fold_array_expression_inner<'ast, T: Field>( f: &mut Flattener, statements_buffer: &mut Vec>, ty: &typed_absy::types::ConcreteType, - size: usize, + size: u32, array: typed_absy::ArrayExpressionInner<'ast, T>, ) -> Vec> { match array { @@ -443,7 +443,7 @@ fn fold_array_expression_inner<'ast, T: Field>( .flat_map(|e| f.fold_expression_or_spread(statements_buffer, e)) .collect(); - assert_eq!(exprs.len(), size * ty.get_primitive_count()); + assert_eq!(exprs.len(), size as usize * ty.get_primitive_count()); exprs } @@ -464,7 +464,7 @@ fn fold_array_expression_inner<'ast, T: Field>( match (from.into_inner(), to.into_inner()) { (zir::UExpressionInner::Value(from), zir::UExpressionInner::Value(to)) => { - assert_eq!(size, to.saturating_sub(from) as usize); + assert_eq!(size, to.saturating_sub(from) as u32); let element_size = ty.get_primitive_count(); let start = from as usize * element_size; @@ -1114,10 +1114,7 @@ fn fold_array_expression<'ast, T: Field>( statements_buffer: &mut Vec>, e: typed_absy::ArrayExpression<'ast, T>, ) -> Vec> { - let size = match e.size().into_inner() { - typed_absy::UExpressionInner::Value(v) => v, - _ => unreachable!(), - } as usize; + let size: u32 = e.size().try_into().unwrap(); f.fold_array_expression_inner( statements_buffer, &typed_absy::types::ConcreteType::try_from(e.inner_type().clone()).unwrap(), diff --git a/zokrates_core/src/static_analysis/mod.rs b/zokrates_core/src/static_analysis/mod.rs index ddaeef66..b46582c6 100644 --- a/zokrates_core/src/static_analysis/mod.rs +++ b/zokrates_core/src/static_analysis/mod.rs @@ -12,6 +12,7 @@ mod flatten_complex_types; mod out_of_bounds; mod propagation; mod reducer; +mod struct_concretizer; mod uint_optimizer; mod unconstrained_vars; mod variable_write_remover; @@ -23,6 +24,7 @@ use self::flatten_complex_types::Flattener; use self::out_of_bounds::OutOfBoundsChecker; use self::propagation::Propagator; use self::reducer::reduce_program; +use self::struct_concretizer::StructConcretizer; use self::uint_optimizer::UintOptimizer; use self::unconstrained_vars::UnconstrainedVariableDetector; use self::variable_write_remover::VariableWriteRemover; @@ -124,6 +126,14 @@ impl<'ast, T: Field> TypedProgram<'ast, T> { let r = reduce_program(r).map_err(Error::from)?; log::trace!("\n{}", r); + log::debug!("Static analyser: Propagate"); + let r = Propagator::propagate(r)?; + log::trace!("\n{}", r); + + log::debug!("Static analyser: Concretize structs"); + let r = StructConcretizer::concretize(r); + log::trace!("\n{}", r); + // generate abi log::debug!("Static analyser: Generate abi"); let abi = r.abi(); diff --git a/zokrates_core/src/static_analysis/propagation.rs b/zokrates_core/src/static_analysis/propagation.rs index 14e4520a..1752dad7 100644 --- a/zokrates_core/src/static_analysis/propagation.rs +++ b/zokrates_core/src/static_analysis/propagation.rs @@ -1078,6 +1078,14 @@ impl<'ast, 'a, T: Field> ResultFolder<'ast, T> for Propagator<'ast, 'a, T> { }) // ignore spreads over empty arrays .filter_map(|e| match e { + // clippy makes a wrong suggestion here: + // ``` + // this creates an owned instance just for comparison + // UExpression::from(0u32) + // help: try: `0u32` + // ``` + // But for `UExpression`, `PartialEq` is different from `PartialEq` (the latter is too optimistic in this case) + #[allow(clippy::cmp_owned)] TypedExpressionOrSpread::Spread(s) if s.array.size() == UExpression::from(0u32) => { @@ -1197,16 +1205,14 @@ impl<'ast, 'a, T: Field> ResultFolder<'ast, T> for Propagator<'ast, 'a, T> { let e1 = self.fold_struct_expression(e1)?; let e2 = self.fold_struct_expression(e2)?; - if let (Ok(t1), Ok(t2)) = ( - ConcreteType::try_from(e1.get_type()), - ConcreteType::try_from(e2.get_type()), - ) { - if t1 != t2 { - return Err(Error::Type(format!( - "Cannot compare {} of type {} to {} of type {}", - e1, t1, e2, t2 - ))); - } + let t1 = e1.get_type(); + let t2 = e2.get_type(); + + if t1 != t2 { + return Err(Error::Type(format!( + "Cannot compare {} of type {} to {} of type {}", + e1, t1, e2, t2 + ))); }; Ok(BooleanExpression::StructEq(box e1, box e2)) @@ -1470,7 +1476,7 @@ mod tests { ] .into(), ) - .annotate(Type::FieldElement, 3usize), + .annotate(Type::FieldElement, 3u32), UExpressionInner::Add(box 1u32.into(), box 1u32.into()) .annotate(UBitwidth::B32), ); diff --git a/zokrates_core/src/static_analysis/reducer/mod.rs b/zokrates_core/src/static_analysis/reducer/mod.rs index 9c788023..f90afdc8 100644 --- a/zokrates_core/src/static_analysis/reducer/mod.rs +++ b/zokrates_core/src/static_analysis/reducer/mod.rs @@ -856,22 +856,22 @@ mod tests { let foo_signature = DeclarationSignature::new() .generics(vec![Some( - GenericIdentifier::with_name("K").index(0).into(), + GenericIdentifier::with_name("K").with_index(0).into(), )]) .inputs(vec![DeclarationType::array(( DeclarationType::FieldElement, - DeclarationConstant::Generic(GenericIdentifier::with_name("K").index(0)), + DeclarationConstant::Generic(GenericIdentifier::with_name("K").with_index(0)), ))]) .outputs(vec![DeclarationType::array(( DeclarationType::FieldElement, - DeclarationConstant::Generic(GenericIdentifier::with_name("K").index(0)), + DeclarationConstant::Generic(GenericIdentifier::with_name("K").with_index(0)), ))]); let foo: TypedFunction = TypedFunction { arguments: vec![DeclarationVariable::array( "a", DeclarationType::FieldElement, - GenericIdentifier::with_name("K").index(0), + GenericIdentifier::with_name("K").with_index(0), ) .into()], statements: vec![TypedStatement::Return(vec![ @@ -979,7 +979,7 @@ mod tests { DeclarationFunctionKey::with_location("main", "foo") .signature(foo_signature.clone()), GGenericsAssignment( - vec![(GenericIdentifier::with_name("K").index(0), 1)] + vec![(GenericIdentifier::with_name("K").with_index(0), 1)] .into_iter() .collect(), ), @@ -1072,22 +1072,22 @@ mod tests { let foo_signature = DeclarationSignature::new() .generics(vec![Some( - GenericIdentifier::with_name("K").index(0).into(), + GenericIdentifier::with_name("K").with_index(0).into(), )]) .inputs(vec![DeclarationType::array(( DeclarationType::FieldElement, - DeclarationConstant::Generic(GenericIdentifier::with_name("K").index(0)), + DeclarationConstant::Generic(GenericIdentifier::with_name("K").with_index(0)), ))]) .outputs(vec![DeclarationType::array(( DeclarationType::FieldElement, - DeclarationConstant::Generic(GenericIdentifier::with_name("K").index(0)), + DeclarationConstant::Generic(GenericIdentifier::with_name("K").with_index(0)), ))]); let foo: TypedFunction = TypedFunction { arguments: vec![DeclarationVariable::array( "a", DeclarationType::FieldElement, - GenericIdentifier::with_name("K").index(0), + GenericIdentifier::with_name("K").with_index(0), ) .into()], statements: vec![TypedStatement::Return(vec![ @@ -1204,7 +1204,7 @@ mod tests { DeclarationFunctionKey::with_location("main", "foo") .signature(foo_signature.clone()), GGenericsAssignment( - vec![(GenericIdentifier::with_name("K").index(0), 1)] + vec![(GenericIdentifier::with_name("K").with_index(0), 1)] .into_iter() .collect(), ), @@ -1300,21 +1300,21 @@ mod tests { let foo_signature = DeclarationSignature::new() .inputs(vec![DeclarationType::array(( DeclarationType::FieldElement, - DeclarationConstant::Generic(GenericIdentifier::with_name("K").index(0)), + DeclarationConstant::Generic(GenericIdentifier::with_name("K").with_index(0)), ))]) .outputs(vec![DeclarationType::array(( DeclarationType::FieldElement, - DeclarationConstant::Generic(GenericIdentifier::with_name("K").index(0)), + DeclarationConstant::Generic(GenericIdentifier::with_name("K").with_index(0)), ))]) .generics(vec![Some( - GenericIdentifier::with_name("K").index(0).into(), + GenericIdentifier::with_name("K").with_index(0).into(), )]); let foo: TypedFunction = TypedFunction { arguments: vec![DeclarationVariable::array( "a", DeclarationType::FieldElement, - DeclarationConstant::Generic(GenericIdentifier::with_name("K").index(0)), + DeclarationConstant::Generic(GenericIdentifier::with_name("K").with_index(0)), ) .into()], statements: vec![ @@ -1378,7 +1378,7 @@ mod tests { arguments: vec![DeclarationVariable::array( "a", DeclarationType::FieldElement, - DeclarationConstant::Generic(GenericIdentifier::with_name("K").index(0)), + DeclarationConstant::Generic(GenericIdentifier::with_name("K").with_index(0)), ) .into()], statements: vec![TypedStatement::Return(vec![ @@ -1453,7 +1453,7 @@ mod tests { DeclarationFunctionKey::with_location("main", "foo") .signature(foo_signature.clone()), GGenericsAssignment( - vec![(GenericIdentifier::with_name("K").index(0), 1)] + vec![(GenericIdentifier::with_name("K").with_index(0), 1)] .into_iter() .collect(), ), @@ -1462,7 +1462,7 @@ mod tests { DeclarationFunctionKey::with_location("main", "bar") .signature(foo_signature.clone()), GGenericsAssignment( - vec![(GenericIdentifier::with_name("K").index(0), 2)] + vec![(GenericIdentifier::with_name("K").with_index(0), 2)] .into_iter() .collect(), ), @@ -1507,22 +1507,22 @@ mod tests { let foo_signature = DeclarationSignature::new() .generics(vec![Some( - GenericIdentifier::with_name("K").index(0).into(), + GenericIdentifier::with_name("K").with_index(0).into(), )]) .inputs(vec![DeclarationType::array(( DeclarationType::FieldElement, - GenericIdentifier::with_name("K").index(0), + GenericIdentifier::with_name("K").with_index(0), ))]) .outputs(vec![DeclarationType::array(( DeclarationType::FieldElement, - GenericIdentifier::with_name("K").index(0), + GenericIdentifier::with_name("K").with_index(0), ))]); let foo: TypedFunction = TypedFunction { arguments: vec![DeclarationVariable::array( "a", DeclarationType::FieldElement, - GenericIdentifier::with_name("K").index(0), + GenericIdentifier::with_name("K").with_index(0), ) .into()], statements: vec![TypedStatement::Return(vec![ diff --git a/zokrates_core/src/static_analysis/reducer/shallow_ssa.rs b/zokrates_core/src/static_analysis/reducer/shallow_ssa.rs index 5ae603bc..aa744e8d 100644 --- a/zokrates_core/src/static_analysis/reducer/shallow_ssa.rs +++ b/zokrates_core/src/static_analysis/reducer/shallow_ssa.rs @@ -105,7 +105,7 @@ impl<'ast, 'a> ShallowTransformer<'ast, 'a> { .map(|(g, v)| { TypedStatement::Definition( TypedAssignee::Identifier(Variable::with_id_and_type( - g.name, + g.name(), Type::Uint(UBitwidth::B32), )), UExpression::from(*v as u32).into(), @@ -662,7 +662,7 @@ mod tests { ], signature: DeclarationSignature::new() .generics(vec![Some( - GenericIdentifier::with_name("K").index(0).into(), + GenericIdentifier::with_name("K").with_index(0).into(), )]) .inputs(vec![DeclarationType::FieldElement]) .outputs(vec![DeclarationType::FieldElement]), @@ -673,7 +673,7 @@ mod tests { let ssa = ShallowTransformer::transform( f, &GGenericsAssignment( - vec![(GenericIdentifier::with_name("K").index(0), 1)] + vec![(GenericIdentifier::with_name("K").with_index(0), 1)] .into_iter() .collect(), ), @@ -742,7 +742,7 @@ mod tests { ], signature: DeclarationSignature::new() .generics(vec![Some( - GenericIdentifier::with_name("K").index(0).into(), + GenericIdentifier::with_name("K").with_index(0).into(), )]) .inputs(vec![DeclarationType::FieldElement]) .outputs(vec![DeclarationType::FieldElement]), @@ -851,7 +851,7 @@ mod tests { ], signature: DeclarationSignature::new() .generics(vec![Some( - GenericIdentifier::with_name("K").index(0).into(), + GenericIdentifier::with_name("K").with_index(0).into(), )]) .inputs(vec![DeclarationType::FieldElement]) .outputs(vec![DeclarationType::FieldElement]), @@ -862,7 +862,7 @@ mod tests { let ssa = ShallowTransformer::transform( f, &GGenericsAssignment( - vec![(GenericIdentifier::with_name("K").index(0), 1)] + vec![(GenericIdentifier::with_name("K").with_index(0), 1)] .into_iter() .collect(), ), @@ -934,7 +934,7 @@ mod tests { ], signature: DeclarationSignature::new() .generics(vec![Some( - GenericIdentifier::with_name("K").index(0).into(), + GenericIdentifier::with_name("K").with_index(0).into(), )]) .inputs(vec![DeclarationType::FieldElement]) .outputs(vec![DeclarationType::FieldElement]), diff --git a/zokrates_core/src/static_analysis/struct_concretizer.rs b/zokrates_core/src/static_analysis/struct_concretizer.rs new file mode 100644 index 00000000..71502cc1 --- /dev/null +++ b/zokrates_core/src/static_analysis/struct_concretizer.rs @@ -0,0 +1,90 @@ +// After all generics are inlined, a program should be completely "concrete", which means that all types must only contain +// litterals for array sizes. This is especially important to generate the ABI of the program. +// It is direct to ensure that with most types, however the way structs are implemented requires a slightly different process: +// Where for an array, `field[N]` ends up being propagated to `field[42]` which is direct to turn into a concrete type, +// for structs, `Foo { field[N] a }` is propagated to `Foo<42> { field[N] a }`. The missing step is replacing `N` by `42` +// *inside* the canonical type, so that it can be concretized in the same way arrays are. + +use crate::typed_absy::folder::*; +use crate::typed_absy::{ + types::{ + ConcreteGenericsAssignment, DeclarationArrayType, DeclarationConstant, + DeclarationStructMember, GGenericsAssignment, + }, + DeclarationStructType, GenericIdentifier, TypedProgram, +}; +use std::marker::PhantomData; +use zokrates_field::Field; + +pub struct StructConcretizer<'ast, T> { + generics: ConcreteGenericsAssignment<'ast>, + marker: PhantomData, +} + +impl<'ast, T: Field> StructConcretizer<'ast, T> { + pub fn concretize(p: TypedProgram<'ast, T>) -> TypedProgram<'ast, T> { + StructConcretizer::with_generics(ConcreteGenericsAssignment::default()).fold_program(p) + } + + pub fn with_generics(generics: ConcreteGenericsAssignment<'ast>) -> Self { + Self { + generics, + marker: PhantomData, + } + } +} + +impl<'ast, T: Field> Folder<'ast, T> for StructConcretizer<'ast, T> { + fn fold_declaration_struct_type( + &mut self, + ty: DeclarationStructType<'ast, T>, + ) -> DeclarationStructType<'ast, T> { + let concrete_generics: Vec = ty + .generics + .clone() + .into_iter() + .map(|g| g.unwrap().map_concrete(&self.generics).unwrap()) + .collect(); + + let concrete_generics_map: ConcreteGenericsAssignment = GGenericsAssignment( + concrete_generics + .iter() + .enumerate() + .map(|(index, g)| (GenericIdentifier::without_name().with_index(index), *g)) + .collect(), + ); + + let mut internal_concretizer: StructConcretizer<'ast, T> = + StructConcretizer::with_generics(concrete_generics_map); + + DeclarationStructType { + members: ty + .members + .into_iter() + .map(|member| { + DeclarationStructMember::new( + member.id, + internal_concretizer.fold_declaration_type(*member.ty), + ) + }) + .collect(), + generics: concrete_generics + .into_iter() + .map(|g| Some(DeclarationConstant::Concrete(g as u32))) + .collect(), + ..ty + } + } + + fn fold_declaration_array_type( + &mut self, + ty: DeclarationArrayType<'ast, T>, + ) -> DeclarationArrayType<'ast, T> { + let size = ty.size.map_concrete(&self.generics).unwrap(); + + DeclarationArrayType { + size: DeclarationConstant::Concrete(size), + ty: box self.fold_declaration_type(*ty.ty), + } + } +} diff --git a/zokrates_core/src/static_analysis/variable_write_remover.rs b/zokrates_core/src/static_analysis/variable_write_remover.rs index d5522641..bbc9b2a8 100644 --- a/zokrates_core/src/static_analysis/variable_write_remover.rs +++ b/zokrates_core/src/static_analysis/variable_write_remover.rs @@ -37,10 +37,9 @@ impl<'ast> VariableWriteRemover { let inner_ty = base.inner_type(); let size = base.size(); - let size = match size.as_inner() { - UExpressionInner::Value(v) => *v as u32, - _ => unreachable!(), - }; + use std::convert::TryInto; + + let size: u32 = size.try_into().unwrap(); let head = indices.remove(0); let tail = indices; diff --git a/zokrates_core/src/typed_absy/abi.rs b/zokrates_core/src/typed_absy/abi.rs index 65b53bba..d55332e8 100644 --- a/zokrates_core/src/typed_absy/abi.rs +++ b/zokrates_core/src/typed_absy/abi.rs @@ -226,12 +226,12 @@ mod tests { ty: ConcreteType::Struct(ConcreteStructType::new( "".into(), "Bar".into(), - vec![Some(1usize)], + vec![Some(1u32)], vec![ConcreteStructMember::new( String::from("a"), ConcreteType::Array(ConcreteArrayType::new( ConcreteType::FieldElement, - 1usize, + 1u32, )), )], )), @@ -395,7 +395,7 @@ mod tests { ConcreteStructMember::new(String::from("c"), ConcreteType::Boolean), ], )), - 2usize, + 2u32, )), }], outputs: vec![ConcreteType::Boolean], @@ -449,8 +449,8 @@ mod tests { name: String::from("a"), public: false, ty: ConcreteType::Array(ConcreteArrayType::new( - ConcreteType::Array(ConcreteArrayType::new(ConcreteType::FieldElement, 2usize)), - 2usize, + ConcreteType::Array(ConcreteArrayType::new(ConcreteType::FieldElement, 2u32)), + 2u32, )), }], outputs: vec![ConcreteType::FieldElement], diff --git a/zokrates_core/src/typed_absy/mod.rs b/zokrates_core/src/typed_absy/mod.rs index a37777af..dbee0862 100644 --- a/zokrates_core/src/typed_absy/mod.rs +++ b/zokrates_core/src/typed_absy/mod.rs @@ -1203,9 +1203,9 @@ impl<'ast, T> IntoIterator for ArrayValue<'ast, T> { } } -impl<'ast, T: Clone + fmt::Debug> ArrayValue<'ast, T> { +impl<'ast, T: Clone> ArrayValue<'ast, T> { fn expression_at_aux< - U: Select<'ast, T> + Into> + From>, + U: Select<'ast, T> + From> + Into>, >( v: TypedExpressionOrSpread<'ast, T>, ) -> Vec> { @@ -1236,7 +1236,7 @@ impl<'ast, T: Clone + fmt::Debug> ArrayValue<'ast, T> { } pub fn expression_at< - U: Select<'ast, T> + Into> + From>, + U: Select<'ast, T> + From> + Into>, >( &self, index: usize, diff --git a/zokrates_core/src/typed_absy/result_folder.rs b/zokrates_core/src/typed_absy/result_folder.rs index 5986ca22..2ca66c83 100644 --- a/zokrates_core/src/typed_absy/result_folder.rs +++ b/zokrates_core/src/typed_absy/result_folder.rs @@ -214,8 +214,8 @@ pub trait ResultFolder<'ast, T: Field>: Sized { fn fold_select_expression< E: Expr<'ast, T> + Select<'ast, T> - + From> - + Into>, + + Into> + + From>, >( &mut self, ty: &E::Ty, diff --git a/zokrates_core/src/typed_absy/types.rs b/zokrates_core/src/typed_absy/types.rs index 7fb2d30c..2cc6a0f0 100644 --- a/zokrates_core/src/typed_absy/types.rs +++ b/zokrates_core/src/typed_absy/types.rs @@ -59,21 +59,39 @@ impl<'ast, T> Types<'ast, T> { } } -#[derive(Debug, Clone, Eq, Ord)] +#[derive(Debug, Clone, Eq)] pub struct GenericIdentifier<'ast> { - pub name: &'ast str, - pub index: usize, + name: Option<&'ast str>, + index: usize, } impl<'ast> GenericIdentifier<'ast> { - pub fn with_name(name: &'ast str) -> Self { - Self { name, index: 0 } + pub fn without_name() -> Self { + Self { + name: None, + index: 0, + } } - pub fn index(mut self, index: usize) -> Self { + pub fn with_name(name: &'ast str) -> Self { + Self { + name: Some(name), + index: 0, + } + } + + pub fn with_index(mut self, index: usize) -> Self { self.index = index; self } + + pub fn name(&self) -> &'ast str { + self.name.unwrap() + } + + pub fn index(&self) -> usize { + self.index + } } impl<'ast> PartialEq for GenericIdentifier<'ast> { @@ -88,6 +106,12 @@ impl<'ast> PartialOrd for GenericIdentifier<'ast> { } } +impl<'ast> Ord for GenericIdentifier<'ast> { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.partial_cmp(other).unwrap() + } +} + impl<'ast> Hash for GenericIdentifier<'ast> { fn hash(&self, state: &mut H) { self.index.hash(state); @@ -96,7 +120,7 @@ impl<'ast> Hash for GenericIdentifier<'ast> { impl<'ast> fmt::Display for GenericIdentifier<'ast> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.name) + write!(f, "{}", self.name()) } } @@ -131,6 +155,34 @@ pub enum DeclarationConstant<'ast, T> { Expression(TypedExpression<'ast, T>), } +impl<'ast, T> DeclarationConstant<'ast, T> { + pub fn map> + From + Clone>( + self, + generics: &GGenericsAssignment<'ast, S>, + ) -> Result> { + match self { + DeclarationConstant::Generic(g) => generics.0.get(&g).cloned().ok_or(g), + DeclarationConstant::Concrete(v) => Ok(v.into()), + DeclarationConstant::Constant(c) => Ok(c.into()), + DeclarationConstant::Expression(_) => unreachable!(), + } + } + + pub fn map_concrete + Clone>( + self, + generics: &GGenericsAssignment<'ast, S>, + ) -> Result> { + match self { + DeclarationConstant::Constant(_) => unreachable!( + "called map_concrete on a constant, it should have been resolved before" + ), + DeclarationConstant::Generic(g) => generics.0.get(&g).cloned().ok_or(g), + DeclarationConstant::Concrete(v) => Ok(v.into()), + DeclarationConstant::Expression(_) => unreachable!(), + } + } +} + impl<'ast, T: PartialEq> PartialEq> for DeclarationConstant<'ast, T> { fn eq(&self, other: &UExpression<'ast, T>) -> bool { match (self, other) { @@ -184,8 +236,8 @@ impl<'ast, T: fmt::Display> fmt::Display for DeclarationConstant<'ast, T> { } } -impl<'ast, T> From for UExpression<'ast, T> { - fn from(i: usize) -> Self { +impl<'ast, T> From for UExpression<'ast, T> { + fn from(i: u32) -> Self { UExpressionInner::Value(i as u128).annotate(UBitwidth::B32) } } @@ -194,7 +246,7 @@ impl<'ast, T> From> for UExpression<'ast, T> { fn from(c: DeclarationConstant<'ast, T>) -> Self { match c { DeclarationConstant::Generic(i) => { - UExpressionInner::Identifier(i.name.into()).annotate(UBitwidth::B32) + UExpressionInner::Identifier(i.name().into()).annotate(UBitwidth::B32) } DeclarationConstant::Concrete(v) => { UExpressionInner::Value(v as u128).annotate(UBitwidth::B32) @@ -208,14 +260,14 @@ impl<'ast, T> From> for UExpression<'ast, T> { } } -impl<'ast, T> TryInto for UExpression<'ast, T> { +impl<'ast, T> TryInto for UExpression<'ast, T> { type Error = SpecializationError; - fn try_into(self) -> Result { + fn try_into(self) -> Result { assert_eq!(self.bitwidth, UBitwidth::B32); match self.into_inner() { - UExpressionInner::Value(v) => Ok(v as usize), + UExpressionInner::Value(v) => Ok(v as u32), _ => Err(SpecializationError), } } @@ -243,7 +295,7 @@ pub struct GStructMember { } pub type DeclarationStructMember<'ast, T> = GStructMember>; -pub type ConcreteStructMember = GStructMember; +pub type ConcreteStructMember = GStructMember; pub type StructMember<'ast, T> = GStructMember>; impl<'ast, S, R: PartialEq> PartialEq> for GStructMember { @@ -283,7 +335,7 @@ pub struct GArrayType { } pub type DeclarationArrayType<'ast, T> = GArrayType>; -pub type ConcreteArrayType = GArrayType; +pub type ConcreteArrayType = GArrayType; pub type ArrayType<'ast, T> = GArrayType>; impl<'ast, S, R: PartialEq> PartialEq> for GArrayType { @@ -365,7 +417,7 @@ pub struct GStructType { } pub type DeclarationStructType<'ast, T> = GStructType>; -pub type ConcreteStructType = GStructType; +pub type ConcreteStructType = GStructType; pub type StructType<'ast, T> = GStructType>; impl<'ast, S, R: PartialEq> PartialEq> for GStructType { @@ -377,8 +429,7 @@ impl<'ast, S, R: PartialEq> PartialEq> for GStructType { .zip(other.generics.iter()) .all(|(a, b)| match (a, b) { (Some(a), Some(b)) => a == b, - (None, None) => true, - _ => false, + _ => true, }) } } @@ -622,7 +673,7 @@ impl<'de, S: Deserialize<'de>> Deserialize<'de> for GType { } pub type DeclarationType<'ast, T> = GType>; -pub type ConcreteType = GType; +pub type ConcreteType = GType; pub type Type<'ast, T> = GType>; impl<'ast, S, R: PartialEq> PartialEq> for GType { @@ -811,7 +862,9 @@ impl ConcreteType { GType::FieldElement => 1, GType::Boolean => 1, GType::Uint(_) => 1, - GType::Array(array_type) => array_type.size * array_type.ty.get_primitive_count(), + GType::Array(array_type) => { + array_type.size as usize * array_type.ty.get_primitive_count() + } GType::Int => unreachable!(), GType::Struct(struct_type) => struct_type .iter() @@ -831,7 +884,7 @@ pub struct GFunctionKey<'ast, S> { } pub type DeclarationFunctionKey<'ast, T> = GFunctionKey<'ast, DeclarationConstant<'ast, T>>; -pub type ConcreteFunctionKey<'ast> = GFunctionKey<'ast, usize>; +pub type ConcreteFunctionKey<'ast> = GFunctionKey<'ast, u32>; pub type FunctionKey<'ast, T> = GFunctionKey<'ast, UExpression<'ast, T>>; impl<'ast, S: fmt::Display> fmt::Display for GFunctionKey<'ast, S> { @@ -843,7 +896,7 @@ impl<'ast, S: fmt::Display> fmt::Display for GFunctionKey<'ast, S> { #[derive(Debug, PartialEq, Eq, Hash, Clone, PartialOrd, Ord)] pub struct GGenericsAssignment<'ast, S>(pub BTreeMap, S>); -pub type ConcreteGenericsAssignment<'ast> = GGenericsAssignment<'ast, usize>; +pub type ConcreteGenericsAssignment<'ast> = GGenericsAssignment<'ast, u32>; pub type GenericsAssignment<'ast, T> = GGenericsAssignment<'ast, UExpression<'ast, T>>; impl<'ast, S> Default for GGenericsAssignment<'ast, S> { @@ -943,32 +996,50 @@ impl<'ast> ConcreteFunctionKey<'ast> { use std::collections::btree_map::Entry; -pub fn check_type<'ast, T, S: Clone + PartialEq + PartialEq>( +// check an optional generic value against the corresponding declaration constant +// if None is provided, return true +// if some value is provided, insert it into the map or check that it doesn't conflict if a value is already thereq +pub fn check_generic<'ast, T, S: Clone + PartialEq + PartialEq>( + generic: &DeclarationConstant<'ast, T>, + value: Option<&S>, + constants: &mut GGenericsAssignment<'ast, S>, +) -> bool { + value + .map(|value| match generic { + // if the generic is an identifier, we insert into the map, or check if the concrete size + // matches if this identifier is already in the map + DeclarationConstant::Generic(id) => match constants.0.entry(id.clone()) { + Entry::Occupied(e) => *e.get() == *value, + Entry::Vacant(e) => { + e.insert(value.clone()); + true + } + }, + DeclarationConstant::Concrete(generic) => *value == *generic, + // in the case of a constant, we do not know the value yet, so we optimistically assume it's correct + // if it does not match, it will be caught during inlining + DeclarationConstant::Constant(..) => true, + DeclarationConstant::Expression(e) => match e { + TypedExpression::Uint(e) => match e.as_inner() { + UExpressionInner::Value(v) => *value == *v as u32, + _ => true, + }, + _ => unreachable!(), + }, + }) + .unwrap_or(true) +} + +pub fn check_type<'ast, T, S: Clone + PartialEq + PartialEq>( decl_ty: &DeclarationType<'ast, T>, ty: >ype, constants: &mut GGenericsAssignment<'ast, S>, ) -> bool { match (decl_ty, ty) { (DeclarationType::Array(t0), GType::Array(t1)) => { - let s1 = t1.size.clone(); - // both the inner type and the size must match check_type(&t0.ty, &t1.ty, constants) - && match &t0.size { - // if the declared size is an identifier, we insert into the map, or check if the concrete size - // matches if this identifier is already in the map - DeclarationConstant::Generic(id) => match constants.0.entry(id.clone()) { - Entry::Occupied(e) => *e.get() == s1, - Entry::Vacant(e) => { - e.insert(s1); - true - } - }, - DeclarationConstant::Concrete(s0) => s1 == *s0 as usize, - // in the other cases, we do not know the value yet, so we optimistically assume it's correct - // if it does not match, it will be caught during inlining - DeclarationConstant::Constant(..) | DeclarationConstant::Expression(..) => true, - } + && check_generic(&t0.size, Some(&t1.size), constants) } (DeclarationType::FieldElement, GType::FieldElement) | (DeclarationType::Boolean, GType::Boolean) => true, @@ -976,10 +1047,10 @@ pub fn check_type<'ast, T, S: Clone + PartialEq + PartialEq>( (DeclarationType::Struct(s0), GType::Struct(s1)) => { s0.canonical_location == s1.canonical_location && s0 - .members + .generics .iter() - .zip(s1.members.iter()) - .all(|(m0, m1)| check_type(&*m0.ty, &*m1.ty, constants)) + .zip(s1.generics.iter()) + .all(|(g0, g1)| check_generic(g0.as_ref().unwrap(), g1.as_ref(), constants)) } _ => false, } @@ -1000,7 +1071,7 @@ impl<'ast, T> From> for DeclarationConstant<'a pub fn specialize_declaration_type< 'ast, - T, + T: Clone, S: Clone + PartialEq + From + fmt::Debug + From>, >( decl_ty: DeclarationType<'ast, T>, @@ -1010,46 +1081,53 @@ pub fn specialize_declaration_type< DeclarationType::Int => unreachable!(), DeclarationType::Array(t0) => { let ty = box specialize_declaration_type(*t0.ty, generics)?; - let size = match t0.size { - DeclarationConstant::Generic(s) => generics.0.get(&s).cloned().ok_or(s), - DeclarationConstant::Concrete(s) => Ok(s.into()), - DeclarationConstant::Constant(c) => Ok(c.into()), - DeclarationConstant::Expression(..) => unreachable!("the semantic checker should not yield this DeclarationConstant variant") - }?; + let size = t0.size.map(generics)?; GType::Array(GArrayType { size, ty }) } DeclarationType::FieldElement => GType::FieldElement, DeclarationType::Boolean => GType::Boolean, DeclarationType::Uint(b0) => GType::Uint(b0), - DeclarationType::Struct(s0) => GType::Struct(GStructType { - members: s0 - .members - .into_iter() - .map(|m| { - let id = m.id; - specialize_declaration_type(*m.ty, generics) - .map(|ty| GStructMember { ty: box ty, id }) - }) - .collect::>()?, - generics: s0 - .generics - .into_iter() - .map(|g| match g { - Some(constant) => match constant { - DeclarationConstant::Generic(s) => { - generics.0.get(&s).cloned().ok_or(s).map(Some) - } - DeclarationConstant::Concrete(s) => Ok(Some(s.into())), - DeclarationConstant::Constant(c) => Ok(Some(c.into())), - DeclarationConstant::Expression(..) => unreachable!("the semantic checker should not yield this DeclarationConstant variant"), - }, - _ => Ok(None), - }) - .collect::>()?, - canonical_location: s0.canonical_location, - location: s0.location, - }), + DeclarationType::Struct(s0) => { + // here we specialize Foo {FooDef} with some values for Generics + // we need to remap these values for InsideGenerics to then visit the members + + let inside_generics = GGenericsAssignment( + s0.generics + .clone() + .into_iter() + .enumerate() + .map(|(index, g)| { + ( + GenericIdentifier::without_name().with_index(index), + g.map(|g| g.map(generics).unwrap()).unwrap(), + ) + }) + .collect(), + ); + + GType::Struct(GStructType { + members: s0 + .members + .into_iter() + .map(|m| { + let id = m.id; + specialize_declaration_type(*m.ty, &inside_generics) + .map(|ty| GStructMember { ty: box ty, id }) + }) + .collect::>()?, + generics: s0 + .generics + .into_iter() + .map(|g| match g { + Some(constant) => constant.map(generics).map(Some), + _ => Ok(None), + }) + .collect::>()?, + canonical_location: s0.canonical_location, + location: s0.location, + }) + } }) } @@ -1107,7 +1185,7 @@ pub mod signature { } pub type DeclarationSignature<'ast, T> = GSignature>; - pub type ConcreteSignature = GSignature; + pub type ConcreteSignature = GSignature; pub type Signature<'ast, T> = GSignature>; impl<'ast, T> PartialEq> for ConcreteSignature { @@ -1120,7 +1198,7 @@ pub mod signature { .iter() .chain(other.outputs.iter()) .zip(self.inputs.iter().chain(self.outputs.iter())) - .all(|(decl_ty, ty)| check_type::(decl_ty, ty, &mut constants)) + .all(|(decl_ty, ty)| check_type::(decl_ty, ty, &mut constants)) } } @@ -1145,7 +1223,7 @@ pub mod signature { constants.0.extend( decl_generics .zip(values.into_iter()) - .filter_map(|(g, v)| v.map(|v| (g, v as usize))), + .filter_map(|(g, v)| v.map(|v| (g, v))), ); let condition = self @@ -1378,33 +1456,19 @@ pub mod signature { let generic1 = DeclarationSignature::::new() .generics(vec![Some( - GenericIdentifier { - name: "P", - index: 0, - } - .into(), + GenericIdentifier::with_name("P").with_index(0).into(), )]) .inputs(vec![DeclarationType::array(DeclarationArrayType::new( DeclarationType::FieldElement, - GenericIdentifier { - name: "P", - index: 0, - }, + GenericIdentifier::with_name("P").with_index(0), ))]); let generic2 = DeclarationSignature::new() .generics(vec![Some( - GenericIdentifier { - name: "Q", - index: 0, - } - .into(), + GenericIdentifier::with_name("Q").with_index(0).into(), )]) .inputs(vec![DeclarationType::array(DeclarationArrayType::new( DeclarationType::FieldElement, - GenericIdentifier { - name: "Q", - index: 0, - }, + GenericIdentifier::with_name("Q").with_index(0), ))]); assert_eq!(generic1, generic2); @@ -1469,8 +1533,8 @@ pub mod signature { fn array_slug() { let s = ConcreteSignature::new() .inputs(vec![ - ConcreteType::array((ConcreteType::FieldElement, 42usize)), - ConcreteType::array((ConcreteType::FieldElement, 21usize)), + ConcreteType::array((ConcreteType::FieldElement, 42u32)), + ConcreteType::array((ConcreteType::FieldElement, 21u32)), ]) .outputs(vec![]); @@ -1485,7 +1549,7 @@ mod tests { #[test] fn array() { - let t = ConcreteType::Array(ConcreteArrayType::new(ConcreteType::FieldElement, 42usize)); + let t = ConcreteType::Array(ConcreteArrayType::new(ConcreteType::FieldElement, 42u32)); assert_eq!(t.get_primitive_count(), 42); } @@ -1493,8 +1557,8 @@ mod tests { fn array_display() { // field[1][2] let t = ConcreteType::Array(ConcreteArrayType::new( - ConcreteType::Array(ConcreteArrayType::new(ConcreteType::FieldElement, 2usize)), - 1usize, + ConcreteType::Array(ConcreteArrayType::new(ConcreteType::FieldElement, 2u32)), + 1u32, )); assert_eq!(format!("{}", t), "field[1][2]"); } diff --git a/zokrates_core/src/typed_absy/uint.rs b/zokrates_core/src/typed_absy/uint.rs index dc5aa09b..0e38fdc9 100644 --- a/zokrates_core/src/typed_absy/uint.rs +++ b/zokrates_core/src/typed_absy/uint.rs @@ -146,12 +146,6 @@ pub struct UExpression<'ast, T> { pub inner: UExpressionInner<'ast, T>, } -impl<'ast, T> From for UExpression<'ast, T> { - fn from(u: u32) -> Self { - UExpressionInner::Value(u as u128).annotate(UBitwidth::B32) - } -} - impl<'ast, T> From for UExpression<'ast, T> { fn from(u: u16) -> Self { UExpressionInner::Value(u as u128).annotate(UBitwidth::B16) @@ -164,8 +158,8 @@ impl<'ast, T> From for UExpression<'ast, T> { } } -impl<'ast, T> PartialEq for UExpression<'ast, T> { - fn eq(&self, other: &usize) -> bool { +impl<'ast, T> PartialEq for UExpression<'ast, T> { + fn eq(&self, other: &u32) -> bool { match self.as_inner() { UExpressionInner::Value(v) => *v == *other as u128, _ => true, diff --git a/zokrates_core/src/typed_absy/variable.rs b/zokrates_core/src/typed_absy/variable.rs index 0e9d6987..f287eda5 100644 --- a/zokrates_core/src/typed_absy/variable.rs +++ b/zokrates_core/src/typed_absy/variable.rs @@ -12,7 +12,7 @@ pub struct GVariable<'ast, S> { } pub type DeclarationVariable<'ast, T> = GVariable<'ast, DeclarationConstant<'ast, T>>; -pub type ConcreteVariable<'ast> = GVariable<'ast, usize>; +pub type ConcreteVariable<'ast> = GVariable<'ast, u32>; pub type Variable<'ast, T> = GVariable<'ast, UExpression<'ast, T>>; impl<'ast, T> TryFrom> for ConcreteVariable<'ast> { diff --git a/zokrates_core/src/zir/identifier.rs b/zokrates_core/src/zir/identifier.rs index 87eea34d..9f7b6a9e 100644 --- a/zokrates_core/src/zir/identifier.rs +++ b/zokrates_core/src/zir/identifier.rs @@ -11,7 +11,7 @@ pub enum Identifier<'ast> { #[derive(Debug, PartialEq, Clone, Hash, Eq)] pub enum SourceIdentifier<'ast> { Basic(CoreIdentifier<'ast>), - Select(Box>, usize), + Select(Box>, u32), Member(Box>, MemberId), } diff --git a/zokrates_parser/src/ace_mode/index.js b/zokrates_parser/src/ace_mode/index.js index 9778609b..b576695f 100644 --- a/zokrates_parser/src/ace_mode/index.js +++ b/zokrates_parser/src/ace_mode/index.js @@ -37,7 +37,7 @@ ace.define("ace/mode/zokrates_highlight_rules",["require","exports","module","ac var ZoKratesHighlightRules = function () { var keywords = ( - "assert|as|bool|byte|const|def|do|else|endfor|export|false|field|for|if|then|fi|import|from|in|private|public|return|struct|true|u8|u16|u32|u64" + "assert|as|bool|byte|const|def|do|else|endfor|export|false|field|for|if|then|fi|import|from|in|private|public|return|struct|true|type|u8|u16|u32|u64" ); var keywordMapper = this.createKeywordMapper({ diff --git a/zokrates_parser/src/textmate/zokrates.tmLanguage.yaml b/zokrates_parser/src/textmate/zokrates.tmLanguage.yaml index 2a2e9fb6..bb200057 100644 --- a/zokrates_parser/src/textmate/zokrates.tmLanguage.yaml +++ b/zokrates_parser/src/textmate/zokrates.tmLanguage.yaml @@ -202,19 +202,23 @@ repository: - comment: 'control flow keywords' name: keyword.control.zokrates - match: \b(do|else|for|do|endfor|if|then|fi|return|assert)\b + match: \b(for|in|do|endfor|if|then|else|fi|return|assert)\b - comment: 'storage keywords' name: storage.type.zokrates match: \b(struct)\b - - comment: const + comment: 'const keyword' name: keyword.other.const.zokrates - match: \bconst\b + match: \b(const)\b - - comment: def + comment: 'type keyword' + name: keyword.other.type.zokrates + match: \b(type)\b + - + comment: 'def keyword' name: keyword.other.def.zokrates - match: \bdef\b + match: \b(def)\b - comment: 'import keywords' name: keyword.other.import.zokrates diff --git a/zokrates_parser/src/zokrates.pest b/zokrates_parser/src/zokrates.pest index 06970e18..569ac279 100644 --- a/zokrates_parser/src/zokrates.pest +++ b/zokrates_parser/src/zokrates.pest @@ -6,7 +6,7 @@ curve = @{ (ASCII_ALPHANUMERIC | "_") * } string = @{(!"\"" ~ ANY)*} quoted_string = _{ "\"" ~ string ~ "\"" } -symbol_declaration = { (import_directive | ty_struct_definition | const_definition | function_definition) ~ NEWLINE* } +symbol_declaration = { (import_directive | ty_struct_definition | const_definition | type_definition | function_definition) ~ NEWLINE* } import_directive = { main_import_directive | from_import_directive } from_import_directive = { "from" ~ quoted_string ~ "import" ~ import_symbol_list ~ NEWLINE* } @@ -15,6 +15,7 @@ import_symbol = { identifier ~ ("as" ~ identifier)? } import_symbol_list = _{ import_symbol ~ ("," ~ import_symbol)* } function_definition = {"def" ~ identifier ~ constant_generics_declaration? ~ "(" ~ parameter_list ~ ")" ~ return_types ~ ":" ~ NEWLINE* ~ statement* } const_definition = {"const" ~ ty ~ identifier ~ "=" ~ expression ~ NEWLINE*} +type_definition = {"type" ~ identifier ~ constant_generics_declaration? ~ "=" ~ ty ~ NEWLINE*} return_types = _{ ( "->" ~ ( "(" ~ type_list ~ ")" | ty ))? } constant_generics_declaration = _{ "<" ~ constant_generics_list ~ ">" } constant_generics_list = _{ identifier ~ ("," ~ identifier)* } @@ -166,6 +167,6 @@ COMMENT = _{ ("/*" ~ (!"*/" ~ ANY)* ~ "*/") | ("//" ~ (!NEWLINE ~ ANY)*) } // the ordering of reserved keywords matters: if "as" is before "assert", then "assert" gets parsed as (as)(sert) and incorrectly // accepted -keyword = @{"assert"|"as"|"bool"|"byte"|"const"|"def"|"do"|"else"|"endfor"|"export"|"false"|"field"|"for"|"if"|"then"|"fi"|"import"|"from"| +keyword = @{"assert"|"as"|"bool"|"const"|"def"|"do"|"else"|"endfor"|"export"|"false"|"field"|"for"|"if"|"then"|"fi"|"import"|"from"| "in"|"private"|"public"|"return"|"struct"|"true"|"u8"|"u16"|"u32"|"u64" } diff --git a/zokrates_pest_ast/src/lib.rs b/zokrates_pest_ast/src/lib.rs index e35b3a42..0b24edeb 100644 --- a/zokrates_pest_ast/src/lib.rs +++ b/zokrates_pest_ast/src/lib.rs @@ -17,8 +17,8 @@ pub use ast::{ InlineStructExpression, InlineStructMember, IterationStatement, LiteralExpression, Parameter, PostfixExpression, Range, RangeOrExpression, ReturnStatement, Span, Spread, SpreadOrExpression, Statement, StructDefinition, StructField, SymbolDeclaration, TernaryExpression, ToExpression, - Type, TypedIdentifier, TypedIdentifierOrAssignee, UnaryExpression, UnaryOperator, Underscore, - Visibility, + Type, TypeDefinition, TypedIdentifier, TypedIdentifierOrAssignee, UnaryExpression, + UnaryOperator, Underscore, Visibility, }; mod ast { @@ -147,6 +147,7 @@ mod ast { Import(ImportDirective<'ast>), Constant(ConstantDefinition<'ast>), Struct(StructDefinition<'ast>), + Type(TypeDefinition<'ast>), Function(FunctionDefinition<'ast>), } @@ -191,6 +192,16 @@ mod ast { pub span: Span<'ast>, } + #[derive(Debug, FromPest, PartialEq, Clone)] + #[pest_ast(rule(Rule::type_definition))] + pub struct TypeDefinition<'ast> { + pub id: IdentifierExpression<'ast>, + pub generics: Vec>, + pub ty: Type<'ast>, + #[pest_ast(outer())] + pub span: Span<'ast>, + } + #[derive(Debug, FromPest, PartialEq, Clone)] #[pest_ast(rule(Rule::import_directive))] pub enum ImportDirective<'ast> { diff --git a/zokrates_stdlib/stdlib/hashes/keccak/256bit.zok b/zokrates_stdlib/stdlib/hashes/keccak/256bit.zok index 59d800fe..a066170c 100644 --- a/zokrates_stdlib/stdlib/hashes/keccak/256bit.zok +++ b/zokrates_stdlib/stdlib/hashes/keccak/256bit.zok @@ -1,4 +1,4 @@ import "hashes/keccak/keccak" as keccak def main(u64[N] input) -> u64[4]: - return keccak::(input, 0x0000000000000001)[..4] \ No newline at end of file + return keccak::<_, 256>(input, 0x0000000000000001)[..4] \ No newline at end of file diff --git a/zokrates_stdlib/stdlib/hashes/keccak/384bit.zok b/zokrates_stdlib/stdlib/hashes/keccak/384bit.zok index f261ebcc..0378c6dd 100644 --- a/zokrates_stdlib/stdlib/hashes/keccak/384bit.zok +++ b/zokrates_stdlib/stdlib/hashes/keccak/384bit.zok @@ -1,4 +1,4 @@ import "hashes/keccak/keccak" as keccak def main(u64[N] input) -> u64[6]: - return keccak::(input, 0x0000000000000001)[..6] \ No newline at end of file + return keccak::<_, 384>(input, 0x0000000000000001)[..6] \ No newline at end of file diff --git a/zokrates_stdlib/stdlib/hashes/keccak/512bit.zok b/zokrates_stdlib/stdlib/hashes/keccak/512bit.zok index 8345df52..00678fcb 100644 --- a/zokrates_stdlib/stdlib/hashes/keccak/512bit.zok +++ b/zokrates_stdlib/stdlib/hashes/keccak/512bit.zok @@ -1,4 +1,4 @@ import "hashes/keccak/keccak" as keccak def main(u64[N] input) -> u64[8]: - return keccak::(input, 0x0000000000000001)[..8] \ No newline at end of file + return keccak::<_, 512>(input, 0x0000000000000001)[..8] \ No newline at end of file diff --git a/zokrates_stdlib/stdlib/hashes/sha3/256bit.zok b/zokrates_stdlib/stdlib/hashes/sha3/256bit.zok index 99d213fa..2dfed2cc 100644 --- a/zokrates_stdlib/stdlib/hashes/sha3/256bit.zok +++ b/zokrates_stdlib/stdlib/hashes/sha3/256bit.zok @@ -1,4 +1,4 @@ import "hashes/keccak/keccak" as keccak def main(u64[N] input) -> (u64[4]): - return keccak::(input, 0x0000000000000006)[..4] \ No newline at end of file + return keccak::<_, 256>(input, 0x0000000000000006)[..4] \ No newline at end of file diff --git a/zokrates_stdlib/stdlib/hashes/sha3/384bit.zok b/zokrates_stdlib/stdlib/hashes/sha3/384bit.zok index 1b6dfeff..95c8dafe 100644 --- a/zokrates_stdlib/stdlib/hashes/sha3/384bit.zok +++ b/zokrates_stdlib/stdlib/hashes/sha3/384bit.zok @@ -1,4 +1,4 @@ import "hashes/keccak/keccak" as keccak def main(u64[N] input) -> (u64[6]): - return keccak::(input, 0x0000000000000006)[..6] \ No newline at end of file + return keccak::<_, 384>(input, 0x0000000000000006)[..6] \ No newline at end of file diff --git a/zokrates_stdlib/stdlib/hashes/sha3/512bit.zok b/zokrates_stdlib/stdlib/hashes/sha3/512bit.zok index 6c37836e..5dbd8d5e 100644 --- a/zokrates_stdlib/stdlib/hashes/sha3/512bit.zok +++ b/zokrates_stdlib/stdlib/hashes/sha3/512bit.zok @@ -1,4 +1,4 @@ import "hashes/keccak/keccak" as keccak def main(u64[N] input) -> (u64[8]): - return keccak::(input, 0x0000000000000006)[..8] \ No newline at end of file + return keccak::<_, 512>(input, 0x0000000000000006)[..8] \ No newline at end of file diff --git a/zokrates_stdlib/stdlib/utils/pack/bool/nonStrictUnpack256.zok b/zokrates_stdlib/stdlib/utils/pack/bool/nonStrictUnpack256.zok index e31dece4..754fc659 100644 --- a/zokrates_stdlib/stdlib/utils/pack/bool/nonStrictUnpack256.zok +++ b/zokrates_stdlib/stdlib/utils/pack/bool/nonStrictUnpack256.zok @@ -7,6 +7,6 @@ import "./unpack_unchecked" // For example, `0` can map to `[0, 0, ..., 0]` or to `bits(p)` def main(field i) -> bool[256]: - bool[254] b = unpack_unchecked::<254>(i) + bool[254] b = unpack_unchecked(i) return [false, false, ...b] \ No newline at end of file diff --git a/zokrates_stdlib/stdlib/utils/pack/bool/unpack128.zok b/zokrates_stdlib/stdlib/utils/pack/bool/unpack128.zok index 8f0b1203..1998bede 100644 --- a/zokrates_stdlib/stdlib/utils/pack/bool/unpack128.zok +++ b/zokrates_stdlib/stdlib/utils/pack/bool/unpack128.zok @@ -3,5 +3,5 @@ import "./unpack" as unpack // Unpack a field element as 128 big-endian bits // If the input is larger than `2**128 - 1`, the output is truncated. def main(field i) -> bool[128]: - bool[128] res = unpack::<128>(i) + bool[128] res = unpack(i) return res \ No newline at end of file diff --git a/zokrates_stdlib/tests/tests/hashes/blake2/blake2s_1536bit.zok b/zokrates_stdlib/tests/tests/hashes/blake2/blake2s_1536bit.zok index 05340e3c..2115a182 100644 --- a/zokrates_stdlib/tests/tests/hashes/blake2/blake2s_1536bit.zok +++ b/zokrates_stdlib/tests/tests/hashes/blake2/blake2s_1536bit.zok @@ -9,7 +9,7 @@ import "hashes/blake2/blake2s" // '879043503b04cab2f3c0d7a4bb01c1db74c238c49887da84e8a619893092b6e2' def main(): - u32[8] h = blake2s::<3>([[0x12345678; 16]; 3]) // 3 * 16 * 32 = 1536 bit input + u32[8] h = blake2s([[0x12345678; 16]; 3]) // 3 * 16 * 32 = 1536 bit input assert(h == [ 0x87904350, 0x3B04CAB2, 0xF3C0D7A4, 0xBB01C1DB, 0x74C238C4, 0x9887DA84, 0xE8A61989, 0x3092B6E2 diff --git a/zokrates_stdlib/tests/tests/hashes/blake2/blake2s_512bit.zok b/zokrates_stdlib/tests/tests/hashes/blake2/blake2s_512bit.zok index 2398c608..62c0c425 100644 --- a/zokrates_stdlib/tests/tests/hashes/blake2/blake2s_512bit.zok +++ b/zokrates_stdlib/tests/tests/hashes/blake2/blake2s_512bit.zok @@ -9,7 +9,7 @@ import "hashes/blake2/blake2s" // '52af1aec3e6663bcc759d55fc7557fbb2f710219f0de138b1b52c919f5c94415' def main(): - u32[8] h = blake2s::<1>([[0x12345678; 16]; 1]) // 16 * 32 = 512 bit input + u32[8] h = blake2s([[0x12345678; 16]; 1]) // 16 * 32 = 512 bit input assert(h == [ 0x52AF1AEC, 0x3E6663BC, 0xC759D55F, 0xC7557FBB, 0x2F710219, 0xF0DE138B, 0x1B52C919, 0xF5C94415 diff --git a/zokrates_stdlib/tests/tests/hashes/blake2/blake2s_p.zok b/zokrates_stdlib/tests/tests/hashes/blake2/blake2s_p.zok index ecea1f26..91d3da97 100644 --- a/zokrates_stdlib/tests/tests/hashes/blake2/blake2s_p.zok +++ b/zokrates_stdlib/tests/tests/hashes/blake2/blake2s_p.zok @@ -9,7 +9,7 @@ import "hashes/blake2/blake2s_p" as blake2s // '780105bc9ca7633b1f289b3d1558dece65e04ac23f88e711dc29600fa3e0258a' def main(): - u32[8] h = blake2s::<1>([[0x12345678; 16]; 1], [0x12345678, 0]) + u32[8] h = blake2s([[0x12345678; 16]; 1], [0x12345678, 0]) assert(h == [ 0x780105BC, 0x9CA7633B, 0x1F289B3D, 0x1558DECE, 0x65E04AC2, 0x3F88E711, 0xDC29600F, 0xA3E0258A diff --git a/zokrates_stdlib/tests/tests/hashes/keccak/384bit.zok b/zokrates_stdlib/tests/tests/hashes/keccak/384bit.zok index a12a3f96..3220ca0b 100644 --- a/zokrates_stdlib/tests/tests/hashes/keccak/384bit.zok +++ b/zokrates_stdlib/tests/tests/hashes/keccak/384bit.zok @@ -9,7 +9,7 @@ import "hashes/keccak/384bit" as keccak384 // 'a944b9b859c1e69d66b52d4cf1f678b24ed8a9ccb0a32bbe882af8a3a1acbd3b68eed9c628307e5d3789f1a64a50e8e7' def main(): - u64[6] h = keccak384::<20>([42; 20]) + u64[6] h = keccak384([42; 20]) assert(h == [ 0xA944B9B859C1E69D, 0x66B52D4CF1F678B2, 0x4ED8A9CCB0A32BBE, 0x882AF8A3A1ACBD3B, 0x68EED9C628307E5D, 0x3789F1A64A50E8E7 diff --git a/zokrates_stdlib/tests/tests/hashes/mimcSponge/mimcSponge.zok b/zokrates_stdlib/tests/tests/hashes/mimcSponge/mimcSponge.zok index 4924b8df..7e61a472 100644 --- a/zokrates_stdlib/tests/tests/hashes/mimcSponge/mimcSponge.zok +++ b/zokrates_stdlib/tests/tests/hashes/mimcSponge/mimcSponge.zok @@ -1,12 +1,12 @@ import "hashes/mimcSponge/mimcSponge" as mimcSponge def main(): - assert(mimcSponge::<2, 3>([1, 2], 3) == [ + assert(mimcSponge::<_, 3>([1, 2], 3) == [ 20225509322021146255705869525264566735642015554514977326536820959638320229084, 13871743498877225461925335509899475799121918157213219438898506786048812913771, 21633608428713573518356618235457250173701815120501233429160399974209848779097 ]) - assert(mimcSponge::<2, 3>([0, 0], 0) == [ + assert(mimcSponge::<_, 3>([0, 0], 0) == [ 20636625426020718969131298365984859231982649550971729229988535915544421356929, 6046202021237334713296073963481784771443313518730771623154467767602059802325, 16227963524034219233279650312501310147918176407385833422019760797222680144279 diff --git a/zokrates_stdlib/tests/tests/hashes/sha3/256bit.zok b/zokrates_stdlib/tests/tests/hashes/sha3/256bit.zok index 203bb970..243dea41 100644 --- a/zokrates_stdlib/tests/tests/hashes/sha3/256bit.zok +++ b/zokrates_stdlib/tests/tests/hashes/sha3/256bit.zok @@ -9,6 +9,6 @@ import "hashes/sha3/256bit" as sha3_256 // '18d00c9e97cd5516243b67b243ede9e2cf0d45d3a844d33340bfc4efc9165100' def main(): - u64[4] h = sha3_256::<20>([42; 20]) + u64[4] h = sha3_256([42; 20]) assert(h == [0x18D00C9E97CD5516, 0x243B67B243EDE9E2, 0xCF0D45D3A844D333, 0x40BFC4EFC9165100]) return \ No newline at end of file diff --git a/zokrates_stdlib/tests/tests/hashes/sha3/512bit.zok b/zokrates_stdlib/tests/tests/hashes/sha3/512bit.zok index 9e65810a..69badc5f 100644 --- a/zokrates_stdlib/tests/tests/hashes/sha3/512bit.zok +++ b/zokrates_stdlib/tests/tests/hashes/sha3/512bit.zok @@ -9,7 +9,7 @@ import "hashes/sha3/512bit" as sha3_512 // '73a0967b68de5ce1093cbd7482fd4de9ccc9c782e2edc71b583d26fe16fb19e3322a2a024b7f6e163fbb1a15161686dd3a39233f9cf8616e7c74e91fa1aa3b2b' def main(): - u64[8] h = sha3_512::<20>([42; 20]) + u64[8] h = sha3_512([42; 20]) assert(h == [ 0x73A0967B68DE5CE1, 0x093CBD7482FD4DE9, 0xCCC9C782E2EDC71B, 0x583D26FE16FB19E3, 0x322A2A024B7F6E16, 0x3FBB1A15161686DD, 0x3A39233F9CF8616E, 0x7C74E91FA1AA3B2B diff --git a/zokrates_stdlib/tests/tests/snark/gm17.zok b/zokrates_stdlib/tests/tests/snark/gm17.zok index d09a2473..6efc36b1 100644 --- a/zokrates_stdlib/tests/tests/snark/gm17.zok +++ b/zokrates_stdlib/tests/tests/snark/gm17.zok @@ -54,4 +54,4 @@ from "snark/gm17" import main as verify, Proof, VerificationKey def main(Proof<3> proof, VerificationKey<4> vk) -> bool: - return verify::<3, 4>(proof, vk) \ No newline at end of file + return verify(proof, vk) \ No newline at end of file