diff --git a/.circleci/config.yml b/.circleci/config.yml index c59b3c8d..a0570b76 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -75,12 +75,11 @@ jobs: - v4-cargo-cache-{{ arch }}-{{ checksum "Cargo.lock" }} - run: name: Test on firefox - command: GECKODRIVER=geckodriver cd zokrates_core && wasm-pack test --firefox --headless -- --no-default-features --features "wasm bellman" + command: cd zokrates_core && wasm-pack test --firefox --headless -- --no-default-features --features "wasm bellman" integration_test: docker: - image: zokrates/env:latest - image: trufflesuite/ganache-cli:next - port: 8545:8545 steps: - checkout - run: diff --git a/Cargo.lock b/Cargo.lock index dd9f13b5..f1725fc4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2087,7 +2087,7 @@ dependencies = [ [[package]] name = "zokrates_abi" -version = "0.1.2" +version = "0.1.3" dependencies = [ "serde", "serde_derive", @@ -2098,7 +2098,7 @@ dependencies = [ [[package]] name = "zokrates_cli" -version = "0.6.2" +version = "0.6.3" dependencies = [ "assert_cli", "bincode", @@ -2122,7 +2122,7 @@ version = "0.1.0" [[package]] name = "zokrates_core" -version = "0.5.2" +version = "0.5.3" dependencies = [ "ark-bls12-377", "ark-bn254", @@ -2161,7 +2161,7 @@ dependencies = [ [[package]] name = "zokrates_core_test" -version = "0.1.3" +version = "0.1.4" dependencies = [ "zokrates_test", "zokrates_test_derive", @@ -2199,7 +2199,7 @@ dependencies = [ [[package]] name = "zokrates_parser" -version = "0.1.5" +version = "0.1.6" dependencies = [ "glob 0.2.11", "pest", @@ -2208,7 +2208,7 @@ dependencies = [ [[package]] name = "zokrates_pest_ast" -version = "0.1.4" +version = "0.1.5" dependencies = [ "from-pest", "glob 0.2.11", diff --git a/Dockerfile b/Dockerfile index c1113613..f46c237e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -9,10 +9,9 @@ RUN cd src; ./build_release.sh FROM ubuntu:18.04 ENV ZOKRATES_HOME=/home/zokrates/.zokrates -COPY --from=build /build/src/scripts/install_libsnark_prerequisites.sh /tmp/ - -RUN /tmp/install_libsnark_prerequisites.sh \ -&& useradd -u 1000 -m zokrates +RUN apt-get update \ + && apt-get install -y --no-install-recommends libgmp3-dev \ + && useradd -u 1000 -m zokrates USER zokrates WORKDIR /home/zokrates diff --git a/Dockerfile.env b/Dockerfile.env index 73de372b..4cbec055 100644 --- a/Dockerfile.env +++ b/Dockerfile.env @@ -22,20 +22,24 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ clang-format \ python3 \ python-markdown \ - && add-apt-repository ppa:jonathonf/firefox-esr; apt-get install -y firefox-esr \ + && add-apt-repository ppa:mozillateam/ppa \ + && apt-get update \ + && apt-get install -y --no-install-recommends firefox-esr \ + && ln -s /usr/bin/firefox-esr /usr/bin/firefox \ && rm -rf /var/lib/apt/lists/* RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --default-toolchain none -y \ && rustup toolchain install nightly --allow-downgrade --profile minimal --component rustfmt \ && cargo install --git https://github.com/rustwasm/wasm-pack \ + && rm -rf /usr/local/cargo/registry \ && curl -sL https://deb.nodesource.com/setup_lts.x | bash - && apt-get install -y nodejs && npm i -g solc \ && curl -sL https://raw.githubusercontent.com/Sarcasm/run-clang-format/master/run-clang-format.py > /opt/run-clang-format.py \ && chmod +x /opt/run-clang-format.py \ && ln -s /opt/run-clang-format.py /usr/bin \ && rustup --version; cargo --version; rustc --version; wasm-pack --version; echo nodejs $(node -v); -RUN cd /opt && curl -LO https://github.com/mozilla/geckodriver/releases/download/v0.26.0/geckodriver-v0.26.0-linux64.tar.gz \ - && tar -xzf geckodriver-v0.26.0-linux64.tar.gz geckodriver \ +RUN cd /opt && curl -LO https://github.com/mozilla/geckodriver/releases/download/v0.28.0/geckodriver-v0.28.0-linux64.tar.gz \ + && tar -xzf geckodriver-v0.28.0-linux64.tar.gz geckodriver \ && ln -s /opt/geckodriver /usr/bin \ && geckodriver --version \ - && rm -rf geckodriver-v0.26.0-linux64.tar.gz \ No newline at end of file + && rm -rf geckodriver-v0.28.0-linux64.tar.gz \ No newline at end of file diff --git a/zokrates_abi/Cargo.toml b/zokrates_abi/Cargo.toml index 368c45b8..f3d9e75e 100644 --- a/zokrates_abi/Cargo.toml +++ b/zokrates_abi/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "zokrates_abi" -version = "0.1.2" +version = "0.1.3" authors = ["Thibaut Schaeffer "] edition = "2018" diff --git a/zokrates_abi/src/lib.rs b/zokrates_abi/src/lib.rs index 762c349c..68788f00 100644 --- a/zokrates_abi/src/lib.rs +++ b/zokrates_abi/src/lib.rs @@ -248,9 +248,9 @@ impl TryFrom for Values { match v { serde_json::Value::Array(a) => a .into_iter() - .map(|v| Value::try_from(v)) + .map(Value::try_from) .collect::>() - .map(|v| Values(v)), + .map(Values), v => Err(format!("Expected an array of values, found `{}`", v)), } } @@ -260,20 +260,22 @@ impl TryFrom for Value { type Error = String; fn try_from(v: serde_json::Value) -> Result, Self::Error> { match v { - serde_json::Value::String(s) => T::try_from_dec_str(&s) - .map(|v| Value::Field(v)) - .or_else(|_| match s.len() { - 4 => u8::from_str_radix(&s[2..], 16) - .map(|v| Value::U8(v)) - .map_err(|_| format!("Expected u8 value, found {}", s)), - 6 => u16::from_str_radix(&s[2..], 16) - .map(|v| Value::U16(v)) - .map_err(|_| format!("Expected u16 value, found {}", s)), - 10 => u32::from_str_radix(&s[2..], 16) - .map(|v| Value::U32(v)) - .map_err(|_| format!("Expected u32 value, found {}", s)), - _ => Err(format!("Cannot parse {} to any type", s)), - }), + serde_json::Value::String(s) => { + T::try_from_dec_str(&s) + .map(Value::Field) + .or_else(|_| match s.len() { + 4 => u8::from_str_radix(&s[2..], 16) + .map(Value::U8) + .map_err(|_| format!("Expected u8 value, found {}", s)), + 6 => u16::from_str_radix(&s[2..], 16) + .map(Value::U16) + .map_err(|_| format!("Expected u16 value, found {}", s)), + 10 => u32::from_str_radix(&s[2..], 16) + .map(Value::U32) + .map_err(|_| format!("Expected u32 value, found {}", s)), + _ => Err(format!("Cannot parse {} to any type", s)), + }) + } serde_json::Value::Bool(b) => Ok(Value::Boolean(b)), serde_json::Value::Number(n) => Err(format!( "Value `{}` isn't allowed, did you mean `\"{}\"`?", @@ -281,14 +283,14 @@ impl TryFrom for Value { )), serde_json::Value::Array(a) => a .into_iter() - .map(|v| Value::try_from(v)) + .map(Value::try_from) .collect::>() - .map(|v| Value::Array(v)), + .map(Value::Array), serde_json::Value::Object(o) => o .into_iter() .map(|(k, v)| Value::try_from(v).map(|v| (k, v))) .collect::, _>>() - .map(|v| Value::Struct(v)), + .map(Value::Struct), v => Err(format!("Value `{}` isn't allowed", v)), } } @@ -321,7 +323,7 @@ impl Into for CheckedValues { fn parse(s: &str) -> Result, Error> { let json_values: serde_json::Value = serde_json::from_str(s).map_err(|e| Error::Json(e.to_string()))?; - Values::try_from(json_values).map_err(|e| Error::Conversion(e)) + Values::try_from(json_values).map_err(Error::Conversion) } pub fn parse_strict( @@ -342,7 +344,7 @@ pub fn parse_strict( .zip(types.into_iter()) .map(|(v, ty)| v.check(ty)) .collect::, _>>() - .map_err(|e| Error::Type(e))?; + .map_err(Error::Type)?; Ok(CheckedValues(checked)) } diff --git a/zokrates_cli/Cargo.toml b/zokrates_cli/Cargo.toml index 7942ac22..85826cd6 100644 --- a/zokrates_cli/Cargo.toml +++ b/zokrates_cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "zokrates_cli" -version = "0.6.2" +version = "0.6.3" authors = ["Jacob Eberhardt ", "Dennis Kuhnert ", "Thibaut Schaeffer "] repository = "https://github.com/JacobEberhardt/ZoKrates.git" edition = "2018" diff --git a/zokrates_cli/build.rs b/zokrates_cli/build.rs index add3c623..bbdc6b48 100644 --- a/zokrates_cli/build.rs +++ b/zokrates_cli/build.rs @@ -11,5 +11,5 @@ fn export_stdlib() { let out_dir = env::var("OUT_DIR").unwrap(); let mut options = CopyOptions::new(); options.overwrite = true; - copy_items(&vec!["tests/contract"], out_dir, &options).unwrap(); + copy_items(&["tests/contract"], out_dir, &options).unwrap(); } diff --git a/zokrates_cli/src/bin.rs b/zokrates_cli/src/bin.rs index f9f41e6d..b87c3011 100644 --- a/zokrates_cli/src/bin.rs +++ b/zokrates_cli/src/bin.rs @@ -84,7 +84,7 @@ fn cli_generate_proof, B: Backend>( .write(proof.as_bytes()) .map_err(|why| format!("Couldn't write to {}: {}", proof_path.display(), why))?; - println!("Proof:\n{}", format!("{}", proof)); + println!("Proof:\n{}", proof); Ok(()) } @@ -211,7 +211,7 @@ fn cli_compute(ir_prog: ir::Prog, sub_matches: &ArgMatches) -> Resu .collect::, _>>() }) .unwrap_or(Ok(vec![])) - .map(|v| Inputs::Raw(v)) + .map(Inputs::Raw) } // take stdin arguments true => { @@ -224,7 +224,7 @@ fn cli_compute(ir_prog: ir::Prog, sub_matches: &ArgMatches) -> Resu use zokrates_abi::parse_strict; parse_strict(&input, signature.inputs) - .map(|parsed| Inputs::Abi(parsed)) + .map(Inputs::Abi) .map_err(|why| why.to_string()) } Err(_) => Err(String::from("???")), @@ -235,10 +235,10 @@ fn cli_compute(ir_prog: ir::Prog, sub_matches: &ArgMatches) -> Resu Ok(_) => { input.retain(|x| x != '\n'); input - .split(" ") + .split(' ') .map(|x| T::try_from_dec_str(x).map_err(|_| x.to_string())) .collect::, _>>() - .map(|v| Inputs::Raw(v)) + .map(Inputs::Raw) } Err(_) => Err(String::from("???")), }, @@ -460,7 +460,7 @@ fn cli() -> Result<(), String> { let matches = App::new("ZoKrates") .setting(AppSettings::SubcommandRequiredElseHelp) .version(env!("CARGO_PKG_VERSION")) - .author("Jacob Eberhardt, Thibaut Schaeffer, Stefan Deml") + .author("Jacob Eberhardt, Thibaut Schaeffer, Stefan Deml, Darko Macesic") .about("Supports generation of zkSNARKs from high level language code including Smart Contracts for proof verification on the Ethereum Blockchain.\n'I know that I show nothing!'") .subcommand(SubCommand::with_name("compile") .about("Compiles into flattened conditions. Produces two files: human-readable '.ztf' file for debugging and binary file") @@ -614,7 +614,6 @@ fn cli() -> Result<(), String> { .short("s") .long("proving-scheme") .help("Proving scheme to use to export the verifier") - .value_name("FILE") .takes_value(true) .required(false) .possible_values(SCHEMES) @@ -726,7 +725,6 @@ fn cli() -> Result<(), String> { .short("s") .long("proving-scheme") .help("Proving scheme to use to generate the proof") - .value_name("FILE") .takes_value(true) .required(false) .possible_values(SCHEMES) @@ -783,7 +781,6 @@ fn cli() -> Result<(), String> { .short("s") .long("proving-scheme") .help("Proving scheme to use in the setup. Available options are G16 (default), PGHR13 and GM17") - .value_name("FILE") .takes_value(true) .required(false) .default_value(&default_scheme) diff --git a/zokrates_cli/src/constants.rs b/zokrates_cli/src/constants.rs index fba1b3e0..213763bd 100644 --- a/zokrates_cli/src/constants.rs +++ b/zokrates_cli/src/constants.rs @@ -9,27 +9,21 @@ pub const BACKENDS: &[&str] = if cfg!(feature = "libsnark") { } else { &[LIBSNARK, ARK] } + } else if cfg!(feature = "bellman") { + &[BELLMAN, LIBSNARK] } else { - if cfg!(feature = "bellman") { - &[BELLMAN, LIBSNARK] - } else { - &[LIBSNARK] - } + &[LIBSNARK] } +} else if cfg!(feature = "ark") { + if cfg!(feature = "bellman") { + &[BELLMAN, ARK] + } else { + &[ARK] + } +} else if cfg!(feature = "bellman") { + &[BELLMAN] } else { - if cfg!(feature = "ark") { - if cfg!(feature = "bellman") { - &[BELLMAN, ARK] - } else { - &[ARK] - } - } else { - if cfg!(feature = "bellman") { - &[BELLMAN] - } else { - &[] - } - } + &[] }; pub const BN128: &str = "bn128"; diff --git a/zokrates_cli/tests/integration.rs b/zokrates_cli/tests/integration.rs index b147d3da..0a666cf6 100644 --- a/zokrates_cli/tests/integration.rs +++ b/zokrates_cli/tests/integration.rs @@ -3,7 +3,7 @@ extern crate serde_json; #[cfg(test)] mod integration { - use assert_cli; + use serde_json::from_reader; use std::fs; use std::fs::File; @@ -147,11 +147,11 @@ mod integration { .map_err(|why| why.to_string()) .unwrap(); - let signature = abi.signature().clone(); + let signature = abi.signature(); let inputs_abi: zokrates_abi::Inputs = parse_strict(&json_input_str, signature.inputs) - .map(|parsed| zokrates_abi::Inputs::Abi(parsed)) + .map(zokrates_abi::Inputs::Abi) .map_err(|why| why.to_string()) .unwrap(); let inputs_raw: Vec<_> = inputs_abi @@ -169,7 +169,7 @@ mod integration { inline_witness_path.to_str().unwrap(), ]; - if inputs_raw.len() > 0 { + if !inputs_raw.is_empty() { compute_inline.push("-a"); for arg in &inputs_raw { @@ -202,7 +202,7 @@ mod integration { assert_eq!(inline_witness, witness); - for line in expected_witness.as_str().split("\n") { + for line in expected_witness.as_str().split('\n') { assert!( witness.contains(line), "Witness generation failed for {}\n\nLine \"{}\" not found in witness", diff --git a/zokrates_core/Cargo.toml b/zokrates_core/Cargo.toml index a13eebda..6a145846 100644 --- a/zokrates_core/Cargo.toml +++ b/zokrates_core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "zokrates_core" -version = "0.5.2" +version = "0.5.3" edition = "2018" authors = ["Jacob Eberhardt ", "Dennis Kuhnert "] repository = "https://github.com/JacobEberhardt/ZoKrates" diff --git a/zokrates_core/src/absy/from_ast.rs b/zokrates_core/src/absy/from_ast.rs index fd5be810..36707398 100644 --- a/zokrates_core/src/absy/from_ast.rs +++ b/zokrates_core/src/absy/from_ast.rs @@ -9,14 +9,14 @@ impl<'ast> From> for absy::Module<'ast> { absy::Module::with_symbols( prog.structs .into_iter() - .map(|t| absy::SymbolDeclarationNode::from(t)) + .map(absy::SymbolDeclarationNode::from) .chain( prog.functions .into_iter() - .map(|f| absy::SymbolDeclarationNode::from(f)), + .map(absy::SymbolDeclarationNode::from), ), ) - .imports(prog.imports.into_iter().map(|i| absy::ImportNode::from(i))) + .imports(prog.imports.into_iter().map(absy::ImportNode::from)) } } @@ -57,7 +57,7 @@ impl<'ast> From> for absy::SymbolDeclarationNode<'a fields: definition .fields .into_iter() - .map(|f| absy::StructDefinitionFieldNode::from(f)) + .map(absy::StructDefinitionFieldNode::from) .collect(), } .span(span.clone()); @@ -104,7 +104,7 @@ impl<'ast> From> for absy::SymbolDeclarationNode<'ast> { .returns .clone() .into_iter() - .map(|r| absy::UnresolvedTypeNode::from(r)) + .map(absy::UnresolvedTypeNode::from) .collect(), ); @@ -119,12 +119,12 @@ impl<'ast> From> for absy::SymbolDeclarationNode<'ast> { arguments: function .parameters .into_iter() - .map(|a| absy::ParameterNode::from(a)) + .map(absy::ParameterNode::from) .collect(), statements: function .statements .into_iter() - .flat_map(|s| statements_from_statement(s)) + .flat_map(statements_from_statement) .collect(), signature, } @@ -261,7 +261,7 @@ impl<'ast> From> for absy::StatementNode<'ast> { expressions: statement .expressions .into_iter() - .map(|e| absy::ExpressionNode::from(e)) + .map(absy::ExpressionNode::from) .collect(), } .span(statement.span.clone()), @@ -289,7 +289,7 @@ impl<'ast> From> for absy::StatementNode<'ast> { let statements: Vec> = statement .statements .into_iter() - .flat_map(|s| statements_from_statement(s)) + .flat_map(statements_from_statement) .collect(); let var = absy::Variable::new(index, ty).span(statement.index.span); @@ -472,7 +472,7 @@ impl<'ast> From> for absy::ExpressionNode<'ast array .expressions .into_iter() - .map(|e| absy::SpreadOrExpression::from(e)) + .map(absy::SpreadOrExpression::from) .collect(), ) .span(array.span) @@ -538,7 +538,7 @@ impl<'ast> From> for absy::ExpressionNode<'ast> { &id_str, a.expressions .into_iter() - .map(|e| absy::ExpressionNode::from(e)) + .map(absy::ExpressionNode::from) .collect(), ), e => unimplemented!("only identifiers are callable, found \"{}\"", e), @@ -933,7 +933,7 @@ mod tests { // we basically accept `()?[]*` : an optional call at first, then only array accesses let vectors = vec![ - ("a", absy::Expression::Identifier("a").into()), + ("a", absy::Expression::Identifier("a")), ( "a[3]", absy::Expression::Select( diff --git a/zokrates_core/src/absy/mod.rs b/zokrates_core/src/absy/mod.rs index e0b96b97..df58d348 100644 --- a/zokrates_core/src/absy/mod.rs +++ b/zokrates_core/src/absy/mod.rs @@ -323,9 +323,9 @@ impl<'ast> fmt::Display for Statement<'ast> { Statement::Definition(ref lhs, ref rhs) => write!(f, "{} = {}", lhs, rhs), Statement::Assertion(ref e) => write!(f, "assert({})", e), Statement::For(ref var, ref start, ref stop, ref list) => { - write!(f, "for {} in {}..{} do\n", var, start, stop)?; + writeln!(f, "for {} in {}..{} do", var, start, stop)?; for l in list { - write!(f, "\t\t{}\n", l)?; + writeln!(f, "\t\t{}", l)?; } write!(f, "\tendfor") } @@ -352,9 +352,9 @@ impl<'ast> fmt::Debug for Statement<'ast> { } Statement::Assertion(ref e) => write!(f, "Assertion({:?})", e), Statement::For(ref var, ref start, ref stop, ref list) => { - write!(f, "for {:?} in {:?}..{:?} do\n", var, start, stop)?; + writeln!(f, "for {:?} in {:?}..{:?} do", var, start, stop)?; for l in list { - write!(f, "\t\t{:?}\n", l)?; + writeln!(f, "\t\t{:?}", l)?; } write!(f, "\tendfor") } diff --git a/zokrates_core/src/compile.rs b/zokrates_core/src/compile.rs index 8fc5c5e0..f2c54cbf 100644 --- a/zokrates_core/src/compile.rs +++ b/zokrates_core/src/compile.rs @@ -198,12 +198,11 @@ fn check_with_arena<'ast, T: Field, E: Into>( arena: &'ast Arena, ) -> Result<(ZirProgram<'ast, T>, Abi), CompileErrors> { let source = arena.alloc(source); - let compiled = compile_program::(source, location.clone(), resolver, &arena)?; + let compiled = compile_program::(source, location, resolver, &arena)?; // check semantics - let typed_ast = Checker::check(compiled).map_err(|errors| { - CompileErrors(errors.into_iter().map(|e| CompileError::from(e)).collect()) - })?; + let typed_ast = Checker::check(compiled) + .map_err(|errors| CompileErrors(errors.into_iter().map(CompileError::from).collect()))?; let main_module = typed_ast.main.clone(); @@ -246,7 +245,7 @@ pub fn compile_module<'ast, T: Field, E: Into>( let module_without_imports: Module = Module::from(ast); - Importer::new().apply_imports::( + Importer::apply_imports::( module_without_imports, location.clone(), resolver, diff --git a/zokrates_core/src/embed.rs b/zokrates_core/src/embed.rs index b4857fea..7e965a3f 100644 --- a/zokrates_core/src/embed.rs +++ b/zokrates_core/src/embed.rs @@ -88,7 +88,7 @@ fn use_variable( ) -> FlatVariable { let var = FlatVariable::new(*index); layout.insert(name, var); - *index = *index + 1; + *index += 1; var } @@ -119,7 +119,7 @@ pub fn unpack_to_bitwidth(bit_width: usize) -> FlatFunction { let directive_inputs = vec![FlatExpression::Identifier(use_variable( &mut layout, - format!("i0"), + "i0".into(), &mut counter, ))]; @@ -132,7 +132,7 @@ pub fn unpack_to_bitwidth(bit_width: usize) -> FlatFunction { let outputs = directive_outputs .iter() .enumerate() - .map(|(_, o)| FlatExpression::Identifier(o.clone())) + .map(|(_, o)| FlatExpression::Identifier(*o)) .collect::>(); // o253, o252, ... o{253 - (bit_width - 1)} are bits @@ -172,7 +172,7 @@ pub fn unpack_to_bitwidth(bit_width: usize) -> FlatFunction { FlatStatement::Directive(FlatDirective { inputs: directive_inputs, outputs: directive_outputs, - solver: solver, + solver, }), ); diff --git a/zokrates_core/src/flat_absy/flat_parameter.rs b/zokrates_core/src/flat_absy/flat_parameter.rs index 788a3ac4..0b9481cb 100644 --- a/zokrates_core/src/flat_absy/flat_parameter.rs +++ b/zokrates_core/src/flat_absy/flat_parameter.rs @@ -41,7 +41,7 @@ impl FlatParameter { substitution: &HashMap, ) -> FlatParameter { FlatParameter { - id: substitution.get(&self.id).unwrap().clone(), + id: *substitution.get(&self.id).unwrap(), private: self.private, } } diff --git a/zokrates_core/src/flat_absy/flat_variable.rs b/zokrates_core/src/flat_absy/flat_variable.rs index 5fc96c96..2679cd99 100644 --- a/zokrates_core/src/flat_absy/flat_variable.rs +++ b/zokrates_core/src/flat_absy/flat_variable.rs @@ -45,7 +45,7 @@ impl FlatVariable { Ok(FlatVariable::public(v)) } None => { - let mut private = s.split("_"); + let mut private = s.split('_'); match private.nth(1) { Some(v) => { let v = v.parse().map_err(|_| s)?; diff --git a/zokrates_core/src/flatten/mod.rs b/zokrates_core/src/flatten/mod.rs index e19f2106..12398c4e 100644 --- a/zokrates_core/src/flatten/mod.rs +++ b/zokrates_core/src/flatten/mod.rs @@ -170,7 +170,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { statements_flattened: &mut FlatStatements, ) -> FlatVariable { match e { - FlatExpression::Identifier(id) => id.into(), + FlatExpression::Identifier(id) => id, e => { let res = self.use_sym(); statements_flattened.push(FlatStatement::Definition(res, e)); @@ -249,10 +249,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { // sizeUnknown is not changing in this case // We sill have to assign the old value to the variable of the current run // This trivial definition will later be removed by the optimiser - FlatStatement::Definition( - size_unknown[i + 1].into(), - size_unknown[i].into(), - ), + FlatStatement::Definition(size_unknown[i + 1], size_unknown[i].into()), ); } @@ -375,7 +372,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { // those will be booleans in the future match expression { BooleanExpression::Identifier(x) => { - FlatExpression::Identifier(self.layout.get(&x).unwrap().clone()) + FlatExpression::Identifier(*self.layout.get(&x).unwrap()) } BooleanExpression::FieldLt(box lhs, box rhs) => { // Get the bit width to know the size of the binary decompositions for this Field @@ -409,12 +406,12 @@ impl<'ast, T: Field> Flattener<'ast, T> { ))); // bitness checks - for i in 0..safe_width { + for bit in lhs_bits_be.iter().take(safe_width) { statements_flattened.push(FlatStatement::Condition( - FlatExpression::Identifier(lhs_bits_be[i]), + FlatExpression::Identifier(*bit), FlatExpression::Mult( - box FlatExpression::Identifier(lhs_bits_be[i]), - box FlatExpression::Identifier(lhs_bits_be[i]), + box FlatExpression::Identifier(*bit), + box FlatExpression::Identifier(*bit), ), )); } @@ -422,11 +419,11 @@ impl<'ast, T: Field> Flattener<'ast, T> { // bit decomposition check let mut lhs_sum = FlatExpression::Number(T::from(0)); - for i in 0..safe_width { + for (i, bit) in lhs_bits_be.iter().enumerate().take(safe_width) { lhs_sum = FlatExpression::Add( box lhs_sum, box FlatExpression::Mult( - box FlatExpression::Identifier(lhs_bits_be[i]), + box FlatExpression::Identifier(*bit), box FlatExpression::Number(T::from(2).pow(safe_width - i - 1)), ), ); @@ -455,12 +452,12 @@ impl<'ast, T: Field> Flattener<'ast, T> { ))); // bitness checks - for i in 0..safe_width { + for bit in rhs_bits_be.iter().take(safe_width) { statements_flattened.push(FlatStatement::Condition( - FlatExpression::Identifier(rhs_bits_be[i]), + FlatExpression::Identifier(*bit), FlatExpression::Mult( - box FlatExpression::Identifier(rhs_bits_be[i]), - box FlatExpression::Identifier(rhs_bits_be[i]), + box FlatExpression::Identifier(*bit), + box FlatExpression::Identifier(*bit), ), )); } @@ -468,11 +465,11 @@ impl<'ast, T: Field> Flattener<'ast, T> { // bit decomposition check let mut rhs_sum = FlatExpression::Number(T::from(0)); - for i in 0..safe_width { + for (i, bit) in rhs_bits_be.iter().enumerate().take(safe_width) { rhs_sum = FlatExpression::Add( box rhs_sum, box FlatExpression::Mult( - box FlatExpression::Identifier(rhs_bits_be[i]), + box FlatExpression::Identifier(*bit), box FlatExpression::Number(T::from(2).pow(safe_width - i - 1)), ), ); @@ -508,12 +505,12 @@ impl<'ast, T: Field> Flattener<'ast, T> { ))); // bitness checks - for i in 0..bit_width { + for bit in sub_bits_be.iter().take(bit_width) { statements_flattened.push(FlatStatement::Condition( - FlatExpression::Identifier(sub_bits_be[i]), + FlatExpression::Identifier(*bit), FlatExpression::Mult( - box FlatExpression::Identifier(sub_bits_be[i]), - box FlatExpression::Identifier(sub_bits_be[i]), + box FlatExpression::Identifier(*bit), + box FlatExpression::Identifier(*bit), ), )); } @@ -528,11 +525,11 @@ impl<'ast, T: Field> Flattener<'ast, T> { // sum(sym_b{i} * 2**i) let mut expr = FlatExpression::Number(T::from(0)); - for i in 0..bit_width { + for (i, bit) in sub_bits_be.iter().enumerate().take(bit_width) { expr = FlatExpression::Add( box expr, box FlatExpression::Mult( - box FlatExpression::Identifier(sub_bits_be[i]), + box FlatExpression::Identifier(*bit), box FlatExpression::Number(T::from(2).pow(bit_width - i - 1)), ), ); @@ -826,8 +823,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { consequence, alternative, ) - .get_field_unchecked() - .clone(), + .get_field_unchecked(), } } @@ -841,12 +837,10 @@ impl<'ast, T: Field> Flattener<'ast, T> { let expression = UExpression::try_from(expression).unwrap(); let from = expression.metadata.clone().unwrap().bitwidth(); let p = self.flatten_uint_expression(symbols, statements_flattened, expression); - let bits = self - .get_bits(p, from as usize, bitwidth, statements_flattened) + self.get_bits(p, from as usize, bitwidth, statements_flattened) .into_iter() - .map(|b| FlatUExpression::with_field(b)) - .collect(); - bits + .map(FlatUExpression::with_field) + .collect() } fn flatten_bits_to_u( @@ -956,11 +950,10 @@ impl<'ast, T: Field> Flattener<'ast, T> { // Ensure renaming and correct returns: // add all flattened statements, adapt return statements - let (mut return_statements, statements): (Vec<_>, Vec<_>) = - funct.statements.into_iter().partition(|s| match s { - FlatStatement::Return(..) => true, - _ => false, - }); + let (mut return_statements, statements): (Vec<_>, Vec<_>) = funct + .statements + .into_iter() + .partition(|s| matches!(s, FlatStatement::Return(..))); let statements: Vec<_> = statements .into_iter() @@ -1009,7 +1002,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { .expressions .into_iter() .map(|x| x.apply_substitution(&replacement_map)) - .map(|x| FlatUExpression::with_field(x)) + .map(FlatUExpression::with_field) .collect(), _ => unreachable!(), } @@ -1083,7 +1076,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { statements_flattened.extend(vec![ FlatStatement::Directive(FlatDirective::new( - vec![name.clone()], + vec![name], Solver::Xor, vec![x.clone(), y.clone()], )), @@ -1149,7 +1142,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { // assert(invd * d == 1) statements_flattened.push(FlatStatement::Condition( FlatExpression::Number(T::one()), - FlatExpression::Mult(box invd.into(), box d.clone().into()), + FlatExpression::Mult(box invd.into(), box d.clone()), )); // now introduce the quotient and remainder @@ -1158,7 +1151,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { statements_flattened.push(FlatStatement::Directive(FlatDirective { inputs: vec![n.clone(), d.clone()], - outputs: vec![q.clone(), r.clone()], + outputs: vec![q, r], solver: Solver::EuclideanDiv, })); @@ -1181,7 +1174,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { // r < d <=> r - d + 2**w < 2**w let _ = self.get_bits( FlatUExpression::with_field(FlatExpression::Add( - box FlatExpression::Sub(box r.into(), box d.clone().into()), + box FlatExpression::Sub(box r.into(), box d.clone()), box FlatExpression::Number(T::from(2usize.pow(target_bitwidth.to_usize() as u32))), )), target_bitwidth.to_usize(), @@ -1214,7 +1207,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { // the bitwidth for this type of uint (8, 16 or 32) let target_bitwidth = expr.bitwidth; - let metadata = expr.metadata.clone().unwrap().clone(); + let metadata = expr.metadata.clone().unwrap(); // the bitwidth on which this value is currently represented let actual_bitwidth = metadata.bitwidth() as usize; @@ -1229,7 +1222,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { FlatUExpression::with_field(FlatExpression::Number(T::from(x as usize))) } // force to be a field element UExpressionInner::Identifier(x) => { - let field = FlatExpression::Identifier(self.layout.get(&x).unwrap().clone()); + let field = FlatExpression::Identifier(*self.layout.get(&x).unwrap()); let bits = self.bits_cache.get(&field).map(|bits| { assert_eq!(bits.len(), target_bitwidth.to_usize()); bits.clone() @@ -1423,8 +1416,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { condition, consequence, alternative, - ) - .clone(), + ), UExpressionInner::Xor(box left, box right) => { let left_metadata = left.metadata.clone().unwrap(); let right_metadata = right.metadata.clone().unwrap(); @@ -1454,7 +1446,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { statements_flattened.extend(vec![ FlatStatement::Directive(FlatDirective::new( - vec![ch.clone()], + vec![ch], Solver::ShaCh, vec![a.clone(), b.clone(), c.clone()], )), @@ -1528,7 +1520,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { statements_flattened.extend(vec![ FlatStatement::Directive(FlatDirective::new( - vec![maj.clone()], + vec![maj], Solver::ShaAndXorAndXorAnd, vec![a.clone(), b.clone(), c.clone()], )), @@ -1672,7 +1664,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { statements_flattened.extend(vec![ FlatStatement::Directive(FlatDirective::new( - vec![name.clone()], + vec![name], Solver::Or, vec![x.clone(), y.clone()], )), @@ -1715,7 +1707,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { box FlatExpression::Number( T::from(2).pow(target_bitwidth.to_usize() - index - 1), ), - box bit.clone().into(), + box bit.clone(), ), ) }, @@ -1745,22 +1737,19 @@ impl<'ast, T: Field> Flattener<'ast, T> { assert!(to < T::get_required_bits()); // constants do not require directives - match e.field { - Some(FlatExpression::Number(ref x)) => { - let bits: Vec<_> = ir::Interpreter::default() - .execute_solver(&Solver::bits(to), &vec![x.clone()]) - .unwrap() - .into_iter() - .map(|x| FlatExpression::Number(x)) - .collect(); + if let Some(FlatExpression::Number(ref x)) = e.field { + let bits: Vec<_> = ir::Interpreter::default() + .execute_solver(&Solver::bits(to), &vec![x.clone()]) + .unwrap() + .into_iter() + .map(FlatExpression::Number) + .collect(); - assert_eq!(bits.len(), to); + assert_eq!(bits.len(), to); - self.bits_cache - .insert(e.field.clone().unwrap(), bits.clone()); - return bits; - } - _ => {} + self.bits_cache + .insert(e.field.clone().unwrap(), bits.clone()); + return bits; }; e.bits.clone().unwrap_or_else(|| { @@ -1771,7 +1760,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { let from = std::cmp::max(from, to); match self.bits_cache.entry(e.field.clone().unwrap()) { Entry::Occupied(entry) => { - let res: Vec<_> = entry.get().clone().into_iter().map(|e| e.into()).collect(); + let res: Vec<_> = entry.get().clone(); // if we already know a decomposition, it has to be of the size of the target bitwidth assert_eq!(res.len(), to); res @@ -1784,21 +1773,15 @@ impl<'ast, T: Field> Flattener<'ast, T> { vec![e.field.clone().unwrap()], ))); - let bits: Vec<_> = bits - .into_iter() - .map(|b| FlatExpression::Identifier(b)) - .collect(); + let bits: Vec<_> = bits.into_iter().map(FlatExpression::Identifier).collect(); // decompose to the actual bitwidth // bit checks - statements_flattened.extend((0..from).map(|i| { + statements_flattened.extend(bits.iter().take(from).map(|bit| { FlatStatement::Condition( - bits[i].clone(), - FlatExpression::Mult( - box bits[i].clone().into(), - box bits[i].clone().into(), - ), + bit.clone(), + FlatExpression::Mult(box bit.clone(), box bit.clone()), ) })); @@ -1818,7 +1801,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { self.bits_cache.insert(e.field.unwrap(), bits.clone()); self.bits_cache.insert(sum, bits.clone()); - bits.into_iter().map(|v| v.into()).collect() + bits } } }) @@ -1936,7 +1919,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { // assert(invb * b == 1) statements_flattened.push(FlatStatement::Condition( FlatExpression::Number(T::one()), - FlatExpression::Mult(box invb.into(), box new_right.clone().into()), + FlatExpression::Mult(box invb.into(), box new_right.clone()), )); // # c = a/b @@ -1948,7 +1931,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { // assert(c * b == a) statements_flattened.push(FlatStatement::Condition( - new_left.into(), + new_left, FlatExpression::Mult(box new_right, box inverse.into()), )); @@ -1996,16 +1979,16 @@ impl<'ast, T: Field> Flattener<'ast, T> { let id = self.use_sym(); // set it to the square of the previous one, stored in state statements_flattened.push(FlatStatement::Definition( - id.clone(), + id, FlatExpression::Mult( box previous.clone(), box previous.clone(), ), )); // store it in the state for later squaring - *state = Some(FlatExpression::Identifier(id.clone())); + *state = Some(FlatExpression::Identifier(id)); // return it for later use constructing the result - Some(FlatExpression::Identifier(id.clone())) + Some(FlatExpression::Identifier(id)) } } }) @@ -2039,8 +2022,7 @@ impl<'ast, T: Field> Flattener<'ast, T> { consequence, alternative, ) - .get_field_unchecked() - .clone(), + .get_field_unchecked(), } } @@ -2071,7 +2053,6 @@ impl<'ast, T: Field> Flattener<'ast, T> { } ZirStatement::Declaration(_) => { // declarations have already been checked - () } ZirStatement::Definition(assignee, expr) => { // define n variables with n the number of primitive types for v_type @@ -2097,12 +2078,9 @@ impl<'ast, T: Field> Flattener<'ast, T> { }; // register bits - match bits { - Some(bits) => { - self.bits_cache - .insert(FlatExpression::Identifier(var), bits); - } - None => {} + if let Some(bits) = bits { + self.bits_cache + .insert(FlatExpression::Identifier(var), bits); } } ZirStatement::Assertion(e) => { diff --git a/zokrates_core/src/imports.rs b/zokrates_core/src/imports.rs index a4d5f970..1ac8ba2f 100644 --- a/zokrates_core/src/imports.rs +++ b/zokrates_core/src/imports.rs @@ -42,7 +42,7 @@ impl fmt::Display for Error { let location = self .pos .map(|p| format!("{}", p.0)) - .unwrap_or("?".to_string()); + .unwrap_or_else(|| "?".to_string()); write!(f, "{}\n\t{}", location, self.message) } } @@ -125,15 +125,10 @@ impl<'ast> fmt::Debug for Import<'ast> { } } -pub struct Importer {} +pub struct Importer; impl Importer { - pub fn new() -> Importer { - Importer {} - } - pub fn apply_imports<'ast, T: Field, E: Into>( - &self, destination: Module<'ast>, location: PathBuf, resolver: Option<&dyn Resolver>, @@ -243,13 +238,15 @@ impl Importer { let alias = import.alias.unwrap_or( std::path::Path::new(import.source) .file_stem() - .ok_or(CompileErrors::from( - CompileErrorInner::ImportError(Error::new(format!( - "Could not determine alias for import {}", - import.source.display() - ))) - .in_file(&location), - ))? + .ok_or_else(|| { + CompileErrors::from( + CompileErrorInner::ImportError(Error::new(format!( + "Could not determine alias for import {}", + import.source.display() + ))) + .in_file(&location), + ) + })? .to_str() .unwrap(), ); @@ -311,7 +308,6 @@ impl Importer { Ok(Module { imports: vec![], symbols, - ..destination }) } } diff --git a/zokrates_core/src/ir/expression.rs b/zokrates_core/src/ir/expression.rs index 3a426141..7ccd264a 100644 --- a/zokrates_core/src/ir/expression.rs +++ b/zokrates_core/src/ir/expression.rs @@ -113,7 +113,7 @@ impl LinComb { } pub fn is_zero(&self) -> bool { - self.0.len() == 0 + self.0.is_empty() } } @@ -141,7 +141,7 @@ impl LinComb { // collect to a Result to short circuit when we hit an error .collect::>() // we didn't hit an error, do final processing. It's fine to clone here. - .map(|v: Vec<_>| (first.clone(), v.iter().fold(T::zero(), |acc, e| acc + *e))) + .map(|v: Vec<_>| (*first, v.iter().fold(T::zero(), |acc, e| acc + *e))) .ok() } } @@ -287,7 +287,7 @@ mod tests { fn add() { let a: LinComb = FlatVariable::new(42).into(); let b: LinComb = FlatVariable::new(42).into(); - let c = a + b.clone(); + let c = a + b; let expected_vec = vec![ (FlatVariable::new(42), Bn128Field::from(1)), @@ -300,7 +300,7 @@ mod tests { fn sub() { let a: LinComb = FlatVariable::new(42).into(); let b: LinComb = FlatVariable::new(42).into(); - let c = a - b.clone(); + let c = a - b; let expected_vec = vec![ (FlatVariable::new(42), Bn128Field::from(1)), diff --git a/zokrates_core/src/ir/from_flat.rs b/zokrates_core/src/ir/from_flat.rs index 90b202da..0f6b2d1c 100644 --- a/zokrates_core/src/ir/from_flat.rs +++ b/zokrates_core/src/ir/from_flat.rs @@ -125,7 +125,7 @@ impl From> for Directive { inputs: ds .inputs .into_iter() - .map(|i| QuadComb::from_flat_expression(i)) + .map(QuadComb::from_flat_expression) .collect(), solver: ds.solver, outputs: ds.outputs, diff --git a/zokrates_core/src/ir/interpreter.rs b/zokrates_core/src/ir/interpreter.rs index 3af7faf6..dc4ab3ac 100644 --- a/zokrates_core/src/ir/interpreter.rs +++ b/zokrates_core/src/ir/interpreter.rs @@ -40,7 +40,7 @@ impl Interpreter { let mut witness = BTreeMap::new(); witness.insert(FlatVariable::one(), T::one()); for (arg, value) in main.arguments.iter().zip(inputs.iter()) { - witness.insert(arg.clone(), value.clone().into()); + witness.insert(*arg, value.clone()); } for statement in main.statements.iter() { @@ -48,7 +48,7 @@ impl Interpreter { Statement::Constraint(quad, lin) => match lin.is_assignee(&witness) { true => { let val = quad.evaluate(&witness).unwrap(); - witness.insert(lin.0.iter().next().unwrap().0.clone(), val); + witness.insert(lin.0.get(0).unwrap().0, val); } false => { let lhs_value = quad.evaluate(&witness).unwrap(); @@ -79,7 +79,7 @@ impl Interpreter { match self.execute_solver(&d.solver, &inputs) { Ok(res) => { for (i, o) in d.outputs.iter().enumerate() { - witness.insert(o.clone(), res[i].clone()); + witness.insert(*o, res[i].clone()); } continue; } @@ -107,12 +107,12 @@ impl Interpreter { value.to_biguint() }; - let mut num = input.clone(); + let mut num = input; let mut res = vec![]; let bits = T::get_required_bits(); for i in (0..bits).rev() { if T::from(2).to_biguint().pow(i as usize) <= num { - num = num - T::from(2).to_biguint().pow(i as usize); + num -= T::from(2).to_biguint().pow(i as usize); res.push(T::one()); } else { res.push(T::zero()); @@ -120,7 +120,7 @@ impl Interpreter { } assert_eq!(num, T::zero().to_biguint()); for (i, o) in d.outputs.iter().enumerate() { - witness.insert(o.clone(), res[i].clone()); + witness.insert(*o, res[i].clone()); } } @@ -135,11 +135,15 @@ impl Interpreter { } } - pub fn execute_solver(&self, s: &Solver, inputs: &Vec) -> Result, String> { - let (expected_input_count, expected_output_count) = s.get_signature(); + pub fn execute_solver( + &self, + solver: &Solver, + inputs: &Vec, + ) -> Result, String> { + let (expected_input_count, expected_output_count) = solver.get_signature(); assert!(inputs.len() == expected_input_count); - let res = match s { + let res = match solver { Solver::ConditionEq => match inputs[0].is_zero() { true => vec![T::zero(), T::one()], false => vec![ @@ -220,8 +224,8 @@ impl LinComb { fn is_assignee(&self, witness: &BTreeMap) -> bool { self.0.iter().count() == 1 - && self.0.iter().next().unwrap().1 == T::from(1) - && !witness.contains_key(&self.0.iter().next().unwrap().0) + && self.0.get(0).unwrap().1 == T::from(1) + && !witness.contains_key(&self.0.get(0).unwrap().0) } } diff --git a/zokrates_core/src/ir/serialize.rs b/zokrates_core/src/ir/serialize.rs index 8b352f32..d97220a4 100644 --- a/zokrates_core/src/ir/serialize.rs +++ b/zokrates_core/src/ir/serialize.rs @@ -16,9 +16,9 @@ pub enum ProgEnum { impl Prog { pub fn serialize(&self, mut w: W) { - w.write(ZOKRATES_MAGIC).unwrap(); - w.write(ZOKRATES_VERSION_1).unwrap(); - w.write(&T::id()).unwrap(); + w.write_all(ZOKRATES_MAGIC).unwrap(); + w.write_all(ZOKRATES_VERSION_1).unwrap(); + w.write_all(&T::id()).unwrap(); serialize_into(&mut w, self, Infinite).unwrap(); } diff --git a/zokrates_core/src/macros.rs b/zokrates_core/src/macros.rs index ff36c1e7..a6d5b969 100644 --- a/zokrates_core/src/macros.rs +++ b/zokrates_core/src/macros.rs @@ -19,7 +19,7 @@ impl fmt::Display for Error { } } -pub fn process_macros<'ast, T: Field>(file: File<'ast>) -> Result, Error> { +pub fn process_macros(file: File) -> Result { match &file.pragma { Some(pragma) => { if T::name() != pragma.curve.name { diff --git a/zokrates_core/src/optimizer/directive.rs b/zokrates_core/src/optimizer/directive.rs index b2972046..d1e9f1e3 100644 --- a/zokrates_core/src/optimizer/directive.rs +++ b/zokrates_core/src/optimizer/directive.rs @@ -49,7 +49,7 @@ impl Folder for DirectiveOptimizer { } Entry::Occupied(e) => { self.substitution - .extend(d.outputs.into_iter().zip(e.get().into_iter().cloned())); + .extend(d.outputs.into_iter().zip(e.get().iter().cloned())); vec![] } } diff --git a/zokrates_core/src/optimizer/duplicate.rs b/zokrates_core/src/optimizer/duplicate.rs index f72b3a9f..abac5304 100644 --- a/zokrates_core/src/optimizer/duplicate.rs +++ b/zokrates_core/src/optimizer/duplicate.rs @@ -120,7 +120,7 @@ mod tests { main: Function { id: "main".to_string(), statements: vec![ - constraint.clone(), + constraint, Statement::Constraint( QuadComb::from_linear_combinations( LinComb::summand(3, FlatVariable::new(42)), diff --git a/zokrates_core/src/optimizer/redefinition.rs b/zokrates_core/src/optimizer/redefinition.rs index e6c3bfd6..c9cb0315 100644 --- a/zokrates_core/src/optimizer/redefinition.rs +++ b/zokrates_core/src/optimizer/redefinition.rs @@ -94,19 +94,13 @@ impl Folder for RedefinitionOptimizer { }; // insert into the ignored set - match to_ignore { - Some(v) => { - self.ignore.insert(v); - } - None => {} + if let Some(v) = to_ignore { + self.ignore.insert(v); } // insert into the substitution map - match to_insert { - Some((k, v)) => { - self.substitution.insert(k, v.into_canonical()); - } - None => {} + if let Some((k, v)) = to_insert { + self.substitution.insert(k, v.into_canonical()); }; // decide whether the constraint should be kept @@ -136,7 +130,7 @@ impl Folder for RedefinitionOptimizer { v if v == FlatVariable::one() => Ok(coefficient), _ => Err(LinComb::summand(coefficient, variable).into()), }) - .unwrap_or(Err(l.into())), + .unwrap_or_else(|| Err(l.into())), }, None => Err(q), }) @@ -184,8 +178,7 @@ impl Folder for RedefinitionOptimizer { match lc .0 .iter() - .find(|(variable, _)| self.substitution.get(&variable).is_some()) - .is_some() + .any(|(variable, _)| self.substitution.get(&variable).is_some()) { true => // for each summand, check if it is equal to a linear term in our substitution, otherwise keep it as is @@ -195,7 +188,7 @@ impl Folder for RedefinitionOptimizer { self.substitution .get(&variable) .map(|l| LinComb::from(l.clone()) * &coefficient) - .unwrap_or(LinComb::summand(coefficient, variable)) + .unwrap_or_else(|| LinComb::summand(coefficient, variable)) }) .fold(LinComb::zero(), |acc, x| acc + x) } @@ -243,7 +236,7 @@ mod tests { id: "foo".to_string(), arguments: vec![x], statements: vec![Statement::definition(y, x), Statement::definition(z, y)], - returns: vec![z.into()], + returns: vec![z], }; let optimized: Function = Function { @@ -270,7 +263,7 @@ mod tests { id: "foo".to_string(), arguments: vec![x], statements: vec![Statement::definition(one, x)], - returns: vec![x.into()], + returns: vec![x], }; let optimized = f.clone(); @@ -305,14 +298,14 @@ mod tests { Statement::definition(z, y), Statement::constraint(z, y), ], - returns: vec![z.into()], + returns: vec![z], }; let optimized: Function = Function { id: "foo".to_string(), arguments: vec![x], statements: vec![Statement::definition(z, x), Statement::constraint(z, x)], - returns: vec![z.into()], + returns: vec![z], }; let mut optimizer = RedefinitionOptimizer::new(); @@ -482,7 +475,7 @@ mod tests { Statement::constraint(x, Bn128Field::from(1)), Statement::constraint(x, Bn128Field::from(2)), ], - returns: vec![x.into()], + returns: vec![x], }; let optimized = f.clone(); diff --git a/zokrates_core/src/optimizer/tautology.rs b/zokrates_core/src/optimizer/tautology.rs index d6558412..4c2a7818 100644 --- a/zokrates_core/src/optimizer/tautology.rs +++ b/zokrates_core/src/optimizer/tautology.rs @@ -26,13 +26,10 @@ impl Folder for TautologyOptimizer { fn fold_statement(&mut self, s: Statement) -> Vec> { match s { Statement::Constraint(quad, lin) => { - match quad.try_linear() { - Some(l) => { - if l == lin { - return vec![]; - } + if let Some(l) = quad.try_linear() { + if l == lin { + return vec![]; } - None => {} } vec![Statement::Constraint(quad, lin)] } diff --git a/zokrates_core/src/proof_system/ark/gm17.rs b/zokrates_core/src/proof_system/ark/gm17.rs index 19888fdf..7c2d5026 100644 --- a/zokrates_core/src/proof_system/ark/gm17.rs +++ b/zokrates_core/src/proof_system/ark/gm17.rs @@ -78,7 +78,7 @@ impl Backend for Ark { query: vk .query .into_iter() - .map(|g1| serialization::to_g1::(g1)) + .map(serialization::to_g1::) .collect(), }; @@ -172,7 +172,7 @@ impl Backend for Ark { query: vk .query .into_iter() - .map(|g1| serialization::to_g1::(g1)) + .map(serialization::to_g1::) .collect(), }; diff --git a/zokrates_core/src/proof_system/ark/mod.rs b/zokrates_core/src/proof_system/ark/mod.rs index a21fc448..ed61e5b0 100644 --- a/zokrates_core/src/proof_system/ark/mod.rs +++ b/zokrates_core/src/proof_system/ark/mod.rs @@ -58,28 +58,25 @@ fn ark_combination( .map(|(k, v)| { ( v.into_ark(), - symbols - .entry(k) - .or_insert_with(|| { - match k.is_output() { - true => cs.new_input_variable(|| { - Ok(witness - .0 - .remove(&k) - .ok_or(SynthesisError::AssignmentMissing)? - .into_ark()) - }), - false => cs.new_witness_variable(|| { - Ok(witness - .0 - .remove(&k) - .ok_or(SynthesisError::AssignmentMissing)? - .into_ark()) - }), - } - .unwrap() - }) - .clone(), + *symbols.entry(k).or_insert_with(|| { + match k.is_output() { + true => cs.new_input_variable(|| { + Ok(witness + .0 + .remove(&k) + .ok_or(SynthesisError::AssignmentMissing)? + .into_ark()) + }), + false => cs.new_witness_variable(|| { + Ok(witness + .0 + .remove(&k) + .ok_or(SynthesisError::AssignmentMissing)? + .into_ark()) + }), + } + .unwrap() + }), ) }) .fold(LinearCombination::zero(), |acc, e| acc + e); @@ -127,7 +124,7 @@ impl Prog { }), } .unwrap(); - (var.clone(), wire) + (*var, wire) }), ); diff --git a/zokrates_core/src/proof_system/bellman/groth16.rs b/zokrates_core/src/proof_system/bellman/groth16.rs index 8db9823c..2c8bdd85 100644 --- a/zokrates_core/src/proof_system/bellman/groth16.rs +++ b/zokrates_core/src/proof_system/bellman/groth16.rs @@ -81,7 +81,7 @@ impl Backend for Bellman { ic: vk .gamma_abc .into_iter() - .map(|g1| serialization::to_g1::(g1)) + .map(serialization::to_g1::) .collect(), }; diff --git a/zokrates_core/src/proof_system/bellman/mod.rs b/zokrates_core/src/proof_system/bellman/mod.rs index df6869de..a45094a4 100644 --- a/zokrates_core/src/proof_system/bellman/mod.rs +++ b/zokrates_core/src/proof_system/bellman/mod.rs @@ -51,34 +51,31 @@ fn bellman_combination cs.alloc_input( - || format!("{}", k), - || { - Ok(witness - .0 - .remove(&k) - .ok_or(SynthesisError::AssignmentMissing)? - .into_bellman()) - }, - ), - false => cs.alloc( - || format!("{}", k), - || { - Ok(witness - .0 - .remove(&k) - .ok_or(SynthesisError::AssignmentMissing)? - .into_bellman()) - }, - ), - } - .unwrap() - }) - .clone(), + *symbols.entry(k).or_insert_with(|| { + match k.is_output() { + true => cs.alloc_input( + || format!("{}", k), + || { + Ok(witness + .0 + .remove(&k) + .ok_or(SynthesisError::AssignmentMissing)? + .into_bellman()) + }, + ), + false => cs.alloc( + || format!("{}", k), + || { + Ok(witness + .0 + .remove(&k) + .ok_or(SynthesisError::AssignmentMissing)? + .into_bellman()) + }, + ), + } + .unwrap() + }), ) }) .fold(LinearCombination::zero(), |acc, e| acc + e) @@ -127,7 +124,7 @@ impl Prog { ), } .unwrap(); - (var.clone(), wire) + (*var, wire) }), ); diff --git a/zokrates_core/src/semantics.rs b/zokrates_core/src/semantics.rs index 24baaf66..0de29c07 100644 --- a/zokrates_core/src/semantics.rs +++ b/zokrates_core/src/semantics.rs @@ -127,7 +127,7 @@ impl fmt::Display for ErrorInner { let location = self .pos .map(|p| format!("{}", p.0)) - .unwrap_or("?".to_string()); + .unwrap_or_else(|| "?".to_string()); write!(f, "{}\n\t{}", location, self.message) } } @@ -159,7 +159,7 @@ impl<'ast, T: fmt::Display> fmt::Display for FunctionQuery<'ast, T> { " -> {}", match &self.outputs[0] { Some(t) => format!("{}", t), - None => format!("_"), + None => "_".into(), } ), _ => { @@ -183,13 +183,13 @@ impl<'ast, T: Field> FunctionQuery<'ast, T> { /// Create a new query. fn new( id: Identifier<'ast>, - inputs: &Vec>, - outputs: &Vec>>, + inputs: &[Type<'ast, T>], + outputs: &[Option>], ) -> Self { FunctionQuery { id, - inputs: inputs.clone(), - outputs: outputs.clone(), + inputs: inputs.to_owned(), + outputs: outputs.to_owned(), } } @@ -289,7 +289,7 @@ impl<'ast, T: Field> Checker<'ast, T> { Err(e) => errors.extend(e), }; - if errors.len() > 0 { + if !errors.is_empty() { return Err(errors); } @@ -343,7 +343,7 @@ impl<'ast, T: Field> Checker<'ast, T> { } } - if errors.len() > 0 { + if !errors.is_empty() { return Err(errors); } @@ -506,7 +506,7 @@ impl<'ast, T: Field> Checker<'ast, T> { .types .entry(module_id.clone()) .or_default() - .insert(declaration.id.to_string(), t.clone()); + .insert(declaration.id.to_string(), t); } (0, None) => { errors.push(ErrorInner { @@ -589,7 +589,7 @@ impl<'ast, T: Field> Checker<'ast, T> { }; // return if any errors occured - if errors.len() > 0 { + if !errors.is_empty() { return Err(errors); } @@ -635,15 +635,12 @@ impl<'ast, T: Field> Checker<'ast, T> { }; // insert into typed_modules if we checked anything - match to_insert { - Some(typed_module) => { - // there should be no checked module at that key just yet, if there is we have a colision or we checked something twice - assert!(state - .typed_modules - .insert(module_id.clone(), typed_module) - .is_none()); - } - None => {} + if let Some(typed_module) = to_insert { + // there should be no checked module at that key just yet, if there is we have a colision or we checked something twice + assert!(state + .typed_modules + .insert(module_id.clone(), typed_module) + .is_none()); }; Ok(()) @@ -659,7 +656,7 @@ impl<'ast, T: Field> Checker<'ast, T> { 1 => Ok(()), 0 => Err(ErrorInner { pos: None, - message: format!("No main function found"), + message: "No main function found".into(), }), n => Err(ErrorInner { pos: None, @@ -857,7 +854,7 @@ impl<'ast, T: Field> Checker<'ast, T> { } } - if errors.len() > 0 { + if !errors.is_empty() { return Err(errors); } @@ -1254,10 +1251,9 @@ impl<'ast, T: Field> Checker<'ast, T> { Statement::Definition(assignee, expr) => { // we create multidef when rhs is a function call to benefit from inference // check rhs is not a function call here - match expr.value { - Expression::FunctionCall(..) => panic!("Parser should not generate Definition where the right hand side is a FunctionCall"), - _ => {} - } + if let Expression::FunctionCall(..) = expr.value { + panic!("Parser should not generate Definition where the right hand side is a FunctionCall") + } // check the expression to be assigned let checked_expr = self @@ -1338,13 +1334,13 @@ impl<'ast, T: Field> Checker<'ast, T> { // check lhs assignees are defined let (assignees, errors): (Vec<_>, Vec<_>) = assignees.into_iter().map(|a| self.check_assignee(a, module_id, types)).partition(|r| r.is_ok()); - if errors.len() > 0 { + if !errors.is_empty() { return Err(errors.into_iter().map(|e| e.unwrap_err()).collect()); } let assignees: Vec<_> = assignees.into_iter().map(|a| a.unwrap()).collect(); - let assignee_types = assignees.iter().map(|a| Some(a.get_type().clone())).collect(); + let assignee_types: Vec<_> = assignees.iter().map(|a| Some(a.get_type().clone())).collect(); // find argument types let mut arguments_checked = vec![]; @@ -1353,7 +1349,7 @@ impl<'ast, T: Field> Checker<'ast, T> { arguments_checked.push(arg_checked); } - let arguments_types = + let arguments_types: Vec<_> = arguments_checked.iter().map(|a| a.get_type()).collect(); let query = FunctionQuery::new(&fun_id, &arguments_types, &assignee_types); @@ -1642,7 +1638,7 @@ impl<'ast, T: Field> Checker<'ast, T> { } (TypedExpression::Uint(e1), TypedExpression::Uint(e2)) => { if e1.get_type() == e2.get_type() { - Ok(UExpression::add(e1, e2).into()) + Ok((e1 + e2).into()) } else { Err(ErrorInner { pos: Some(pos), @@ -1684,7 +1680,7 @@ impl<'ast, T: Field> Checker<'ast, T> { (Int(e1), Int(e2)) => Ok(IntExpression::Sub(box e1, box e2).into()), (TypedExpression::Uint(e1), TypedExpression::Uint(e2)) => { if e1.get_type() == e2.get_type() { - Ok(UExpression::sub(e1, e2).into()) + Ok((e1 - e2).into()) } else { Err(ErrorInner { pos: Some(pos), @@ -1732,7 +1728,7 @@ impl<'ast, T: Field> Checker<'ast, T> { } (TypedExpression::Uint(e1), TypedExpression::Uint(e2)) => { if e1.get_type() == e2.get_type() { - Ok(UExpression::mult(e1, e2).into()) + Ok((e1 * e2).into()) } else { Err(ErrorInner { pos: Some(pos), @@ -1787,7 +1783,7 @@ impl<'ast, T: Field> Checker<'ast, T> { } (TypedExpression::Uint(e1), TypedExpression::Uint(e2)) => { if e1.get_type() == e2.get_type() { - Ok(UExpression::div(e1, e2).into()) + Ok((e1 / e2).into()) } else { Err(ErrorInner { pos: Some(pos), @@ -1818,7 +1814,7 @@ impl<'ast, T: Field> Checker<'ast, T> { match (e1_checked, e2_checked) { (TypedExpression::Uint(e1), TypedExpression::Uint(e2)) => { if e1.get_type() == e2.get_type() { - Ok(UExpression::rem(e1, e2).into()) + Ok((e1 % e2).into()) } else { Err(ErrorInner { pos: Some(pos), @@ -1954,7 +1950,7 @@ impl<'ast, T: Field> Checker<'ast, T> { // outside of multidef, function calls must have a single return value // we use type inference to determine the type of the return, so we don't specify it - let query = FunctionQuery::new(&fun_id, &arguments_types, &vec![None]); + let query = FunctionQuery::new(&fun_id, &arguments_types, &[None]); let functions = self.find_functions(&query); @@ -3167,7 +3163,7 @@ impl<'ast, T: Field> Checker<'ast, T> { match e_checked { TypedExpression::Int(e) => Ok(IntExpression::Not(box e).into()), TypedExpression::Boolean(e) => Ok(BooleanExpression::Not(box e).into()), - TypedExpression::Uint(e) => Ok(UExpression::not(e).into()), + TypedExpression::Uint(e) => Ok((!e).into()), e => Err(ErrorInner { pos: Some(pos), message: format!("Cannot negate {}", e.get_type()), @@ -3243,7 +3239,7 @@ mod tests { let module_id = "".into(); let value = Bn128Field::max_value().to_biguint().add(1u32); - let expr = Expression::FieldConstant(BigUint::from(value)).mock(); + let expr = Expression::FieldConstant(value).mock(); assert!(Checker::::new() .check_expression(expr, &module_id, &types) @@ -3367,7 +3363,7 @@ mod tests { fn struct1() -> StructDefinitionNode<'static> { StructDefinition { fields: vec![StructDefinitionField { - id: "foo".into(), + id: "foo", ty: UnresolvedType::FieldElement.mock(), } .mock()], @@ -3564,7 +3560,7 @@ mod tests { let mut checker: Checker = Checker::new(); assert_eq!( checker - .check_module(&PathBuf::from(MODULE_ID).into(), &mut state) + .check_module(&PathBuf::from(MODULE_ID), &mut state) .unwrap_err()[0] .inner .message, @@ -4716,7 +4712,7 @@ mod tests { ) .mock(), Statement::Definition( - Assignee::Identifier("a".into()).mock(), + Assignee::Identifier("a").mock(), Expression::InlineArray(vec![absy::SpreadOrExpression::Expression( Expression::IntConstant(0usize.into()).mock(), )]) @@ -5511,7 +5507,7 @@ mod tests { assert_eq!( checker.check_type( UnresolvedType::User("Foo".into()).mock(), - &PathBuf::from(MODULE_ID).into(), + &PathBuf::from(MODULE_ID), &state.types ), Ok(Type::Struct(StructType::new( @@ -5525,7 +5521,7 @@ mod tests { checker .check_type( UnresolvedType::User("Bar".into()).mock(), - &PathBuf::from(MODULE_ID).into(), + &PathBuf::from(MODULE_ID), &state.types ) .unwrap_err() @@ -5557,7 +5553,7 @@ mod tests { private: true, } .mock(), - &PathBuf::from(MODULE_ID).into(), + &PathBuf::from(MODULE_ID), &state.types, &mut vec![] ), @@ -5589,7 +5585,7 @@ mod tests { private: true, } .mock(), - &PathBuf::from(MODULE_ID).into(), + &PathBuf::from(MODULE_ID), &state.types, &mut vec![] ) @@ -5620,7 +5616,7 @@ mod tests { .mock() ) .mock(), - &PathBuf::from(MODULE_ID).into(), + &PathBuf::from(MODULE_ID), &state.types, ), Ok(TypedStatement::Declaration(Variable::with_id_and_type( @@ -5645,7 +5641,7 @@ mod tests { private: true, } .mock(), - &PathBuf::from(MODULE_ID).into(), + &PathBuf::from(MODULE_ID), &state.types, &mut vec![] ) @@ -5686,7 +5682,7 @@ mod tests { "foo".into() ) .mock(), - &PathBuf::from(MODULE_ID).into(), + &PathBuf::from(MODULE_ID), &state.types ), Ok(FieldElementExpression::Member( @@ -5732,7 +5728,7 @@ mod tests { "bar".into() ) .mock(), - &PathBuf::from(MODULE_ID).into(), + &PathBuf::from(MODULE_ID), &state.types ) .unwrap_err() @@ -5766,7 +5762,7 @@ mod tests { vec![("foo", Expression::IntConstant(42usize.into()).mock())] ) .mock(), - &PathBuf::from(MODULE_ID).into(), + &PathBuf::from(MODULE_ID), &state.types ) .unwrap_err() @@ -5807,7 +5803,7 @@ mod tests { ] ) .mock(), - &PathBuf::from(MODULE_ID).into(), + &PathBuf::from(MODULE_ID), &state.types ), Ok(StructExpressionInner::Value(vec![ @@ -5858,7 +5854,7 @@ mod tests { ] ) .mock(), - &PathBuf::from(MODULE_ID).into(), + &PathBuf::from(MODULE_ID), &state.types ), Ok(StructExpressionInner::Value(vec![ @@ -5907,7 +5903,7 @@ mod tests { vec![("foo", Expression::IntConstant(42usize.into()).mock())] ) .mock(), - &PathBuf::from(MODULE_ID).into(), + &PathBuf::from(MODULE_ID), &state.types ) .unwrap_err() @@ -5954,7 +5950,7 @@ mod tests { )] ) .mock(), - &PathBuf::from(MODULE_ID).into(), + &PathBuf::from(MODULE_ID), &state.types ).unwrap_err() .message, @@ -5972,7 +5968,7 @@ mod tests { ] ) .mock(), - &PathBuf::from(MODULE_ID).into(), + &PathBuf::from(MODULE_ID), &state.types ) .unwrap_err() diff --git a/zokrates_core/src/solvers/mod.rs b/zokrates_core/src/solvers/mod.rs index ed3e1ae5..f9c6e1c4 100644 --- a/zokrates_core/src/solvers/mod.rs +++ b/zokrates_core/src/solvers/mod.rs @@ -42,7 +42,7 @@ impl Solver { } pub trait Executable: Signed { - fn execute(&self, inputs: &Vec) -> Result, String>; + fn execute(&self, inputs: &[T]) -> Result, String>; } pub trait Signed { diff --git a/zokrates_core/src/static_analysis/flatten_complex_types.rs b/zokrates_core/src/static_analysis/flatten_complex_types.rs index d5511bb2..c30ccbac 100644 --- a/zokrates_core/src/static_analysis/flatten_complex_types.rs +++ b/zokrates_core/src/static_analysis/flatten_complex_types.rs @@ -298,9 +298,7 @@ pub fn fold_statement<'ast, T: Field>( } typed_absy::TypedStatement::Declaration(v) => { let v = f.fold_variable(v); - v.into_iter() - .map(|v| zir::ZirStatement::Declaration(v)) - .collect() + v.into_iter().map(zir::ZirStatement::Declaration).collect() } typed_absy::TypedStatement::Assertion(e) => { let e = f.fold_boolean_expression(e); @@ -323,15 +321,15 @@ pub fn fold_statement<'ast, T: Field>( pub fn fold_array_expression_inner<'ast, T: Field>( f: &mut Flattener, - t: &typed_absy::types::ConcreteType, + ty: &typed_absy::types::ConcreteType, size: usize, - e: typed_absy::ArrayExpressionInner<'ast, T>, + array: typed_absy::ArrayExpressionInner<'ast, T>, ) -> Vec> { - match e { + match array { typed_absy::ArrayExpressionInner::Identifier(id) => { let variables = flatten_identifier_rec( f.fold_name(id), - &typed_absy::types::ConcreteType::array(t.clone(), size), + &typed_absy::types::ConcreteType::array(ty.clone(), size), ); variables .into_iter() @@ -395,7 +393,7 @@ pub fn fold_array_expression_inner<'ast, T: Field>( .sum(); // we also need the size of this member - let size = t.get_primitive_count() * size; + let size = ty.get_primitive_count() * size; s[offset..offset + size].to_vec() } @@ -405,7 +403,7 @@ pub fn fold_array_expression_inner<'ast, T: Field>( match index.into_inner() { zir::UExpressionInner::Value(i) => { - let size = typed_absy::types::ConcreteType::try_from(t.clone()) + let size = typed_absy::types::ConcreteType::try_from(ty.clone()) .unwrap() .get_primitive_count() * size; @@ -421,14 +419,14 @@ pub fn fold_array_expression_inner<'ast, T: Field>( pub fn fold_struct_expression_inner<'ast, T: Field>( f: &mut Flattener, - t: &typed_absy::types::ConcreteStructType, - e: typed_absy::StructExpressionInner<'ast, T>, + ty: &typed_absy::types::ConcreteStructType, + struc: typed_absy::StructExpressionInner<'ast, T>, ) -> Vec> { - match e { + match struc { typed_absy::StructExpressionInner::Identifier(id) => { let variables = flatten_identifier_rec( f.fold_name(id), - &typed_absy::types::ConcreteType::struc(t.clone()), + &typed_absy::types::ConcreteType::struc(ty.clone()), ); variables .into_iter() @@ -493,7 +491,11 @@ pub fn fold_struct_expression_inner<'ast, T: Field>( // we also need the size of this member let size = typed_absy::types::ConcreteType::try_from( - *t.iter().find(|member| member.id == id).cloned().unwrap().ty, + *ty.iter() + .find(|member| member.id == id) + .cloned() + .unwrap() + .ty, ) .unwrap() .get_primitive_count(); @@ -506,7 +508,7 @@ pub fn fold_struct_expression_inner<'ast, T: Field>( match index.into_inner() { zir::UExpressionInner::Value(i) => { - let size = t + let size = ty .iter() .map(|m| m.ty.get_primitive_count()) .fold(0, |acc, current| acc + current); diff --git a/zokrates_core/src/static_analysis/propagation.rs b/zokrates_core/src/static_analysis/propagation.rs index 11c3e395..607c02a9 100644 --- a/zokrates_core/src/static_analysis/propagation.rs +++ b/zokrates_core/src/static_analysis/propagation.rs @@ -104,10 +104,7 @@ fn is_constant<'ast, T: Field>(e: &TypedExpression<'ast, T>) -> bool { StructExpressionInner::Value(v) => v.iter().all(|e| is_constant(e)), _ => false, }, - TypedExpression::Uint(a) => match a.as_inner() { - UExpressionInner::Value(..) => true, - _ => false, - }, + TypedExpression::Uint(a) => matches!(a.as_inner(), UExpressionInner::Value(..)), _ => false, } } @@ -302,7 +299,7 @@ impl<'ast, 'a, T: Field> Folder<'ast, T> for Propagator<'ast, 'a, T> { for i in (0..bitwidth as u32).rev() { if 2u128.pow(i) <= num { - num = num - 2u128.pow(i); + num -= 2u128.pow(i); res.push(true); } else { res.push(false); @@ -1010,20 +1007,20 @@ impl<'ast, 'a, T: Field> Folder<'ast, T> for Propagator<'ast, 'a, T> { c => ArrayExpressionInner::IfElse(box c, box consequence, box alternative), } } - ArrayExpressionInner::Member(box s, m) => { - let s = self.fold_struct_expression(s); + ArrayExpressionInner::Member(box struc, id) => { + let struc = self.fold_struct_expression(struc); - let members = match s.get_type() { + let members = match struc.get_type() { Type::Struct(members) => members, _ => unreachable!("should be a struct"), }; - match s.into_inner() { + match struc.into_inner() { StructExpressionInner::Value(v) => { match members .iter() .zip(v) - .find(|(member, _)| member.id == m) + .find(|(member, _)| member.id == id) .unwrap() .1 { @@ -1031,7 +1028,7 @@ impl<'ast, 'a, T: Field> Folder<'ast, T> for Propagator<'ast, 'a, T> { _ => unreachable!("should be an array"), } } - inner => ArrayExpressionInner::Member(box inner.annotate(members), m), + inner => ArrayExpressionInner::Member(box inner.annotate(members), id), } } e => fold_array_expression_inner(self, ty, size, e), diff --git a/zokrates_core/src/static_analysis/redefinition.rs b/zokrates_core/src/static_analysis/redefinition.rs index dbcd8602..f44a8450 100644 --- a/zokrates_core/src/static_analysis/redefinition.rs +++ b/zokrates_core/src/static_analysis/redefinition.rs @@ -68,6 +68,6 @@ impl<'ast, T: Field> Folder<'ast, T> for RedefinitionOptimizer<'ast> { } fn fold_name(&mut self, s: Identifier<'ast>) -> Identifier<'ast> { - self.identifiers.get(&s).map(|r| r.clone()).unwrap_or(s) + self.identifiers.get(&s).cloned().unwrap_or(s) } } diff --git a/zokrates_core/src/static_analysis/reducer/mod.rs b/zokrates_core/src/static_analysis/reducer/mod.rs index ae03f143..019bb1ef 100644 --- a/zokrates_core/src/static_analysis/reducer/mod.rs +++ b/zokrates_core/src/static_analysis/reducer/mod.rs @@ -249,7 +249,7 @@ impl<'ast, 'a, T: Field> Reducer<'ast, 'a, T> { statement_buffer: vec![], for_loop_versions_after: vec![], for_loop_versions, - cache: cache, + cache, substitutions, program, versions, diff --git a/zokrates_core/src/static_analysis/uint_optimizer.rs b/zokrates_core/src/static_analysis/uint_optimizer.rs index c7c2d3d0..b157a035 100644 --- a/zokrates_core/src/static_analysis/uint_optimizer.rs +++ b/zokrates_core/src/static_analysis/uint_optimizer.rs @@ -24,7 +24,7 @@ impl<'ast, T: Field> UintOptimizer<'ast, T> { } } -fn force_reduce<'ast, T: Field>(e: UExpression<'ast, T>) -> UExpression<'ast, T> { +fn force_reduce(e: UExpression) -> UExpression { let metadata = e.metadata.unwrap(); let should_reduce = metadata.should_reduce.make_true(); @@ -38,7 +38,7 @@ fn force_reduce<'ast, T: Field>(e: UExpression<'ast, T>) -> UExpression<'ast, T> } } -fn force_no_reduce<'ast, T: Field>(e: UExpression<'ast, T>) -> UExpression<'ast, T> { +fn force_no_reduce(e: UExpression) -> UExpression { let metadata = e.metadata.unwrap(); let should_reduce = metadata.should_reduce.make_false(); @@ -130,7 +130,7 @@ impl<'ast, T: Field> Folder<'ast, T> for UintOptimizer<'ast, T> { self.ids .get(&Variable::uint(id.clone(), range)) .cloned() - .expect(&format!("identifier should have been defined: {}", id)), + .unwrap_or_else(|| panic!("identifier should have been defined: {}", id)), ), Add(box left, box right) => { // reduce the two terms @@ -145,7 +145,6 @@ impl<'ast, T: Field> Folder<'ast, T> for UintOptimizer<'ast, T> { .map(|max| (false, false, max)) .unwrap_or_else(|| { range_max - .clone() .checked_add(&right_max) .map(|max| (true, false, max)) .unwrap_or_else(|| { @@ -203,7 +202,7 @@ impl<'ast, T: Field> Folder<'ast, T> for UintOptimizer<'ast, T> { // if and only if `right_bitwidth` is `T::get_required_bits() - 1`, then `offset` is out of the interval // [0, 2**(max_bitwidth)[, therefore we need to reduce `right` left_max - .checked_add(&target_offset.clone()) + .checked_add(&target_offset) .map(|max| (false, true, max)) .unwrap_or_else(|| (true, true, range_max.clone() + target_offset)) } else { @@ -270,7 +269,6 @@ impl<'ast, T: Field> Folder<'ast, T> for UintOptimizer<'ast, T> { .map(|max| (false, false, max)) .unwrap_or_else(|| { range_max - .clone() .checked_mul(&right_max) .map(|max| (true, false, max)) .unwrap_or_else(|| { diff --git a/zokrates_core/src/static_analysis/unroll.rs b/zokrates_core/src/static_analysis/unroll.rs index 27ead9d7..81ead1c1 100644 --- a/zokrates_core/src/static_analysis/unroll.rs +++ b/zokrates_core/src/static_analysis/unroll.rs @@ -121,9 +121,9 @@ impl<'ast, T: Field> Folder<'ast, T> for Unroller<'ast> { stats.clone(), ] .into_iter() - .flat_map(|x| x) + .flatten() }) - .flat_map(|x| x) + .flatten() .flat_map(|x| self.fold_statement(x)) .collect(); @@ -150,7 +150,7 @@ impl<'ast, T: Field> Folder<'ast, T> for Unroller<'ast> { fn fold_name(&mut self, n: Identifier<'ast>) -> Identifier<'ast> { Identifier { - version: self.substitution.get(&n.id).unwrap_or(&0).clone(), + version: *self.substitution.get(&n.id).unwrap_or(&0), ..n } } diff --git a/zokrates_core/src/static_analysis/variable_read_remover.rs b/zokrates_core/src/static_analysis/variable_read_remover.rs index 46ecbfc4..18a1d934 100644 --- a/zokrates_core/src/static_analysis/variable_read_remover.rs +++ b/zokrates_core/src/static_analysis/variable_read_remover.rs @@ -56,8 +56,7 @@ impl<'ast, T: Field> VariableReadRemover<'ast, T> { Some(acc) => Some(BooleanExpression::Or(box acc, box e)), None => Some(e), }) - .unwrap() - .into(), + .unwrap(), )); (0..size) @@ -179,19 +178,16 @@ mod tests { assert_eq!( VariableReadRemover::new().fold_statement(access), vec![ - TypedStatement::Assertion( - BooleanExpression::Or( - box BooleanExpression::UintEq( - box UExpressionInner::Identifier("i".into()).annotate(UBitwidth::B32), - box UExpressionInner::Value(0).annotate(UBitwidth::B32) - ), - box BooleanExpression::UintEq( - box UExpressionInner::Identifier("i".into()).annotate(UBitwidth::B32), - box UExpressionInner::Value(1).annotate(UBitwidth::B32) - ) + TypedStatement::Assertion(BooleanExpression::Or( + box BooleanExpression::UintEq( + box UExpressionInner::Identifier("i".into()).annotate(UBitwidth::B32), + box UExpressionInner::Value(0).annotate(UBitwidth::B32) + ), + box BooleanExpression::UintEq( + box UExpressionInner::Identifier("i".into()).annotate(UBitwidth::B32), + box UExpressionInner::Value(1).annotate(UBitwidth::B32) ) - .into(), - ), + )), TypedStatement::Definition( TypedAssignee::Identifier(Variable::field_element("b")), FieldElementExpression::if_else( diff --git a/zokrates_core/src/typed_absy/integer.rs b/zokrates_core/src/typed_absy/integer.rs index 616a94f2..e799eb58 100644 --- a/zokrates_core/src/typed_absy/integer.rs +++ b/zokrates_core/src/typed_absy/integer.rs @@ -299,18 +299,15 @@ impl<'ast, T: Field> UExpression<'ast, T> { Err(Value(i)) } } - Add(box e1, box e2) => Ok(UExpression::add( - Self::try_from_int(e1, bitwidth)?, - Self::try_from_int(e2, bitwidth)?, - )), - Sub(box e1, box e2) => Ok(UExpression::sub( - Self::try_from_int(e1, bitwidth)?, - Self::try_from_int(e2, bitwidth)?, - )), - Mult(box e1, box e2) => Ok(UExpression::mult( - Self::try_from_int(e1, bitwidth)?, - Self::try_from_int(e2, bitwidth)?, - )), + Add(box e1, box e2) => { + Ok(Self::try_from_int(e1, bitwidth)? + Self::try_from_int(e2, bitwidth)?) + } + Sub(box e1, box e2) => { + Ok(Self::try_from_int(e1, bitwidth)? - Self::try_from_int(e2, bitwidth)?) + } + Mult(box e1, box e2) => { + Ok(Self::try_from_int(e1, bitwidth)? * Self::try_from_int(e2, bitwidth)?) + } And(box e1, box e2) => Ok(UExpression::and( Self::try_from_int(e1, bitwidth)?, Self::try_from_int(e2, bitwidth)?, @@ -319,7 +316,7 @@ impl<'ast, T: Field> UExpression<'ast, T> { Self::try_from_int(e1, bitwidth)?, Self::try_from_int(e2, bitwidth)?, )), - Not(box e) => Ok(UExpression::not(Self::try_from_int(e, bitwidth)?)), + Not(box e) => Ok(!Self::try_from_int(e, bitwidth)?), Xor(box e1, box e2) => Ok(UExpression::xor( Self::try_from_int(e1, bitwidth)?, Self::try_from_int(e2, bitwidth)?, @@ -551,15 +548,15 @@ mod tests { let expected = vec![ t.clone(), - UExpression::add(t.clone(), t.clone()), + t.clone() + t.clone(), UExpression::xor(t.clone(), t.clone()), UExpression::or(t.clone(), t.clone()), UExpression::and(t.clone(), t.clone()), - UExpression::sub(t.clone(), t.clone()), - UExpression::mult(t.clone(), t.clone()), + t.clone() - t.clone(), + t.clone() * t.clone(), UExpression::left_shift(t.clone(), s.clone()), UExpression::right_shift(t.clone(), s.clone()), - UExpression::not(t.clone()), + !t.clone(), UExpression::if_else(c.clone(), t.clone(), t.clone()), UExpression::select(t_a.clone(), i.clone()), ]; diff --git a/zokrates_core/src/typed_absy/mod.rs b/zokrates_core/src/typed_absy/mod.rs index cb038a0f..0e4887ad 100644 --- a/zokrates_core/src/typed_absy/mod.rs +++ b/zokrates_core/src/typed_absy/mod.rs @@ -123,7 +123,7 @@ impl<'ast, T: fmt::Display> fmt::Display for TypedProgram<'ast, T> { writeln!(f, "{}", "-".repeat(100))?; writeln!(f, "{}", module)?; writeln!(f, "{}", "-".repeat(100))?; - writeln!(f, "")?; + writeln!(f)?; } write!(f, "") } @@ -265,7 +265,7 @@ impl<'ast, T: fmt::Display> fmt::Display for TypedFunction<'ast, T> { } )?; - writeln!(f, "")?; + writeln!(f)?; let mut tab = 0; @@ -406,9 +406,9 @@ impl<'ast, T: fmt::Debug> fmt::Debug for TypedStatement<'ast, T> { } TypedStatement::Assertion(ref e) => write!(f, "Assertion({:?})", e), TypedStatement::For(ref var, ref start, ref stop, ref list) => { - write!(f, "for {:?} in {:?}..{:?} do\n", var, start, stop)?; + writeln!(f, "for {:?} in {:?}..{:?} do", var, start, stop)?; for l in list { - write!(f, "\t\t{:?}\n", l)?; + writeln!(f, "\t\t{:?}", l)?; } write!(f, "\tendfor") } @@ -431,7 +431,7 @@ impl<'ast, T: fmt::Display> TypedStatement<'ast, T> { writeln!(f, "for {} in {}..{} do", variable, from, to)?; for s in statements { s.fmt_indented(f, depth + 1)?; - writeln!(f, "")?; + writeln!(f)?; } write!(f, "{}endfor", "\t".repeat(depth)) } @@ -457,9 +457,9 @@ impl<'ast, T: fmt::Display> fmt::Display for TypedStatement<'ast, T> { TypedStatement::Definition(ref lhs, ref rhs) => write!(f, "{} = {}", lhs, rhs), TypedStatement::Assertion(ref e) => write!(f, "assert({})", e), TypedStatement::For(ref var, ref start, ref stop, ref list) => { - write!(f, "for {} in {}..{} do\n", var, start, stop)?; + writeln!(f, "for {} in {}..{} do", var, start, stop)?; for l in list { - write!(f, "\t\t{}\n", l)?; + writeln!(f, "\t\t{}", l)?; } write!(f, "\tendfor") } diff --git a/zokrates_core/src/typed_absy/types.rs b/zokrates_core/src/typed_absy/types.rs index 7b6efaf4..f40fb8ad 100644 --- a/zokrates_core/src/typed_absy/types.rs +++ b/zokrates_core/src/typed_absy/types.rs @@ -1112,12 +1112,10 @@ pub mod signature { let len = res.len(); if len == 0 { res.push((1, t)) + } else if res[len - 1].1 == t { + res[len - 1].0 += 1; } else { - if res[len - 1].1 == t { - res[len - 1].0 += 1; - } else { - res.push((1, t)) - } + res.push((1, t)) } } res.into_iter() diff --git a/zokrates_core/src/typed_absy/uint.rs b/zokrates_core/src/typed_absy/uint.rs index 403dda66..3f3eb4b0 100644 --- a/zokrates_core/src/typed_absy/uint.rs +++ b/zokrates_core/src/typed_absy/uint.rs @@ -1,40 +1,70 @@ use crate::typed_absy::types::UBitwidth; use crate::typed_absy::*; +use std::ops::{Add, Div, Mul, Not, Rem, Sub}; use zokrates_field::Field; type Bitwidth = usize; -impl<'ast, T: Field> UExpression<'ast, T> { - pub fn add(self, other: Self) -> UExpression<'ast, T> { +impl<'ast, T> Add for UExpression<'ast, T> { + type Output = Self; + + fn add(self, other: Self) -> UExpression<'ast, T> { let bitwidth = self.bitwidth; assert_eq!(bitwidth, other.bitwidth); UExpressionInner::Add(box self, box other).annotate(bitwidth) } +} - pub fn sub(self, other: Self) -> UExpression<'ast, T> { +impl<'ast, T> Sub for UExpression<'ast, T> { + type Output = Self; + + fn sub(self, other: Self) -> UExpression<'ast, T> { let bitwidth = self.bitwidth; assert_eq!(bitwidth, other.bitwidth); UExpressionInner::Sub(box self, box other).annotate(bitwidth) } +} - pub fn mult(self, other: Self) -> UExpression<'ast, T> { +impl<'ast, T> Mul for UExpression<'ast, T> { + type Output = Self; + + fn mul(self, other: Self) -> UExpression<'ast, T> { let bitwidth = self.bitwidth; assert_eq!(bitwidth, other.bitwidth); UExpressionInner::Mult(box self, box other).annotate(bitwidth) } +} - pub fn div(self, other: Self) -> UExpression<'ast, T> { +impl<'ast, T> Div for UExpression<'ast, T> { + type Output = Self; + + fn div(self, other: Self) -> UExpression<'ast, T> { let bitwidth = self.bitwidth; assert_eq!(bitwidth, other.bitwidth); UExpressionInner::Div(box self, box other).annotate(bitwidth) } +} - pub fn rem(self, other: Self) -> UExpression<'ast, T> { +impl<'ast, T> Rem for UExpression<'ast, T> { + type Output = Self; + + fn rem(self, other: Self) -> UExpression<'ast, T> { let bitwidth = self.bitwidth; assert_eq!(bitwidth, other.bitwidth); UExpressionInner::Rem(box self, box other).annotate(bitwidth) } +} +impl<'ast, T> Not for UExpression<'ast, T> { + type Output = Self; + + fn not(self) -> UExpression<'ast, T> { + let bitwidth = self.bitwidth; + UExpressionInner::Not(box self).annotate(bitwidth) + } +} + +impl<'ast, T: Field> UExpression<'ast, T> { pub fn xor(self, other: Self) -> UExpression<'ast, T> { let bitwidth = self.bitwidth; assert_eq!(bitwidth, other.bitwidth); @@ -53,11 +83,6 @@ impl<'ast, T: Field> UExpression<'ast, T> { UExpressionInner::And(box self, box other).annotate(bitwidth) } - pub fn not(self) -> UExpression<'ast, T> { - let bitwidth = self.bitwidth; - UExpressionInner::Not(box self).annotate(bitwidth) - } - pub fn left_shift(self, by: FieldElementExpression<'ast, T>) -> UExpression<'ast, T> { let bitwidth = self.bitwidth; UExpressionInner::LeftShift(box self, box by).annotate(bitwidth) diff --git a/zokrates_core/src/zir/from_typed.rs b/zokrates_core/src/zir/from_typed.rs index 42d7b296..8f4f3e82 100644 --- a/zokrates_core/src/zir/from_typed.rs +++ b/zokrates_core/src/zir/from_typed.rs @@ -13,8 +13,8 @@ impl<'ast> From> for zir::types::Fu impl From for zir::types::Signature { fn from(s: typed_absy::types::ConcreteSignature) -> zir::types::Signature { zir::types::Signature { - inputs: s.inputs.into_iter().flat_map(|t| from_type(t)).collect(), - outputs: s.outputs.into_iter().flat_map(|t| from_type(t)).collect(), + inputs: s.inputs.into_iter().flat_map(from_type).collect(), + outputs: s.outputs.into_iter().flat_map(from_type).collect(), } } } diff --git a/zokrates_core/src/zir/mod.rs b/zokrates_core/src/zir/mod.rs index 83c33599..02a7214d 100644 --- a/zokrates_core/src/zir/mod.rs +++ b/zokrates_core/src/zir/mod.rs @@ -58,7 +58,7 @@ impl<'ast, T: fmt::Display> fmt::Display for ZirProgram<'ast, T> { writeln!(f, "{}", "-".repeat(100))?; writeln!(f, "{}", module)?; writeln!(f, "{}", "-".repeat(100))?; - writeln!(f, "")?; + writeln!(f)?; } write!(f, "") } diff --git a/zokrates_core/src/zir/types.rs b/zokrates_core/src/zir/types.rs index f8a61050..167e12f2 100644 --- a/zokrates_core/src/zir/types.rs +++ b/zokrates_core/src/zir/types.rs @@ -200,12 +200,10 @@ pub mod signature { let len = res.len(); if len == 0 { res.push((1, t)) + } else if res[len - 1].1 == t { + res[len - 1].0 += 1; } else { - if res[len - 1].1 == t { - res[len - 1].0 += 1; - } else { - res.push((1, t)) - } + res.push((1, t)) } } res.into_iter() diff --git a/zokrates_core_test/Cargo.toml b/zokrates_core_test/Cargo.toml index 285ddd5b..51f22d40 100644 --- a/zokrates_core_test/Cargo.toml +++ b/zokrates_core_test/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "zokrates_core_test" -version = "0.1.3" +version = "0.1.4" authors = ["schaeff "] edition = "2018" diff --git a/zokrates_field/src/lib.rs b/zokrates_field/src/lib.rs index 120b11ca..0ea05595 100644 --- a/zokrates_field/src/lib.rs +++ b/zokrates_field/src/lib.rs @@ -94,7 +94,7 @@ pub trait Field: /// Returns the number of bits required to represent any element of this field type. fn get_required_bits() -> usize; /// Tries to parse a string into this representation - fn try_from_dec_str<'a>(s: &'a str) -> Result; + fn try_from_dec_str(s: &str) -> Result; fn try_from_str(s: &str, radix: u32) -> Result; /// Returns a decimal string representing a the member of the equivalence class of this `Field` in Z/pZ /// which lies in [-(p-1)/2, (p-1)/2] @@ -208,7 +208,7 @@ mod prime_field { fn get_required_bits() -> usize { (*P).bits() } - fn try_from_dec_str<'a>(s: &'a str) -> Result { + fn try_from_dec_str(s: &str) -> Result { Self::try_from_str(s, 10) } fn try_from_str(s: &str, radix: u32) -> Result { diff --git a/zokrates_fs_resolver/src/lib.rs b/zokrates_fs_resolver/src/lib.rs index 9da6900e..b38a0b17 100644 --- a/zokrates_fs_resolver/src/lib.rs +++ b/zokrates_fs_resolver/src/lib.rs @@ -37,14 +37,12 @@ impl<'a> Resolver for FileSystemResolver<'a> { // other paths `abc/def` are interpreted relative to the standard library root path let base = match source.components().next() { Some(Component::CurDir) | Some(Component::ParentDir) => { - PathBuf::from(current_location).parent().unwrap().into() + current_location.parent().unwrap().into() } _ => PathBuf::from(self.stdlib_root_path.unwrap_or("")), }; - let path_owned = base - .join(PathBuf::from(import_location.clone())) - .with_extension("zok"); + let path_owned = base.join(import_location.clone()).with_extension("zok"); if !path_owned.is_file() { return Err(io::Error::new( @@ -96,7 +94,7 @@ mod tests { // create a source folder with a zok file let folder = tempfile::tempdir().unwrap(); let dir_path = folder.path().join("dir"); - std::fs::create_dir(dir_path.clone()).unwrap(); + std::fs::create_dir(dir_path).unwrap(); let fs_resolver = FileSystemResolver::default(); let res = fs_resolver.resolve(".".into(), "./dir/".into()); @@ -155,7 +153,7 @@ mod tests { let stdlib_root_path = temp_dir.path().to_owned(); let fs_resolver = FileSystemResolver::with_stdlib_root(stdlib_root_path.to_str().unwrap()); - let result = fs_resolver.resolve(file_path.clone(), "bar.zok".into()); + let result = fs_resolver.resolve(file_path, "bar.zok".into()); assert!(result.is_ok()); // the imported file should be the user's assert_eq!(result.unwrap().0, String::from("\n")); diff --git a/zokrates_js/Cargo.toml b/zokrates_js/Cargo.toml index f0abcc86..8aa884fb 100644 --- a/zokrates_js/Cargo.toml +++ b/zokrates_js/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "zokrates_js" -version = "1.0.26" +version = "1.0.27" authors = ["Darko Macesic"] edition = "2018" diff --git a/zokrates_js/package.json b/zokrates_js/package.json index a473d4a2..20991963 100644 --- a/zokrates_js/package.json +++ b/zokrates_js/package.json @@ -2,7 +2,7 @@ "name": "zokrates-js", "main": "index.js", "author": "Darko Macesic ", - "version": "1.0.26", + "version": "1.0.27", "keywords": [ "zokrates", "wasm-bindgen", diff --git a/zokrates_parser/Cargo.toml b/zokrates_parser/Cargo.toml index dcafff07..e056c0d8 100644 --- a/zokrates_parser/Cargo.toml +++ b/zokrates_parser/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "zokrates_parser" -version = "0.1.5" +version = "0.1.6" authors = ["JacobEberhardt "] edition = "2018" diff --git a/zokrates_pest_ast/Cargo.toml b/zokrates_pest_ast/Cargo.toml index 9918c917..d9f2dddd 100644 --- a/zokrates_pest_ast/Cargo.toml +++ b/zokrates_pest_ast/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "zokrates_pest_ast" -version = "0.1.4" +version = "0.1.5" authors = ["schaeff "] edition = "2018" diff --git a/zokrates_pest_ast/src/lib.rs b/zokrates_pest_ast/src/lib.rs index b2652098..e4c55eec 100644 --- a/zokrates_pest_ast/src/lib.rs +++ b/zokrates_pest_ast/src/lib.rs @@ -852,7 +852,7 @@ impl fmt::Display for Error { } pub fn generate_ast(input: &str) -> Result { - let parse_tree = parse(input).map_err(|e| Error(e))?; + let parse_tree = parse(input).map_err(Error)?; Ok(Prog::from(parse_tree).0) } diff --git a/zokrates_stdlib/build.rs b/zokrates_stdlib/build.rs index 5081027d..cb2dd02c 100644 --- a/zokrates_stdlib/build.rs +++ b/zokrates_stdlib/build.rs @@ -15,5 +15,5 @@ fn export_stdlib() { let out_dir = env::var("OUT_DIR").unwrap(); let mut options = CopyOptions::new(); options.overwrite = true; - copy_items(&vec!["stdlib"], out_dir, &options).unwrap(); + copy_items(&["stdlib"], out_dir, &options).unwrap(); } diff --git a/zokrates_test/src/lib.rs b/zokrates_test/src/lib.rs index e5c17a40..5e70a560 100644 --- a/zokrates_test/src/lib.rs +++ b/zokrates_test/src/lib.rs @@ -154,7 +154,7 @@ fn compile_and_run(t: Tests) { s, input .iter() - .map(|i| format!("{}", i)) + .map(|i| i.to_string()) .collect::>() .join(", ") );