diff --git a/circom/src/compilation_user.rs b/circom/src/compilation_user.rs index c2b03bfa7..3d77b2ea8 100644 --- a/circom/src/compilation_user.rs +++ b/circom/src/compilation_user.rs @@ -43,17 +43,9 @@ pub fn compile(config: CompilerConfig) -> Result<(), ()> { config.dat_file ); println!( - "{} {}/{}, {}, {}, {}, {}, {}, {} and {}", + "{} {}/main.cpp, circom.hpp, calcwit.hpp, calcwit.cpp, fr.hpp, fr.cpp, fr.asm and Makefile", Colour::Green.paint("Written successfully:"), - &config.c_folder, - "main.cpp".to_string(), - "circom.hpp".to_string(), - "calcwit.hpp".to_string(), - "calcwit.cpp".to_string(), - "fr.hpp".to_string(), - "fr.cpp".to_string(), - "fr.asm".to_string(), - "Makefile".to_string() + &config.c_folder ); } @@ -64,7 +56,7 @@ pub fn compile(config: CompilerConfig) -> Result<(), ()> { let result = wat_to_wasm(&config.wat_file, &config.wasm_file); match result { Result::Err(report) => { - Report::print_reports(&[report], &FileLibrary::new()); + Report::print_reports(&[*report], &FileLibrary::new()); return Err(()); } Result::Ok(()) => { @@ -78,7 +70,7 @@ pub fn compile(config: CompilerConfig) -> Result<(), ()> { std::fs::remove_file(&config.wat_file).unwrap(); match result { Result::Err(report) => { - Report::print_reports(&[report], &FileLibrary::new()); + Report::print_reports(&[*report], &FileLibrary::new()); return Err(()); } Result::Ok(()) => { @@ -99,7 +91,7 @@ pub fn compile(config: CompilerConfig) -> Result<(), ()> { } -fn wat_to_wasm(wat_file: &str, wasm_file: &str) -> Result<(), Report> { +fn wat_to_wasm(wat_file: &str, wasm_file: &str) -> Result<(), Box> { use std::fs::read_to_string; use std::fs::File; use std::io::BufWriter; @@ -112,19 +104,19 @@ fn wat_to_wasm(wat_file: &str, wasm_file: &str) -> Result<(), Report> { let result_wasm_contents = parser::parse::(&buf); match result_wasm_contents { Result::Err(error) => { - Result::Err(Report::error( + Result::Err(Box::new(Report::error( format!("Error translating the circuit from wat to wasm.\n\nException encountered when parsing WAT: {}", error), ReportCode::ErrorWat2Wasm, - )) + ))) } Result::Ok(mut wat) => { let wasm_contents = wat.module.encode(); match wasm_contents { Result::Err(error) => { - Result::Err(Report::error( + Result::Err(Box::new(Report::error( format!("Error translating the circuit from wat to wasm.\n\nException encountered when encoding WASM: {}", error), ReportCode::ErrorWat2Wasm, - )) + ))) } Result::Ok(wasm_contents) => { let file = File::create(wasm_file).unwrap(); diff --git a/circom/src/execution_user.rs b/circom/src/execution_user.rs index dfe18537a..da5a139fe 100644 --- a/circom/src/execution_user.rs +++ b/circom/src/execution_user.rs @@ -80,7 +80,7 @@ fn generate_json_constraints( debug: &DebugWriter, exporter: &dyn ConstraintExporter, ) -> Result<(), ()> { - if let Ok(()) = exporter.json_constraints(&debug) { + if let Ok(()) = exporter.json_constraints(debug) { println!("{} {}", Colour::Green.paint("Constraints written in:"), debug.json_constraints); Result::Ok(()) } else { diff --git a/circom/src/input_user.rs b/circom/src/input_user.rs index 9417b067a..eb59bfd4a 100644 --- a/circom/src/input_user.rs +++ b/circom/src/input_user.rs @@ -36,14 +36,14 @@ pub struct Input { } -const R1CS: &'static str = "r1cs"; -const WAT: &'static str = "wat"; -const WASM: &'static str = "wasm"; -const CPP: &'static str = "cpp"; -const JS: &'static str = "js"; -const DAT: &'static str = "dat"; -const SYM: &'static str = "sym"; -const JSON: &'static str = "json"; +const R1CS: &str = "r1cs"; +const WAT: &str = "wat"; +const WASM: &str = "wasm"; +const CPP: &str = "cpp"; +const JS: &str = "js"; +const DAT: &str = "dat"; +const SYM: &str = "sym"; +const JSON: &str = "json"; impl Input { @@ -90,7 +90,7 @@ impl Input { ), wat_flag:input_processing::get_wat(&matches), wasm_flag: input_processing::get_wasm(&matches), - c_flag: c_flag, + c_flag, r1cs_flag: input_processing::get_r1cs(&matches), sym_flag: input_processing::get_sym(&matches), main_inputs_flag: input_processing::get_main_inputs_log(&matches), @@ -109,6 +109,7 @@ impl Input { }) } + #[allow(clippy::ptr_arg)] fn build_folder(output_path: &PathBuf, filename: &str, ext: &str) -> PathBuf { let mut file = output_path.clone(); let folder_name = format!("{}_{}",filename,ext); @@ -116,6 +117,7 @@ impl Input { file } + #[allow(clippy::ptr_arg)] fn build_output(output_path: &PathBuf, filename: &str, ext: &str) -> PathBuf { let mut file = output_path.clone(); file.push(format!("{}.{}",filename,ext)); @@ -127,7 +129,7 @@ impl Input { } pub fn input_file(&self) -> &str { - &self.input_program.to_str().unwrap() + self.input_program.to_str().unwrap() } pub fn r1cs_file(&self) -> &str { self.out_r1cs.to_str().unwrap() @@ -257,7 +259,7 @@ mod input_processing { (_, true, _, _) => Ok(SimplificationStyle::O1), (_, _, true, _) => { let o_2_argument = matches.value_of("simplification_rounds").unwrap(); - let rounds_r = usize::from_str_radix(o_2_argument, 10); + let rounds_r = o_2_argument.parse::(); if let Result::Ok(no_rounds) = rounds_r { if no_rounds == 0 { Ok(SimplificationStyle::O1) } else {Ok(SimplificationStyle::O2(no_rounds))}} diff --git a/circom/src/main.rs b/circom/src/main.rs index 614bad155..4103ae836 100644 --- a/circom/src/main.rs +++ b/circom/src/main.rs @@ -4,7 +4,7 @@ mod input_user; mod parser_user; mod type_analysis_user; -const VERSION: &'static str = env!("CARGO_PKG_VERSION"); +const VERSION: &str = env!("CARGO_PKG_VERSION"); use ansi_term::Colour; diff --git a/circom_algebra/src/algebra.rs b/circom_algebra/src/algebra.rs index bfddd49e2..d6ac98a08 100644 --- a/circom_algebra/src/algebra.rs +++ b/circom_algebra/src/algebra.rs @@ -6,6 +6,7 @@ use std::collections::{HashMap, HashSet, BTreeSet}; use std::fmt::{Display, Formatter}; use std::hash::Hash; +#[derive(Default)] pub enum ArithmeticExpression where C: Hash + Eq, @@ -30,6 +31,7 @@ where b: HashMap, c: HashMap, }, + #[default] NonQuadratic, } impl Display for ArithmeticExpression { @@ -80,11 +82,7 @@ impl PartialEq for ArithmeticExpressio } } -impl Default for ArithmeticExpression { - fn default() -> Self { - ArithmeticExpression::NonQuadratic - } -} + impl ArithmeticExpression { pub fn new() -> ArithmeticExpression { @@ -237,7 +235,7 @@ impl ArithmeticExpression { let inverse_constant = modular_arithmetic::div( &BigInt::from(1), constant, - &field + field )?; ArithmeticExpression::multiply_coefficients_by_constant(&inverse_constant, coefficients, field); debug_assert!(ArithmeticExpression::valid_hashmap_for_expression(coefficients)); @@ -898,7 +896,7 @@ impl Substitution { let symbol = substitution.from; let mut coefficients = substitution.to; ArithmeticExpression::initialize_hashmap_for_expression(&mut coefficients); - coefficients.insert(symbol, BigInt::from(-1 % field)); + coefficients.insert(symbol, -1 % field); let arith = ArithmeticExpression::Linear { coefficients }; ArithmeticExpression::transform_expression_to_constraint_form(arith, field).unwrap() } @@ -1060,7 +1058,7 @@ impl Constraint { ) -> Substitution { debug_assert!(Constraint::is_linear(&constraint)); debug_assert!(constraint.c.contains_key(signal)); - let raw_expression = Constraint::clear_signal(constraint.c, &signal, field); + let raw_expression = Constraint::clear_signal(constraint.c, signal, field); Substitution { from: signal.clone(), to: raw_expression } } @@ -1071,7 +1069,7 @@ impl Constraint { ) -> (BigInt, Substitution) { debug_assert!(Constraint::is_linear(&constraint)); debug_assert!(constraint.c.contains_key(signal)); - let (coefficient, raw_expression) = Constraint::clear_signal_not_normalized(constraint.c, &signal, field); + let (coefficient, raw_expression) = Constraint::clear_signal_not_normalized(constraint.c, signal, field); (coefficient, Substitution {from: signal.clone(), to: raw_expression}) } @@ -1110,7 +1108,7 @@ impl Constraint { key: &C, field: &BigInt, ) -> HashMap { - let key_value = symbols.remove(&key).unwrap(); + let key_value = symbols.remove(key).unwrap(); assert!(!key_value.is_zero()); let value_to_the_right = modular_arithmetic::mul(&key_value, &BigInt::from(-1), field); ArithmeticExpression::initialize_hashmap_for_expression(&mut symbols); @@ -1128,7 +1126,7 @@ impl Constraint { key: &C, field: &BigInt, ) -> (BigInt, HashMap) { - let key_value = symbols.remove(&key).unwrap(); + let key_value = symbols.remove(key).unwrap(); assert!(!key_value.is_zero()); let value_to_the_right = modular_arithmetic::mul(&key_value, &BigInt::from(-1), field); ArithmeticExpression::initialize_hashmap_for_expression(&mut symbols); @@ -1220,6 +1218,7 @@ impl Constraint { let c = apply_raw_offset(&self.c, offset); Constraint::new(a, b, c) } + #[allow(clippy::ptr_arg)] pub fn apply_witness(&self, witness: &Vec) -> Constraint { let a = apply_vectored_correspondence(&self.a, witness); let b = apply_vectored_correspondence(&self.b, witness); @@ -1233,7 +1232,7 @@ type RawExpr = HashMap; fn apply_vectored_correspondence( symbols: &HashMap, - map: &Vec, + map: &[usize], ) -> HashMap { let mut mapped = HashMap::new(); for (s, v) in symbols { @@ -1256,7 +1255,7 @@ where let id = if key.eq(&constant_coefficient) { ArithmeticExpression::constant_coefficient() } else { - map.get(&key).expect(&format!("Unknown signal: {}", key)).clone() + map.get(key).unwrap_or_else(|| panic!("Unknown signal: {}", key)).clone() }; coefficients_as_correspondence.insert(id, value.clone()); } diff --git a/circom_algebra/src/constraint_storage/mod.rs b/circom_algebra/src/constraint_storage/mod.rs index dd25a7b81..5b9c92838 100644 --- a/circom_algebra/src/constraint_storage/mod.rs +++ b/circom_algebra/src/constraint_storage/mod.rs @@ -19,6 +19,12 @@ pub struct ConstraintStorage { constraints: Vec, } +impl Default for ConstraintStorage { + fn default() -> Self { + Self::new() + } +} + impl ConstraintStorage { pub fn new() -> ConstraintStorage { ConstraintStorage { field_tracker: FieldTracker::new(), constraints: Vec::new() } diff --git a/circom_algebra/src/modular_arithmetic.rs b/circom_algebra/src/modular_arithmetic.rs index 6fdfce35a..44f18a272 100644 --- a/circom_algebra/src/modular_arithmetic.rs +++ b/circom_algebra/src/modular_arithmetic.rs @@ -41,7 +41,7 @@ pub fn sub(left: &BigInt, right: &BigInt, field: &BigInt) -> BigInt { pub fn div(left: &BigInt, right: &BigInt, field: &BigInt) -> Result { let right_inverse = right .mod_inverse(field) - .map_or(Result::Err(ArithmeticError::DivisionByZero), |a| Result::Ok(a))?; + .map_or(Result::Err(ArithmeticError::DivisionByZero), Result::Ok)?; let res = mul(left, &right_inverse, field); Result::Ok(res) } @@ -73,21 +73,21 @@ pub fn multi_inv(values: &Vec, field: &BigInt) -> Vec{ let mut partials : Vec = Vec::new(); partials.push(one.clone()); for i in 0..values.len(){ - partials.push(mul(partials.get(partials.len()-1).unwrap(), + partials.push(mul(partials.last().unwrap(), values.get(i).unwrap(), - &field)); + field)); } let mut inverse = div(&one, - partials.get(partials.len()-1).unwrap(), - &field).ok().unwrap(); + partials.last().unwrap(), + field).ok().unwrap(); let mut outputs : Vec = vec![BigInt::from(0); partials.len()]; let mut i = values.len(); while i > 0{ - outputs[i-1] = mul(partials.get(i-1).unwrap(), &inverse, &field); - inverse = mul(&inverse, values.get(i-1).unwrap(), &field); - i = i - 1; + outputs[i-1] = mul(partials.get(i-1).unwrap(), &inverse, field); + inverse = mul(&inverse, values.get(i-1).unwrap(), field); + i -= 1; } - return outputs; + outputs } //Bit operations @@ -114,7 +114,7 @@ pub fn shift_l(left: &BigInt, right: &BigInt, field: &BigInt) -> Result Result, signals: &SignalDefinition4, num_signals: usize) -> (SignalsInformation, BTreeMap) { let mut signal_to_ocurrences: HashMap = HashMap::with_capacity(num_signals); let mut signal_to_rep: HashMap = HashMap::with_capacity(num_signals); let mut uniques: BTreeMap = BTreeMap::new(); - for pos in 0..constraints.len(){ - for k in constraints[pos].c().keys() { + for (pos, item) in constraints.iter().enumerate() { + for k in item.c().keys() { if signals.can_be_taken(*k) { - match signal_to_ocurrences.get_mut(k){ - Some(prev_ocu) =>{ - *prev_ocu = *prev_ocu + 1; - }, + match signal_to_ocurrences.get_mut(k) { + Some(prev_ocu) => { + *prev_ocu += 1; + } None => { signal_to_ocurrences.insert(*k, 1); signal_to_rep.insert(*k, pos); @@ -91,18 +91,14 @@ impl SignalsInformation { (SignalsInformation{signal_to_ocurrences}, uniques) } - pub fn remove_constraint(&mut self, constraint: &C, signals: &SignalDefinition4){ - for signal in constraint.c().keys(){ - if signals.can_be_taken(*signal){ - match self.signal_to_ocurrences.get_mut(&signal){ - Some(ocurrences) =>{ - *ocurrences = *ocurrences - 1; - }, - None => {}, + pub fn remove_constraint(&mut self, constraint: &C, signals: &SignalDefinition4) { + for signal in constraint.c().keys() { + if signals.can_be_taken(*signal) { + if let Some(ocurrences) = self.signal_to_ocurrences.get_mut(signal) { + *ocurrences -= 1; } } } - } @@ -204,7 +200,7 @@ fn treat_constraint_1( let out = out.unwrap(); signals.delete(out); let substitution = C::clear_signal_from_linear(work, &out, field); - let in_conflict = substitutions.get(&substitution.from()).cloned(); + let in_conflict = substitutions.get(substitution.from()).cloned(); if in_conflict.is_none() { substitutions.insert(*substitution.from(), substitution); break; @@ -238,7 +234,7 @@ fn treat_constraint_2( let out = out.unwrap(); signals.delete(out); let (coefficient, substitution) = C::clear_signal_from_linear_not_normalized(work, &out, field); - let in_conflict = substitutions.get(&substitution.from()).cloned(); + let in_conflict = substitutions.get(substitution.from()).cloned(); if in_conflict.is_none() { substitutions.insert(*substitution.from(), (coefficient, substitution)); break; @@ -275,7 +271,7 @@ fn treat_constraint_3( let out = out.unwrap(); signals.delete(out); let (coefficient, substitution) = C::clear_signal_from_linear_not_normalized(work, &out, field); - let in_conflict = substitutions.get(&substitution.from()).cloned(); + let in_conflict = substitutions.get(substitution.from()).cloned(); if in_conflict.is_none() { substitutions.insert(*substitution.from(), (coefficient, substitution)); break; @@ -328,7 +324,7 @@ fn treat_constraint_4( } let out = out.unwrap(); let (coefficient, substitution) = C::clear_signal_from_linear_not_normalized(work, &out, field); - let in_conflict = substitutions.get(&substitution.from()).cloned(); + let in_conflict = substitutions.get(substitution.from()).cloned(); if in_conflict.is_none() { signals.delete(out); info_ocurrences.remove_signal(out); @@ -393,10 +389,8 @@ fn take_signal_4(signals: &SignalDefinition4, info_ocurrences: &SignalsInformati ret = Some(*k); ocurrences_ret = Some(*new_ocurrences); } - else if *new_ocurrences == val_ant{ - if ret.unwrap() < *k{ - ret = Some(*k); - } + else if *new_ocurrences == val_ant && ret.unwrap() < *k { + ret = Some(*k); } }, None => { @@ -410,28 +404,21 @@ fn take_signal_4(signals: &SignalDefinition4, info_ocurrences: &SignalsInformati ret } +fn normalize_substitutions(substitutions: SHNotNormalized, field: &BigInt) -> SH { + let mut coeffs: Vec = Vec::new(); -fn normalize_substitutions(substitutions: SHNotNormalized, field: &BigInt) -> SH{ - let mut coeffs : Vec = Vec::new(); - - for (_signal, (coeff, _sub)) in &substitutions{ + for (coeff, _sub) in substitutions.values() { coeffs.push(coeff.clone()); } - + let inverses = modular_arithmetic::multi_inv(&coeffs, field); - let mut tree : BTreeMap = BTreeMap::new(); - let mut i = 0; - for (signal, (_coeff, sub)) in substitutions{ + let mut tree: BTreeMap = BTreeMap::new(); + for (i, (signal, (_coeff, sub))) in substitutions.into_iter().enumerate() { let inv = inverses.get(i).unwrap(); let arith_sub = A::hashmap_into_arith(sub.to().clone()); - let mult_by_inverse = A::mul( - &arith_sub, - &A::Number {value : inv.clone()}, - field - ); - let new_sub = S::new(signal.clone(), mult_by_inverse).unwrap(); + let mult_by_inverse = A::mul(&arith_sub, &A::Number { value: inv.clone() }, field); + let new_sub = S::new(signal, mult_by_inverse).unwrap(); tree.insert(signal, new_sub); - i = i + 1; } tree } diff --git a/code_producers/src/c_elements/c_code_generator.rs b/code_producers/src/c_elements/c_code_generator.rs index 2556b539d..ef05fb5b2 100644 --- a/code_producers/src/c_elements/c_code_generator.rs +++ b/code_producers/src/c_elements/c_code_generator.rs @@ -74,7 +74,7 @@ pub fn declare_index_multiple_eq() -> CInstruction { format!("uint {}", INDEX_MULTIPLE_EQ) } pub fn index_multiple_eq() -> CInstruction { - format!("{}", INDEX_MULTIPLE_EQ) + INDEX_MULTIPLE_EQ.to_string() } pub const FUNCTION_DESTINATION: &str = "destination"; // type PFrElements[] @@ -92,7 +92,7 @@ pub fn declare_ctx_index() -> CInstruction { } pub fn ctx_index() -> CInstruction { - format!("{}", CTX_INDEX) + CTX_INDEX.to_string() } pub fn store_ctx_index(value: CInstruction) -> CInstruction { format!("{} = {}", ctx_index(), value) @@ -135,12 +135,12 @@ pub fn declare_circom_calc_wit() -> CInstruction { format!("Circom_CalcWit* {}", CIRCOM_CALC_WIT) } pub fn circom_calc_wit() -> CInstruction { - format!("{}", CIRCOM_CALC_WIT) + CIRCOM_CALC_WIT.to_string() } pub const TEMP_INS_2_IO_INFO: &str = "templateInsId2IOSignalInfo"; pub fn template_ins_2_io_info() -> CInstruction { - format!("{}", TEMP_INS_2_IO_INFO) + TEMP_INS_2_IO_INFO.to_string() } pub fn template_id_in_component(idx: CInstruction) -> CInstruction { @@ -154,7 +154,7 @@ pub fn declare_my_signal_start() -> CInstruction { ) } pub fn my_signal_start() -> CInstruction { - format!("{}", MY_SIGNAL_START) + MY_SIGNAL_START.to_string() } pub const MY_TEMPLATE_NAME: &str = "myTemplateName"; @@ -167,11 +167,11 @@ pub fn declare_my_template_name() -> CInstruction { pub fn declare_my_template_name_function(name: &String) -> CInstruction { format!( "std::string {} = \"{}\"", - MY_TEMPLATE_NAME, name.to_string() + MY_TEMPLATE_NAME, name ) } pub fn my_template_name() -> CInstruction { - format!("{}", MY_TEMPLATE_NAME) + MY_TEMPLATE_NAME.to_string() } @@ -183,7 +183,7 @@ pub fn declare_my_component_name() -> CInstruction { ) } pub fn my_component_name() -> CInstruction { - format!("{}", MY_COMPONENT_NAME) + MY_COMPONENT_NAME.to_string() } pub const MY_FATHER: &str = "myFather"; @@ -194,7 +194,7 @@ pub fn declare_my_father() -> CInstruction { ) } pub fn my_father() -> CInstruction { - format!("{}", MY_FATHER) + MY_FATHER.to_string() } pub const MY_ID: &str = "myId"; @@ -205,17 +205,17 @@ pub fn declare_my_id() -> CInstruction { ) } pub fn my_id() -> CInstruction { - format!("{}", MY_ID) + MY_ID.to_string() } pub const FUNCTION_TABLE: &str = "_functionTable"; pub fn function_table() -> CInstruction { - format!("{}", FUNCTION_TABLE) + FUNCTION_TABLE.to_string() } pub const FUNCTION_TABLE_PARALLEL: &str = "_functionTableParallel"; pub fn function_table_parallel() -> CInstruction { - format!("{}", FUNCTION_TABLE_PARALLEL) + FUNCTION_TABLE_PARALLEL.to_string() } pub const SIGNAL_VALUES: &str = "signalValues"; @@ -292,7 +292,7 @@ pub fn declare_my_subcomponents() -> CInstruction { ) } pub fn my_subcomponents() -> CInstruction { - format!("{}", MY_SUBCOMPONENTS) + MY_SUBCOMPONENTS.to_string() } pub const MY_SUBCOMPONENTS_PARALLEL: &str = "mySubcomponentsParallel"; @@ -303,7 +303,7 @@ pub fn declare_my_subcomponents_parallel() -> CInstruction { ) } pub fn my_subcomponents_parallel() -> CInstruction { - format!("{}", MY_SUBCOMPONENTS_PARALLEL) + MY_SUBCOMPONENTS_PARALLEL.to_string() } pub const CIRCUIT_CONSTANTS: &str = "circuitConstants"; @@ -322,7 +322,7 @@ pub fn declare_free_position_in_component_memory() -> CInstruction { format!("u32 {} = {}->{}", FREE_IN_COMPONENT_MEM, CIRCOM_CALC_WIT, FREE_IN_COMPONENT_MEM) } pub fn free_position_in_component_memory() -> CInstruction { - format!("{}", FREE_IN_COMPONENT_MEM) + FREE_IN_COMPONENT_MEM.to_string() } pub fn store_free_position_in_component_memory(value: String) -> CInstruction { format!("{} = {}", FREE_IN_COMPONENT_MEM, value) @@ -336,7 +336,7 @@ pub fn declare_list_of_template_messages_use() -> CInstruction { ) } pub fn list_of_template_messages_use() -> CInstruction { - format!("{}", LIST_OF_TEMPLATE_MESSAGES) + LIST_OF_TEMPLATE_MESSAGES.to_string() } pub fn build_callable(header: String, params: Vec, body: Vec) -> String { @@ -473,13 +473,13 @@ pub fn generate_hash_map(signal_name_list: &Vec<(String, usize, usize)>) -> Vec< assert!(signal_name_list.len() <= 256); let len = 256; let mut hash_map = vec![(0, 0, 0); len]; - for i in 0..signal_name_list.len() { - let h = hasher(&signal_name_list[i].0); + for (name, start, size) in signal_name_list { + let h = hasher(name); let mut p = (h % 256) as usize; while hash_map[p].1 != 0 { p = (p + 1) % 256; } - hash_map[p] = (h, signal_name_list[i].1 as u64, signal_name_list[i].2 as u64); + hash_map[p] = (h, *start as u64, *size as u64); } hash_map } @@ -521,10 +521,10 @@ pub fn generate_dat_constant_list(producer: &CProducer, constant_list: &Vec().unwrap(); let b = ((p.bits() + 63) / 64) * 64; let mut r = BigInt::from(1); - r = r << b; - n = n % BigInt::clone(&p); - n = n + BigInt::clone(&p); - n = n % BigInt::clone(&p); + r <<= b; + n %= BigInt::clone(&p); + n += BigInt::clone(&p); + n %= BigInt::clone(&p); let hp = BigInt::clone(&p) / 2; let mut nn; if BigInt::clone(&n) > hp { @@ -547,7 +547,7 @@ pub fn generate_dat_constant_list(producer: &CProducer, constant_list: &Vec = sm.to_be_bytes().to_vec(); v.reverse(); constant_list_data.append(&mut v); @@ -556,7 +556,7 @@ pub fn generate_dat_constant_list(producer: &CProducer, constant_list: &Vec = lm.to_be_bytes().to_vec(); v.reverse(); constant_list_data.append(&mut v); @@ -582,14 +582,14 @@ pub fn generate_dat_io_signals_info( ) -> Vec { // println!("size: {}",io_map.len()); let mut io_signals_info = vec![]; - for (t_ins, _) in io_map { + for t_ins in io_map.keys() { //println!("info: {}",t_ins); let t32 = *t_ins as u32; let mut v: Vec = t32.to_be_bytes().to_vec(); v.reverse(); io_signals_info.append(&mut v); } - for (_, l_io_def) in io_map { + for l_io_def in io_map.values() { //println!("io_def_len: {}",l_io_def.len()); let l32 = l_io_def.len() as u32; let mut v: Vec = l32.to_be_bytes().to_vec(); @@ -601,12 +601,11 @@ pub fn generate_dat_io_signals_info( let mut v: Vec = l32.to_be_bytes().to_vec(); v.reverse(); io_signals_info.append(&mut v); - let n32: u32; - if s.lengths.len() > 0 { - n32 = (s.lengths.len() - 1) as u32; + let n32 = if !s.lengths.is_empty() { + (s.lengths.len() - 1) as u32 } else { - n32 = 0; - } + 0 + }; // println!("dims-1: {}",n32); let mut v: Vec = n32.to_be_bytes().to_vec(); v.reverse(); @@ -653,7 +652,7 @@ pub fn generate_dat_file(dat_file: &mut dyn Write, producer: &CProducer) -> std: //dfile.flush()?; let aux = producer.get_main_input_list(); - let map = generate_hash_map(&aux); + let map = generate_hash_map(aux); let hashmap = generate_dat_from_hash_map(&map); //bytes u64 --> u64 //let hml = 256 as u32; //dfile.write_all(&hml.to_be_bytes())?; @@ -669,7 +668,7 @@ pub fn generate_dat_file(dat_file: &mut dyn Write, producer: &CProducer) -> std: //dat_file.flush()?; //let ioml = producer.get_io_map().len() as u64; //dfile.write_all(&ioml.to_be_bytes())?; - let iomap = generate_dat_io_signals_info(&producer, producer.get_io_map()); + let iomap = generate_dat_io_signals_info(producer, producer.get_io_map()); dat_file.write_all(&iomap)?; /* let ml = producer.get_message_list(); @@ -689,27 +688,27 @@ pub fn generate_dat_file(dat_file: &mut dyn Write, producer: &CProducer) -> std: pub fn generate_function_list(_producer: &CProducer, list: &TemplateListParallel) -> (String, String) { let mut func_list= "".to_string(); let mut func_list_parallel= "".to_string(); - if list.len() > 0 { + if !list.is_empty() { if list[0].is_parallel{ func_list_parallel.push_str(&format!("\n{}_run_parallel",list[0].name)); }else{ - func_list_parallel.push_str(&format!("\nNULL")); + func_list_parallel.push_str("\nNULL"); } if list[0].is_not_parallel{ func_list.push_str(&format!("\n{}_run",list[0].name)); }else{ - func_list.push_str(&format!("\nNULL")); + func_list.push_str("\nNULL"); } - for i in 1..list.len() { - if list[i].is_parallel{ - func_list_parallel.push_str(&format!(",\n{}_run_parallel",list[i].name)); + for item in list.iter().skip(1) { + if item.is_parallel{ + func_list_parallel.push_str(&format!(",\n{}_run_parallel",item.name)); }else{ - func_list_parallel.push_str(&format!(",\nNULL")); + func_list_parallel.push_str(",\nNULL"); } - if list[i].is_not_parallel{ - func_list.push_str(&format!(",\n{}_run",list[i].name)); + if item.is_not_parallel{ + func_list.push_str(&format!(",\n{}_run",item.name)); }else{ - func_list.push_str(&format!(",\nNULL")); + func_list.push_str(",\nNULL"); } } } @@ -722,10 +721,10 @@ pub fn generate_message_list_def(_producer: &CProducer, message_list: &MessageLi let start = format!("std::string {}1 [] = {{\n", list_of_messages); // let start = format!("{}1 [] = {{\n",producer.get_list_of_messages_name()); instructions.push(start); - if message_list.len() > 0 { + if !message_list.is_empty() { instructions.push(format!("\"{}\"", message_list[0])); - for i in 1..message_list.len() { - instructions.push(format!(",\n\"{}\"", message_list[i])); + for item in message_list.iter().skip(1) { + instructions.push(format!(",\n\"{}\"", item)); } instructions.push("\n".to_string()); } @@ -734,38 +733,39 @@ pub fn generate_message_list_def(_producer: &CProducer, message_list: &MessageLi instructions } -pub fn generate_function_release_memory_component() -> Vec{ - let mut instructions = vec![]; - instructions.push("void release_memory_component(Circom_CalcWit* ctx, uint pos) {{\n".to_string()); - instructions.push("if (pos != 0){{\n".to_string()); - instructions.push("if(ctx->componentMemory[pos].subcomponents)".to_string()); - instructions.push("delete []ctx->componentMemory[pos].subcomponents;\n".to_string()); - instructions.push("if(ctx->componentMemory[pos].subcomponentsParallel)".to_string()); - instructions.push("delete []ctx->componentMemory[pos].subcomponentsParallel;\n".to_string()); - instructions.push("if(ctx->componentMemory[pos].outputIsSet)".to_string()); - instructions.push("delete []ctx->componentMemory[pos].outputIsSet;\n".to_string()); - instructions.push("if(ctx->componentMemory[pos].mutexes)".to_string()); - instructions.push("delete []ctx->componentMemory[pos].mutexes;\n".to_string()); - instructions.push("if(ctx->componentMemory[pos].cvs)".to_string()); - instructions.push("delete []ctx->componentMemory[pos].cvs;\n".to_string()); - instructions.push("if(ctx->componentMemory[pos].sbct)".to_string()); - instructions.push("delete []ctx->componentMemory[pos].sbct;\n".to_string()); - instructions.push("}}\n\n".to_string()); - instructions.push("}}\n\n".to_string()); - instructions -} - -pub fn generate_function_release_memory_circuit() -> Vec{ +pub fn generate_function_release_memory_component() -> Vec { + vec![ + "void release_memory_component(Circom_CalcWit* ctx, uint pos) {{\n".to_string(), + "if (pos != 0){{\n".to_string(), + "if(ctx->componentMemory[pos].subcomponents)".to_string(), + "delete []ctx->componentMemory[pos].subcomponents;\n".to_string(), + "if(ctx->componentMemory[pos].subcomponentsParallel)".to_string(), + "delete []ctx->componentMemory[pos].subcomponentsParallel;\n".to_string(), + "if(ctx->componentMemory[pos].outputIsSet)".to_string(), + "delete []ctx->componentMemory[pos].outputIsSet;\n".to_string(), + "if(ctx->componentMemory[pos].mutexes)".to_string(), + "delete []ctx->componentMemory[pos].mutexes;\n".to_string(), + "if(ctx->componentMemory[pos].cvs)".to_string(), + "delete []ctx->componentMemory[pos].cvs;\n".to_string(), + "if(ctx->componentMemory[pos].sbct)".to_string(), + "delete []ctx->componentMemory[pos].sbct;\n".to_string(), + "}}\n\n".to_string(), + "}}\n\n".to_string(), + ] +} + +pub fn generate_function_release_memory_circuit() -> Vec { // deleting each one of the components - let mut instructions = vec![]; - instructions.push("void release_memory(Circom_CalcWit* ctx) {{\n".to_string()); - instructions.push("for (int i = 0; i < get_number_of_components(); i++) {{\n".to_string()); - instructions.push("release_memory_component(ctx, i);\n".to_string()); - instructions.push("}}\n".to_string()); - instructions.push("}}\n".to_string()); - instructions - } + vec![ + "void release_memory(Circom_CalcWit* ctx) {{\n".to_string(), + "for (int i = 0; i < get_number_of_components(, i++) {{\n".to_string(), + "release_memory_component(ctx, i,\n".to_string(), + "}}\n".to_string(), + "}}\n".to_string(), + ] +} +#[allow(clippy::ptr_arg)] pub fn generate_main_cpp_file(c_folder: &PathBuf) -> std::io::Result<()> { use std::io::BufWriter; let mut file_path = c_folder.clone(); @@ -783,6 +783,7 @@ pub fn generate_main_cpp_file(c_folder: &PathBuf) -> std::io::Result<()> { Ok(()) } +#[allow(clippy::ptr_arg)] pub fn generate_circom_hpp_file(c_folder: &PathBuf) -> std::io::Result<()> { use std::io::BufWriter; let mut file_path = c_folder.clone(); @@ -800,6 +801,7 @@ pub fn generate_circom_hpp_file(c_folder: &PathBuf) -> std::io::Result<()> { Ok(()) } +#[allow(clippy::ptr_arg)] pub fn generate_fr_hpp_file(c_folder: &PathBuf, prime: &String) -> std::io::Result<()> { use std::io::BufWriter; let mut file_path = c_folder.clone(); @@ -826,6 +828,7 @@ pub fn generate_fr_hpp_file(c_folder: &PathBuf, prime: &String) -> std::io::Resu Ok(()) } +#[allow(clippy::ptr_arg)] pub fn generate_calcwit_hpp_file(c_folder: &PathBuf) -> std::io::Result<()> { use std::io::BufWriter; let mut file_path = c_folder.clone(); @@ -843,6 +846,7 @@ pub fn generate_calcwit_hpp_file(c_folder: &PathBuf) -> std::io::Result<()> { Ok(()) } +#[allow(clippy::ptr_arg)] pub fn generate_fr_cpp_file(c_folder: &PathBuf, prime: &String) -> std::io::Result<()> { use std::io::BufWriter; let mut file_path = c_folder.clone(); @@ -870,6 +874,7 @@ pub fn generate_fr_cpp_file(c_folder: &PathBuf, prime: &String) -> std::io::Resu Ok(()) } +#[allow(clippy::ptr_arg)] pub fn generate_calcwit_cpp_file(c_folder: &PathBuf) -> std::io::Result<()> { use std::io::BufWriter; let mut file_path = c_folder.clone(); @@ -887,6 +892,7 @@ pub fn generate_calcwit_cpp_file(c_folder: &PathBuf) -> std::io::Result<()> { Ok(()) } +#[allow(clippy::ptr_arg)] pub fn generate_fr_asm_file(c_folder: &PathBuf, prime: &String) -> std::io::Result<()> { use std::io::BufWriter; let mut file_path = c_folder.clone(); @@ -913,6 +919,7 @@ pub fn generate_fr_asm_file(c_folder: &PathBuf, prime: &String) -> std::io::Resu Ok(()) } +#[allow(clippy::ptr_arg)] pub fn generate_make_file( c_folder: &PathBuf, run_name: &str, @@ -996,7 +1003,7 @@ mod tests { use std::path::Path; // use std::fs::File; use super::*; - const LOCATION: &'static str = "../target/code_generator_test"; + const LOCATION: &str = "../target/code_generator_test"; fn create_producer() -> CProducer { CProducer::default() diff --git a/code_producers/src/wasm_elements/mod.rs b/code_producers/src/wasm_elements/mod.rs index 57e7e6b54..dee39a6af 100644 --- a/code_producers/src/wasm_elements/mod.rs +++ b/code_producers/src/wasm_elements/mod.rs @@ -226,17 +226,17 @@ impl WASMProducer { } pub fn get_number_of_io_signals(&self) -> usize { let mut n = 0; - for (_c, v) in &self.io_map { + for v in self.io_map.values() { n += v.len(); } n } pub fn get_io_signals_info_size(&self) -> usize { let mut n = 0; - for (_c, v) in &self.io_map { + for v in self.io_map.values() { for s in v { // since we take offset and all lengths but last one - if s.lengths.len() == 0 { + if s.lengths.is_empty() { n += 1; } else { n += s.lengths.len(); diff --git a/code_producers/src/wasm_elements/wasm_code_generator.rs b/code_producers/src/wasm_elements/wasm_code_generator.rs index f5440660c..a68747102 100644 --- a/code_producers/src/wasm_elements/wasm_code_generator.rs +++ b/code_producers/src/wasm_elements/wasm_code_generator.rs @@ -230,13 +230,13 @@ pub fn generate_hash_map(signal_name_list: &Vec<(String, usize, usize)>) -> Vec< assert!(signal_name_list.len() <= 256); let len = 256; let mut hash_map = vec![(0, 0, 0); len]; - for i in 0..signal_name_list.len() { - let h = hasher(&signal_name_list[i].0); + for (name, start, size) in signal_name_list { + let h = hasher(name); let mut p = (h % 256) as usize; while hash_map[p].1 != 0 { p = (p + 1) % 256; } - hash_map[p] = (h, signal_name_list[i].1, signal_name_list[i].2); + hash_map[p] = (h, *start, *size); } hash_map } @@ -268,10 +268,10 @@ pub fn generate_data_template_instance_to_io( for c in 0..producer.get_number_of_template_instances() { match io_map.get(&c) { Some(value) => { - io_map_data.push_str(&&wasm_hexa(4, &BigInt::from(s))); + io_map_data.push_str(&wasm_hexa(4, &BigInt::from(s))); s += value.len() * 4; } - None => io_map_data.push_str(&&wasm_hexa(4, &BigInt::from(0))), + None => io_map_data.push_str(&wasm_hexa(4, &BigInt::from(0))), } } io_map_data @@ -284,22 +284,17 @@ pub fn generate_data_io_signals_to_info( let mut io_signals = "".to_string(); let mut pos = producer.get_io_signals_info_start(); for c in 0..producer.get_number_of_template_instances() { - match io_map.get(&c) { - Some(value) => { - let mut n = 0; - for s in value { - assert_eq!(s.code, n); - io_signals.push_str(&&wasm_hexa(4, &BigInt::from(pos))); - //do not store code and the first one of lengths - if s.lengths.len() == 0 { - pos += 4; - } else { - pos += s.lengths.len() * 4; - } - n += 1; + if let Some(value) = io_map.get(&c) { + for (n, s) in value.iter().enumerate() { + assert_eq!(s.code, n); + io_signals.push_str(&wasm_hexa(4, &BigInt::from(pos))); + //do not store code and the first one of lengths + if s.lengths.is_empty() { + pos += 4; + } else { + pos += s.lengths.len() * 4; } } - None => (), } } io_signals @@ -311,20 +306,17 @@ pub fn generate_data_io_signals_info( ) -> String { let mut io_signals_info = "".to_string(); for c in 0..producer.get_number_of_components() { - match io_map.get(&c) { - Some(value) => { - for s in value { - // add the actual offset in memory, taking into account the size of field nums - io_signals_info.push_str(&&wasm_hexa( - 4, - &BigInt::from(s.offset * producer.get_size_32_bits_in_memory() * 4), - )); - for i in 1..s.lengths.len() { - io_signals_info.push_str(&&wasm_hexa(4, &BigInt::from(s.lengths[i]))); - } + if let Some(value) = io_map.get(&c) { + for s in value { + // add the actual offset in memory, taking into account the size of field nums + io_signals_info.push_str(&wasm_hexa( + 4, + &BigInt::from(s.offset * producer.get_size_32_bits_in_memory() * 4), + )); + for i in 1..s.lengths.len() { + io_signals_info.push_str(&wasm_hexa(4, &BigInt::from(s.lengths[i]))); } } - None => (), } } io_signals_info @@ -348,10 +340,10 @@ pub fn generate_data_constants(producer: &WASMProducer, constant_list: &Vec().unwrap(); let b = ((p.bits() + 63) / 64) * 64; let mut r = BigInt::from(1); - r = r << b; - n = n % BigInt::clone(&p); - n = n + BigInt::clone(&p); - n = n % BigInt::clone(&p); + r <<= b; + n %= BigInt::clone(&p); + n += BigInt::clone(&p); + n %= BigInt::clone(&p); let hp = BigInt::clone(&p) / 2; let mut nn; if BigInt::clone(&n) > hp { @@ -489,64 +481,54 @@ pub fn to_array_hex(num: &BigInt, size: usize, group_size: usize) -> Vec // ------ fix elements -------------------------- pub fn generate_imports_list() -> Vec { - let mut imports = vec![]; - imports.push( + vec![ "(import \"runtime\" \"exceptionHandler\" (func $exceptionHandler (type $_t_i32)))" .to_string(), - ); - imports.push( "(import \"runtime\" \"printErrorMessage\" (func $printErrorMessage (type $_t_void)))" .to_string(), - ); - imports.push( "(import \"runtime\" \"writeBufferMessage\" (func $writeBufferMessage (type $_t_void)))" .to_string(), - ); - imports.push( "(import \"runtime\" \"showSharedRWMemory\" (func $showSharedRWMemory (type $_t_void)))" .to_string(), - ); - imports + ] } pub fn generate_memory_def_list(producer: &WASMProducer) -> Vec { - let mut wmemory = vec![]; - wmemory.push(format!("(memory {})", get_initial_size_of_memory(&producer))); - wmemory + vec![format!("(memory {})", get_initial_size_of_memory(producer))] } pub fn generate_types_list() -> Vec { - let mut types = vec![]; - types.push("(type $_t_void (func ))".to_string()); - types.push("(type $_t_ri32 (func (result i32)))".to_string()); - types.push("(type $_t_i32 (func (param i32)))".to_string()); - types.push("(type $_t_i32ri32 (func (param i32) (result i32)))".to_string()); - types.push("(type $_t_i64ri32 (func (param i64) (result i32)))".to_string()); - types.push("(type $_t_i32i32 (func (param i32 i32)))".to_string()); - types.push("(type $_t_i32i32ri32 (func (param i32 i32) (result i32)))".to_string()); - types.push("(type $_t_i32i32i32 (func (param i32 i32 i32)))".to_string()); - types + vec![ + "(type $_t_void (func ))".to_string(), + "(type $_t_ri32 (func (result i32)))".to_string(), + "(type $_t_i32 (func (param i32)))".to_string(), + "(type $_t_i32ri32 (func (param i32) (result i32)))".to_string(), + "(type $_t_i64ri32 (func (param i64) (result i32)))".to_string(), + "(type $_t_i32i32 (func (param i32 i32)))".to_string(), + "(type $_t_i32i32ri32 (func (param i32 i32) (result i32)))".to_string(), + "(type $_t_i32i32i32 (func (param i32 i32 i32)))".to_string(), + ] } pub fn generate_exports_list() -> Vec { - let mut exports = vec![]; - exports.push("(export \"memory\" (memory 0))".to_string()); - exports.push("(export \"getVersion\" (func $getVersion))".to_string()); - exports.push("(export \"getMinorVersion\" (func $getMinorVersion))".to_string()); - exports.push("(export \"getPatchVersion\" (func $getPatchVersion))".to_string()); - exports.push("(export \"getSharedRWMemoryStart\" (func $getSharedRWMemoryStart))".to_string()); - exports.push("(export \"readSharedRWMemory\" (func $readSharedRWMemory))".to_string()); - exports.push("(export \"writeSharedRWMemory\" (func $writeSharedRWMemory))".to_string()); - exports.push("(export \"init\" (func $init))".to_string()); - exports.push("(export \"setInputSignal\" (func $setInputSignal))".to_string()); - exports.push("(export \"getInputSignalSize\" (func $getInputSignalSize))".to_string()); - exports.push("(export \"getRawPrime\" (func $getRawPrime))".to_string()); - exports.push("(export \"getFieldNumLen32\" (func $getFieldNumLen32))".to_string()); - exports.push("(export \"getWitnessSize\" (func $getWitnessSize))".to_string()); - exports.push("(export \"getInputSize\" (func $getInputSize))".to_string()); - exports.push("(export \"getWitness\" (func $getWitness))".to_string()); - exports.push("(export \"getMessageChar\" (func $getMessageChar))".to_string()); - exports + vec![ + "(export \"memory\" (memory 0))".to_string(), + "(export \"getVersion\" (func $getVersion))".to_string(), + "(export \"getMinorVersion\" (func $getMinorVersion))".to_string(), + "(export \"getPatchVersion\" (func $getPatchVersion))".to_string(), + "(export \"getSharedRWMemoryStart\" (func $getSharedRWMemoryStart))".to_string(), + "(export \"readSharedRWMemory\" (func $readSharedRWMemory))".to_string(), + "(export \"writeSharedRWMemory\" (func $writeSharedRWMemory))".to_string(), + "(export \"init\" (func $init))".to_string(), + "(export \"setInputSignal\" (func $setInputSignal))".to_string(), + "(export \"getInputSignalSize\" (func $getInputSignalSize))".to_string(), + "(export \"getRawPrime\" (func $getRawPrime))".to_string(), + "(export \"getFieldNumLen32\" (func $getFieldNumLen32))".to_string(), + "(export \"getWitnessSize\" (func $getWitnessSize))".to_string(), + "(export \"getInputSize\" (func $getInputSize))".to_string(), + "(export \"getWitness\" (func $getWitness))".to_string(), + "(export \"getMessageChar\" (func $getMessageChar))".to_string(), + ] } pub fn generate_data_list(producer: &WASMProducer) -> Vec { @@ -567,7 +549,7 @@ pub fn generate_data_list(producer: &WASMProducer) -> Vec { producer.get_shared_rw_memory_start() - 8, "\\00\\00\\00\\00\\00\\00\\00\\80" )); - let map = generate_hash_map(&producer.get_main_input_list()); + let map = generate_hash_map(producer.get_main_input_list()); wdata.push(format!( "(data (i32.const {}) \"{}\")", producer.get_input_signals_hashmap_start(), @@ -583,56 +565,56 @@ pub fn generate_data_list(producer: &WASMProducer) -> Vec { wdata.push(format!( "(data (i32.const {}) \"{}\")", producer.get_template_instance_to_io_signal_start(), - generate_data_template_instance_to_io(&producer, producer.get_io_map()) + generate_data_template_instance_to_io(producer, producer.get_io_map()) )); wdata.push(format!( "(data (i32.const {}) \"{}\")", producer.get_io_signals_to_info_start(), - generate_data_io_signals_to_info(&producer, producer.get_io_map()) + generate_data_io_signals_to_info(producer, producer.get_io_map()) )); wdata.push(format!( "(data (i32.const {}) \"{}\")", producer.get_io_signals_info_start(), - generate_data_io_signals_info(&producer, producer.get_io_map()) + generate_data_io_signals_info(producer, producer.get_io_map()) )); let ml = producer.get_message_list(); let m = producer.get_message_list_start(); - for i in 0..ml.len() { - if ml[i].len() < producer.get_size_of_message_in_bytes() { + for (i, item) in ml.iter().enumerate() { + if item.len() < producer.get_size_of_message_in_bytes() { wdata.push(format!( "(data (i32.const {}) \"{}\\00\")", m + i * producer.get_size_of_message_in_bytes(), - ml[i] + item )); } else { wdata.push(format!( "(data (i32.const {}) \"{}\\00\")", m + i * producer.get_size_of_message_in_bytes(), - &ml[i][..producer.get_size_of_message_in_bytes()-1] + &item[..producer.get_size_of_message_in_bytes() - 1] )); } } let st = producer.get_string_table(); let s = producer.get_string_list_start(); - for i in 0..st.len() { - if st[i].len() < producer.get_size_of_message_in_bytes() { + for (i, item) in st.iter().enumerate() { + if item.len() < producer.get_size_of_message_in_bytes() { wdata.push(format!( "(data (i32.const {}) \"{}\\00\")", s + i * producer.get_size_of_message_in_bytes(), - st[i] + item )); } else { wdata.push(format!( "(data (i32.const {}) \"{}\\00\")", s + i * producer.get_size_of_message_in_bytes(), - &st[i][..producer.get_size_of_message_in_bytes()-1] + &item[..producer.get_size_of_message_in_bytes() - 1] )); } } wdata.push(format!( "(data (i32.const {}) \"{}\")", producer.get_constant_numbers_start(), - generate_data_constants(&producer, producer.get_field_constant_list()) + generate_data_constants(producer, producer.get_field_constant_list()) )); wdata } @@ -640,157 +622,143 @@ pub fn generate_data_list(producer: &WASMProducer) -> Vec { // ------ stack handling operations pub fn reserve_stack_fr(producer: &WASMProducer, nbytes: usize) -> Vec { - let mut instructions = vec![]; - instructions.push(set_constant(&nbytes.to_string())); - instructions.push(call("$reserveStackFr")); - instructions.push(set_local(producer.get_cstack_tag())); - instructions + vec![ + set_constant(&nbytes.to_string()), + call("$reserveStackFr"), + set_local(producer.get_cstack_tag()), + ] } pub fn reserve_stack_fr_function_generator() -> Vec { - let mut instructions = vec![]; - let header = "(func $reserveStackFr (type $_t_i32ri32)".to_string(); - instructions.push(header); - instructions.push(" (param $nbytes i32)".to_string()); - instructions.push("(result i32)".to_string()); - instructions.push(" (local $inistack i32)".to_string()); - instructions.push(" (local $newbsize i32)".to_string()); - instructions.push(" (local $memorybsize i32)".to_string()); - instructions.push(set_constant("0")); - instructions.push(load32(None)); - instructions.push(set_local("$inistack")); - instructions.push(get_local("$inistack")); - instructions.push(get_local("$nbytes")); - instructions.push(add32()); - instructions.push(set_local("$newbsize")); - instructions.push(set_constant("0")); - instructions.push(get_local("$newbsize")); - instructions.push(store32(None)); - // check if enough memory; otherwise grow - // bytes per page 64 * 1024 = 2^16 - instructions.push(memory_size()); - instructions.push(set_constant("16")); - instructions.push(shl32()); - instructions.push(set_local("$memorybsize")); - instructions.push(get_local("$newbsize")); - instructions.push(get_local("$memorybsize")); - instructions.push(gt32_u()); - instructions.push(add_if()); - instructions.push(get_local("$newbsize")); - instructions.push(get_local("$memorybsize")); - instructions.push(sub32()); - instructions.push(set_constant("65535")); //64KiB-1 - instructions.push(add32()); - instructions.push(set_constant("16")); - instructions.push(shr32_u()); //needed pages - instructions.push(memory_grow()); - instructions.push(set_constant("-1")); - instructions.push(eq32()); - instructions.push(add_if()); - instructions.push(set_constant(&exception_code_not_enough_memory().to_string())); - instructions.push(call("$exceptionHandler")); - instructions.push(add_end()); - instructions.push(add_end()); - instructions.push(get_local("$inistack")); - instructions.push(")".to_string()); - instructions + vec![ + "(func $reserveStackFr (type $_t_i32ri32)".to_string(), + " (param $nbytes i32)".to_string(), + "(result i32)".to_string(), + " (local $inistack i32)".to_string(), + " (local $newbsize i32)".to_string(), + " (local $memorybsize i32)".to_string(), + set_constant("0"), + load32(None), + set_local("$inistack"), + get_local("$inistack"), + get_local("$nbytes"), + add32(), + set_local("$newbsize"), + set_constant("0"), + get_local("$newbsize"), + store32(None), + // check if enough memory; otherwise grow + // bytes per page 64 * 1024 = 2^16 + memory_size(), + set_constant("16"), + shl32(), + set_local("$memorybsize"), + get_local("$newbsize"), + get_local("$memorybsize"), + gt32_u(), + add_if(), + get_local("$newbsize"), + get_local("$memorybsize"), + sub32(), + set_constant("65535"), //64KiB-1 + add32(), + set_constant("16"), + shr32_u(), //needed pages + memory_grow(), + set_constant("-1"), + eq32(), + add_if(), + set_constant(&exception_code_not_enough_memory().to_string()), + call("$exceptionHandler"), + add_end(), + add_end(), + get_local("$inistack"), + ")".to_string(), + ] } pub fn free_stack(producer: &WASMProducer) -> Vec { - let mut instructions = vec![]; - instructions.push(set_constant("0")); - instructions.push(get_local(producer.get_cstack_tag())); - instructions.push(store32(Option::None)); - instructions + vec![set_constant("0"), get_local(producer.get_cstack_tag()), store32(Option::None)] } // ---------------------- functions ------------------------ pub fn desp_io_subcomponent_generator(producer: &WASMProducer) -> Vec { - let mut instructions = vec![]; - let header = "(func $getOffsetIOSubComponet (type $_t_i32i32ri32)".to_string(); - instructions.push(header); - instructions.push(" (param $comp i32)".to_string()); - instructions.push(" (param $ios i32)".to_string()); - instructions.push("(result i32)".to_string()); - instructions - .push(set_constant(&producer.get_template_instance_to_io_signal_start().to_string())); - instructions.push(get_local("$comp")); - instructions.push(add32()); - instructions.push(load32(None)); - instructions.push(get_local("$ios")); - instructions.push(set_constant("4")); - instructions.push(mul32()); - instructions.push(add32()); - instructions.push(load32(None)); - instructions.push(")".to_string()); - instructions + vec![ + "(func $getOffsetIOSubComponet (type $_t_i32i32ri32)".to_string(), + " (param $comp i32)".to_string(), + " (param $ios i32)".to_string(), + "(result i32)".to_string(), + set_constant(&producer.get_template_instance_to_io_signal_start().to_string()), + get_local("$comp"), + add32(), + load32(None), + get_local("$ios"), + set_constant("4"), + mul32(), + add32(), + load32(None), + ")".to_string(), + ] } pub fn get_shared_rw_memory_start_generator(producer: &WASMProducer) -> Vec { - let mut instructions = vec![]; - let header = "(func $getSharedRWMemoryStart (type $_t_ri32)".to_string(); - instructions.push(header); - instructions.push("(result i32)".to_string()); - instructions.push(set_constant(&producer.get_shared_rw_memory_start().to_string())); - instructions.push(")".to_string()); - instructions + vec![ + "(func $getSharedRWMemoryStart (type $_t_ri32)".to_string(), + "(result i32)".to_string(), + set_constant(&producer.get_shared_rw_memory_start().to_string()), + ")".to_string(), + ] } pub fn read_shared_rw_memory_generator(producer: &WASMProducer) -> Vec { - let mut instructions = vec![]; - let header = "(func $readSharedRWMemory (type $_t_i32ri32)".to_string(); - instructions.push(header); - instructions.push(" (param $p i32)".to_string()); - instructions.push("(result i32)".to_string()); - instructions.push(set_constant(&producer.get_shared_rw_memory_start().to_string())); - instructions.push(get_local("$p")); - instructions.push(set_constant("4")); - instructions.push(mul32()); - instructions.push(add32()); - instructions.push(load32(None)); - instructions.push(")".to_string()); - instructions + vec![ + "(func $readSharedRWMemory (type $_t_i32ri32)".to_string(), + " (param $p i32)".to_string(), + "(result i32)".to_string(), + set_constant(&producer.get_shared_rw_memory_start().to_string()), + get_local("$p"), + set_constant("4"), + mul32(), + add32(), + load32(None), + ")".to_string(), + ] } pub fn write_shared_rw_memory_generator(producer: &WASMProducer) -> Vec { - let mut instructions = vec![]; - let header = "(func $writeSharedRWMemory (type $_t_i32i32)".to_string(); - instructions.push(header); - instructions.push(" (param $p i32)".to_string()); - instructions.push(" (param $v i32)".to_string()); - instructions.push(set_constant(&producer.get_shared_rw_memory_start().to_string())); - instructions.push(get_local("$p")); - instructions.push(set_constant("4")); - instructions.push(mul32()); - instructions.push(add32()); - instructions.push(get_local("$v")); - instructions.push(store32(None)); - instructions.push(")".to_string()); - instructions + vec![ + "(func $writeSharedRWMemory (type $_t_i32i32)".to_string(), + " (param $p i32)".to_string(), + " (param $v i32)".to_string(), + set_constant(&producer.get_shared_rw_memory_start().to_string()), + get_local("$p"), + set_constant("4"), + mul32(), + add32(), + get_local("$v"), + store32(None), + ")".to_string(), + ] } pub fn get_version_generator(producer: &WASMProducer) -> Vec { - let mut instructions = vec![]; - let header = "(func $getVersion (type $_t_ri32)".to_string(); - instructions.push(header); - instructions.push(set_constant(&producer.get_version().to_string())); - instructions.push(")".to_string()); - let header = "(func $getMinorVersion (type $_t_ri32)".to_string(); - instructions.push(header); - instructions.push(set_constant(&producer.get_minor_version().to_string())); - instructions.push(")".to_string()); - let header = "(func $getPatchVersion (type $_t_ri32)".to_string(); - instructions.push(header); - instructions.push(set_constant(&producer.get_patch_version().to_string())); - instructions.push(")".to_string()); - instructions + vec![ + "(func $getVersion (type $_t_ri32)".to_string(), + set_constant(&producer.get_version().to_string()), + ")".to_string(), + "(func $getMinorVersion (type $_t_ri32)".to_string(), + set_constant(&producer.get_minor_version().to_string()), + ")".to_string(), + "(func $getPatchVersion (type $_t_ri32)".to_string(), + set_constant(&producer.get_patch_version().to_string()), + ")".to_string(), + ] } pub fn init_generator(producer: &WASMProducer) -> Vec { let mut instructions = vec![]; - let header = "(func $init (type $_t_i32)".to_string(); - instructions.push(header); + instructions.push("(func $init (type $_t_i32)".to_string()); instructions.push(" (param $t i32)".to_string()); instructions.push(" (local $i i32)".to_string()); instructions.push(format!(" (local {} i32)", producer.get_merror_tag())); @@ -832,105 +800,98 @@ pub fn init_generator(producer: &WASMProducer) -> Vec { // instructions.push(set_constant(&next_to_one.to_string())); // instructions.push(store32(None)); instructions.push(set_constant(&next_to_one.to_string())); - let funcname = format!("${}_create", producer.get_main_header()); - instructions.push(call(&funcname)); + instructions.push(call(&format!("${}_create", producer.get_main_header()))); instructions.push(drop()); if producer.get_number_of_main_inputs() == 0 { - instructions.push(set_constant(&producer.get_component_tree_start().to_string())); - let funcname = format!("${}_run", producer.get_main_header()); - instructions.push(call(&funcname)); - instructions.push(tee_local(producer.get_merror_tag())); - instructions.push(add_if()); - instructions.push(get_local("$merror")); - instructions.push(call("$exceptionHandler")); - instructions.push(add_end()); + instructions.push(set_constant(&producer.get_component_tree_start().to_string())); + instructions.push(call(&format!("${}_run", producer.get_main_header()))); + instructions.push(tee_local(producer.get_merror_tag())); + instructions.push(add_if()); + instructions.push(get_local("$merror")); + instructions.push(call("$exceptionHandler")); + instructions.push(add_end()); } instructions.push(")".to_string()); instructions } pub fn get_input_signal_map_position_generator(producer: &WASMProducer) -> Vec { - let mut instructions = vec![]; - let header = "(func $getInputSignalMapPosition (type $_t_i64ri32)".to_string(); - instructions.push(header); - instructions.push(" (param $hn i64)".to_string()); - instructions.push("(result i32)".to_string()); - instructions.push(" (local $ini i32)".to_string()); - instructions.push(" (local $i i32)".to_string()); - instructions.push(" (local $aux i32)".to_string()); - instructions.push(get_local("$hn")); - instructions.push(wrap_i6432()); - instructions.push(set_constant("255")); - instructions.push(and32()); - instructions.push(set_local("$ini")); - instructions.push(get_local("$ini")); - instructions.push(set_local("$i")); - instructions.push(add_block()); // block 1 - instructions.push(add_loop()); // loop 2 - instructions.push(set_constant(&producer.get_input_signals_hashmap_start().to_string())); - instructions.push(get_local("$i")); - instructions.push(set_constant("16")); // 8(h)+4(p)+4(s) - instructions.push(mul32()); - instructions.push(add32()); - instructions.push(set_local("$aux")); - instructions.push(get_local("$aux")); - instructions.push(load64(None)); - instructions.push(get_local("$hn")); - instructions.push(eq64()); - instructions.push(add_if()); // if 3 - instructions.push(get_local("$aux")); - instructions.push(add_return()); - instructions.push(add_end()); // end if 3 - instructions.push(get_local("$aux")); - instructions.push(load64(None)); - instructions.push(eqz64()); - instructions.push(add_if()); // if 4 - instructions.push(set_constant("0")); // error - instructions.push(add_return()); - instructions.push(add_end()); // end if 4 - instructions.push(get_local("$i")); - instructions.push(set_constant("1")); - instructions.push(add32()); - instructions.push(set_constant("255")); - instructions.push(and32()); - instructions.push(set_local("$i")); - instructions.push(get_local("$i")); - instructions.push(get_local("$ini")); - instructions.push(eq32()); - instructions.push(add_if()); //if 5 - instructions.push(set_constant("0")); // error - instructions.push(add_return()); - instructions.push(add_end()); // end if 5 - instructions.push(br("0")); - instructions.push(add_end()); // end loop 2 - instructions.push(add_end()); // end block 1 - instructions.push(set_constant("0")); - instructions.push(")".to_string()); - instructions + vec![ + "(func $getInputSignalMapPosition (type $_t_i64ri32)".to_string(), + " (param $hn i64)".to_string(), + "(result i32)".to_string(), + " (local $ini i32)".to_string(), + " (local $i i32)".to_string(), + " (local $aux i32)".to_string(), + get_local("$hn"), + wrap_i6432(), + set_constant("255"), + and32(), + set_local("$ini"), + get_local("$ini"), + set_local("$i"), + add_block(), // block 1 + add_loop(), // loop 2 + set_constant(&producer.get_input_signals_hashmap_start().to_string()), + get_local("$i"), + set_constant("16"), // 8(h)+4(p)+4(s) + mul32(), + add32(), + set_local("$aux"), + get_local("$aux"), + load64(None), + get_local("$hn"), + eq64(), + add_if(), // if 3 + get_local("$aux"), + add_return(), + add_end(), // end if 3 + get_local("$aux"), + load64(None), + eqz64(), + add_if(), // if 4 + set_constant("0"), // error + add_return(), + add_end(), // end if 4 + get_local("$i"), + set_constant("1"), + add32(), + set_constant("255"), + and32(), + set_local("$i"), + get_local("$i"), + get_local("$ini"), + eq32(), + add_if(), //if 5 + set_constant("0"), // error + add_return(), + add_end(), // end if 5 + br("0"), + add_end(), // end loop 2 + add_end(), // end block 1 + set_constant("0"), + ")".to_string(), + ] } pub fn check_if_input_signal_set_generator(producer: &WASMProducer) -> Vec { - let mut instructions = vec![]; - let header = "(func $checkIfInputSignalSet (type $_t_i32ri32)".to_string(); - instructions.push(header); - instructions.push(" (param $sip i32)".to_string()); - instructions.push("(result i32)".to_string()); - instructions.push(set_constant(&producer.get_input_signal_set_map_start().to_string())); - instructions.push(get_local("$sip")); - instructions.push(add32()); - instructions.push(load32(None)); - instructions.push(")".to_string()); - instructions + vec![ + "(func $checkIfInputSignalSet (type $_t_i32ri32)".to_string(), + " (param $sip i32)".to_string(), + "(result i32)".to_string(), + set_constant(&producer.get_input_signal_set_map_start().to_string()), + get_local("$sip"), + add32(), + load32(None), + ")".to_string(), + ] } pub fn set_input_signal_generator(producer: &WASMProducer) -> Vec { let mut instructions = vec![]; - let mut code_aux = get_input_signal_map_position_generator(&producer); - instructions.append(&mut code_aux); - code_aux = check_if_input_signal_set_generator(&producer); - instructions.append(&mut code_aux); - let header = "(func $setInputSignal (type $_t_i32i32i32)".to_string(); - instructions.push(header); + instructions.append(&mut get_input_signal_map_position_generator(producer)); + instructions.append(&mut check_if_input_signal_set_generator(producer)); + instructions.push("(func $setInputSignal (type $_t_i32i32i32)".to_string()); instructions.push(" (param $hmsb i32)".to_string()); instructions.push(" (param $hlsb i32)".to_string()); instructions.push(" (param $pos i32)".to_string()); @@ -1035,8 +996,7 @@ pub fn set_input_signal_generator(producer: &WASMProducer) -> Vec Vec Vec { - let mut instructions = vec![]; - let header = "(func $getInputSignalSize (type $_t_i32i32ri32)".to_string(); - instructions.push(header); - instructions.push(" (param $hmsb i32)".to_string()); - instructions.push(" (param $hlsb i32)".to_string()); - instructions.push("(result i32)".to_string()); - instructions.push(get_local("$hmsb")); - instructions.push(extend_i32_u64()); - instructions.push(set_constant_64("32")); - instructions.push(shl64()); - instructions.push(get_local("$hlsb")); - instructions.push(extend_i32_u64()); - instructions.push(or64()); - instructions.push(call("$getInputSignalMapPosition")); - instructions.push(load32(Some("12"))); - instructions.push(")".to_string()); - instructions + vec![ + "(func $getInputSignalSize (type $_t_i32i32ri32)".to_string(), + " (param $hmsb i32)".to_string(), + " (param $hlsb i32)".to_string(), + "(result i32)".to_string(), + get_local("$hmsb"), + extend_i32_u64(), + set_constant_64("32"), + shl64(), + get_local("$hlsb"), + extend_i32_u64(), + or64(), + call("$getInputSignalMapPosition"), + load32(Some("12")), + ")".to_string(), + ] } pub fn get_raw_prime_generator(producer: &WASMProducer) -> Vec { - let mut instructions = vec![]; - let header = "(func $getRawPrime (type $_t_void)".to_string(); - instructions.push(header); - instructions.push(set_constant(&producer.get_raw_prime_start().to_string())); // address of the raw prime number - instructions.push(set_constant(&producer.get_shared_rw_memory_start().to_string())); // address of the shared memory - instructions.push(call("$Fr_int_copy")); - instructions.push(")".to_string()); - instructions + vec![ + "(func $getRawPrime (type $_t_void)".to_string(), + set_constant(&producer.get_raw_prime_start().to_string()), // address of the raw prime number + set_constant(&producer.get_shared_rw_memory_start().to_string()), // address of the shared memory + call("$Fr_int_copy"), + ")".to_string(), + ] } pub fn get_field_num_len32_generator(producer: &WASMProducer) -> Vec { - let mut instructions = vec![]; - let header = "(func $getFieldNumLen32 (type $_t_ri32)".to_string(); - instructions.push(header); - instructions.push("(result i32)".to_string()); - instructions.push(set_constant(&producer.get_size_32_bit().to_string())); - instructions.push(")".to_string()); - instructions + vec![ + "(func $getFieldNumLen32 (type $_t_ri32)".to_string(), + "(result i32)".to_string(), + set_constant(&producer.get_size_32_bit().to_string()), + ")".to_string(), + ] } pub fn get_input_size_generator(producer: &WASMProducer) -> Vec { - let mut instructions = vec![]; - let header = "(func $getInputSize (type $_t_ri32)".to_string(); - instructions.push(header); - instructions.push("(result i32)".to_string()); - instructions.push(set_constant(&producer.get_number_of_main_inputs().to_string())); - instructions.push(")".to_string()); - instructions + vec![ + "(func $getInputSize (type $_t_ri32)".to_string(), + "(result i32)".to_string(), + set_constant(&producer.get_number_of_main_inputs().to_string()), + ")".to_string(), + ] } pub fn get_witness_size_generator(producer: &WASMProducer) -> Vec { - let mut instructions = vec![]; - let header = "(func $getWitnessSize (type $_t_ri32)".to_string(); - instructions.push(header); - instructions.push("(result i32)".to_string()); - instructions.push(set_constant(&producer.get_number_of_witness().to_string())); - instructions.push(")".to_string()); - instructions + vec![ + "(func $getWitnessSize (type $_t_ri32)".to_string(), + "(result i32)".to_string(), + set_constant(&producer.get_number_of_witness().to_string()), + ")".to_string(), + ] } +#[allow(clippy::vec_init_then_push)] pub fn copy_32_in_shared_rw_memory_generator(producer: &WASMProducer) -> Vec { let mut instructions = vec![]; - let header = "(func $copy32inSharedRWMemory (type $_t_i32)".to_string(); //receives i32 to be put in 0 of SharedRWMemory - instructions.push(header); + instructions.push("(func $copy32inSharedRWMemory (type $_t_i32)".to_string()); //receives i32 to be put in 0 of SharedRWMemory instructions.push(" (param $p i32)".to_string()); instructions.push(set_constant(&producer.get_shared_rw_memory_start().to_string())); instructions.push(get_local("$p")); @@ -1123,11 +1078,10 @@ pub fn copy_32_in_shared_rw_memory_generator(producer: &WASMProducer) -> Vec Vec Vec { let mut instructions = vec![]; - let header = "(func $copyFr2SharedRWMemory (type $_t_i32)".to_string(); //receives address to be copied - instructions.push(header); + instructions.push("(func $copyFr2SharedRWMemory (type $_t_i32)".to_string()); //receives address to be copied instructions.push(" (param $p i32)".to_string()); let pos = producer.get_shared_rw_memory_start() - 8; instructions.push(set_constant(&pos.to_string())); @@ -1150,8 +1103,7 @@ pub fn copy_fr_in_shared_rw_memory_generator(producer: &WASMProducer) -> Vec Vec { let mut instructions = vec![]; - let header = "(func $getWitness (type $_t_i32)".to_string(); - instructions.push(header); + instructions.push("(func $getWitness (type $_t_i32)".to_string()); instructions.push(" (param $p i32)".to_string()); instructions.push(" (local $c i32)".to_string()); instructions.push(set_constant(&producer.get_witness_signal_id_list_start().to_string())); @@ -1176,275 +1128,275 @@ pub fn get_witness_generator(producer: &WASMProducer) -> Vec { } pub fn get_message_char_generator(producer: &WASMProducer) -> Vec { - let mut instructions = vec![]; - let header = "(func $getMessageChar (type $_t_ri32)".to_string(); - instructions.push(header); - instructions.push(" (local $c i32)".to_string()); - instructions.push(set_constant(&producer.get_message_buffer_counter_position().to_string())); - instructions.push(load32(None)); // current position in buffer - instructions.push(set_local("$c")); - instructions.push(get_local("$c")); - instructions.push(set_constant(&producer.get_size_of_message_buffer_in_bytes().to_string())); - instructions.push(ge32_u()); - instructions.push(add_if()); - instructions.push(set_constant("0")); - instructions.push(add_return()); - instructions.push(add_else()); - instructions.push(set_constant(&producer.get_message_buffer_start().to_string())); - instructions.push(get_local("$c")); - instructions.push(add32()); - instructions.push(load32_8u(None)); - instructions.push(set_constant(&producer.get_message_buffer_counter_position().to_string())); - instructions.push(get_local("$c")); - instructions.push(set_constant("1")); - instructions.push(add32()); - instructions.push(store32(None)); // new current position in buffer - instructions.push(add_return()); - instructions.push(add_end()); - instructions.push(set_constant("0")); - instructions.push(")".to_string()); - instructions + vec![ + "(func $getMessageChar (type $_t_ri32)".to_string(), + " (local $c i32)".to_string(), + set_constant(&producer.get_message_buffer_counter_position().to_string()), + load32(None), // current position in buffer + set_local("$c"), + get_local("$c"), + set_constant(&producer.get_size_of_message_buffer_in_bytes().to_string()), + ge32_u(), + add_if(), + set_constant("0"), + add_return(), + add_else(), + set_constant(&producer.get_message_buffer_start().to_string()), + get_local("$c"), + add32(), + load32_8u(None), + set_constant(&producer.get_message_buffer_counter_position().to_string()), + get_local("$c"), + set_constant("1"), + add32(), + store32(None), // new current position in buffer + add_return(), + add_end(), + set_constant("0"), + ")".to_string(), + ] } pub fn build_log_message_generator(producer: &WASMProducer) -> Vec { - let mut instructions = vec![]; - let header = "(func $buildLogMessage (type $_t_i32)".to_string(); - instructions.push(header); - instructions.push(" (param $m i32)".to_string()); //string position - instructions.push(" (local $em i32)".to_string()); //position in error message - instructions.push(" (local $bm i32)".to_string()); //position in buffer - instructions.push(" (local $mc i32)".to_string()); //message char - instructions.push(get_local("$m")); - instructions.push(set_local("$em")); - instructions.push(set_constant(&producer.get_message_buffer_start().to_string())); - instructions.push(set_local("$bm")); - instructions.push(add_block()); - instructions.push(add_loop()); //move bytes until end of message or zero found - // check if end of message - let final_pos = producer.get_size_of_message_in_bytes() + producer.get_message_buffer_start(); - instructions.push(set_constant(&final_pos.to_string())); - instructions.push(get_local("$em")); - instructions.push(eq32()); - instructions.push(br_if("1")); // jump to end of block 1 - instructions.push(get_local("$em")); - instructions.push(load32_8u(None)); - instructions.push(set_local("$mc")); - instructions.push(get_local("$mc")); - instructions.push(eqz32()); - instructions.push(br_if("1")); // jump to end of block 1 - instructions.push(get_local("$bm")); - instructions.push(get_local("$mc")); - instructions.push(store32_8(None)); - instructions.push(get_local("$em")); - instructions.push(set_constant("1")); - instructions.push(add32()); - instructions.push(set_local("$em")); - instructions.push(get_local("$bm")); - instructions.push(set_constant("1")); - instructions.push(add32()); - instructions.push(set_local("$bm")); - instructions.push(br("0")); - instructions.push(add_end()); - instructions.push(add_end()); - //fill rest of buffer with 0's - instructions.push(add_block()); - instructions.push(add_loop()); - instructions.push(get_local("$bm")); - let buff_final_pos = - producer.get_message_buffer_start() + producer.get_size_of_message_buffer_in_bytes(); - instructions.push(set_constant(&buff_final_pos.to_string())); - instructions.push(eq32()); - instructions.push(br_if("1")); //jump to the end of block - instructions.push(get_local("$bm")); - instructions.push(set_constant("0")); - instructions.push(store32_8(None)); // stores the digit in the buffer - instructions.push(get_local("$bm")); - instructions.push(set_constant("1")); - instructions.push(add32()); - instructions.push(set_local("$bm")); - instructions.push(br("0")); // jump to the loop - instructions.push(add_end()); - instructions.push(add_end()); - // initialize message buffer position to 0 - instructions.push(set_constant(&producer.get_message_buffer_counter_position().to_string())); - instructions.push(set_constant("0")); - instructions.push(store32(None)); - instructions.push(")".to_string()); - instructions + vec![ + "(func $buildLogMessage (type $_t_i32)".to_string(), + " (param $m i32)".to_string(), //string position + " (local $em i32)".to_string(), //position in error message + " (local $bm i32)".to_string(), //position in buffer + " (local $mc i32)".to_string(), //message char + get_local("$m"), + set_local("$em"), + set_constant(&producer.get_message_buffer_start().to_string()), + set_local("$bm"), + add_block(), + add_loop(), //move bytes until end of message or zero found + set_constant( + &(producer.get_size_of_message_in_bytes() + producer.get_message_buffer_start()) + .to_string(), + ), // check if end of message + get_local("$em"), + eq32(), + br_if("1"), // jump to end of block 1 + get_local("$em"), + load32_8u(None), + set_local("$mc"), + get_local("$mc"), + eqz32(), + br_if("1"), // jump to end of block 1 + get_local("$bm"), + get_local("$mc"), + store32_8(None), + get_local("$em"), + set_constant("1"), + add32(), + set_local("$em"), + get_local("$bm"), + set_constant("1"), + add32(), + set_local("$bm"), + br("0"), + add_end(), + add_end(), + //fill rest of buffer with 0's + add_block(), + add_loop(), + get_local("$bm"), + set_constant( + &(producer.get_message_buffer_start() + producer.get_size_of_message_buffer_in_bytes()) + .to_string(), + ), + eq32(), + br_if("1"), //jump to the end of block + get_local("$bm"), + set_constant("0"), + store32_8(None), // stores the digit in the buffer + get_local("$bm"), + set_constant("1"), + add32(), + set_local("$bm"), + br("0"), // jump to the loop + add_end(), + add_end(), + // initialize message buffer position to 0 + set_constant(&producer.get_message_buffer_counter_position().to_string()), + set_constant("0"), + store32(None), + ")".to_string(), + ] } pub fn build_buffer_message_generator(producer: &WASMProducer) -> Vec { - let mut instructions = vec![]; - let header = "(func $buildBufferMessage (type $_t_i32i32)".to_string(); - instructions.push(header); - instructions.push(" (param $m i32)".to_string()); //message id - instructions.push(" (param $l i32)".to_string()); //line - instructions.push(" (local $em i32)".to_string()); //position in error message - instructions.push(" (local $bm i32)".to_string()); //position in buffer - instructions.push(" (local $mc i32)".to_string()); //message char - instructions.push(" (local $p10 i32)".to_string()); //power of 10 - instructions.push(set_constant(&producer.get_message_list_start().to_string())); - instructions.push(get_local("$m")); - instructions.push(set_constant(&producer.get_size_of_message_in_bytes().to_string())); - instructions.push(mul32()); - instructions.push(add32()); - instructions.push(set_local("$em")); - instructions.push(set_constant(&producer.get_message_buffer_start().to_string())); - instructions.push(set_local("$bm")); - instructions.push(add_block()); - instructions.push(add_loop()); //move bytes until end of message or zero found - // check if end of message - let final_pos = producer.get_size_of_message_in_bytes() + producer.get_message_buffer_start(); - instructions.push(set_constant(&final_pos.to_string())); - instructions.push(get_local("$em")); - instructions.push(eq32()); - instructions.push(br_if("1")); // jump to end of block 1 - instructions.push(get_local("$em")); - instructions.push(load32_8u(None)); - instructions.push(set_local("$mc")); - instructions.push(get_local("$mc")); - instructions.push(eqz32()); - instructions.push(br_if("1")); // jump to end of block 1 - instructions.push(get_local("$bm")); - instructions.push(get_local("$mc")); - instructions.push(store32_8(None)); - instructions.push(get_local("$em")); - instructions.push(set_constant("1")); - instructions.push(add32()); - instructions.push(set_local("$em")); - instructions.push(get_local("$bm")); - instructions.push(set_constant("1")); - instructions.push(add32()); - instructions.push(set_local("$bm")); - instructions.push(br("0")); - instructions.push(add_end()); - instructions.push(add_end()); - //adding the line " line: " - instructions.push(get_local("$bm")); - instructions.push(set_constant("0x20")); //space - instructions.push(store32_8(None)); - instructions.push(get_local("$bm")); - instructions.push(set_constant("1")); - instructions.push(add32()); - instructions.push(set_local("$bm")); - instructions.push(get_local("$bm")); - instructions.push(set_constant("0x6C")); //l - instructions.push(store32_8(None)); - instructions.push(get_local("$bm")); - instructions.push(set_constant("1")); - instructions.push(add32()); - instructions.push(set_local("$bm")); - instructions.push(get_local("$bm")); - instructions.push(set_constant("0x69")); //i - instructions.push(store32_8(None)); - instructions.push(get_local("$bm")); - instructions.push(set_constant("1")); - instructions.push(add32()); - instructions.push(set_local("$bm")); - instructions.push(get_local("$bm")); - instructions.push(set_constant("0x6E")); //n - instructions.push(store32_8(None)); - instructions.push(get_local("$bm")); - instructions.push(set_constant("1")); - instructions.push(add32()); - instructions.push(set_local("$bm")); - instructions.push(get_local("$bm")); - instructions.push(set_constant("0x65")); //e - instructions.push(store32_8(None)); - instructions.push(get_local("$bm")); - instructions.push(set_constant("1")); - instructions.push(add32()); - instructions.push(set_local("$bm")); - instructions.push(get_local("$bm")); - instructions.push(set_constant("0x3A")); //: - instructions.push(store32_8(None)); - instructions.push(get_local("$bm")); - instructions.push(set_constant("1")); - instructions.push(add32()); - instructions.push(set_local("$bm")); - instructions.push(get_local("$bm")); - instructions.push(set_constant("0x20")); //space - instructions.push(store32_8(None)); - instructions.push(get_local("$bm")); - instructions.push(set_constant("1")); - instructions.push(add32()); - instructions.push(set_local("$bm")); - //adding the line number - //compute the power of 10 with the number of digits - instructions.push(set_constant("1")); - instructions.push(set_local("$p10")); - instructions.push(add_block()); - instructions.push(add_loop()); - //check if $p10 * 10 > $l - instructions.push(get_local("$p10")); - instructions.push(set_constant("10")); - instructions.push(mul32()); - instructions.push(get_local("$l")); - instructions.push(gt32_u()); - instructions.push(br_if("1")); // jump to end of block 1 - instructions.push(get_local("$p10")); - instructions.push(set_constant("10")); - instructions.push(mul32()); - instructions.push(set_local("$p10")); - instructions.push(br("0")); // jump to the loop - instructions.push(add_end()); - instructions.push(add_end()); - - //now we extract the digits and add them to buffer. We assume line > 0 - instructions.push(add_block()); - instructions.push(add_loop()); - //check if $p10 != 0 - instructions.push(get_local("$p10")); - instructions.push(eqz32()); - instructions.push(br_if("1")); // jump to end of block 1 - instructions.push(get_local("$bm")); //next position in the buffer - //get the next digit left-to-right - instructions.push(get_local("$l")); - instructions.push(get_local("$p10")); - instructions.push(div32_u()); // highest digit - instructions.push(set_constant("0x30")); - instructions.push(add32()); // hex of the digit - instructions.push(store32_8(None)); // stores the digit in the buffer - instructions.push(get_local("$bm")); - instructions.push(set_constant("1")); - instructions.push(add32()); - instructions.push(set_local("$bm")); - instructions.push(get_local("$l")); - instructions.push(get_local("$p10")); - instructions.push(rem32_u()); // remove the highest digit - instructions.push(set_local("$l")); - instructions.push(get_local("$p10")); - instructions.push(set_constant("10")); - instructions.push(div32_u()); // decrease power of 10 - instructions.push(set_local("$p10")); - instructions.push(br("0")); // jump to the loop - instructions.push(add_end()); - instructions.push(add_end()); - //fill rest of buffer with 0's - instructions.push(add_block()); - instructions.push(add_loop()); - instructions.push(get_local("$bm")); - let buff_final_pos = - producer.get_message_buffer_start() + producer.get_size_of_message_buffer_in_bytes(); - instructions.push(set_constant(&buff_final_pos.to_string())); - instructions.push(eq32()); - instructions.push(br_if("1")); //jump to the end of block - instructions.push(get_local("$bm")); - instructions.push(set_constant("0")); - instructions.push(store32_8(None)); // stores the digit in the buffer - instructions.push(get_local("$bm")); - instructions.push(set_constant("1")); - instructions.push(add32()); - instructions.push(set_local("$bm")); - instructions.push(br("0")); // jump to the loop - instructions.push(add_end()); - instructions.push(add_end()); - // initialize message buffer position to 0 - instructions.push(set_constant(&producer.get_message_buffer_counter_position().to_string())); - instructions.push(set_constant("0")); - instructions.push(store32(None)); - instructions.push(")".to_string()); - instructions + vec![ + "(func $buildBufferMessage (type $_t_i32i32)".to_string(), + " (param $m i32)".to_string(), //message id + " (param $l i32)".to_string(), //line + " (local $em i32)".to_string(), //position in error message + " (local $bm i32)".to_string(), //position in buffer + " (local $mc i32)".to_string(), //message char + " (local $p10 i32)".to_string(), //power of 10 + set_constant(&producer.get_message_list_start().to_string()), + get_local("$m"), + set_constant(&producer.get_size_of_message_in_bytes().to_string()), + mul32(), + add32(), + set_local("$em"), + set_constant(&producer.get_message_buffer_start().to_string()), + set_local("$bm"), + add_block(), + add_loop(), //move bytes until end of message or zero found + set_constant( + &(producer.get_size_of_message_in_bytes() + producer.get_message_buffer_start()) + .to_string(), + ), // check if end of message + get_local("$em"), + eq32(), + br_if("1"), // jump to end of block 1 + get_local("$em"), + load32_8u(None), + set_local("$mc"), + get_local("$mc"), + eqz32(), + br_if("1"), // jump to end of block 1 + get_local("$bm"), + get_local("$mc"), + store32_8(None), + get_local("$em"), + set_constant("1"), + add32(), + set_local("$em"), + get_local("$bm"), + set_constant("1"), + add32(), + set_local("$bm"), + br("0"), + add_end(), + add_end(), + //adding the line " line: " + get_local("$bm"), + set_constant("0x20"), //space + store32_8(None), + get_local("$bm"), + set_constant("1"), + add32(), + set_local("$bm"), + get_local("$bm"), + set_constant("0x6C"), //l + store32_8(None), + get_local("$bm"), + set_constant("1"), + add32(), + set_local("$bm"), + get_local("$bm"), + set_constant("0x69"), //i + store32_8(None), + get_local("$bm"), + set_constant("1"), + add32(), + set_local("$bm"), + get_local("$bm"), + set_constant("0x6E"), //n + store32_8(None), + get_local("$bm"), + set_constant("1"), + add32(), + set_local("$bm"), + get_local("$bm"), + set_constant("0x65"), //e + store32_8(None), + get_local("$bm"), + set_constant("1"), + add32(), + set_local("$bm"), + get_local("$bm"), + set_constant("0x3A"), //: + store32_8(None), + get_local("$bm"), + set_constant("1"), + add32(), + set_local("$bm"), + get_local("$bm"), + set_constant("0x20"), //space + store32_8(None), + get_local("$bm"), + set_constant("1"), + add32(), + set_local("$bm"), + //adding the line number + //compute the power of 10 with the number of digits + set_constant("1"), + set_local("$p10"), + add_block(), + add_loop(), + //check if $p10 * 10 > $l + get_local("$p10"), + set_constant("10"), + mul32(), + get_local("$l"), + gt32_u(), + br_if("1"), // jump to end of block 1 + get_local("$p10"), + set_constant("10"), + mul32(), + set_local("$p10"), + br("0"), // jump to the loop + add_end(), + add_end(), + //now we extract the digits and add them to buffer. We assume line > 0 + add_block(), + add_loop(), + //check if $p10 != 0 + get_local("$p10"), + eqz32(), + br_if("1"), // jump to end of block 1 + get_local("$bm"), //next position in the buffer + //get the next digit left-to-right + get_local("$l"), + get_local("$p10"), + div32_u(), // highest digit + set_constant("0x30"), + add32(), // hex of the digit + store32_8(None), // stores the digit in the buffer + get_local("$bm"), + set_constant("1"), + add32(), + set_local("$bm"), + get_local("$l"), + get_local("$p10"), + rem32_u(), // remove the highest digit + set_local("$l"), + get_local("$p10"), + set_constant("10"), + div32_u(), // decrease power of 10 + set_local("$p10"), + br("0"), // jump to the loop + add_end(), + add_end(), + //fill rest of buffer with 0's + add_block(), + add_loop(), + get_local("$bm"), + set_constant( + &(producer.get_message_buffer_start() + producer.get_size_of_message_buffer_in_bytes()) + .to_string(), + ), + eq32(), + br_if("1"), //jump to the end of block + get_local("$bm"), + set_constant("0"), + store32_8(None), // stores the digit in the buffer + get_local("$bm"), + set_constant("1"), + add32(), + set_local("$bm"), + br("0"), // jump to the loop + add_end(), + add_end(), + // initialize message buffer position to 0 + set_constant(&producer.get_message_buffer_counter_position().to_string()), + set_constant("0"), + store32(None), + ")".to_string(), + ] } pub fn generate_table_of_template_runs(producer: &WASMProducer) -> Vec { @@ -1546,10 +1498,8 @@ fn get_file_instructions(name: &str) -> Vec { if Path::new(&path).exists() { let file = File::open(path).unwrap(); let reader = BufReader::new(file); - for rline in reader.lines() { - if let Result::Ok(line) = rline { - instructions.push(line); - } + for line in reader.lines().flatten() { + instructions.push(line); } } else { panic!("FILE NOT FOUND {}", name); @@ -1629,6 +1579,7 @@ pub fn generate_utils_js_file(js_folder: &PathBuf) -> std::io::Result<()> { } */ + #[allow(clippy::ptr_arg)] pub fn generate_generate_witness_js_file(js_folder: &PathBuf) -> std::io::Result<()> { use std::io::BufWriter; let mut file_path = js_folder.clone(); @@ -1646,6 +1597,7 @@ pub fn generate_generate_witness_js_file(js_folder: &PathBuf) -> std::io::Result Ok(()) } +#[allow(clippy::ptr_arg)] pub fn generate_witness_calculator_js_file(js_folder: &PathBuf) -> std::io::Result<()> { use std::io::BufWriter; let mut file_path = js_folder.clone(); @@ -1668,7 +1620,7 @@ mod tests { use super::*; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::path::Path; - const LOCATION: &'static str = "../target/code_generator_test"; + const LOCATION: &str = "../target/code_generator_test"; fn create_producer() -> WASMProducer { WASMProducer::default() diff --git a/compiler/src/circuit_design/build.rs b/compiler/src/circuit_design/build.rs index 1e71090cc..a0d53a6c9 100644 --- a/compiler/src/circuit_design/build.rs +++ b/compiler/src/circuit_design/build.rs @@ -26,23 +26,9 @@ fn build_template_instances( ti: Vec, mut field_tracker: FieldTracker, ) -> (FieldTracker, HashMap) { - - fn compute_jump(lengths: &Vec, indexes: &[usize]) -> usize { - let mut jump = 0; - let mut full_length = lengths.iter().fold(1, |p, c| p * (*c)); - let mut lengths = lengths.clone(); - lengths.reverse(); - for index in indexes { - let length = lengths.pop().unwrap(); - full_length /= length; - jump += (*index) * full_length; - } - jump - } let mut cmp_id = 0; - let mut tmp_id = 0; let mut string_table = HashMap::new(); - for template in ti { + for (tmp_id, template) in ti.into_iter().enumerate() { let header = template.template_header; let name = template.template_name; let instance_values = template.header; @@ -62,10 +48,8 @@ fn build_template_instances( match component_to_parallel.get_mut(&trigger.component_name){ Some(parallel_info) => { parallel_info.positions_to_parallel.insert(trigger.indexed_with.clone(), trigger.is_parallel); - if parallel_info.uniform_parallel_value.is_some(){ - if parallel_info.uniform_parallel_value.unwrap() != trigger.is_parallel{ - parallel_info.uniform_parallel_value = None; - } + if parallel_info.uniform_parallel_value.is_some() && parallel_info.uniform_parallel_value.unwrap() != trigger.is_parallel { + parallel_info.uniform_parallel_value = None; } }, None => { @@ -96,7 +80,7 @@ fn build_template_instances( fresh_cmp_id: cmp_id, components: template.components, template_database: &c_info.template_database, - string_table : string_table, + string_table, signals_to_tags: template.signals_to_tags, }; let mut template_info = TemplateCodeInfo { @@ -123,7 +107,6 @@ fn build_template_instances( string_table = out.string_table; cmp_id = out.next_cmp_id; circuit.add_template_code(template_info); - tmp_id += 1; } (field_tracker, string_table) } @@ -160,7 +143,7 @@ fn build_function_instances( cmp_to_type: HashMap::with_capacity(0), component_to_parallel: HashMap::with_capacity(0), template_database: &c_info.template_database, - string_table : string_table, + string_table, signals_to_tags: BTreeMap::new(), }; let mut function_info = FunctionCodeInfo { @@ -345,7 +328,7 @@ fn write_main_inputs_log(vcp: &VCP) { fn get_number_version(version: &str) -> (usize, usize, usize) { use std::str::FromStr; - let version_splitted: Vec<&str> = version.split(".").collect(); + let version_splitted: Vec<&str> = version.split('.').collect(); ( usize::from_str(version_splitted[0]).unwrap(), usize::from_str(version_splitted[1]).unwrap(), @@ -365,9 +348,11 @@ pub fn build_circuit(vcp: VCP, flag: CompilationFlags, version: &str) -> Circuit write_main_inputs_log(&vcp); } let template_database = TemplateDB::build(&vcp.templates); - let mut circuit = Circuit::default(); - circuit.wasm_producer = initialize_wasm_producer(&vcp, &template_database, flag.wat_flag, version); - circuit.c_producer = initialize_c_producer(&vcp, &template_database, version); + let mut circuit = Circuit { + wasm_producer: initialize_wasm_producer(&vcp, &template_database, flag.wat_flag, version), + c_producer: initialize_c_producer(&vcp, &template_database, version), + ..Default::default() + }; let field_tracker = FieldTracker::new(); let circuit_info = CircuitInfo { diff --git a/compiler/src/circuit_design/circuit.rs b/compiler/src/circuit_design/circuit.rs index 4ec5242f3..c92b5120a 100644 --- a/compiler/src/circuit_design/circuit.rs +++ b/compiler/src/circuit_design/circuit.rs @@ -12,6 +12,7 @@ pub struct CompilationFlags { pub wat_flag:bool, } +#[derive(Default)] pub struct Circuit { pub wasm_producer: WASMProducer, pub c_producer: CProducer, @@ -19,16 +20,7 @@ pub struct Circuit { pub functions: Vec, } -impl Default for Circuit { - fn default() -> Self { - Circuit { - c_producer: CProducer::default(), - wasm_producer: WASMProducer::default(), - templates: Vec::new(), - functions: Vec::new(), - } - } -} + impl WriteWasm for Circuit { fn produce_wasm(&self, producer: &WASMProducer) -> Vec { @@ -37,7 +29,7 @@ impl WriteWasm for Circuit { code.push("(module".to_string()); let mut code_aux = generate_imports_list(); code.append(&mut code_aux); - code_aux = generate_memory_def_list(&producer); + code_aux = generate_memory_def_list(producer); code.append(&mut code_aux); code_aux = fr_types(&producer.prime_str); @@ -51,61 +43,61 @@ impl WriteWasm for Circuit { code_aux = fr_code(&producer.prime_str); code.append(&mut code_aux); - code_aux = desp_io_subcomponent_generator(&producer); + code_aux = desp_io_subcomponent_generator(producer); code.append(&mut code_aux); - code_aux = get_version_generator(&producer); + code_aux = get_version_generator(producer); code.append(&mut code_aux); - code_aux = get_shared_rw_memory_start_generator(&producer); + code_aux = get_shared_rw_memory_start_generator(producer); code.append(&mut code_aux); - code_aux = read_shared_rw_memory_generator(&producer); + code_aux = read_shared_rw_memory_generator(producer); code.append(&mut code_aux); - code_aux = write_shared_rw_memory_generator(&producer); + code_aux = write_shared_rw_memory_generator(producer); code.append(&mut code_aux); code_aux = reserve_stack_fr_function_generator(); code.append(&mut code_aux); - code_aux = init_generator(&producer); + code_aux = init_generator(producer); code.append(&mut code_aux); - code_aux = set_input_signal_generator(&producer); + code_aux = set_input_signal_generator(producer); code.append(&mut code_aux); - code_aux = get_input_signal_size_generator(&producer); + code_aux = get_input_signal_size_generator(producer); code.append(&mut code_aux); - code_aux = get_raw_prime_generator(&producer); + code_aux = get_raw_prime_generator(producer); code.append(&mut code_aux); - code_aux = get_field_num_len32_generator(&producer); + code_aux = get_field_num_len32_generator(producer); code.append(&mut code_aux); - code_aux = get_input_size_generator(&producer); + code_aux = get_input_size_generator(producer); code.append(&mut code_aux); - code_aux = get_witness_size_generator(&producer); + code_aux = get_witness_size_generator(producer); code.append(&mut code_aux); - code_aux = get_witness_generator(&producer); + code_aux = get_witness_generator(producer); code.append(&mut code_aux); - code_aux = copy_32_in_shared_rw_memory_generator(&producer); + code_aux = copy_32_in_shared_rw_memory_generator(producer); code.append(&mut code_aux); - code_aux = copy_fr_in_shared_rw_memory_generator(&producer); + code_aux = copy_fr_in_shared_rw_memory_generator(producer); code.append(&mut code_aux); - code_aux = get_message_char_generator(&producer); + code_aux = get_message_char_generator(producer); code.append(&mut code_aux); - code_aux = build_buffer_message_generator(&producer); + code_aux = build_buffer_message_generator(producer); code.append(&mut code_aux); - code_aux = build_log_message_generator(&producer); + code_aux = build_log_message_generator(producer); code.append(&mut code_aux); // Actual code from the program @@ -118,13 +110,13 @@ impl WriteWasm for Circuit { code.append(&mut t.produce_wasm(producer)); } - code_aux = generate_table_of_template_runs(&producer); + code_aux = generate_table_of_template_runs(producer); code.append(&mut code_aux); code_aux = fr_data(&producer.prime_str); code.append(&mut code_aux); - code_aux = generate_data_list(&producer); + code_aux = generate_data_list(producer); code.append(&mut code_aux); code.push(")".to_string()); @@ -142,7 +134,7 @@ impl WriteWasm for Circuit { writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = generate_memory_def_list(&producer); + code_aux = generate_memory_def_list(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; @@ -167,27 +159,27 @@ impl WriteWasm for Circuit { writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = desp_io_subcomponent_generator(&producer); + code_aux = desp_io_subcomponent_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = get_version_generator(&producer); + code_aux = get_version_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = get_shared_rw_memory_start_generator(&producer); + code_aux = get_shared_rw_memory_start_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = read_shared_rw_memory_generator(&producer); + code_aux = read_shared_rw_memory_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = write_shared_rw_memory_generator(&producer); + code_aux = write_shared_rw_memory_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; @@ -197,67 +189,67 @@ impl WriteWasm for Circuit { writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = init_generator(&producer); + code_aux = init_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = set_input_signal_generator(&producer); + code_aux = set_input_signal_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = get_input_signal_size_generator(&producer); + code_aux = get_input_signal_size_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = get_raw_prime_generator(&producer); + code_aux = get_raw_prime_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = get_field_num_len32_generator(&producer); + code_aux = get_field_num_len32_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = get_input_size_generator(&producer); + code_aux = get_input_size_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = get_witness_size_generator(&producer); + code_aux = get_witness_size_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = get_witness_generator(&producer); + code_aux = get_witness_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = copy_32_in_shared_rw_memory_generator(&producer); + code_aux = copy_32_in_shared_rw_memory_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = copy_fr_in_shared_rw_memory_generator(&producer); + code_aux = copy_fr_in_shared_rw_memory_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = get_message_char_generator(&producer); + code_aux = get_message_char_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = build_buffer_message_generator(&producer); + code_aux = build_buffer_message_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = build_log_message_generator(&producer); + code_aux = build_log_message_generator(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; @@ -274,7 +266,7 @@ impl WriteWasm for Circuit { //writer.flush().map_err(|_| {})?; } - code_aux = generate_table_of_template_runs(&producer); + code_aux = generate_table_of_template_runs(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; @@ -284,7 +276,7 @@ impl WriteWasm for Circuit { writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; - code_aux = generate_data_list(&producer); + code_aux = generate_data_list(producer); code = merge_code(code_aux); writer.write_all(code.as_bytes()).map_err(|_| {})?; //writer.flush().map_err(|_| {})?; @@ -297,13 +289,14 @@ impl WriteWasm for Circuit { impl WriteC for Circuit { fn produce_c(&self, producer: &CProducer, _parallel: Option) -> (Vec, String) { use c_code_generator::*; - let mut code = vec![]; - // Prologue - code.push("#include ".to_string()); - code.push("#include ".to_string()); - code.push("#include ".to_string()); - code.push("#include \"circom.hpp\"".to_string()); - code.push("#include \"calcwit.hpp\"".to_string()); + let mut code = vec![ + // Prologue + "#include ".to_string(), + "#include ".to_string(), + "#include ".to_string(), + "#include \"circom.hpp\"".to_string(), + "#include \"calcwit.hpp\"".to_string(), + ]; let mut template_headers = collect_template_headers(producer.get_template_instance_list()); let function_headers: Vec<_> = self.functions @@ -399,11 +392,12 @@ impl WriteC for Circuit { } else{ producer.main_header.clone() + "_run" }; - let mut run_args = vec![]; - // run_args.push(CTX_INDEX.to_string()); - run_args.push("0".to_string()); - run_args.push(CIRCOM_CALC_WIT.to_string()); - let run_call = format!("{};", build_call(main_template_run, run_args.clone())); + let run_args = vec![ + // CTX_INDEX.to_string(), + "0".to_string(), + CIRCOM_CALC_WIT.to_string(), + ]; + let run_call = format!("{};", build_call(main_template_run, run_args)); let main_run_body = vec![ctx_index, run_call]; code.push(build_callable(run_circuit, run_circuit_args, main_run_body)); @@ -530,11 +524,12 @@ impl WriteC for Circuit { } else{ producer.main_header.clone() + "_run" }; - let mut run_args = vec![]; - // run_args.push(CTX_INDEX.to_string()); - run_args.push("0".to_string()); - run_args.push(CIRCOM_CALC_WIT.to_string()); - let run_call = format!("{};", build_call(main_template_run, run_args.clone())); + let run_args = vec![ + // CTX_INDEX.to_string(), + "0".to_string(), + CIRCOM_CALC_WIT.to_string(), + ]; + let run_call = format!("{};", build_call(main_template_run, run_args)); let main_run_body = vec![ctx_index, run_call]; code_write = build_callable(run_circuit, run_circuit_args, main_run_body) + "\n"; @@ -574,6 +569,7 @@ impl Circuit { pub fn produce_ir_string_for_function(&self, id: ID) -> String { self.functions[id].to_string() } + #[allow(clippy::result_unit_err)] pub fn produce_c(&self, c_folder: &str, run_name: &str, c_circuit: &mut W, c_dat: &mut W) -> Result<(), ()> { use std::path::Path; let c_folder_path = Path::new(c_folder).to_path_buf(); @@ -588,6 +584,7 @@ impl Circuit { c_code_generator::generate_dat_file(c_dat, &self.c_producer).map_err(|_err| {})?; self.write_c(c_circuit, &self.c_producer) } + #[allow(clippy::result_unit_err)] pub fn produce_wasm(&self, js_folder: &str, _wasm_name: &str, writer: &mut W) -> Result<(), ()> { use std::path::Path; let js_folder_path = Path::new(js_folder).to_path_buf(); diff --git a/compiler/src/circuit_design/template.rs b/compiler/src/circuit_design/template.rs index 399ca43e8..14be0a6d0 100644 --- a/compiler/src/circuit_design/template.rs +++ b/compiler/src/circuit_design/template.rs @@ -16,7 +16,7 @@ pub struct TemplateCodeInfo { pub is_not_parallel_component: bool, pub has_parallel_sub_cmp: bool, pub number_of_inputs: usize, - pub number_of_outputs: usize, + pub number_of_outputs: usize, pub number_of_intermediates: usize, // Not used now pub body: InstructionList, pub var_stack_depth: usize, @@ -24,6 +24,7 @@ pub struct TemplateCodeInfo { pub signal_stack_depth: usize, // Not used now pub number_of_components: usize, } + impl ToString for TemplateCodeInfo { fn to_string(&self) -> String { let mut body = "".to_string(); @@ -33,13 +34,13 @@ impl ToString for TemplateCodeInfo { format!("TEMPLATE({})(\n{})", self.header, body) } } + impl WriteWasm for TemplateCodeInfo { fn produce_wasm(&self, producer: &WASMProducer) -> Vec { use code_producers::wasm_elements::wasm_code_generator::*; // create function code let mut instructions = vec![]; - let funcdef1 = format!("(func ${}_create (type $_t_i32ri32)", self.header); //return offset - instructions.push(funcdef1); + instructions.push(format!("(func ${}_create (type $_t_i32ri32)", self.header)); //return offset instructions.push(format!(" (param {} i32)", producer.get_signal_offset_tag())); instructions.push("(result i32)".to_string()); instructions.push(format!(" (local {} i32)", producer.get_offset_tag())); //here is a local var to be returned @@ -64,9 +65,10 @@ impl WriteWasm for TemplateCodeInfo { //reserve memory for component instructions.push(set_constant(&producer.get_component_free_pos().to_string())); instructions.push(get_local(producer.get_offset_tag())); - let nbytes_component = - producer.get_sub_component_start_in_component() + self.number_of_components * 4; - instructions.push(set_constant(&nbytes_component.to_string())); + instructions.push(set_constant( + &(producer.get_sub_component_start_in_component() + self.number_of_components * 4) + .to_string(), + )); instructions.push(add32()); instructions.push(store32(None)); //add the position of the component in the tree as result @@ -74,11 +76,9 @@ impl WriteWasm for TemplateCodeInfo { instructions.push(")".to_string()); // run function code - - let funcdef2 = format!("(func ${}_run (type $_t_i32ri32)", self.header); - instructions.push(funcdef2); + instructions.push(format!("(func ${}_run (type $_t_i32ri32)", self.header)); instructions.push(format!(" (param {} i32)", producer.get_offset_tag())); - instructions.push("(result i32)".to_string()); //state 0 = OK; > 0 error + instructions.push("(result i32)".to_string()); //state 0 = OK; > 0 error instructions.push(format!(" (local {} i32)", producer.get_cstack_tag())); instructions.push(format!(" (local {} i32)", producer.get_signal_start_tag())); instructions.push(format!(" (local {} i32)", producer.get_sub_cmp_tag())); @@ -123,7 +123,7 @@ impl WriteWasm for TemplateCodeInfo { instructions.append(&mut reserve_stack_fr_code); if producer.needs_comments() { instructions.push(";; start of the template code".to_string()); - } + } //set signalstart local instructions.push(get_local(producer.get_offset_tag())); instructions @@ -131,8 +131,8 @@ impl WriteWasm for TemplateCodeInfo { instructions.push(add32()); instructions.push(load32(None)); instructions.push(set_local(producer.get_signal_start_tag())); - //generate code + //generate code for t in &self.body { let mut instructions_body = t.produce_wasm(producer); instructions.append(&mut instructions_body); @@ -141,7 +141,7 @@ impl WriteWasm for TemplateCodeInfo { //free stack let mut free_stack_code = free_stack(producer); instructions.append(&mut free_stack_code); - instructions.push(set_constant("0")); + instructions.push(set_constant("0")); instructions.push(")".to_string()); instructions } @@ -150,75 +150,78 @@ impl WriteWasm for TemplateCodeInfo { impl WriteC for TemplateCodeInfo { fn produce_c(&self, producer: &CProducer, _parallel: Option) -> (Vec, String) { let mut produced_c = Vec::new(); - if self.is_parallel || self.is_parallel_component{ + if self.is_parallel || self.is_parallel_component { produced_c.append(&mut self.produce_c_parallel_case(producer, true)); } - if !self.is_parallel && self.is_not_parallel_component{ + if !self.is_parallel && self.is_not_parallel_component { produced_c.append(&mut self.produce_c_parallel_case(producer, false)); - } + } (produced_c, "".to_string()) } } - impl TemplateCodeInfo { fn produce_c_parallel_case(&self, producer: &CProducer, parallel: bool) -> Vec { use c_code_generator::*; - let create_header = if parallel {format!("void {}_create_parallel", self.header)} - else{format!("void {}_create", self.header)} ; - let mut create_params = vec![]; - create_params.push(declare_signal_offset()); - create_params.push(declare_component_offset()); - create_params.push(declare_circom_calc_wit()); - create_params.push(declare_component_name()); - create_params.push(declare_component_father()); - let mut create_body = vec![]; + let create_header = if parallel { + format!("void {}_create_parallel", self.header) + } else { + format!("void {}_create", self.header) + }; + let create_params = vec![ + declare_signal_offset(), + declare_component_offset(), + declare_circom_calc_wit(), + declare_component_name(), + declare_component_father(), + ]; + let mut create_body = vec![]; create_body.push(format!( "{}->componentMemory[{}].templateId = {};", CIRCOM_CALC_WIT, - component_offset(), + component_offset(), &self.id.to_string() )); create_body.push(format!( "{}->componentMemory[{}].templateName = \"{}\";", CIRCOM_CALC_WIT, - component_offset(), + component_offset(), &self.name.to_string() )); create_body.push(format!( "{}->componentMemory[{}].signalStart = {};", CIRCOM_CALC_WIT, - component_offset(), - SIGNAL_OFFSET + component_offset(), + SIGNAL_OFFSET )); create_body.push(format!( "{}->componentMemory[{}].inputCounter = {};", CIRCOM_CALC_WIT, - component_offset(), + component_offset(), &self.number_of_inputs.to_string() )); create_body.push(format!( "{}->componentMemory[{}].componentName = {};", CIRCOM_CALC_WIT, - component_offset(), + component_offset(), COMPONENT_NAME )); create_body.push(format!( "{}->componentMemory[{}].idFather = {};", CIRCOM_CALC_WIT, - component_offset(), + component_offset(), COMPONENT_FATHER )); - if self.number_of_components > 0{ + if self.number_of_components > 0 { create_body.push(format!( "{}->componentMemory[{}].subcomponents = new uint[{}]{{0}};", CIRCOM_CALC_WIT, component_offset(), &self.number_of_components.to_string() )); - } else{ + } else { create_body.push(format!( "{}->componentMemory[{}].subcomponents = new uint[{}];", CIRCOM_CALC_WIT, @@ -226,115 +229,141 @@ impl TemplateCodeInfo { &self.number_of_components.to_string() )); } - if self.has_parallel_sub_cmp { + if self.has_parallel_sub_cmp { create_body.push(format!( - "{}->componentMemory[{}].sbct = new std::thread[{}];", - CIRCOM_CALC_WIT, - component_offset(), - &self.number_of_components.to_string() + "{}->componentMemory[{}].sbct = new std::thread[{}];", + CIRCOM_CALC_WIT, + component_offset(), + &self.number_of_components.to_string() )); - create_body.push(format!( - "{}->componentMemory[{}].subcomponentsParallel = new bool[{}];", - CIRCOM_CALC_WIT, - component_offset(), - &self.number_of_components.to_string() - )); - } - if parallel { create_body.push(format!( - "{}->componentMemory[{}].outputIsSet = new bool[{}]();", - CIRCOM_CALC_WIT, - component_offset(), - &self.number_of_outputs.to_string() + "{}->componentMemory[{}].subcomponentsParallel = new bool[{}];", + CIRCOM_CALC_WIT, + component_offset(), + &self.number_of_components.to_string() + )); + } + if parallel { + create_body.push(format!( + "{}->componentMemory[{}].outputIsSet = new bool[{}]();", + CIRCOM_CALC_WIT, + component_offset(), + &self.number_of_outputs.to_string() )); create_body.push(format!( - "{}->componentMemory[{}].mutexes = new std::mutex[{}];", - CIRCOM_CALC_WIT, - component_offset(), - &self.number_of_outputs.to_string() + "{}->componentMemory[{}].mutexes = new std::mutex[{}];", + CIRCOM_CALC_WIT, + component_offset(), + &self.number_of_outputs.to_string() )); create_body.push(format!( - "{}->componentMemory[{}].cvs = new std::condition_variable[{}];", - CIRCOM_CALC_WIT, - component_offset(), - &self.number_of_outputs.to_string() + "{}->componentMemory[{}].cvs = new std::condition_variable[{}];", + CIRCOM_CALC_WIT, + component_offset(), + &self.number_of_outputs.to_string() )); - } - // if has no inputs should be runned - if self.number_of_inputs == 0 { - let cmp_call_name = format!("{}_run", self.header); - let cmp_call_arguments = vec![component_offset(), CIRCOM_CALC_WIT.to_string()]; - create_body.push(format!("{};",build_call(cmp_call_name, cmp_call_arguments))); + } + // if has no inputs should be runned + if self.number_of_inputs == 0 { + let cmp_call_name = format!("{}_run", self.header); + let cmp_call_arguments = vec![component_offset(), CIRCOM_CALC_WIT.to_string()]; + create_body.push(format!("{};", build_call(cmp_call_name, cmp_call_arguments))); } let create_fun = build_callable(create_header, create_params, create_body); - let run_header = if parallel {format!("void {}_run_parallel", self.header)} - else{format!("void {}_run", self.header)} ; - let mut run_params = vec![]; - run_params.push(declare_ctx_index()); - run_params.push(declare_circom_calc_wit()); - let mut run_body = vec![]; - run_body.push(format!("{};", declare_signal_values())); - run_body.push(format!("{};", declare_my_signal_start())); - run_body.push(format!("{};", declare_my_template_name())); - run_body.push(format!("{};", declare_my_component_name())); - run_body.push(format!("{};", declare_my_father())); - run_body.push(format!("{};", declare_my_id())); - run_body.push(format!("{};", declare_my_subcomponents())); - run_body.push(format!("{};", declare_my_subcomponents_parallel())); - run_body.push(format!("{};", declare_circuit_constants())); - run_body.push(format!("{};", declare_list_of_template_messages_use())); - run_body.push(format!("{};", declare_expaux(self.expression_stack_depth))); - run_body.push(format!("{};", declare_lvar(self.var_stack_depth))); - run_body.push(format!("{};", declare_sub_component_aux())); - run_body.push(format!("{};", declare_index_multiple_eq())); - + let run_header = if parallel { + format!("void {}_run_parallel", self.header) + } else { + format!("void {}_run", self.header) + }; + let run_params = vec![declare_ctx_index(), declare_circom_calc_wit()]; + + let mut run_body = vec![ + format!("{};", declare_signal_values()), + format!("{};", declare_my_signal_start()), + format!("{};", declare_my_template_name()), + format!("{};", declare_my_component_name()), + format!("{};", declare_my_father()), + format!("{};", declare_my_id()), + format!("{};", declare_my_subcomponents()), + format!("{};", declare_my_subcomponents_parallel()), + format!("{};", declare_circuit_constants()), + format!("{};", declare_list_of_template_messages_use()), + format!("{};", declare_expaux(self.expression_stack_depth)), + format!("{};", declare_lvar(self.var_stack_depth)), + format!("{};", declare_sub_component_aux()), + format!("{};", declare_index_multiple_eq()), + ]; + for t in &self.body { let (mut instructions_body, _) = t.produce_c(producer, Some(parallel)); run_body.append(&mut instructions_body); } - // parallelism (join at the end of the function) - if self.number_of_components > 0 && self.has_parallel_sub_cmp { - run_body.push(format!("{{")); - run_body.push(format!("for (uint i = 0; i < {}; i++) {{",&self.number_of_components.to_string())); - run_body.push(format!("if (ctx->componentMemory[ctx_index].sbct[i].joinable()) {{")); - run_body.push(format!("ctx->componentMemory[ctx_index].sbct[i].join();")); - run_body.push(format!("}}")); - run_body.push(format!("}}")); - run_body.push(format!("}}")); - } - if parallel { - // parallelism - // set to true all outputs - run_body.push(format!("for (uint i = 0; i < {}; i++) {{", &self.number_of_outputs.to_string())); - run_body.push(format!("{}->componentMemory[{}].mutexes[i].lock();",CIRCOM_CALC_WIT,CTX_INDEX)); - run_body.push(format!("{}->componentMemory[{}].outputIsSet[i]=true;",CIRCOM_CALC_WIT,CTX_INDEX)); - run_body.push(format!("{}->componentMemory[{}].mutexes[i].unlock();",CIRCOM_CALC_WIT,CTX_INDEX)); - run_body.push(format!("{}->componentMemory[{}].cvs[i].notify_all();",CIRCOM_CALC_WIT,CTX_INDEX)); - run_body.push(format!("}}")); - //parallelism - run_body.push(format!("ctx->numThreadMutex.lock();")); - run_body.push(format!("ctx->numThread--;")); - //run_body.push(format!("printf(\"%i \\n\", ctx->numThread);")); - run_body.push(format!("ctx->numThreadMutex.unlock();")); - run_body.push(format!("ctx->ntcvs.notify_one();")); - } + // parallelism (join at the end of the function) + if self.number_of_components > 0 && self.has_parallel_sub_cmp { + run_body.push("{".to_string()); + run_body.push(format!( + "for (uint i = 0; i < {}; i++) {{", + &self.number_of_components.to_string() + )); + run_body.push("if (ctx->componentMemory[ctx_index].sbct[i].joinable()) {".to_string()); + run_body.push("ctx->componentMemory[ctx_index].sbct[i].join();".to_string()); + run_body.push("}".to_string()); + run_body.push("}".to_string()); + run_body.push("}".to_string()); + } + if parallel { + // parallelism + // set to true all outputs + run_body.push(format!( + "for (uint i = 0; i < {}; i++) {{", + &self.number_of_outputs.to_string() + )); + run_body.push(format!( + "{}->componentMemory[{}].mutexes[i].lock();", + CIRCOM_CALC_WIT, CTX_INDEX + )); + run_body.push(format!( + "{}->componentMemory[{}].outputIsSet[i]=true;", + CIRCOM_CALC_WIT, CTX_INDEX + )); + run_body.push(format!( + "{}->componentMemory[{}].mutexes[i].unlock();", + CIRCOM_CALC_WIT, CTX_INDEX + )); + run_body.push(format!( + "{}->componentMemory[{}].cvs[i].notify_all();", + CIRCOM_CALC_WIT, CTX_INDEX + )); + run_body.push("}".to_string()); + //parallelism + run_body.push("ctx->numThreadMutex.lock();".to_string()); + run_body.push("ctx->numThread--;".to_string()); + //run_body.push(format!("printf(\"%i \\n\", ctx->numThread);")); + run_body.push("ctx->numThreadMutex.unlock();".to_string()); + run_body.push("ctx->ntcvs.notify_one();".to_string()); + } // to release the memory of its subcomponents - run_body.push(format!("for (uint i = 0; i < {}; i++){{", &self.number_of_components.to_string())); + run_body.push(format!( + "for (uint i = 0; i < {}; i++){{", + &self.number_of_components.to_string() + )); run_body.push(format!( "uint index_subc = {}->componentMemory[{}].subcomponents[i];", CIRCOM_CALC_WIT, ctx_index(), )); - run_body.push(format!("if (index_subc != 0){};", + run_body.push(format!( + "if (index_subc != 0){};", build_call( - "release_memory_component".to_string(), + "release_memory_component".to_string(), vec![CIRCOM_CALC_WIT.to_string(), "index_subc".to_string()] - ))); - - run_body.push(format!("}}")); + ) + )); + + run_body.push("}".to_string()); let run_fun = build_callable(run_header, run_params, run_body); vec![create_fun, run_fun] } diff --git a/compiler/src/compiler_interface.rs b/compiler/src/compiler_interface.rs index cb84476c8..bcf7959d2 100644 --- a/compiler/src/compiler_interface.rs +++ b/compiler/src/compiler_interface.rs @@ -9,6 +9,7 @@ pub struct Config { pub wat_flag: bool, } +#[allow(clippy::result_unit_err)] pub fn run_compiler(vcp: VCP, config: Config, version: &str) -> Result { let flags = CompilationFlags { main_inputs_log: config.produce_input_log, wat_flag: config.wat_flag }; let circuit = Circuit::build(vcp, flags, version); @@ -18,6 +19,7 @@ pub fn run_compiler(vcp: VCP, config: Config, version: &str) -> Result Result<(), ()> { use std::path::Path; if Path::new(js_folder).is_dir() { @@ -29,6 +31,7 @@ pub fn write_wasm(circuit: &Circuit, js_folder: &str, wasm_name: &str, file: &st circuit.produce_wasm(js_folder, wasm_name, &mut writer) } +#[allow(clippy::result_unit_err)] pub fn write_c(circuit: &Circuit, c_folder: &str, c_run_name: &str, c_file: &str, dat_file: &str) -> Result<(), ()> { use std::path::Path; if Path::new(c_folder).is_dir() { @@ -45,7 +48,7 @@ pub fn write_c(circuit: &Circuit, c_folder: &str, c_run_name: &str, c_file: &str fn produce_debug_output(circuit: &Circuit) -> Result<(), ()> { use std::io::Write; use std::path::Path; - let path = format!("ir_log"); + let path = "ir_log".to_string(); if Path::new(&path).is_dir() { std::fs::remove_dir_all(&path).map_err(|_err| {})?; } diff --git a/compiler/src/hir/merger.rs b/compiler/src/hir/merger.rs index 4cb428b79..9d6d32ae4 100644 --- a/compiler/src/hir/merger.rs +++ b/compiler/src/hir/merger.rs @@ -29,7 +29,7 @@ fn produce_vcf(vcp: &VCP, state: &mut State) { let mut index = 0; while index < state.vcf_collector.len() { state.external_signals = build_component_info(&vec![]); - let mut env = build_environment(&vec![], &state.vcf_collector[index].params_types); + let mut env = build_environment(&[], &state.vcf_collector[index].params_types); let body = state.vcf_collector[index].body.clone(); produce_vcf_stmt(&body, state, &mut env); index += 1; @@ -38,7 +38,7 @@ fn produce_vcf(vcp: &VCP, state: &mut State) { fn link_circuit(vcp: &mut VCP, state: &mut State) { for node in &mut vcp.templates { - let mut env = build_environment(&node.header, &vec![]); + let mut env = build_environment(&node.header, &[]); state.external_signals = build_component_info(&node.triggers); link_stmt(&mut node.code, state, &mut env); } @@ -163,7 +163,7 @@ fn produce_vcf_log_call(stmt: &Statement, state: &mut State, environment: &E) { if let LogArgument::LogExp(arg) = arglog { produce_vcf_expr(arg, state, environment); } - else {}// unimplemented!(); } + // unimplemented!(); } } } else { unreachable!(); @@ -646,7 +646,7 @@ fn cast_type_array(expr: &Expression, state: &State, environment: &E) -> VCT { result.append(&mut inner_type); result } else if let UniformArray { value, dimension, .. } = expr { - let usable_dimension = if let Option::Some(dimension) = cast_dimension(&dimension) { + let usable_dimension = if let Option::Some(dimension) = cast_dimension(dimension) { dimension } else { unreachable!() diff --git a/compiler/src/hir/sugar_cleaner.rs b/compiler/src/hir/sugar_cleaner.rs index 693d58c6b..a181372e4 100644 --- a/compiler/src/hir/sugar_cleaner.rs +++ b/compiler/src/hir/sugar_cleaner.rs @@ -1,6 +1,6 @@ use super::very_concrete_program::*; use program_structure::ast::*; -use num_traits::{ToPrimitive}; +use num_traits::ToPrimitive; struct ExtendedSyntax { @@ -257,7 +257,7 @@ fn extend_prefix(expr: &mut Expression, state: &mut State, context: &Context) -> use Expression::PrefixOp; if let PrefixOp { rhe, .. } = expr { let mut extended = extend_expression(rhe, state, context); - let mut expr = vec![*rhe.clone()]; + let mut expr = vec![rhe.as_ref().clone()]; sugar_filter(&mut expr, state, &mut extended.initializations); *rhe = Box::new(expr.pop().unwrap()); extended @@ -270,7 +270,7 @@ fn extend_parallel(expr: &mut Expression, state: &mut State, context: &Context) use Expression::ParallelOp; if let ParallelOp { rhe, .. } = expr { let mut extended = extend_expression(rhe, state, context); - let mut expr = vec![*rhe.clone()]; + let mut expr = vec![rhe.as_ref().clone()]; sugar_filter(&mut expr, state, &mut extended.initializations); *rhe = Box::new(expr.pop().unwrap()); extended @@ -291,7 +291,7 @@ fn extend_infix(expr: &mut Expression, state: &mut State, context: &Context) -> let mut rh_expand = extend_expression(rhe, state, context); lh_expand.initializations.append(&mut rh_expand.initializations); let mut extended = lh_expand; - let mut expr = vec![*lhe.clone(), *rhe.clone()]; + let mut expr = vec![lhe.as_ref().clone(), rhe.as_ref().clone()]; sugar_filter(&mut expr, state, &mut extended.initializations); let mut expr_rhe = expr.pop().unwrap(); @@ -348,7 +348,7 @@ fn extend_switch(expr: &mut Expression, state: &mut State, context: &Context) -> let mut false_expand = extend_expression(if_false, state, context); true_expand.initializations.append(&mut false_expand.initializations); let mut extended = true_expand; - let mut expr = vec![*if_true.clone(), *if_false.clone()]; + let mut expr = vec![if_true.as_ref().clone(), if_false.as_ref().clone()]; sugar_filter(&mut expr, state, &mut extended.initializations); *if_false = Box::new(expr.pop().unwrap()); *if_true = Box::new(expr.pop().unwrap()); @@ -373,7 +373,7 @@ fn extend_array(expr: &mut Expression, state: &mut State, context: &Context) -> let mut dimension_expand = extend_expression(dimension, state, context); value_expand.initializations.append(&mut dimension_expand.initializations); let mut extended = value_expand; - let mut expr = vec![*value.clone(), *dimension.clone()]; + let mut expr = vec![value.as_ref().clone(), dimension.as_ref().clone()]; sugar_filter(&mut expr, state, &mut extended.initializations); *dimension = Box::new(expr.pop().unwrap()); *value = Box::new(expr.pop().unwrap()); @@ -566,6 +566,7 @@ fn into_single_substitution(stmt: Statement, stmts: &mut Vec) { fn rhe_switch_case(stmt: Statement, stmts: &mut Vec) { use Expression::InlineSwitchOp; use Statement::{Block, IfThenElse, Substitution}; + #[allow(clippy::collapsible_match)] if let Substitution { var, access, op, rhe, meta } = stmt { if let InlineSwitchOp { cond, if_true, if_false, .. } = rhe { let mut if_assigns = vec![]; @@ -573,7 +574,7 @@ fn rhe_switch_case(stmt: Statement, stmts: &mut Vec) { meta: meta.clone(), var: var.clone(), access: access.clone(), - op: op.clone(), + op, rhe: *if_true, }; if_assigns.push(sub_if); @@ -613,8 +614,7 @@ fn rhe_array_case(stmt: Statement, stmts: &mut Vec) { use Statement::Substitution; if let Substitution { var, access, op, rhe, meta } = stmt { if let ArrayInLine { values, .. } = rhe { - let mut index = 0; - for v in values { + for (index, v) in values.into_iter().enumerate() { let mut index_meta = meta.clone(); index_meta.get_mut_memory_knowledge().set_concrete_dimensions(vec![]); let expr_index = Number(index_meta, BigInt::from(index)); @@ -629,7 +629,6 @@ fn rhe_array_case(stmt: Statement, stmts: &mut Vec) { rhe: v, }; stmts.push(sub); - index += 1; } } else if let UniformArray { value, dimension, .. } = rhe { let usable_dimension = if let Option::Some(dimension) = cast_dimension(&dimension) { @@ -650,7 +649,7 @@ fn rhe_array_case(stmt: Statement, stmts: &mut Vec) { var: var.clone(), access: accessed_with, meta: meta.clone(), - rhe: *value.clone(), + rhe: value.as_ref().clone(), }; stmts.push(sub); index += 1; @@ -697,17 +696,17 @@ fn lhe_array_ce(meta: &Meta, expr_array: &Expression, other_expr: &Expression, s } } else if let UniformArray {value, ..} = other_expr { - for i in 0..values_l.len() { + for item in values_l { let ce = ConstraintEquality { - lhe: values_l[i].clone(), - rhe: *value.clone(), + lhe: item.clone(), + rhe: value.as_ref().clone(), meta: meta.clone(), }; stmts.push(ce); } } else if let Variable { meta: meta_var, name, access, ..} = other_expr { - for i in 0..values_l.len() { + for (i, item) in values_l.iter().enumerate() { let mut index_meta = meta.clone(); index_meta.get_mut_memory_knowledge().set_concrete_dimensions(vec![]); let expr_index = Number(index_meta, BigInt::from(i)); @@ -715,7 +714,7 @@ fn lhe_array_ce(meta: &Meta, expr_array: &Expression, other_expr: &Expression, s let mut accessed_with = access.clone(); accessed_with.push(as_access); let ce = ConstraintEquality { - lhe: values_l[i].clone(), + lhe: item.clone(), rhe: Variable {name: name.clone(), access: accessed_with, meta: meta_var.clone()}, meta: meta.clone(), }; diff --git a/compiler/src/hir/type_inference.rs b/compiler/src/hir/type_inference.rs index 02b82ee9d..c80c84951 100644 --- a/compiler/src/hir/type_inference.rs +++ b/compiler/src/hir/type_inference.rs @@ -2,7 +2,7 @@ use super::analysis_utilities::*; use super::very_concrete_program::*; use program_structure::ast::*; use std::collections::HashSet; -use num_traits::{ToPrimitive}; +use num_traits::ToPrimitive; struct SearchInfo { environment: E, @@ -20,6 +20,7 @@ pub fn infer_function_result(id: &str, params: Vec, state: &State) -> VCT } fn infer_type_stmt(stmt: &Statement, state: &State, context: &mut SearchInfo) -> Option { + #[allow(clippy::if_same_then_else)] if stmt.is_return() { infer_type_return(stmt, state, context) } else if stmt.is_block() { @@ -129,6 +130,7 @@ fn infer_type_while(stmt: &Statement, state: &State, context: &mut SearchInfo) - } fn infer_type_expresion(expr: &Expression, state: &State, context: &mut SearchInfo) -> Option { + #[allow(clippy::if_same_then_else)] if expr.is_call() { infer_type_call(expr, state, context) } else if expr.is_variable() { @@ -203,13 +205,13 @@ fn infer_type_array(expr: &Expression, state: &State, context: &mut SearchInfo) lengths }) } else if let UniformArray { value, dimension, .. } = expr { - let usable_dimension = if let Option::Some(dimension) = cast_dimension(&dimension) { + let usable_dimension = if let Option::Some(dimension) = cast_dimension(dimension) { dimension } else { unreachable!() }; let mut lengths = vec![usable_dimension]; - let with_type = infer_type_expresion(&value, state, context); + let with_type = infer_type_expresion(value, state, context); with_type.map(|mut l| { lengths.append(&mut l); lengths @@ -227,17 +229,13 @@ fn infer_type_call(expr: &Expression, state: &State, context: &mut SearchInfo) - } else { context.open_calls.insert(id.clone()); context.environment.add_variable_block(); - let mut index = 0; let body = &state.generic_functions.get(id).unwrap().body; let names = &state.generic_functions.get(id).unwrap().params_names; let arg_types = infer_args(args, state, context); - if arg_types.is_none() { - return Option::None; - } + arg_types.as_ref()?; let arg_types = arg_types.unwrap(); - for arg_type in arg_types { + for (index, arg_type) in arg_types.into_iter().enumerate() { context.environment.add_variable(&names[index], arg_type); - index += 1; } let inferred = infer_type_stmt(body, state, context); context.environment.remove_variable_block(); diff --git a/compiler/src/intermediate_representation/branch_bucket.rs b/compiler/src/intermediate_representation/branch_bucket.rs index 830b361ef..166138bb3 100644 --- a/compiler/src/intermediate_representation/branch_bucket.rs +++ b/compiler/src/intermediate_representation/branch_bucket.rs @@ -59,7 +59,7 @@ impl WriteWasm for BranchBucket { if producer.needs_comments() { instructions.push(";; branch bucket".to_string()); } - if self.if_branch.len() > 0 { + if !self.if_branch.is_empty() { let mut instructions_cond = self.cond.produce_wasm(producer); instructions.append(&mut instructions_cond); instructions.push(call("$Fr_isTrue")); @@ -68,7 +68,7 @@ impl WriteWasm for BranchBucket { let mut instructions_if = ins.produce_wasm(producer); instructions.append(&mut instructions_if); } - if self.else_branch.len() > 0 { + if !self.else_branch.is_empty() { instructions.push(add_else()); for ins in &self.else_branch { let mut instructions_else = ins.produce_wasm(producer); @@ -76,20 +76,18 @@ impl WriteWasm for BranchBucket { } } instructions.push(add_end()); - } else { - if self.else_branch.len() > 0 { - let mut instructions_cond = self.cond.produce_wasm(producer); - instructions.append(&mut instructions_cond); - instructions.push(call("$Fr_isTrue")); - instructions.push(eqz32()); - instructions.push(add_if()); - for ins in &self.else_branch { - let mut instructions_else = ins.produce_wasm(producer); - instructions.append(&mut instructions_else); - } - instructions.push(add_end()); - } - } + } else if !self.else_branch.is_empty() { + let mut instructions_cond = self.cond.produce_wasm(producer); + instructions.append(&mut instructions_cond); + instructions.push(call("$Fr_isTrue")); + instructions.push(eqz32()); + instructions.push(add_if()); + for ins in &self.else_branch { + let mut instructions_else = ins.produce_wasm(producer); + instructions.append(&mut instructions_else); + } + instructions.push(add_end()); + } if producer.needs_comments() { instructions.push(";; end of branch bucket".to_string()); } diff --git a/compiler/src/intermediate_representation/call_bucket.rs b/compiler/src/intermediate_representation/call_bucket.rs index dbe6fb0ce..c2c055d34 100644 --- a/compiler/src/intermediate_representation/call_bucket.rs +++ b/compiler/src/intermediate_representation/call_bucket.rs @@ -55,8 +55,8 @@ impl ToString for CallBucket { let line = self.line.to_string(); let template_id = self.message_id.to_string(); let ret = match &self.return_info { - ReturnType::Intermediate { op_aux_no } => {format!("Intermediate({})",op_aux_no.to_string())} - _ => {format!("Final")} + ReturnType::Intermediate { op_aux_no } => {format!("Intermediate({})",op_aux_no)} + _ => {"Final".to_string()} }; let mut args = "".to_string(); for i in &self.arguments { @@ -73,7 +73,7 @@ impl WriteWasm for CallBucket { if producer.needs_comments() { instructions.push(";; call bucket".to_string()); } - if self.arguments.len() > 0 { + if !self.arguments.is_empty() { let local_info_size_u32 = producer.get_local_info_size_u32(); instructions.push(set_constant("0")); instructions.push(load32(None)); // current stack size @@ -84,11 +84,10 @@ impl WriteWasm for CallBucket { } instructions.push(set_local(producer.get_call_lvar_tag())); let mut count = 0; - let mut i = 0; - for p in &self.arguments { - if producer.needs_comments() { + for (i, p) in self.arguments.iter().enumerate() { + if producer.needs_comments() { instructions.push(format!(";; copying argument {}", i)); - } + } instructions.push(get_local(producer.get_call_lvar_tag())); instructions.push(set_constant(&count.to_string())); instructions.push(add32()); @@ -128,11 +127,10 @@ impl WriteWasm for CallBucket { instructions.push(add_end()); instructions.push(add_end()); } - if producer.needs_comments() { + if producer.needs_comments() { instructions.push(format!(";; end copying argument {}", i)); - } + } count += self.argument_types[i].size * 4 * producer.get_size_32_bits_in_memory(); - i += 1; } } match &self.return_info { @@ -243,13 +241,12 @@ impl WriteWasm for CallBucket { // compute de move with 2 or more dimensions let mut instructions_idx0 = indexes[0].produce_wasm(producer); instructions.append(&mut instructions_idx0); // start with dimension 0 - for i in 1..indexes.len() { + for (i, item) in indexes.iter().enumerate().skip(1) { instructions.push(get_local(producer.get_io_info_tag())); let offsetdim = 4 * i; instructions.push(load32(Some(&offsetdim.to_string()))); // get size of ith dimension instructions.push(mul32()); // multiply the current move by size of the ith dimension - let mut instructions_idxi = - indexes[i].produce_wasm(producer); + let mut instructions_idxi = item.produce_wasm(producer); instructions.append(&mut instructions_idxi); instructions.push(add32()); // add move upto dimension i } @@ -268,7 +265,7 @@ impl WriteWasm for CallBucket { instructions.push(add32()); // we get the position of the signal (with indexes) in memory } _ => { - assert!(false); + unreachable!() } } } @@ -284,76 +281,71 @@ impl WriteWasm for CallBucket { instructions.push(get_local(producer.get_merror_tag())); instructions.push(add_return()); instructions.push(add_end()); - match &data.dest_address_type { - AddressType::SubcmpSignal { .. } => { - // if subcomponent input check if run needed - if producer.needs_comments() { - instructions.push(";; decrease counter".to_string()); // by self.context.size - } - instructions.push(get_local(producer.get_sub_cmp_tag())); - instructions.push(get_local(producer.get_sub_cmp_tag())); - instructions.push(load32(Some( - &producer.get_input_counter_address_in_component().to_string(), - ))); //remaining inputs to be set - instructions.push(set_constant(&data.context.size.to_string())); - instructions.push(sub32()); - instructions.push(store32(Some( - &producer.get_input_counter_address_in_component().to_string(), - ))); // update remaining inputs to be set - if producer.needs_comments() { - instructions.push(";; check if run is needed".to_string()); - } - instructions.push(get_local(producer.get_sub_cmp_tag())); - instructions.push(load32(Some( - &producer.get_input_counter_address_in_component().to_string(), - ))); - instructions.push(eqz32()); - instructions.push(add_if()); - if producer.needs_comments() { - instructions.push(";; run sub component".to_string()); - } - instructions.push(get_local(producer.get_sub_cmp_tag())); - match &data.dest { - LocationRule::Indexed { .. } => { - if let Some(name) = &my_template_header { - instructions.push(call(&format!("${}_run", name))); - instructions.push(tee_local(producer.get_merror_tag())); - instructions.push(add_if()); - instructions.push(set_constant(&self.message_id.to_string())); - instructions.push(set_constant(&self.line.to_string())); - instructions.push(call("$buildBufferMessage")); - instructions.push(call("$printErrorMessage")); - instructions.push(get_local(producer.get_merror_tag())); - instructions.push(add_return()); - instructions.push(add_end()); - } else { - assert!(false); - } - } - LocationRule::Mapped { .. } => { - instructions.push(get_local(producer.get_sub_cmp_tag())); - instructions.push(load32(None)); // get template id - instructions.push(call_indirect( - &"$runsmap".to_string(), - &"(type $_t_i32ri32)".to_string(), - )); + if let AddressType::SubcmpSignal { .. } = data.dest_address_type { + // if subcomponent input check if run needed + if producer.needs_comments() { + instructions.push(";; decrease counter".to_string()); + // by self.context.size + } + instructions.push(get_local(producer.get_sub_cmp_tag())); + instructions.push(get_local(producer.get_sub_cmp_tag())); + instructions.push(load32(Some( + &producer.get_input_counter_address_in_component().to_string(), + ))); //remaining inputs to be set + instructions.push(set_constant(&data.context.size.to_string())); + instructions.push(sub32()); + instructions.push(store32(Some( + &producer.get_input_counter_address_in_component().to_string(), + ))); // update remaining inputs to be set + if producer.needs_comments() { + instructions.push(";; check if run is needed".to_string()); + } + instructions.push(get_local(producer.get_sub_cmp_tag())); + instructions.push(load32(Some( + &producer.get_input_counter_address_in_component().to_string(), + ))); + instructions.push(eqz32()); + instructions.push(add_if()); + if producer.needs_comments() { + instructions.push(";; run sub component".to_string()); + } + instructions.push(get_local(producer.get_sub_cmp_tag())); + match &data.dest { + LocationRule::Indexed { .. } => { + if let Some(name) = &my_template_header { + instructions.push(call(&format!("${}_run", name))); instructions.push(tee_local(producer.get_merror_tag())); instructions.push(add_if()); instructions.push(set_constant(&self.message_id.to_string())); instructions.push(set_constant(&self.line.to_string())); instructions.push(call("$buildBufferMessage")); instructions.push(call("$printErrorMessage")); - instructions.push(get_local(producer.get_merror_tag())); + instructions.push(get_local(producer.get_merror_tag())); instructions.push(add_return()); instructions.push(add_end()); + } else { + unreachable!(); } } - if producer.needs_comments() { - instructions.push(";; end run sub component".to_string()); - } - instructions.push(add_end()); + LocationRule::Mapped { .. } => { + instructions.push(get_local(producer.get_sub_cmp_tag())); + instructions.push(load32(None)); // get template id + instructions.push(call_indirect("$runsmap", "(type $_t_i32ri32)")); + instructions.push(tee_local(producer.get_merror_tag())); + instructions.push(add_if()); + instructions.push(set_constant(&self.message_id.to_string())); + instructions.push(set_constant(&self.line.to_string())); + instructions.push(call("$buildBufferMessage")); + instructions.push(call("$printErrorMessage")); + instructions.push(get_local(producer.get_merror_tag())); + instructions.push(add_return()); + instructions.push(add_end()); + } } - _ => (), + if producer.needs_comments() { + instructions.push(";; end run sub component".to_string()); + } + instructions.push(add_end()); } } } @@ -375,8 +367,7 @@ impl WriteC for CallBucket { prologue.push(format!("{};", declare_lvar_func_call(self.arena_size))); // copying parameters let mut count = 0; - let mut i = 0; - for p in &self.arguments { + for (i, p) in self.arguments.iter().enumerate() { prologue.push(format!("// copying argument {}", i)); let (mut prologue_value, src) = p.produce_c(producer, parallel); prologue.append(&mut prologue_value); @@ -393,7 +384,6 @@ impl WriteC for CallBucket { } prologue.push(format!("// end copying argument {}", i)); count += self.argument_types[i].size; - i += 1; } let result; let mut call_arguments = vec![]; @@ -414,7 +404,7 @@ impl WriteC for CallBucket { if let AddressType::SubcmpSignal { cmp_address, .. } = &data.dest_address_type { let (mut cmp_prologue, cmp_index) = cmp_address.produce_c(producer, parallel); prologue.append(&mut cmp_prologue); - prologue.push(format!("{{")); + prologue.push("{".to_string()); prologue.push(format!("uint {} = {};", cmp_index_ref, cmp_index)); } @@ -428,29 +418,28 @@ impl WriteC for CallBucket { let mut map_access = format!("{}->{}[{}].defs[{}].offset", circom_calc_wit(), template_ins_2_io_info(), template_id_in_component(sub_component_pos_in_memory.clone()), - signal_code.to_string()); - if indexes.len()>0 { - map_prologue.push(format!("{{")); - map_prologue.push(format!("uint map_index_aux[{}];",indexes.len().to_string())); + signal_code); + if !indexes.is_empty() { + map_prologue.push("{".to_string()); + map_prologue.push(format!("uint map_index_aux[{}];",indexes.len())); let (mut index_code_0, mut map_index) = indexes[0].produce_c(producer, parallel); map_prologue.append(&mut index_code_0); map_prologue.push(format!("map_index_aux[0]={};",map_index)); - map_index = format!("map_index_aux[0]"); - for i in 1..indexes.len() { - let (mut index_code, index_exp) = indexes[i].produce_c(producer, parallel); - map_prologue.append(&mut index_code); - map_prologue.push(format!("map_index_aux[{}]={};",i.to_string(),index_exp)); - map_index = format!("({})*{}->{}[{}].defs[{}].lengths[{}]+map_index_aux[{}]", - map_index, circom_calc_wit(), template_ins_2_io_info(), - template_id_in_component(sub_component_pos_in_memory.clone()), - signal_code.to_string(),(i-1).to_string(),i.to_string()); + map_index = "map_index_aux[0]".to_string(); + for (i, item) in indexes.iter().enumerate().skip(1) { + let (mut index_code, index_exp) = item.produce_c(producer, parallel); + map_prologue.append(&mut index_code); + map_prologue.push(format!("map_index_aux[{}]={};",i,index_exp)); + map_index = format!("({})*{}->{}[{}].defs[{}].lengths[{}]+map_index_aux[{}]", + map_index, circom_calc_wit(), template_ins_2_io_info(), + template_id_in_component(sub_component_pos_in_memory.clone()), + signal_code,(i-1),i); } map_access = format!("{}+{}",map_access,map_index); } ((map_prologue, map_access),Some(template_id_in_component(sub_component_pos_in_memory.clone()))) } else { - assert!(false); - ((vec![], "".to_string()),Option::::None) + unreachable!(); }; prologue.append(&mut dest_prologue); let result_ref = match &data.dest_address_type { @@ -475,22 +464,22 @@ impl WriteC for CallBucket { call_arguments.push(data.context.size.to_string()); prologue.push(format!("{};", build_call(self.symbol.clone(), call_arguments))); if let LocationRule::Mapped { indexes, .. } = &data.dest { - if indexes.len() > 0 { - prologue.push(format!("}}")); + if !indexes.is_empty() { + prologue.push("}".to_string()); } } // if output and parallel send notify if let AddressType::Signal = &data.dest_address_type { if parallel.unwrap() && data.dest_is_output { if data.context.size > 0 { - prologue.push(format!("{{")); + prologue.push("{".to_string()); prologue.push(format!("for (int i = 0; i < {}; i++) {{",data.context.size)); prologue.push(format!("{}->componentMemory[{}].mutexes[{}+i].lock();",CIRCOM_CALC_WIT,CTX_INDEX,dest_index.clone())); prologue.push(format!("{}->componentMemory[{}].outputIsSet[{}+i]=true;",CIRCOM_CALC_WIT,CTX_INDEX,dest_index.clone())); prologue.push(format!("{}->componentMemory[{}].mutexes[{}+i].unlock();",CIRCOM_CALC_WIT,CTX_INDEX,dest_index.clone())); prologue.push(format!("{}->componentMemory[{}].cvs[{}+i].notify_all();",CIRCOM_CALC_WIT,CTX_INDEX,dest_index.clone())); - prologue.push(format!("}}")); - prologue.push(format!("}}")); + prologue.push("}".to_string()); + prologue.push("}".to_string()); } else { prologue.push(format!("{}->componentMemory[{}].mutexes[{}].lock();",CIRCOM_CALC_WIT,CTX_INDEX,dest_index.clone())); prologue.push(format!("{}->componentMemory[{}].outputIsSet[{}]=true;",CIRCOM_CALC_WIT,CTX_INDEX,dest_index.clone())); @@ -500,8 +489,7 @@ impl WriteC for CallBucket { } } // like store update counters and check if Subcomponent needs to be run - match &data.dest_address_type { - AddressType::SubcmpSignal { uniform_parallel_value, input_information, .. } => { + if let AddressType::SubcmpSignal { uniform_parallel_value, input_information, .. } = &data.dest_address_type { // if subcomponent input check if run needed let sub_cmp_counter = format!( "{}->componentMemory[{}[{}]].inputCounter", @@ -537,7 +525,7 @@ impl WriteC for CallBucket { thread_call_instr.push(format!("{}->componentMemory[{}].sbct[{}] = std::thread({},{});",CIRCOM_CALC_WIT,CTX_INDEX,cmp_index_ref, sub_cmp_call_name, argument_list(sub_cmp_call_arguments))); thread_call_instr.push(format!("std::unique_lock lkt({}->numThreadMutex);",CIRCOM_CALC_WIT)); thread_call_instr.push(format!("{}->ntcvs.wait(lkt, [{}]() {{return {}->numThread < {}->maxThread; }});",CIRCOM_CALC_WIT,CIRCOM_CALC_WIT,CIRCOM_CALC_WIT,CIRCOM_CALC_WIT)); - thread_call_instr.push(format!("ctx->numThread++;")); + thread_call_instr.push("ctx->numThread++;".to_string()); //thread_call_instr.push(format!("printf(\"%i \\n\", ctx->numThread);")); thread_call_instr @@ -586,7 +574,7 @@ impl WriteC for CallBucket { call_instructions.push(format!("{}->componentMemory[{}].sbct[{}] = std::thread({},{});",CIRCOM_CALC_WIT,CTX_INDEX,cmp_index_ref, sub_cmp_call_name, argument_list(sub_cmp_call_arguments.clone()))); call_instructions.push(format!("std::unique_lock lkt({}->numThreadMutex);",CIRCOM_CALC_WIT)); call_instructions.push(format!("{}->ntcvs.wait(lkt, [{}]() {{return {}->numThread < {}->maxThread; }});",CIRCOM_CALC_WIT,CIRCOM_CALC_WIT,CIRCOM_CALC_WIT,CIRCOM_CALC_WIT)); - call_instructions.push(format!("ctx->numThread++;")); + call_instructions.push("ctx->numThread++;".to_string()); //call_instructions.push(format!("printf(\"%i \\n\", ctx->numThread);")); if let StatusInput::Unknown = status { let sub_cmp_counter_decrease_andcheck = format!("!({})",sub_cmp_counter_decrease); @@ -602,7 +590,7 @@ impl WriteC for CallBucket { } // end of case parallel - prologue.push(format!("}} else {{")); + prologue.push("} else {".to_string()); // case not parallel let sub_cmp_call_name = if let LocationRule::Indexed { .. } = &data.dest { @@ -627,17 +615,15 @@ impl WriteC for CallBucket { prologue.append(&mut call_instructions); } - prologue.push(format!("}}")); + prologue.push("}".to_string()); } } } else { - assert!(false); + unreachable!(); } } - _ => (), - } if let AddressType::SubcmpSignal { .. } = &data.dest_address_type { - prologue.push(format!("}}")); + prologue.push("}".to_string()); } result = "".to_string(); } diff --git a/compiler/src/intermediate_representation/compute_bucket.rs b/compiler/src/intermediate_representation/compute_bucket.rs index 1f14a1ffa..9f66f3e6d 100644 --- a/compiler/src/intermediate_representation/compute_bucket.rs +++ b/compiler/src/intermediate_representation/compute_bucket.rs @@ -351,7 +351,7 @@ impl WriteC for ComputeBucket { let mut arguments = vec![result_ref.clone()]; let operands_copy = operands.clone(); arguments.append(&mut operands); - compute_c.push(format!("{}; // line circom {}", build_call(operator.clone(), arguments),self.line.to_string())); + compute_c.push(format!("{}; // line circom {}", build_call(operator.clone(), arguments),self.line)); if *n > 1 { compute_c.push(format!("{} = 1;", index_multiple_eq())); compute_c.push(format!("while({} < {} && Fr_isTrue({})) {{", index_multiple_eq(), n, result_ref)); @@ -361,9 +361,9 @@ impl WriteC for ComputeBucket { operands.push(format!("{} + {}", operand, index_multiple_eq())); } arguments.append(&mut operands); - compute_c.push(format!("{}; // line circom {}", build_call(operator.clone(), arguments),self.line.to_string())); + compute_c.push(format!("{}; // line circom {}", build_call(operator.clone(), arguments),self.line)); compute_c.push(format!("{}++;", index_multiple_eq())); - compute_c.push(format!("}}")); + compute_c.push("}".to_string()); } result = result_ref; @@ -378,7 +378,7 @@ impl WriteC for ComputeBucket { let result_ref = format!("&{}", expaux(exp_aux_index.clone())); let mut arguments = vec![result_ref.clone()]; arguments.append(&mut operands); - compute_c.push(format!("{}; // line circom {}", build_call(operator, arguments),self.line.to_string())); + compute_c.push(format!("{}; // line circom {}", build_call(operator, arguments),self.line)); //value address result = result_ref; diff --git a/compiler/src/intermediate_representation/create_component_bucket.rs b/compiler/src/intermediate_representation/create_component_bucket.rs index 5205353d9..80d1304af 100644 --- a/compiler/src/intermediate_representation/create_component_bucket.rs +++ b/compiler/src/intermediate_representation/create_component_bucket.rs @@ -212,7 +212,7 @@ impl WriteC for CreateCmpBucket { instructions.push("{".to_string()); instructions.push(format!("uint aux_create = {};", scmp_idx)); instructions.push(format!("int aux_cmp_num = {}+{}+1;", self.component_offset, CTX_INDEX)); - instructions.push(format!("uint csoffset = {}+{};", MY_SIGNAL_START.to_string(), self.signal_offset)); + instructions.push(format!("uint csoffset = {}+{};", MY_SIGNAL_START, self.signal_offset)); if self.number_of_cmp > 1{ instructions.push(format!("uint aux_dimensions[{}] = {};", self.dimensions.len(), set_list(self.dimensions.clone()))); } @@ -228,7 +228,7 @@ impl WriteC for CreateCmpBucket { instructions.push(format!("for (uint i = 0; i < {}; i++) {{", self.number_of_cmp)); // update the value of the the parallel status if it is not uniform parallel using the array aux_parallel if self.uniform_parallel.is_none(){ - instructions.push(format!("bool status_parallel = aux_parallel[i];")); + instructions.push("bool status_parallel = aux_parallel[i];".to_string()); } } // generate array with the positions that are actually created if there are empty components @@ -236,23 +236,23 @@ impl WriteC for CreateCmpBucket { else{ instructions.push(format!("uint aux_positions [{}]= {};", self.defined_positions.len(), set_list(self.defined_positions.iter().map(|(x, _y)| *x).collect()))); instructions.push(format!("for (uint i_aux = 0; i_aux < {}; i_aux++) {{", self.defined_positions.len())); - instructions.push(format!("uint i = aux_positions[i_aux];")); + instructions.push("uint i = aux_positions[i_aux];".to_string()); // update the value of the the parallel status if it is not uniform parallel using the array aux_parallel if self.uniform_parallel.is_none(){ - instructions.push(format!("bool status_parallel = aux_parallel[i_aux];")); + instructions.push("bool status_parallel = aux_parallel[i_aux];".to_string()); } } if self.number_of_cmp > 1{ instructions.push( format!("std::string new_cmp_name = \"{}\"+{};", - self.name_subcomponent.to_string(), + self.name_subcomponent, generate_my_array_position("aux_dimensions".to_string(), self.dimensions.len().to_string(), "i".to_string()) ) ); } else { - instructions.push(format!("std::string new_cmp_name = \"{}\";", self.name_subcomponent.to_string())); + instructions.push(format!("std::string new_cmp_name = \"{}\";", self.name_subcomponent)); } let create_args = vec![ "csoffset".to_string(), diff --git a/compiler/src/intermediate_representation/ir_interface.rs b/compiler/src/intermediate_representation/ir_interface.rs index 5dc9fc33d..c3abc9963 100644 --- a/compiler/src/intermediate_representation/ir_interface.rs +++ b/compiler/src/intermediate_representation/ir_interface.rs @@ -97,12 +97,7 @@ impl ObtainMeta for Instruction { impl CheckCompute for Instruction { fn has_compute_in(&self) -> bool { use Instruction::*; - match self { - Load(_v) => {true - }, - Compute(_) => true, - _ => false, - } + matches!(self, Load(_) | Compute(_)) } } diff --git a/compiler/src/intermediate_representation/load_bucket.rs b/compiler/src/intermediate_representation/load_bucket.rs index 18001e331..ae5ffaf2e 100644 --- a/compiler/src/intermediate_representation/load_bucket.rs +++ b/compiler/src/intermediate_representation/load_bucket.rs @@ -138,12 +138,12 @@ impl WriteWasm for LoadBucket { // compute de move with 2 or more dimensions let mut instructions_idx0 = indexes[0].produce_wasm(producer); instructions.append(&mut instructions_idx0); // start with dimension 0 - for i in 1..indexes.len() { + for (i, item) in indexes.iter().enumerate().skip(1) { instructions.push(get_local(producer.get_io_info_tag())); let offsetdim = 4 * i; instructions.push(load32(Some(&offsetdim.to_string()))); // get size of ith dimension instructions.push(mul32()); // multiply the current move by size of the ith dimension - let mut instructions_idxi = indexes[i].produce_wasm(producer); + let mut instructions_idxi = item.produce_wasm(producer); instructions.append(&mut instructions_idxi); instructions.push(add32()); // add move upto dimension i } @@ -165,7 +165,7 @@ impl WriteWasm for LoadBucket { } } _ => { - assert!(false); + unreachable!(); } } } @@ -197,24 +197,23 @@ impl WriteC for LoadBucket { let mut map_access = format!("{}->{}[{}].defs[{}].offset", circom_calc_wit(), template_ins_2_io_info(), template_id_in_component(sub_component_pos_in_memory.clone()), - signal_code.to_string()); - if indexes.len()>0 { + signal_code); + if !indexes.is_empty() { let (mut index_code_0, mut map_index) = indexes[0].produce_c(producer, parallel); map_prologue.append(&mut index_code_0); - for i in 1..indexes.len() { - let (mut index_code, index_exp) = indexes[i].produce_c(producer, parallel); - map_prologue.append(&mut index_code); - map_index = format!("({})*{}->{}[{}].defs[{}].lengths[{}]+{}", - map_index, circom_calc_wit(), template_ins_2_io_info(), - template_id_in_component(sub_component_pos_in_memory.clone()), - signal_code.to_string(), (i-1).to_string(),index_exp); + for (i, item) in indexes.iter().enumerate().skip(1) { + let (mut index_code, index_exp) = item.produce_c(producer, parallel); + map_prologue.append(&mut index_code); + map_index = format!("({})*{}->{}[{}].defs[{}].lengths[{}]+{}", + map_index, circom_calc_wit(), template_ins_2_io_info(), + template_id_in_component(sub_component_pos_in_memory.clone()), + signal_code, (i-1),index_exp); } map_access = format!("{}+{}",map_access,map_index); } (map_prologue, map_access) } else { - assert!(false); - (vec![], "".to_string()) + unreachable!(); }; prologue.append(&mut src_prologue); let access = match &self.address_type { @@ -228,16 +227,16 @@ impl WriteC for LoadBucket { if *is_output { if uniform_parallel_value.is_some(){ if uniform_parallel_value.unwrap(){ - prologue.push(format!("{{")); + prologue.push("{".to_string()); prologue.push(format!("int aux1 = {};",cmp_index_ref.clone())); prologue.push(format!("int aux2 = {};",src_index.clone())); // check each one of the outputs of the assignment, we add i to check them one by one prologue.push(format!("for (int i = 0; i < {}; i++) {{",self.context.size)); - prologue.push(format!("ctx->numThreadMutex.lock();")); - prologue.push(format!("ctx->numThread--;")); + prologue.push("ctx->numThreadMutex.lock();".to_string()); + prologue.push("ctx->numThread--;".to_string()); //prologue.push(format!("printf(\"%i \\n\", ctx->numThread);")); - prologue.push(format!("ctx->numThreadMutex.unlock();")); - prologue.push(format!("ctx->ntcvs.notify_one();")); + prologue.push("ctx->numThreadMutex.unlock();".to_string()); + prologue.push("ctx->ntcvs.notify_one();".to_string()); prologue.push(format!( "std::unique_lock lk({}->componentMemory[{}[aux1]].mutexes[aux2 + i]);", CIRCOM_CALC_WIT, MY_SUBCOMPONENTS) @@ -249,10 +248,10 @@ impl WriteC for LoadBucket { ); prologue.push(format!("std::unique_lock lkt({}->numThreadMutex);",CIRCOM_CALC_WIT)); prologue.push(format!("{}->ntcvs.wait(lkt, [{}]() {{return {}->numThread < {}->maxThread; }});",CIRCOM_CALC_WIT,CIRCOM_CALC_WIT,CIRCOM_CALC_WIT,CIRCOM_CALC_WIT)); - prologue.push(format!("ctx->numThread++;")); + prologue.push("ctx->numThread++;".to_string()); //prologue.push(format!("printf(\"%i \\n\", ctx->numThread);")); - prologue.push(format!("}}")); - prologue.push(format!("}}")); + prologue.push("}".to_string()); + prologue.push("}".to_string()); } } // Case we only know if it is parallel at execution @@ -264,16 +263,16 @@ impl WriteC for LoadBucket { )); // case parallel - prologue.push(format!("{{")); + prologue.push("{".to_string()); prologue.push(format!("int aux1 = {};",cmp_index_ref.clone())); prologue.push(format!("int aux2 = {};",src_index.clone())); // check each one of the outputs of the assignment, we add i to check them one by one prologue.push(format!("for (int i = 0; i < {}; i++) {{",self.context.size)); - prologue.push(format!("ctx->numThreadMutex.lock();")); - prologue.push(format!("ctx->numThread--;")); + prologue.push("ctx->numThreadMutex.lock();".to_string()); + prologue.push("ctx->numThread--;".to_string()); //prologue.push(format!("printf(\"%i \\n\", ctx->numThread);")); - prologue.push(format!("ctx->numThreadMutex.unlock();")); - prologue.push(format!("ctx->ntcvs.notify_one();")); + prologue.push("ctx->numThreadMutex.unlock();".to_string()); + prologue.push("ctx->ntcvs.notify_one();".to_string()); prologue.push(format!( "std::unique_lock lk({}->componentMemory[{}[aux1]].mutexes[aux2 + i]);", CIRCOM_CALC_WIT, MY_SUBCOMPONENTS) @@ -285,14 +284,14 @@ impl WriteC for LoadBucket { ); prologue.push(format!("std::unique_lock lkt({}->numThreadMutex);",CIRCOM_CALC_WIT)); prologue.push(format!("{}->ntcvs.wait(lkt, [{}]() {{return {}->numThread < {}->maxThread; }});",CIRCOM_CALC_WIT,CIRCOM_CALC_WIT,CIRCOM_CALC_WIT,CIRCOM_CALC_WIT)); - prologue.push(format!("ctx->numThread++;")); + prologue.push("ctx->numThread++;".to_string()); //prologue.push(format!("printf(\"%i \\n\", ctx->numThread);")); - prologue.push(format!("}}")); - prologue.push(format!("}}")); + prologue.push("}".to_string()); + prologue.push("}".to_string()); // end of case parallel, in case no parallel we do nothing - prologue.push(format!("}}")); + prologue.push("}".to_string()); } } let sub_cmp_start = format!( diff --git a/compiler/src/intermediate_representation/log_bucket.rs b/compiler/src/intermediate_representation/log_bucket.rs index 30044146e..aa3f3f90f 100644 --- a/compiler/src/intermediate_representation/log_bucket.rs +++ b/compiler/src/intermediate_representation/log_bucket.rs @@ -106,8 +106,7 @@ impl WriteC for LogBucket { fn produce_c(&self, producer: &CProducer, parallel: Option) -> (Vec, String) { use c_code_generator::*; let mut log_c = Vec::new(); - let mut index = 0; - for logarg in &self.argsprint { + for (index, logarg) in self.argsprint.iter().enumerate() { if let LogBucketArg::LogExp(exp) = logarg { let (mut argument_code, argument_result) = exp.produce_c(producer, parallel); let to_string_call = build_call("Fr_element2str".to_string(), vec![argument_result]); @@ -122,8 +121,7 @@ impl WriteC for LogBucket { log_c.push(format!("{};", print_c)); log_c.push(format!("{};", delete_temp)); log_c.push("}".to_string()); - } - else if let LogBucketArg::LogStr(string_id) = logarg { + } else if let LogBucketArg::LogStr(string_id) = logarg { let string_value = &producer.get_string_table()[*string_id]; let print_c = @@ -134,8 +132,7 @@ impl WriteC for LogBucket { log_c.push("{".to_string()); log_c.push(format!("{};", print_c)); log_c.push("}".to_string()); - } - else{ + } else { unreachable!(); } if index != self.argsprint.len() - 1 { @@ -148,7 +145,6 @@ impl WriteC for LogBucket { log_c.push(format!("{};", print_c)); log_c.push("}".to_string()); } - index += 1; } let print_end_line = build_call( "printf".to_string(), diff --git a/compiler/src/intermediate_representation/mod.rs b/compiler/src/intermediate_representation/mod.rs index 8448d98d9..0c83b44fe 100644 --- a/compiler/src/intermediate_representation/mod.rs +++ b/compiler/src/intermediate_representation/mod.rs @@ -15,4 +15,4 @@ mod value_bucket; pub mod ir_interface; pub mod translate; -pub use ir_interface::{Instruction, InstructionList, InstructionPointer}; +pub use ir_interface::{InstructionList}; diff --git a/compiler/src/intermediate_representation/store_bucket.rs b/compiler/src/intermediate_representation/store_bucket.rs index 25111ddf1..2ed818cd6 100644 --- a/compiler/src/intermediate_representation/store_bucket.rs +++ b/compiler/src/intermediate_representation/store_bucket.rs @@ -146,12 +146,12 @@ impl WriteWasm for StoreBucket { // compute de move with 2 or more dimensions let mut instructions_idx0 = indexes[0].produce_wasm(producer); instructions.append(&mut instructions_idx0); // start with dimension 0 - for i in 1..indexes.len() { + for (i, item) in indexes.iter().enumerate().skip(1) { instructions.push(get_local(producer.get_io_info_tag())); let offsetdim = 4 * i; instructions.push(load32(Some(&offsetdim.to_string()))); // get size of ith dimension instructions.push(mul32()); // multiply the current move by size of the ith dimension - let mut instructions_idxi = indexes[i].produce_wasm(producer); + let mut instructions_idxi = item.produce_wasm(producer); instructions.append(&mut instructions_idxi); instructions.push(add32()); // add move upto dimension i } @@ -170,7 +170,7 @@ impl WriteWasm for StoreBucket { instructions.push(add32()); // we get the position of the signal (with indexes) in memory } _ => { - assert!(false); + unreachable!(); } } } @@ -214,8 +214,7 @@ impl WriteWasm for StoreBucket { instructions.push(add_end()); instructions.push(add_end()); } - match &self.dest_address_type { - AddressType::SubcmpSignal { .. } => { + if let AddressType::SubcmpSignal { .. } = &self.dest_address_type { // if subcomponent input check if run needed if producer.needs_comments() { instructions.push(";; decrease counter".to_string()); // by self.context.size @@ -257,15 +256,15 @@ impl WriteWasm for StoreBucket { instructions.push(add_return()); instructions.push(add_end()); } else { - assert!(false); + unreachable!(); } } LocationRule::Mapped { .. } => { instructions.push(get_local(producer.get_sub_cmp_tag())); instructions.push(load32(None)); // get template id instructions.push(call_indirect( - &"$runsmap".to_string(), - &"(type $_t_i32ri32)".to_string(), + "$runsmap", + "(type $_t_i32ri32)", )); instructions.push(tee_local(producer.get_merror_tag())); instructions.push(add_if()); @@ -283,8 +282,6 @@ impl WriteWasm for StoreBucket { } instructions.push(add_end()); } - _ => (), - } if producer.needs_comments() { instructions.push(";; end of store bucket".to_string()); } @@ -301,7 +298,7 @@ impl WriteC for StoreBucket { if let AddressType::SubcmpSignal { cmp_address, .. } = &self.dest_address_type { let (mut cmp_prologue, cmp_index) = cmp_address.produce_c(producer, parallel); prologue.append(&mut cmp_prologue); - prologue.push(format!("{{")); + prologue.push("{".to_string()); prologue.push(format!("uint {} = {};", cmp_index_ref, cmp_index)); } let ((mut dest_prologue, dest_index), my_template_header) = @@ -314,29 +311,28 @@ impl WriteC for StoreBucket { let mut map_access = format!("{}->{}[{}].defs[{}].offset", circom_calc_wit(), template_ins_2_io_info(), template_id_in_component(sub_component_pos_in_memory.clone()), - signal_code.to_string()); - if indexes.len()>0 { - map_prologue.push(format!("{{")); - map_prologue.push(format!("uint map_index_aux[{}];",indexes.len().to_string())); + signal_code); + if !indexes.is_empty() { + map_prologue.push("{".to_string()); + map_prologue.push(format!("uint map_index_aux[{}];",indexes.len())); let (mut index_code_0, mut map_index) = indexes[0].produce_c(producer, parallel); map_prologue.append(&mut index_code_0); map_prologue.push(format!("map_index_aux[0]={};",map_index)); - map_index = format!("map_index_aux[0]"); - for i in 1..indexes.len() { - let (mut index_code, index_exp) = indexes[i].produce_c(producer, parallel); - map_prologue.append(&mut index_code); - map_prologue.push(format!("map_index_aux[{}]={};",i.to_string(),index_exp)); - map_index = format!("({})*{}->{}[{}].defs[{}].lengths[{}]+map_index_aux[{}]", - map_index, circom_calc_wit(), template_ins_2_io_info(), - template_id_in_component(sub_component_pos_in_memory.clone()), - signal_code.to_string(),(i-1).to_string(),i.to_string()); + map_index = "map_index_aux[0]".to_string(); + for (i, item) in indexes.iter().enumerate().skip(1) { + let (mut index_code, index_exp) = item.produce_c(producer, parallel); + map_prologue.append(&mut index_code); + map_prologue.push(format!("map_index_aux[{}]={};",i,index_exp)); + map_index = format!("({})*{}->{}[{}].defs[{}].lengths[{}]+map_index_aux[{}]", + map_index, circom_calc_wit(), template_ins_2_io_info(), + template_id_in_component(sub_component_pos_in_memory.clone()), + signal_code,(i-1),i); } map_access = format!("{}+{}",map_access,map_index); } ((map_prologue, map_access),Some(template_id_in_component(sub_component_pos_in_memory.clone()))) } else { - assert!(false); - ((vec![], "".to_string()),Option::::None) + unreachable!(); }; prologue.append(&mut dest_prologue); // Build dest @@ -358,34 +354,34 @@ impl WriteC for StoreBucket { //keep dest_index in an auxiliar if parallel and out put if let AddressType::Signal = &self.dest_address_type { if parallel.unwrap() && self.dest_is_output { - prologue.push(format!("{{")); + prologue.push("{".to_string()); prologue.push(format!("uint {} = {};", aux_dest_index, dest_index.clone())); } } // store src in dest - prologue.push(format!("{{")); + prologue.push("{".to_string()); let aux_dest = "aux_dest".to_string(); prologue.push(format!("{} {} = {};", T_P_FR_ELEMENT, aux_dest, dest)); // Load src - prologue.push(format!("// load src")); + prologue.push("// load src".to_string()); let (mut src_prologue, src) = self.src.produce_c(producer, parallel); prologue.append(&mut src_prologue); - prologue.push(format!("// end load src")); + prologue.push("// end load src".to_string()); std::mem::drop(src_prologue); if self.context.size > 1 { let copy_arguments = vec![aux_dest, src, self.context.size.to_string()]; prologue.push(format!("{};", build_call("Fr_copyn".to_string(), copy_arguments))); if let AddressType::Signal = &self.dest_address_type { if parallel.unwrap() && self.dest_is_output { - prologue.push(format!("{{")); + prologue.push("{".to_string()); prologue.push(format!("for (int i = 0; i < {}; i++) {{",self.context.size)); prologue.push(format!("{}->componentMemory[{}].mutexes[{}+i].lock();",CIRCOM_CALC_WIT,CTX_INDEX,aux_dest_index.clone())); prologue.push(format!("{}->componentMemory[{}].outputIsSet[{}+i]=true;",CIRCOM_CALC_WIT,CTX_INDEX,aux_dest_index.clone())); prologue.push(format!("{}->componentMemory[{}].mutexes[{}+i].unlock();",CIRCOM_CALC_WIT,CTX_INDEX,aux_dest_index.clone())); prologue.push(format!("{}->componentMemory[{}].cvs[{}+i].notify_all();",CIRCOM_CALC_WIT,CTX_INDEX,aux_dest_index.clone())); - prologue.push(format!("}}")); - prologue.push(format!("}}")); - prologue.push(format!("}}")); + prologue.push("}".to_string()); + prologue.push("}".to_string()); + prologue.push("}".to_string()); } } } else { @@ -397,13 +393,12 @@ impl WriteC for StoreBucket { prologue.push(format!("{}->componentMemory[{}].outputIsSet[{}]=true;",CIRCOM_CALC_WIT,CTX_INDEX,aux_dest_index.clone())); prologue.push(format!("{}->componentMemory[{}].mutexes[{}].unlock();",CIRCOM_CALC_WIT,CTX_INDEX,aux_dest_index.clone())); prologue.push(format!("{}->componentMemory[{}].cvs[{}].notify_all();",CIRCOM_CALC_WIT,CTX_INDEX,aux_dest_index.clone())); - prologue.push(format!("}}")); + prologue.push("}".to_string()); } } } - prologue.push(format!("}}")); - match &self.dest_address_type { - AddressType::SubcmpSignal{ uniform_parallel_value, input_information, .. } => { + prologue.push("}".to_string()); + if let AddressType::SubcmpSignal{ uniform_parallel_value, input_information, .. } = &self.dest_address_type { // if subcomponent input check if run needed let sub_cmp_counter = format!( "{}->componentMemory[{}[{}]].inputCounter", @@ -438,7 +433,7 @@ impl WriteC for StoreBucket { thread_call_instr.push(format!("{}->componentMemory[{}].sbct[{}] = std::thread({},{});",CIRCOM_CALC_WIT,CTX_INDEX,cmp_index_ref, sub_cmp_call_name, argument_list(sub_cmp_call_arguments))); thread_call_instr.push(format!("std::unique_lock lkt({}->numThreadMutex);",CIRCOM_CALC_WIT)); thread_call_instr.push(format!("{}->ntcvs.wait(lkt, [{}]() {{return {}->numThread < {}->maxThread; }});",CIRCOM_CALC_WIT,CIRCOM_CALC_WIT,CIRCOM_CALC_WIT,CIRCOM_CALC_WIT)); - thread_call_instr.push(format!("ctx->numThread++;")); + thread_call_instr.push("ctx->numThread++;".to_string()); thread_call_instr } @@ -486,7 +481,7 @@ impl WriteC for StoreBucket { call_instructions.push(format!("{}->componentMemory[{}].sbct[{}] = std::thread({},{});",CIRCOM_CALC_WIT,CTX_INDEX,cmp_index_ref, sub_cmp_call_name, argument_list(sub_cmp_call_arguments.clone()))); call_instructions.push(format!("std::unique_lock lkt({}->numThreadMutex);",CIRCOM_CALC_WIT)); call_instructions.push(format!("{}->ntcvs.wait(lkt, [{}]() {{return {}->numThread < {}->maxThread; }});",CIRCOM_CALC_WIT,CIRCOM_CALC_WIT,CIRCOM_CALC_WIT,CIRCOM_CALC_WIT)); - call_instructions.push(format!("ctx->numThread++;")); + call_instructions.push("ctx->numThread++;".to_string()); if let StatusInput::Unknown = status { let sub_cmp_counter_decrease_andcheck = format!("!({})",sub_cmp_counter_decrease); @@ -502,7 +497,7 @@ impl WriteC for StoreBucket { } // end of case parallel - prologue.push(format!("}} else {{")); + prologue.push("} else {".to_string()); // case not parallel let sub_cmp_call_name = if let LocationRule::Indexed { .. } = &self.dest { @@ -527,21 +522,19 @@ impl WriteC for StoreBucket { prologue.append(&mut call_instructions); } // end of not parallel case - prologue.push(format!("}}")); + prologue.push("}".to_string()); } } } else { - assert!(false); + unreachable!(); } - } - _ => (), } if let AddressType::SubcmpSignal { .. } = &self.dest_address_type { - prologue.push(format!("}}")); + prologue.push("}".to_string()); } if let LocationRule::Mapped { indexes, .. } = &self.dest { - if indexes.len() > 0 { - prologue.push(format!("}}")); + if !indexes.is_empty() { + prologue.push("}".to_string()); } } diff --git a/compiler/src/intermediate_representation/translate.rs b/compiler/src/intermediate_representation/translate.rs index 04309bb23..a974a3aee 100644 --- a/compiler/src/intermediate_representation/translate.rs +++ b/compiler/src/intermediate_representation/translate.rs @@ -195,8 +195,7 @@ fn initialize_constants(state: &mut State, constants: Vec) { let symbol_info = SymbolInfo { access_instruction: address_instruction.clone(), dimensions, is_component:false }; state.environment.add_variable(&arg.name, symbol_info); - let mut index = 0; - for value in arg.values { + for (index, value) in arg.values.into_iter().enumerate() { let cid = bigint_to_cid(&mut state.field_tracker, &value); let offset_instruction = ValueBucket { line: 0, @@ -233,7 +232,6 @@ fn initialize_constants(state: &mut State, constants: Vec) { } .allocate(); state.code.push(store_instruction); - index += 1; } } } @@ -298,13 +296,13 @@ fn create_components(state: &mut State, triggers: &[Trigger], clusters: Vec) -> usize { + fn compute_number_cmp(lengths: &[usize]) -> usize { lengths.iter().fold(1, |p, c| p * (*c)) } - fn compute_jump(lengths: &Vec, indexes: &[usize]) -> usize { + fn compute_jump(lengths: &[usize], indexes: &[usize]) -> usize { let mut jump = 0; let mut full_length = lengths.iter().fold(1, |p, c| p * (*c)); - let mut lengths = lengths.clone(); + let mut lengths = lengths.to_owned(); lengths.reverse(); for index in indexes { let length = lengths.pop().unwrap(); @@ -344,7 +342,7 @@ fn create_uniform_components(state: &mut State, triggers: &[Trigger], cluster: T number_of_cmp: compute_number_cmp(&symbol.dimensions), dimensions: symbol.dimensions, signal_offset_jump: offset_jump, - component_offset_jump: component_offset_jump, + component_offset_jump, } .allocate(); state.code.push(creation_instr); @@ -354,10 +352,10 @@ fn create_uniform_components(state: &mut State, triggers: &[Trigger], cluster: T } fn create_mixed_components(state: &mut State, triggers: &[Trigger], cluster: TriggerCluster) { - fn compute_jump(lengths: &Vec, indexes: &[usize]) -> usize { + fn compute_jump(lengths: &[usize], indexes: &[usize]) -> usize { let mut jump = 0; let mut full_length = lengths.iter().fold(1, |p, c| p * (*c)); - let mut lengths = lengths.clone(); + let mut lengths = lengths.to_owned(); lengths.reverse(); for index in indexes { let length = lengths.pop().unwrap(); @@ -389,14 +387,11 @@ fn create_mixed_components(state: &mut State, triggers: &[Trigger], cluster: Tri .allocate(); let info_parallel_cluster = state.component_to_parallel.get(&c_info.component_name).unwrap(); - let parallel_value: bool; - if info_parallel_cluster.uniform_parallel_value.is_some(){ - parallel_value = info_parallel_cluster.uniform_parallel_value.unwrap(); - } - else{ - parallel_value = *info_parallel_cluster. - positions_to_parallel.get(&c_info.indexed_with).unwrap(); - } + let parallel_value = if let Some(b) = info_parallel_cluster.uniform_parallel_value { + b + } else{ + *info_parallel_cluster.positions_to_parallel.get(&c_info.indexed_with).unwrap() + }; let creation_instr = CreateCmpBucket { line: 0, @@ -453,10 +448,10 @@ fn translate_if_then_else(stmt: Statement, state: &mut State, context: &Context) use Statement::IfThenElse; if let IfThenElse { meta, cond, if_case, else_case, .. } = stmt { let starts_at = context.files.get_line(meta.start, meta.get_file_id()).unwrap(); - let main_program = std::mem::replace(&mut state.code, vec![]); + let main_program = std::mem::take(&mut state.code); let cond_translation = translate_expression(cond, state, context); translate_statement(*if_case, state, context); - let if_code = std::mem::replace(&mut state.code, vec![]); + let if_code = std::mem::take(&mut state.code); if let Option::Some(else_case) = else_case { translate_statement(*else_case, state, context); } @@ -477,7 +472,7 @@ fn translate_while(stmt: Statement, state: &mut State, context: &Context) { use Statement::While; if let While { meta, cond, stmt, .. } = stmt { let starts_at = context.files.get_line(meta.start, meta.get_file_id()).unwrap(); - let main_program = std::mem::replace(&mut state.code, vec![]); + let main_program = std::mem::take(&mut state.code); let cond_translation = translate_expression(cond, state, context); translate_statement(*stmt, state, context); let loop_code = std::mem::replace(&mut state.code, main_program); @@ -523,7 +518,7 @@ fn translate_call_case( use Expression::Call; if let Call { id, args, .. } = info.src { let args_instr = translate_call_arguments(args, state, context); - info.prc_symbol.into_call_assign(id, args_instr, &state) + info.prc_symbol.into_call_assign(id, args_instr, state) } else { unreachable!() } @@ -681,9 +676,7 @@ fn translate_expression( translate_number(expression, state, context) } else if expression.is_call() { translate_call(expression, state, context) - } else if expression.is_array() { - unreachable!("This expression is syntactic sugar") - } else if expression.is_switch() { + } else if expression.is_array() || expression.is_switch() { unreachable!("This expression is syntactic sugar") } else { unreachable!("Unknown expression") @@ -787,11 +780,10 @@ fn translate_variable( state: &mut State, context: &Context, ) -> InstructionPointer { - use Expression::{Variable}; + use Expression::Variable; if let Variable { meta, name, access, .. } = expression { - let tag_access = check_tag_access(&name, &access, state); - if tag_access.is_some(){ - translate_number( Expression::Number(meta.clone(), tag_access.unwrap()), state, context) + if let Some(ta) = check_tag_access(&name, &access, state) { + translate_number( Expression::Number(meta.clone(), ta), state, context) } else{ let def = SymbolDef { meta, symbol: name, acc: access }; ProcessedSymbol::new(def, state, context).into_load(state) @@ -954,10 +946,8 @@ impl ProcessedSymbol { with_length = possible_length.iter().fold(1, |r, c| r * (*c)); is_first = false; } - else{ - if with_length != possible_length.iter().fold(1, |r, c| r * (*c)){ - unreachable!("On development: Circom compiler does not accept for now the assignment of arrays of unknown sizes during the execution of loops"); - } + else if with_length != possible_length.iter().fold(1, |r, c| r * (*c)){ + unreachable!("On development: Circom compiler does not accept for now the assignment of arrays of unknown sizes during the execution of loops"); } } } @@ -1144,7 +1134,7 @@ fn compute_full_address( stack.push(jump); } stack.push(at); - fold(OperatorType::AddAddress, stack, state) + fold(OperatorType::AddAddress, stack) } } @@ -1192,13 +1182,11 @@ fn check_if_possible_to_usize_single( // returns if it is possible to convert to } Value(v) if v.parse_as == ValueType::BigInt => { let field = state.field_tracker.get_constant(v.value).unwrap(); - let new_value = usize::from_str_radix(field, 10); - - match new_value{ - Ok(_) =>{ - (true, new_value.unwrap() < 100) + match field.parse::() { + Ok(v) => { + (true, v < 100) } - _ =>{ + _ => { (false, false) } } @@ -1238,13 +1226,8 @@ fn check_if_possible_to_usize_multiple( // returns if all of them are usize and (is_usize, number_non_small <= 1) } - - -fn convert_to_usize_single( - index: InstructionPointer, - state: &State, -)-> InstructionPointer{ - +#[allow(clippy::boxed_local)] +fn convert_to_usize_single(index: InstructionPointer, state: &State) -> InstructionPointer { use Instruction::{Value, Compute}; match *index { @@ -1253,15 +1236,13 @@ fn convert_to_usize_single( } Value(mut v) if v.parse_as == ValueType::BigInt => { let field = state.field_tracker.get_constant(v.value).unwrap(); - let new_value = usize::from_str_radix(field, 10); - - match new_value{ - Ok(value) =>{ + match field.parse::() { + Ok(value) => { v.parse_as = ValueType::U32; v.value = value; v.allocate() } - _ =>{ + _ => { unreachable!() } } @@ -1307,9 +1288,9 @@ fn convert_to_usize_multiple( } -fn fold(using: OperatorType, mut stack: Vec, state: &State) -> InstructionPointer { +fn fold(using: OperatorType, mut stack: Vec) -> InstructionPointer { let instruction = stack.pop().unwrap(); - if stack.len() == 0 { + if stack.is_empty() { instruction } else { ComputeBucket { @@ -1317,7 +1298,7 @@ fn fold(using: OperatorType, mut stack: Vec, state: &State) message_id: instruction.get_message_id(), op_aux_no: 0, op: using, - stack: vec![fold(using, stack, state), instruction], + stack: vec![fold(using, stack), instruction], } .allocate() } diff --git a/compiler/src/intermediate_representation/value_bucket.rs b/compiler/src/intermediate_representation/value_bucket.rs index 8575e5335..6878bda31 100644 --- a/compiler/src/intermediate_representation/value_bucket.rs +++ b/compiler/src/intermediate_representation/value_bucket.rs @@ -39,7 +39,7 @@ impl ToString for ValueBucket { let template_id = self.message_id.to_string(); let parse_as = self.parse_as.to_string(); let op_aux_number = self.op_aux_no.to_string(); - let value = self.value.clone(); + let value = self.value; format!( "VALUE(line:{},template_id:{},as:{},op_number:{},value:{})", line, template_id, parse_as, op_aux_number, value diff --git a/compiler/src/ir_processing/build_inputs_info.rs b/compiler/src/ir_processing/build_inputs_info.rs index 49e6edb9b..483159b09 100644 --- a/compiler/src/ir_processing/build_inputs_info.rs +++ b/compiler/src/ir_processing/build_inputs_info.rs @@ -1,5 +1,5 @@ use crate::intermediate_representation::ir_interface::*; -use std::collections::{HashSet}; +use std::collections::HashSet; type ComponentsSet = HashSet; @@ -75,16 +75,16 @@ pub fn visit_branch( inside_loop ); - let known_component_both_branches: ComponentsSet = known_last_component_if.intersection(& known_last_component_else).map(|s| s.clone()).collect(); - let known_component_one_branch: ComponentsSet = known_last_component_if.symmetric_difference(&known_last_component_else).map(|s| s.clone()).collect(); + let known_component_both_branches: ComponentsSet = known_last_component_if.intersection(& known_last_component_else).cloned().collect(); + let known_component_one_branch: ComponentsSet = known_last_component_if.symmetric_difference(&known_last_component_else).cloned().collect(); - let mut new_unknown_component: ComponentsSet = unknown_last_component_if.union(&unknown_last_component_else).map(|s| s.clone()).collect(); - new_unknown_component = new_unknown_component.union(&known_component_one_branch).map(|s| s.clone()).collect(); + let mut new_unknown_component: ComponentsSet = unknown_last_component_if.union(&unknown_last_component_else).cloned().collect(); + new_unknown_component = new_unknown_component.union(&known_component_one_branch).cloned().collect(); - let joined_unknown_component: ComponentsSet = unknown_last_component.union(&new_unknown_component).map(|s| s.clone()).collect(); + let joined_unknown_component: ComponentsSet = unknown_last_component.union(&new_unknown_component).cloned().collect(); - *known_last_component = known_last_component.union(&known_component_both_branches).map(|s| s.clone()).collect(); - *unknown_last_component = joined_unknown_component.difference(&known_component_both_branches).map(|s| s.clone()).collect(); + *known_last_component = known_last_component.union(&known_component_both_branches).cloned().collect(); + *unknown_last_component = joined_unknown_component.difference(&known_component_both_branches).cloned().collect(); found_unknown_if || found_unknown_else } @@ -152,10 +152,10 @@ pub fn visit_loop( true ); - let new_unknown_component: ComponentsSet = known_last_component_loop.union(&unknown_last_component_loop).map(|s| s.clone()).collect(); + let new_unknown_component: ComponentsSet = known_last_component_loop.union(&unknown_last_component_loop).cloned().collect(); - *known_last_component = known_last_component.difference(&new_unknown_component).map(|s| s.clone()).collect(); - *unknown_last_component = unknown_last_component.union(&new_unknown_component).map(|s| s.clone()).collect(); + *known_last_component = known_last_component.difference(&new_unknown_component).cloned().collect(); + *unknown_last_component = unknown_last_component.union(&new_unknown_component).cloned().collect(); found_unknown_address_new } @@ -255,31 +255,22 @@ pub fn visit_address_type( //println!("Poniendo un unknown en {}", cmp_address.to_string()); found_unknown_address } - else{ - if let Value {..} = **cmp_address{ - if found_unknown_address{ - *input_information = Input{status: Unknown}; - //println!("Poniendo un unknown en {}", cmp_address.to_string()); - } - else{ - if inside_loop { - *input_information = Input{status: Unknown}; - //println!("Poniendo un unknown en {}", cmp_address.to_string()); - } - else{ - *input_information = Input{status: Last}; - //println!("Poniendo un last en {}", cmp_address.to_string()); - } - } - known_last_component.insert(cmp_address.to_string()); - unknown_last_component.remove(&cmp_address.to_string()); - found_unknown_address - } - else{ + else if let Value {..} = **cmp_address{ + if found_unknown_address || inside_loop { *input_information = Input{status: Unknown}; //println!("Poniendo un unknown en {}", cmp_address.to_string()); - false + } else { + *input_information = Input{status: Last}; + //println!("Poniendo un last en {}", cmp_address.to_string()); } + known_last_component.insert(cmp_address.to_string()); + unknown_last_component.remove(&cmp_address.to_string()); + found_unknown_address + } + else{ + *input_information = Input{status: Unknown}; + //println!("Poniendo un unknown en {}", cmp_address.to_string()); + false } } else{ diff --git a/compiler/src/ir_processing/build_stack.rs b/compiler/src/ir_processing/build_stack.rs index f17b30e64..25dae36c7 100644 --- a/compiler/src/ir_processing/build_stack.rs +++ b/compiler/src/ir_processing/build_stack.rs @@ -75,8 +75,8 @@ pub fn build_compute(bucket: &mut ComputeBucket, mut fresh: usize) -> usize { pub fn build_load(bucket: &mut LoadBucket, fresh: usize) -> usize { let v0 = build_address_type(&mut bucket.address_type, fresh); - let v1 = build_location(&mut bucket.src, v0); - v1 + + build_location(&mut bucket.src, v0) } pub fn build_create_cmp(bucket: &mut CreateCmpBucket, fresh: usize) -> usize { diff --git a/constant_tracking/src/lib.rs b/constant_tracking/src/lib.rs index f661d98bf..29ea96bc2 100644 --- a/constant_tracking/src/lib.rs +++ b/constant_tracking/src/lib.rs @@ -10,6 +10,15 @@ where constants: Vec, } +impl Default for ConstantTracker +where + C: Eq + Hash + Clone, + { + fn default() -> Self { + Self::new() + } +} + impl ConstantTracker where C: Eq + Hash + Clone, diff --git a/constraint_generation/src/compute_constants.rs b/constraint_generation/src/compute_constants.rs index d16020959..06c404b21 100644 --- a/constraint_generation/src/compute_constants.rs +++ b/constraint_generation/src/compute_constants.rs @@ -89,9 +89,7 @@ fn treat_statement(stmt: &mut Statement, context: &Context, reports: &mut Report treat_declaration(stmt, context, reports, flags, prime) } else if stmt.is_substitution(){ treat_substitution(stmt, context, reports, flags, prime) - } else{ - - } + } } fn treat_init_block(stmt: &mut Statement, context: &Context, reports: &mut ReportCollection, flags: FlagsExecution, prime: &String) { @@ -184,15 +182,14 @@ fn treat_expression( ){ use Expression::{Number, UniformArray}; if let UniformArray {meta, value, dimension} = expr{ - let execution_response = treat_dimension(&dimension, context, reports, flags, prime); + let execution_response = treat_dimension(dimension, context, reports, flags, prime); if let Option::Some(v) = execution_response { **dimension = Number(meta.clone(), BigInt::from(v)); } else { report_invalid_dimension(meta, reports); } treat_expression(value, context, reports, flags, prime) - } else{ - } + } } fn treat_dimension( diff --git a/constraint_generation/src/environment_utils/component_representation.rs b/constraint_generation/src/environment_utils/component_representation.rs index 3d6505466..c57a933c6 100644 --- a/constraint_generation/src/environment_utils/component_representation.rs +++ b/constraint_generation/src/environment_utils/component_representation.rs @@ -4,6 +4,7 @@ use crate::execution_data::ExecutedProgram; use std::collections::{BTreeMap,HashMap, HashSet}; use crate::ast::Meta; +#[derive(Default)] pub struct ComponentRepresentation { pub node_pointer: Option, pub is_parallel: bool, @@ -18,23 +19,7 @@ pub struct ComponentRepresentation { pub is_initialized: bool, } -impl Default for ComponentRepresentation { - fn default() -> Self { - ComponentRepresentation { - node_pointer: Option::None, - is_parallel: false, - unassigned_inputs: HashMap::new(), - unassigned_tags: HashSet::new(), - to_assign_inputs: Vec::new(), - inputs: HashMap::new(), - inputs_tags: BTreeMap::new(), - outputs: HashMap::new(), - outputs_tags: BTreeMap::new(), - is_initialized: false, - meta: Option::None, - } - } -} + impl Clone for ComponentRepresentation { fn clone(&self) -> Self { ComponentRepresentation { @@ -267,15 +252,13 @@ impl ComponentRepresentation { for (t, value) in tags_input{ if !tags.contains_key(t){ return Result::Err(MemoryError::AssignmentMissingTags(signal_name.to_string(), t.clone())); - } else{ - if is_first_assignment_signal{ - *value = tags.get(t).unwrap().clone(); - } - else{ - // already given a value, check that it is the same - if value != tags.get(t).unwrap(){ - return Result::Err(MemoryError::AssignmentTagInputTwice(signal_name.to_string(), t.clone())); - } + } else if is_first_assignment_signal{ + *value = tags.get(t).unwrap().clone(); + } + else{ + // already given a value, check that it is the same + if value != tags.get(t).unwrap(){ + return Result::Err(MemoryError::AssignmentTagInputTwice(signal_name.to_string(), t.clone())); } } } @@ -316,7 +299,7 @@ impl ComponentRepresentation { let inputs_response = component.inputs.get_mut(signal_name).unwrap(); let signal_previous_value = SignalSlice::access_values( inputs_response, - &access, + access, )?; let new_value_slice = &SignalSlice::new_with_route(slice_route, &true); @@ -324,7 +307,7 @@ impl ComponentRepresentation { SignalSlice::check_correct_dims( &signal_previous_value, &Vec::new(), - &new_value_slice, + new_value_slice, true )?; @@ -337,19 +320,16 @@ impl ComponentRepresentation { SignalSlice::insert_values( inputs_response, - &access, - &new_value_slice, + access, + new_value_slice, true )?; let dim = SignalSlice::get_number_of_cells(new_value_slice); - match component.unassigned_inputs.get_mut(signal_name){ - Some(left) => { - *left -= dim; - if *left == 0 { - component.unassigned_inputs.remove(signal_name); - } + if let Some(left) = component.unassigned_inputs.get_mut(signal_name) { + *left -= dim; + if *left == 0 { + component.unassigned_inputs.remove(signal_name); } - None => {} } Result::Ok(()) diff --git a/constraint_generation/src/environment_utils/environment.rs b/constraint_generation/src/environment_utils/environment.rs index 3dca8c5a8..a5cf057c9 100644 --- a/constraint_generation/src/environment_utils/environment.rs +++ b/constraint_generation/src/environment_utils/environment.rs @@ -72,13 +72,13 @@ pub fn environment_shortcut_add_variable( environment.add_variable(variable_name, (TagInfo::new(), slice)); } -pub fn environment_check_all_components_assigned(environment: &ExecutionEnvironment)-> Result<(), (MemoryError, Meta)>{ +pub fn environment_check_all_components_assigned(environment: &ExecutionEnvironment)-> Result<(), Box<(MemoryError, Meta)>>{ use program_structure::memory_slice::MemorySlice; for (name, slice) in environment.get_components_ref(){ for i in 0..MemorySlice::get_number_of_cells(slice){ let component = MemorySlice::get_reference_to_single_value_by_index_or_break(slice, i); - if component.is_preinitialized() && component.has_unassigned_inputs(){ - return Result::Err((MemoryError::MissingInputs(name.clone()), component.meta.as_ref().unwrap().clone())); + if component.is_preinitialized() && component.has_unassigned_inputs() { + return Result::Err(Box::new((MemoryError::MissingInputs(name.clone()), component.meta.as_ref().unwrap().clone()))); } } } diff --git a/constraint_generation/src/execute.rs b/constraint_generation/src/execute.rs index a4d085fff..de25c497b 100644 --- a/constraint_generation/src/execute.rs +++ b/constraint_generation/src/execute.rs @@ -61,6 +61,7 @@ impl RuntimeInformation { } } +#[derive(Default)] struct FoldedValue { pub arithmetic_slice: Option, pub node_pointer: Option, @@ -76,16 +77,7 @@ impl FoldedValue { } } -impl Default for FoldedValue { - fn default() -> Self { - FoldedValue { - arithmetic_slice: Option::None, - node_pointer: Option::None, - is_parallel: Option::None, - tags: Option::None, - } - } -} + enum ExecutionError { NonQuadraticConstraint, @@ -199,7 +191,7 @@ fn execute_statement( execute_anonymous_component_declaration( name, meta.clone(), - &dimensions, + dimensions, &mut runtime.environment, &mut runtime.anonymous_components, ); @@ -373,7 +365,7 @@ fn execute_statement( AExpr::sub( &value_left, &value_right, - &runtime.constants.get_p() + runtime.constants.get_p() ); if possible_non_quadratic.is_nonquadratic() { treat_result_with_execution_error( @@ -457,9 +449,8 @@ fn execute_statement( } LogCall { args, .. } => { can_be_simplified = false; - if flags.verbose{ - let mut index = 0; - for arglog in args { + if flags.verbose { + for (index, arglog) in args.iter().enumerate() { if let LogArgument::LogExp(arg) = arglog{ let f_result = execute_expression(arg, program_archive, runtime, flags)?; let arith = safe_unwrap_to_single_arithmetic_expression(f_result, line!()); @@ -476,9 +467,8 @@ fn execute_statement( if index != args.len()-1{ print!(" "); } - index += 1; } - println!(""); + println!(); } else{ for arglog in args { if let LogArgument::LogExp(arg) = arglog{ @@ -690,8 +680,8 @@ fn execute_expression( //************************************************* Statement execution support ************************************************* fn execute_call( - id: &String, - args: &Vec, + id: &str, + args: &[Expression], program_archive: &ProgramArchive, runtime: &mut RuntimeInformation, flags: FlagsExecution, @@ -705,12 +695,12 @@ fn execute_call( let new_environment = prepare_environment_for_call(id, &arg_values, program_archive); let previous_environment = std::mem::replace(&mut runtime.environment, new_environment); let previous_block_type = std::mem::replace(&mut runtime.block_type, BlockType::Known); - let previous_anonymous_components = std::mem::replace(&mut runtime.anonymous_components, AnonymousComponentsInfo::new()); + let previous_anonymous_components = std::mem::take(&mut runtime.anonymous_components); let new_file_id = program_archive.get_function_data(id).get_file_id(); let previous_id = std::mem::replace(&mut runtime.current_file, new_file_id); - runtime.call_trace.push(id.clone()); + runtime.call_trace.push(id.to_owned()); let folded_result = execute_function_call(id, program_archive, runtime, flags)?; runtime.environment = previous_environment; @@ -726,7 +716,7 @@ fn execute_call( } fn execute_template_call_complete( - id: &String, + id: &str, arg_values: Vec, tags: BTreeMap, program_archive: &ProgramArchive, @@ -737,12 +727,12 @@ fn execute_template_call_complete( let new_environment = prepare_environment_for_call(id, &arg_values, program_archive); let previous_environment = std::mem::replace(&mut runtime.environment, new_environment); let previous_block_type = std::mem::replace(&mut runtime.block_type, BlockType::Known); - let previous_anonymous_components = std::mem::replace(&mut runtime.anonymous_components, AnonymousComponentsInfo::new()); + let previous_anonymous_components = std::mem::take(&mut runtime.anonymous_components); let new_file_id = program_archive.get_template_data(id).get_file_id(); let previous_id = std::mem::replace(&mut runtime.current_file, new_file_id); - runtime.call_trace.push(id.clone()); + runtime.call_trace.push(id.to_owned()); let folded_result = execute_template_call(id, arg_values, tags, program_archive, runtime, flags)?; runtime.environment = previous_environment; @@ -773,12 +763,12 @@ fn execute_component_declaration( fn execute_anonymous_component_declaration( component_name: &str, meta: Meta, - dimensions: &Vec, + dimensions: &[Expression], environment: &mut ExecutionEnvironment, anonymous_components: &mut AnonymousComponentsInfo, ) { environment_shortcut_add_component(environment, component_name, &Vec::new()); - anonymous_components.insert(component_name.to_string(), (meta, dimensions.clone())); + anonymous_components.insert(component_name.to_string(), (meta, dimensions.to_owned())); } fn execute_signal_declaration( @@ -799,7 +789,7 @@ fn execute_signal_declaration( match signal_type { Input => { if let Some(tags_input) = node.tag_instances().get(signal_name){ - environment_shortcut_add_input(environment, signal_name, dimensions, &tags_input); + environment_shortcut_add_input(environment, signal_name, dimensions, tags_input); } else{ environment_shortcut_add_input(environment, signal_name, dimensions, &tags); } @@ -827,6 +817,7 @@ struct Constrained { left: String, right: AExpressionSlice, } +#[allow(clippy::too_many_arguments)] fn perform_assign( meta: &Meta, symbol: &str, @@ -839,7 +830,7 @@ fn perform_assign( flags: FlagsExecution ) -> Result, ()> { use super::execution_data::type_definitions::SubComponentData; - let full_symbol = create_symbol(symbol, &accessing_information); + let full_symbol = create_symbol(symbol, accessing_information); let possible_arithmetic_slice = if ExecutionEnvironment::has_variable(&runtime.environment, symbol) { @@ -866,7 +857,7 @@ fn perform_assign( let new_value = AExpressionSlice::new_with_route(symbol_content.route(), &AExpr::NonQuadratic); let memory_result = - AExpressionSlice::insert_values(symbol_content, &vec![], &new_value, false); + AExpressionSlice::insert_values(symbol_content, &[], &new_value, false); treat_result_with_memory_error_void( memory_result, meta, @@ -915,7 +906,7 @@ fn perform_assign( &runtime.call_trace, )?; - if SignalSlice::get_number_of_inserts(&reference_to_signal_content) > 0{ + if SignalSlice::get_number_of_inserts(reference_to_signal_content) > 0{ treat_result_with_memory_error( Result::Err(MemoryError::AssignmentTagAfterInit), meta, @@ -929,7 +920,7 @@ fn perform_assign( ArithmeticExpressionGen::Number { value } => { let possible_tag = reference_to_tags.get(&tag.clone()); if let Some(val) = possible_tag { - if let Some(_) = val { + if val.is_some() { treat_result_with_memory_error( Result::Err(MemoryError::AssignmentTagTwice), meta, @@ -1017,28 +1008,26 @@ fn perform_assign( if tag_state.value_defined{ // already with value, store the same value reference_to_tags.insert(tag, value); - } else{ - if signal_is_init { - // only keep value if same as previous - let to_store_value = if new_tags.contains_key(&tag){ - let value_new = new_tags.get(&tag).unwrap(); - if value != *value_new{ - None - } else{ - value - } - } else{ + } else if signal_is_init { + // only keep value if same as previous + let to_store_value = if new_tags.contains_key(&tag){ + let value_new = new_tags.get(&tag).unwrap(); + if value != *value_new{ None - }; - reference_to_tags.insert(tag, to_store_value); - } else{ - // always keep - if new_tags.contains_key(&tag){ - let value_new = new_tags.get(&tag).unwrap(); - reference_to_tags.insert(tag, value_new.clone()); } else{ - reference_to_tags.insert(tag, None); + value } + } else{ + None + }; + reference_to_tags.insert(tag, to_store_value); + } else{ + // always keep + if new_tags.contains_key(&tag){ + let value_new = new_tags.get(&tag).unwrap(); + reference_to_tags.insert(tag, value_new.clone()); + } else{ + reference_to_tags.insert(tag, None); } } } else{ @@ -1074,7 +1063,7 @@ fn perform_assign( let correct_dims_result = SignalSlice::check_correct_dims( &signal_previous_value, &Vec::new(), - &new_value_slice, + new_value_slice, true ); treat_result_with_memory_error_void( @@ -1107,7 +1096,7 @@ fn perform_assign( let access_response = SignalSlice::insert_values( reference_to_signal_content, &accessing_information.before_signal, - &new_value_slice, + new_value_slice, true ); @@ -1124,7 +1113,7 @@ fn perform_assign( tag_state.complete = true; if let Option::Some(node) = actual_node{ if !tag_state.value_defined{ - node.add_tag_signal(symbol, &tag, value.clone()); + node.add_tag_signal(symbol, tag, value.clone()); } } else{ unreachable!(); @@ -1230,7 +1219,7 @@ fn perform_assign( let init_result = ComponentRepresentation::initialize_component( component, node_pointer, - &mut runtime.exec_program, + &runtime.exec_program, ); treat_result_with_memory_error( init_result, @@ -1265,7 +1254,7 @@ fn perform_assign( component, &signal_accessed, &accessing_information.after_signal, - &arithmetic_slice.route(), + arithmetic_slice.route(), tags, ); treat_result_with_memory_error_void( @@ -1320,7 +1309,7 @@ fn perform_assign( let init_result = ComponentRepresentation::initialize_component( component, node_pointer, - &mut runtime.exec_program, + &runtime.exec_program, ); treat_result_with_memory_error_void( init_result, @@ -1335,7 +1324,7 @@ fn perform_assign( is_parallel: component.is_parallel, indexed_with: accessing_information.before_signal.clone(), }; - let component_symbol = create_component_symbol(symbol, &accessing_information); + let component_symbol = create_component_symbol(symbol, accessing_information); actual_node.add_arrow(component_symbol, data); } else { unreachable!(); @@ -1390,7 +1379,7 @@ fn execute_conditional_statement( } } runtime.block_type = previous_block_type; - return Result::Ok((ret_value, can_simplify, Option::None)); + Result::Ok((ret_value, can_simplify, Option::None)) } } @@ -1508,7 +1497,7 @@ fn execute_variable( &mut runtime.runtime_errors, &runtime.call_trace, )?; - let memory_response = AExpressionSlice::access_values(&ae_slice, &indexing); + let memory_response = AExpressionSlice::access_values(ae_slice, &indexing); let ae_slice = treat_result_with_memory_error( memory_response, meta, @@ -1715,7 +1704,7 @@ fn execute_component( &mut runtime.runtime_errors, &runtime.call_trace, )?; - let slice = SignalSlice::access_values(signal, &access_after_signal); + let slice = SignalSlice::access_values(signal, access_after_signal); let slice = treat_result_with_memory_error( slice, meta, @@ -1803,7 +1792,7 @@ fn execute_template_call( flags: FlagsExecution ) -> Result { debug_assert!(runtime.block_type == BlockType::Known); - let is_main = std::mem::replace(&mut runtime.public_inputs, vec![]); + let is_main = std::mem::take(&mut runtime.public_inputs); let is_parallel = program_archive.get_template_data(id).is_parallel(); let is_custom_gate = program_archive.get_template_data(id).is_custom_gate(); let args_names = program_archive.get_template_data(id).get_name_of_params(); @@ -1813,19 +1802,17 @@ fn execute_template_call( let mut instantiation_name = format!("{}(", id); let mut not_empty_name = false; for (name, value) in args_names.iter().zip(parameter_values) { - instantiation_name.push_str(&format!("{},", value.to_string())); + instantiation_name.push_str(&format!("{},", value)); not_empty_name = true; args_to_values.insert(name.clone(), value.clone()); } - for (_input, input_tags) in &tag_values{ - for (_tag, value) in input_tags { - if value.is_none(){ + for input_tags in tag_values.values() { + for value in input_tags.values() { + if let Some(v) = value { + instantiation_name.push_str(&format!("{},", v)); + } else { instantiation_name.push_str("null,"); } - else{ - let value = value.clone().unwrap(); - instantiation_name.push_str(&format!("{},", value.to_string())); - } not_empty_name = true; } } @@ -1862,22 +1849,19 @@ fn execute_template_call( debug_assert!(ret.is_none()); let result_check_components = environment_check_all_components_assigned(&runtime.environment); - match result_check_components{ - Err((error, meta)) =>{ - treat_result_with_memory_error_void( - Err(error), - &meta, - &mut runtime.runtime_errors, - &runtime.call_trace, - )?; - }, - Ok(_) => {}, + if let Err(err) = result_check_components { + treat_result_with_memory_error_void( + Err(err.0), + &err.1, + &mut runtime.runtime_errors, + &runtime.call_trace, + )?; } let new_node = node_wrap.unwrap(); let analysis = std::mem::replace(&mut runtime.analysis, analysis); - let node_pointer = runtime.exec_program.add_node_to_scheme(new_node, analysis); - node_pointer + + runtime.exec_program.add_node_to_scheme(new_node, analysis) }; Result::Ok(FoldedValue { node_pointer: Option::Some(node_pointer), is_parallel: Option::Some(false), ..FoldedValue::default() }) } @@ -1904,14 +1888,12 @@ fn preexecute_template_call( outputs_to_tags.insert(name.clone(), info_output.1.clone()); } - let node_wrap = Option::Some(PreExecutedTemplate::new( + let new_node = PreExecutedTemplate::new( id.to_string(), parameter_values.to_vec(), inputs_to_tags, outputs_to_tags, - )); - - let new_node = node_wrap.unwrap(); + ); let node_pointer = runtime.exec_program.add_prenode_to_scheme(new_node); Result::Ok(FoldedValue { node_pointer: Option::Some(node_pointer), is_parallel: Option::Some(false), ..FoldedValue::default() }) } @@ -2055,10 +2037,7 @@ fn cast_index(ae_index: &AExpr) -> Option { if !ae_index.is_number() { return Option::None; } - match AExpr::get_usize(ae_index) { - Some(index) => { Option::Some(index) }, - None => { Option::None }, - } + AExpr::get_usize(ae_index) } /* @@ -2438,9 +2417,7 @@ fn treat_result_with_execution_warning( Result::Err(execution_error) => { let report = match execution_error { CanBeQuadraticConstraintSingle() => { - let msg = format!( - "Consider using <== instead of <-- to add the corresponding constraint.\n The constraint representing the assignment satisfies the R1CS format and can be added to the constraint system." - ); + let msg = "Consider using <== instead of <-- to add the corresponding constraint.\n The constraint representing the assignment satisfies the R1CS format and can be added to the constraint system.".to_string(); Report::warning( msg, ReportCode::RuntimeWarning, @@ -2448,10 +2425,9 @@ fn treat_result_with_execution_warning( }, CanBeQuadraticConstraintMultiple(positions) =>{ let mut msg_positions = positions[0].clone(); - for i in 1..positions.len(){ - msg_positions = format!("{}, {}", msg_positions, positions[i].clone()) - }; - + for item in positions.iter().skip(1) { + msg_positions = format!("{}, {}", msg_positions, item) + } let msg = format!( "Consider using <== instead of <-- for some of positions of the array of signals being assigned.\n The constraints representing the assignment of the positions {} satisfy the R1CS format and can be added to the constraint system.", msg_positions @@ -2461,8 +2437,6 @@ fn treat_result_with_execution_warning( ReportCode::RuntimeWarning, ) } - - }; add_report_to_runtime(report, meta, runtime_errors, call_trace); Result::Ok(()) @@ -2484,7 +2458,7 @@ fn add_report_to_runtime( for call in call_trace.iter() { let msg = format!("{}->{}\n", spacing, call); trace.push_str(msg.as_str()); - spacing.push_str(" "); + spacing.push(' '); } report.add_note(trace); runtime_errors.push(report); diff --git a/constraint_generation/src/execution_data/executed_program.rs b/constraint_generation/src/execution_data/executed_program.rs index dcb1ce2da..d1d3a70c9 100644 --- a/constraint_generation/src/execution_data/executed_program.rs +++ b/constraint_generation/src/execution_data/executed_program.rs @@ -19,6 +19,7 @@ pub struct ExecutedProgram { } impl ExecutedProgram { + #[allow(clippy::ptr_arg)] pub fn new(prime: &String) -> ExecutedProgram { ExecutedProgram{ model: Vec::new(), @@ -93,7 +94,7 @@ impl ExecutedProgram { if let Option::Some(index) = possible_index { return index; } - self.template_to_nodes.entry(node.template_name().clone()).or_insert_with(|| vec![]); + self.template_to_nodes.entry(node.template_name().clone()).or_default(); let nodes_for_template = self.template_to_nodes.get_mut(node.template_name()).unwrap(); let node_index = self.model.len(); self.model.push(node); @@ -143,12 +144,10 @@ impl ExecutedProgram { crate::compute_constants::manage_functions(&mut program, flags, &self.prime)?; crate::compute_constants::compute_vct(&mut temp_instances, &program, flags, &self.prime)?; let mut mixed = vec![]; - let mut index = 0; - for in_mixed in mixed_instances { + for (index, in_mixed) in mixed_instances.into_iter().enumerate() { if in_mixed { mixed.push(index); } - index += 1; } let config = VCPConfig { stats: dag_stats, diff --git a/constraint_generation/src/execution_data/executed_template.rs b/constraint_generation/src/execution_data/executed_template.rs index a56fc328a..e1e4331e2 100644 --- a/constraint_generation/src/execution_data/executed_template.rs +++ b/constraint_generation/src/execution_data/executed_template.rs @@ -83,6 +83,7 @@ pub struct ExecutedTemplate { } impl ExecutedTemplate { + #[allow(clippy::too_many_arguments)] pub fn new( public: Vec, name: String, @@ -164,12 +165,12 @@ impl ExecutedTemplate { pub fn add_tag_signal(&mut self, signal_name: &str, tag_name: &str, value: Option){ let tags_signal = self.signal_to_tags.get_mut(signal_name); - if tags_signal.is_none(){ + if let Some(s) = tags_signal { + s.insert(tag_name.to_string(), value); + } else { let mut new_tags_signal = TagInfo::new(); new_tags_signal.insert(tag_name.to_string(), value); self.signal_to_tags.insert(signal_name.to_string(), new_tags_signal); - } else { - tags_signal.unwrap().insert(tag_name.to_string(), value); } } @@ -293,7 +294,7 @@ impl ExecutedTemplate { } for s in &self.underscored_signals{ let correspondence = dag.get_main().unwrap().correspondence(); - let new_s = correspondence.get(s).unwrap().clone(); + let new_s = *correspondence.get(s).unwrap(); dag.add_underscored_signal(new_s); } } @@ -445,7 +446,7 @@ fn as_big_int(exprs: Vec>) -> Vec { } fn filter_used_components(tmp: &ExecutedTemplate) -> (ComponentCollector, usize) { - fn compute_number_cmp(lengths: &Vec) -> usize { + fn compute_number_cmp(lengths: &[usize]) -> usize { lengths.iter().fold(1, |p, c| p * (*c)) } let mut used = HashSet::with_capacity(tmp.components.len()); @@ -457,12 +458,13 @@ fn filter_used_components(tmp: &ExecutedTemplate) -> (ComponentCollector, usize) for cmp in &tmp.components { if used.contains(&cmp.0) { filtered.push(cmp.clone()); - number_of_components = number_of_components + compute_number_cmp(&cmp.1); + number_of_components += compute_number_cmp(&cmp.1); } } (filtered, number_of_components) } +#[allow(clippy::upper_case_acronyms)] #[derive(Copy, Clone)] enum POS { T, @@ -526,9 +528,7 @@ fn build_clusters(tmp: &ExecutedTemplate, instances: &[TemplateInstance]) -> Vec let mut end = index; let mut defined_positions: Vec> = vec![]; loop { - if end == connexions.len() { - break; - } else if connexions[end].inspect.name != cnn_data.name { + if end == connexions.len() || connexions[end].inspect.name != cnn_data.name { break; } else { defined_positions.push(connexions[end].inspect.indexed_with.clone()); @@ -539,7 +539,7 @@ fn build_clusters(tmp: &ExecutedTemplate, instances: &[TemplateInstance]) -> Vec let cluster = TriggerCluster { slice: start..end, length: end - start, - defined_positions: defined_positions, + defined_positions, cmp_name: cnn_data.name.clone(), xtype: ClusterType::Uniform { offset_jump, component_offset_jump, instance_id, header: sub_cmp_header }, }; diff --git a/constraint_generation/src/execution_data/filters.rs b/constraint_generation/src/execution_data/filters.rs index 20b080ab4..1596df788 100644 --- a/constraint_generation/src/execution_data/filters.rs +++ b/constraint_generation/src/execution_data/filters.rs @@ -13,7 +13,6 @@ fn clean_dead_code(stmt: &mut Statement, analysis: &Analysis, prime: &String) -> MultSubstitution { .. } => unreachable!(), IfThenElse { if_case, else_case, cond, meta } => { let field = program_structure::constants::UsefulConstants::new(prime).get_p().clone(); - let empty_block = Box::new(Block { meta: meta.clone(), stmts: vec![] }); let if_case_empty = clean_dead_code(if_case, analysis, prime); let else_case_empty = if let Some(case) = else_case { clean_dead_code(case, analysis, prime) } else { true }; @@ -22,9 +21,14 @@ fn clean_dead_code(stmt: &mut Statement, analysis: &Analysis, prime: &String) -> } match Analysis::read_computed(analysis, cond.get_meta().elem_id) { - Some(val) if as_bool(&val, &field) => *stmt = *if_case.clone(), + Some(val) if as_bool(&val, &field) => { + *stmt = if_case.as_ref().clone() + } Some(val) if !as_bool(&val, &field) => { - *stmt = *else_case.clone().unwrap_or(empty_block) + *stmt = match else_case { + Some(s) => s.as_ref().clone(), + None => Block { meta: meta.clone(), stmts: vec![] }, + } } _ => {} } diff --git a/constraint_generation/src/lib.rs b/constraint_generation/src/lib.rs index a7d26eb2a..0ed727a64 100644 --- a/constraint_generation/src/lib.rs +++ b/constraint_generation/src/lib.rs @@ -42,6 +42,7 @@ pub struct FlagsExecution{ pub type ConstraintWriter = Box; type BuildResponse = Result<(ConstraintWriter, VCP), ()>; +#[allow(clippy::result_unit_err)] pub fn build_circuit(program: ProgramArchive, config: BuildConfig) -> BuildResponse { let files = program.file_library.clone(); let flags = FlagsExecution{ @@ -79,7 +80,7 @@ pub fn build_circuit(program: ProgramArchive, config: BuildConfig) -> BuildRespo type InstantiationResponse = Result<(ExecutedProgram, ReportCollection), ReportCollection>; fn instantiation(program: &ProgramArchive, flags: FlagsExecution, prime: &String) -> InstantiationResponse { - let execution_result = execute::constraint_execution(&program, flags, prime); + let execution_result = execute::constraint_execution(program, flags, prime); match execution_result { Ok((program_exe, warnings)) => { let no_nodes = program_exe.number_of_nodes(); @@ -93,8 +94,8 @@ fn instantiation(program: &ProgramArchive, flags: FlagsExecution, prime: &String } fn export(exe: ExecutedProgram, program: ProgramArchive, flags: FlagsExecution) -> ExportResult { - let exported = exe.export(program, flags); - exported + + exe.export(program, flags) } fn sync_dag_and_vcp(vcp: &mut VCP, dag: &mut DAG) { diff --git a/constraint_list/src/constraint_simplification.rs b/constraint_list/src/constraint_simplification.rs index dc87deedc..4dbb655dd 100644 --- a/constraint_list/src/constraint_simplification.rs +++ b/constraint_list/src/constraint_simplification.rs @@ -24,21 +24,21 @@ struct Cluster { impl Cluster { pub fn new(constraint: C, num_signals: usize) -> Cluster { let mut new = Cluster::default(); - LinkedList::push_back(&mut new.constraints, constraint); + new.constraints.push_back(constraint); new.num_signals = num_signals; new } pub fn merge(mut c0: Cluster, mut c1: Cluster) -> Cluster { let mut result = Cluster::default(); - LinkedList::append(&mut result.constraints, &mut c0.constraints); - LinkedList::append(&mut result.constraints, &mut c1.constraints); + result.constraints.append(&mut c0.constraints); + result.constraints.append(&mut c1.constraints); result.num_signals = c0.num_signals + c1.num_signals - 1; result } pub fn size(&self) -> usize { - LinkedList::len(&self.constraints) + self.constraints.len() } } @@ -49,10 +49,10 @@ fn build_clusters(linear: LinkedList, no_vars: usize) -> Vec { let mut current = org; let mut jumps = Vec::new(); while current != c_to_c[current] { - Vec::push(&mut jumps, current); + jumps.push(current); current = c_to_c[current]; } - while let Some(redirect) = Vec::pop(&mut jumps) { + while let Some(redirect) = jumps.pop() { c_to_c[redirect] = current; } current @@ -61,23 +61,23 @@ fn build_clusters(linear: LinkedList, no_vars: usize) -> Vec { fn arena_merge(arena: &mut ClusterArena, c_to_c: &mut ClusterPath, src: usize, dest: usize) { let current_dest = shrink_jumps_and_find(c_to_c, dest); let current_src = shrink_jumps_and_find(c_to_c, src); - let c0 = std::mem::replace(&mut arena[current_dest], None).unwrap_or_default(); - let c1 = std::mem::replace(&mut arena[current_src], None).unwrap_or_default(); + let c0 = arena[current_dest].take().unwrap_or_default(); + let c1 = arena[current_src].take().unwrap_or_default(); let merged = Cluster::merge(c0, c1); arena[current_dest] = Some(merged); c_to_c[current_src] = current_dest; } - let no_linear = LinkedList::len(&linear); + let no_linear = linear.len(); let mut arena = ClusterArena::with_capacity(no_linear); let mut cluster_to_current = ClusterPath::with_capacity(no_linear); let mut signal_to_cluster = vec![no_linear; no_vars]; for constraint in linear { - if !constraint.is_empty(){ - let signals = C::take_cloned_signals(&constraint); - let dest = ClusterArena::len(&arena); - ClusterArena::push(&mut arena, Some(Cluster::new(constraint, signals.len()))); - Vec::push(&mut cluster_to_current, dest); + if !constraint.is_empty() { + let signals = constraint.take_cloned_signals(); + let dest = arena.len(); + arena.push(Some(Cluster::new(constraint, signals.len()))); + cluster_to_current.push(dest); for signal in signals { let prev = signal_to_cluster[signal]; signal_to_cluster[signal] = dest; @@ -88,11 +88,9 @@ fn build_clusters(linear: LinkedList, no_vars: usize) -> Vec { } } let mut clusters = Vec::new(); - for cluster in arena { - if let Some(cluster) = cluster { - if Cluster::size(&cluster) != 0 { - Vec::push(&mut clusters, cluster); - } + for cluster in arena.into_iter().flatten() { + if cluster.size() != 0 { + clusters.push(cluster); } } clusters @@ -128,28 +126,22 @@ fn eq_cluster_simplification( forbidden: &HashSet, field: &BigInt, ) -> (LinkedList, LinkedList) { - if Cluster::size(&cluster) == 1 { + if cluster.size() == 1 { let mut substitutions = LinkedList::new(); let mut constraints = LinkedList::new(); - let constraint = LinkedList::pop_back(&mut cluster.constraints).unwrap(); - let signals: Vec<_> = C::take_cloned_signals_ordered(&constraint).iter().cloned().collect(); + let constraint = cluster.constraints.pop_back().unwrap(); + let signals: Vec<_> = constraint.take_cloned_signals_ordered().iter().cloned().collect(); let s_0 = signals[0]; let s_1 = signals[1]; - if HashSet::contains(forbidden, &s_0) && HashSet::contains(forbidden, &s_1) { - LinkedList::push_back(&mut constraints, constraint); - } else if HashSet::contains(forbidden, &s_0) { - LinkedList::push_back( - &mut substitutions, - S::new(s_1, A::Signal { symbol: s_0 }).unwrap(), - ); - } else if HashSet::contains(forbidden, &s_1) { - LinkedList::push_back( - &mut substitutions, - S::new(s_0, A::Signal { symbol: s_1 }).unwrap(), - ); + if forbidden.contains(&s_0) && forbidden.contains(&s_1) { + constraints.push_back(constraint); + } else if forbidden.contains(&s_0) { + substitutions.push_back(S::new(s_1, A::Signal { symbol: s_0 }).unwrap()); + } else if forbidden.contains(&s_1) { + substitutions.push_back(S::new(s_0, A::Signal { symbol: s_1 }).unwrap()); } else { let (l, r) = if s_0 > s_1 { (s_0, s_1) } else { (s_1, s_0) }; - LinkedList::push_back(&mut substitutions, S::new(l, A::Signal { symbol: r }).unwrap()); + substitutions.push_back(S::new(l, A::Signal { symbol: r }).unwrap()); } (substitutions, constraints) } else { @@ -158,23 +150,23 @@ fn eq_cluster_simplification( let (mut remains, mut min_remains) = (BTreeSet::new(), None); let (mut remove, mut min_remove) = (HashSet::new(), None); for c in cluster.constraints { - for signal in C::take_cloned_signals_ordered(&c) { - if HashSet::contains(&forbidden, &signal) { - BTreeSet::insert(&mut remains, signal); + for signal in c.take_cloned_signals_ordered() { + if forbidden.contains(&signal) { + remains.insert(signal); min_remains = Some(min_remains.map_or(signal, |s| std::cmp::min(s, signal))); } else { min_remove = Some(min_remove.map_or(signal, |s| std::cmp::min(s, signal))); - HashSet::insert(&mut remove, signal); + remove.insert(signal); } } } let rh_signal = if let Some(signal) = min_remains { - BTreeSet::remove(&mut remains, &signal); + remains.remove(&signal); signal } else { let signal = min_remove.unwrap(); - HashSet::remove(&mut remove, &signal); + remove.remove(&signal); signal }; @@ -183,12 +175,12 @@ fn eq_cluster_simplification( let r = A::Signal { symbol: rh_signal }; let expr = A::sub(&l, &r, field); let c = A::transform_expression_to_constraint_form(expr, field).unwrap(); - LinkedList::push_back(&mut cons, c); + cons.push_back(c); } for signal in remove { let sub = S::new(signal, A::Signal { symbol: rh_signal }).unwrap(); - LinkedList::push_back(&mut subs, sub); + subs.push_back(sub); } (subs, cons) @@ -210,41 +202,38 @@ fn eq_simplification( let clusters = build_clusters(equalities, no_vars); let (cluster_tx, simplified_rx) = mpsc::channel(); let pool = ThreadPool::new(num_cpus::get()); - let no_clusters = Vec::len(&clusters); + let no_clusters = clusters.len(); // println!("Clusters: {}", no_clusters); let mut single_clusters = 0; - let mut id = 0; let mut aux_constraints = vec![LinkedList::new(); clusters.len()]; - for cluster in clusters { - if Cluster::size(&cluster) == 1 { + for (id, cluster) in clusters.into_iter().enumerate() { + if cluster.size() == 1 { let (mut subs, cons) = eq_cluster_simplification(cluster, &forbidden, &field); aux_constraints[id] = cons; - LinkedList::append(&mut substitutions, &mut subs); + substitutions.append(&mut subs); single_clusters += 1; } else { let cluster_tx = cluster_tx.clone(); - let forbidden = Arc::clone(&forbidden); - let field = Arc::clone(&field); + let forbidden = forbidden.clone(); + let field = field.clone(); let job = move || { //println!("Cluster: {}", id); let result = eq_cluster_simplification(cluster, &forbidden, &field); //println!("End of cluster: {}", id); cluster_tx.send((id, result)).unwrap(); }; - ThreadPool::execute(&pool, job); + pool.execute(job); } - let _ = id; - id += 1; } // println!("{} clusters were of size 1", single_clusters); - ThreadPool::join(&pool); + pool.join(); for _ in 0..(no_clusters - single_clusters) { let (id, (mut subs, cons)) = simplified_rx.recv().unwrap(); aux_constraints[id] = cons; - LinkedList::append(&mut substitutions, &mut subs); + substitutions.append(&mut subs); } - for id in 0..no_clusters { - LinkedList::append(&mut constraints, &mut aux_constraints[id]); + for item in aux_constraints.iter_mut().take(no_clusters) { + constraints.append(item); } log_substitutions(&substitutions, substitution_log); (substitutions, constraints) @@ -259,13 +248,13 @@ fn constant_eq_simplification( let mut cons = LinkedList::new(); let mut subs = LinkedList::new(); for constraint in c_eq { - let mut signals: Vec<_> = C::take_cloned_signals_ordered(&constraint).iter().cloned().collect(); + let mut signals: Vec<_> = constraint.take_cloned_signals_ordered().iter().cloned().collect(); let signal = signals.pop().unwrap(); - if HashSet::contains(&forbidden, &signal) { - LinkedList::push_back(&mut cons, constraint); + if forbidden.contains(&signal) { + cons.push_back(constraint); } else { let sub = C::clear_signal_from_linear(constraint, &signal, field); - LinkedList::push_back(&mut subs, sub); + subs.push_back(sub); } } log_substitutions(&subs, substitution_log); @@ -291,15 +280,14 @@ fn linear_simplification( let clusters = build_clusters(linear, no_labels); let (cluster_tx, simplified_rx) = mpsc::channel(); let pool = ThreadPool::new(num_cpus::get()); - let no_clusters = Vec::len(&clusters); + let no_clusters = clusters.len(); // println!("Clusters: {}", no_clusters); - let mut id = 0; for cluster in clusters { let cluster_tx = cluster_tx.clone(); let config = Config { field: field.clone(), constraints: cluster.constraints, - forbidden: Arc::clone(&forbidden), + forbidden: forbidden.clone(), num_signals: cluster.num_signals, use_old_heuristics, }; @@ -309,17 +297,15 @@ fn linear_simplification( // println!("End of cluster: {}", id); cluster_tx.send(result).unwrap(); }; - ThreadPool::execute(&pool, job); - let _ = id; - id += 1; + pool.execute(job); } - ThreadPool::join(&pool); + pool.join(); for _ in 0..no_clusters { let mut result = simplified_rx.recv().unwrap(); log_substitutions(&result.substitutions, log); - LinkedList::append(&mut cons, &mut result.constraints); - LinkedList::append(&mut substitutions, &mut result.substitutions); + cons.append(&mut result.constraints); + substitutions.append(&mut result.substitutions); } (substitutions, cons) } @@ -329,7 +315,7 @@ fn build_non_linear_signal_map(non_linear: &ConstraintStorage) -> SignalToConstr let mut map = SignalToConstraints::new(); for c_id in non_linear.get_ids() { let constraint = non_linear.read_constraint(c_id).unwrap(); - for signal in C::take_cloned_signals(&constraint) { + for signal in constraint.take_cloned_signals() { if let Some(list) = map.get_mut(&signal) { list.push_back(c_id); } else { @@ -367,7 +353,7 @@ fn apply_substitution_to_map( } storage.replace(c_id, constraint); for signal in &signals { - if let Some(list) = map.get_mut(&signal) { + if let Some(list) = map.get_mut(signal) { list.push_back(c_id); } else { let mut new = LinkedList::new(); @@ -409,15 +395,15 @@ fn build_relevant_set( None } }; - SEncoded::get(map, &signal).map_or(None, f) + map.get(&signal).and_then(f) } let (_, non_linear) = EncodingIterator::take(&mut iter); for c in non_linear { - for signal in C::take_cloned_signals(&c) { + for signal in c.take_cloned_signals() { let signal = unwrapped_signal(renames, signal).unwrap_or(signal); - if !SEncoded::contains_key(deletes, &signal) { - HashSet::insert(relevant, signal); + if !deletes.contains_key(&signal) { + relevant.insert(signal); } } } @@ -431,8 +417,8 @@ fn build_relevant_set( fn remove_not_relevant(substitutions: &mut SEncoded, relevant: &HashSet) { let signals: Vec<_> = substitutions.keys().cloned().collect(); for signal in signals { - if !HashSet::contains(&relevant, &signal) { - SEncoded::remove(substitutions, &signal); + if !relevant.contains(&signal) { + substitutions.remove(&signal); } } } @@ -455,11 +441,11 @@ pub fn simplification(smp: &mut Simplifier) -> (ConstraintStorage, SignalMap, us let use_old_heuristics = smp.flag_old_heuristics; let field = smp.field.clone(); let forbidden = Arc::new(std::mem::replace(&mut smp.forbidden, HashSet::with_capacity(0))); - let no_labels = Simplifier::no_labels(smp); - let equalities = std::mem::replace(&mut smp.equalities, LinkedList::new()); + let no_labels = smp.no_labels(); + let equalities = std::mem::take(&mut smp.equalities); let max_signal = smp.max_signal; - let mut cons_equalities = std::mem::replace(&mut smp.cons_equalities, LinkedList::new()); - let mut linear = std::mem::replace(&mut smp.linear, LinkedList::new()); + let mut cons_equalities = std::mem::take(&mut smp.cons_equalities); + let mut linear = std::mem::take(&mut smp.linear); let mut deleted = HashSet::new(); let mut lconst = LinkedList::new(); let mut no_rounds = smp.no_rounds; @@ -483,13 +469,13 @@ pub fn simplification(smp: &mut Simplifier) -> (ConstraintStorage, SignalMap, us let now = SystemTime::now(); let (subs, mut cons) = eq_simplification( equalities, - Arc::clone(&forbidden), + forbidden.clone(), no_labels, &field, &mut substitution_log, ); - LinkedList::append(&mut lconst, &mut cons); + lconst.append(&mut cons); let mut substitutions = build_encoded_fast_substitutions(subs); for constraint in &mut linear { if fast_encoded_constraint_substitution(constraint, &substitutions, &field){ @@ -515,7 +501,7 @@ pub fn simplification(smp: &mut Simplifier) -> (ConstraintStorage, SignalMap, us let now = SystemTime::now(); let (subs, mut cons) = constant_eq_simplification(cons_equalities, &forbidden, &field, &mut substitution_log); - LinkedList::append(&mut lconst, &mut cons); + lconst.append(&mut cons); let substitutions = build_encoded_fast_substitutions(subs); for constraint in &mut linear { if fast_encoded_constraint_substitution(constraint, &substitutions, &field){ @@ -546,7 +532,7 @@ pub fn simplification(smp: &mut Simplifier) -> (ConstraintStorage, SignalMap, us let (subs, mut cons) = linear_simplification( &mut substitution_log, linear, - Arc::clone(&forbidden), + forbidden.clone(), no_labels, &field, use_old_heuristics, @@ -565,7 +551,7 @@ pub fn simplification(smp: &mut Simplifier) -> (ConstraintStorage, SignalMap, us // println!("End of substitution map: {} ms", dur0); let _dur = now.elapsed().unwrap().as_millis(); // println!("End of cluster simplification: {} ms", dur); - LinkedList::append(&mut lconst, &mut cons); + lconst.append(&mut cons); for constraint in &mut lconst { if fast_encoded_constraint_substitution(constraint, &substitutions, &field){ C::fix_constraint(constraint, &field); @@ -573,7 +559,7 @@ pub fn simplification(smp: &mut Simplifier) -> (ConstraintStorage, SignalMap, us } substitutions } else { - LinkedList::append(&mut lconst, &mut linear); + lconst.append(&mut linear); HashMap::with_capacity(0) }; @@ -581,9 +567,9 @@ pub fn simplification(smp: &mut Simplifier) -> (ConstraintStorage, SignalMap, us // println!("Building constraint storage"); let now = SystemTime::now(); let mut frames = LinkedList::new(); - LinkedList::push_back(&mut frames, single_substitutions); - LinkedList::push_back(&mut frames, cons_substitutions); - LinkedList::push_back(&mut frames, linear_substitutions); + frames.push_back(single_substitutions); + frames.push_back(cons_substitutions); + frames.push_back(linear_substitutions); let iter = EncodingIterator::new(&smp.dag_encoding); let mut storage = ConstraintStorage::new(); let with_linear = obtain_and_simplify_non_linear(iter, &mut storage, &frames, &field); @@ -614,7 +600,7 @@ pub fn simplification(smp: &mut Simplifier) -> (ConstraintStorage, SignalMap, us let (substitutions, mut constants) = linear_simplification( &mut substitution_log, linear, - Arc::clone(&forbidden), + forbidden.clone(), no_labels, &field, use_old_heuristics, @@ -645,7 +631,7 @@ pub fn simplification(smp: &mut Simplifier) -> (ConstraintStorage, SignalMap, us for constraint in linear { if remove_unused { - let signals = C::take_cloned_signals(&constraint); + let signals = constraint.take_cloned_signals(); let c_id = constraint_storage.add_constraint(constraint); for signal in signals { if let Some(list) = non_linear_map.get_mut(&signal) { @@ -664,7 +650,7 @@ pub fn simplification(smp: &mut Simplifier) -> (ConstraintStorage, SignalMap, us for mut constraint in lconst { if remove_unused{ C::fix_constraint(&mut constraint, &field); - let signals = C::take_cloned_signals(&constraint); + let signals = constraint.take_cloned_signals(); let c_id = constraint_storage.add_constraint(constraint); for signal in signals { if let Some(list) = non_linear_map.get_mut(&signal) { @@ -692,7 +678,7 @@ pub fn simplification(smp: &mut Simplifier) -> (ConstraintStorage, SignalMap, us deleted.insert(signal); } - let _trash = constraint_storage.extract_with(&|c| C::is_empty(c)); + let _trash = constraint_storage.extract_with(&C::is_empty); let signal_map = { diff --git a/constraint_list/src/non_linear_utils.rs b/constraint_list/src/non_linear_utils.rs index 91fd5078e..f84761423 100644 --- a/constraint_list/src/non_linear_utils.rs +++ b/constraint_list/src/non_linear_utils.rs @@ -13,9 +13,9 @@ pub fn obtain_and_simplify_non_linear( let (_, non_linear) = EncodingIterator::take(&mut iter); for mut constraint in non_linear { for frame in frames { - fast_encoded_constraint_substitution(&mut constraint, frame, &field); + fast_encoded_constraint_substitution(&mut constraint, frame, field); } - C::fix_constraint(&mut constraint, &field); + C::fix_constraint(&mut constraint, field); if C::is_linear(&constraint) { linear.push_back(constraint); } else { diff --git a/constraint_writers/src/debug_writer.rs b/constraint_writers/src/debug_writer.rs index 06cc9a76c..640d13f9c 100644 --- a/constraint_writers/src/debug_writer.rs +++ b/constraint_writers/src/debug_writer.rs @@ -5,10 +5,12 @@ pub struct DebugWriter { pub json_constraints: String, } impl DebugWriter { + #[allow(clippy::result_unit_err)] pub fn new(c: String) -> Result { Result::Ok(DebugWriter { json_constraints: c }) } + #[allow(clippy::result_unit_err)] pub fn build_constraints_file(&self) -> Result { ConstraintJSON::new(&self.json_constraints) } diff --git a/constraint_writers/src/json_writer.rs b/constraint_writers/src/json_writer.rs index efa299c88..534a64d16 100644 --- a/constraint_writers/src/json_writer.rs +++ b/constraint_writers/src/json_writer.rs @@ -7,6 +7,7 @@ pub struct ConstraintJSON { } impl ConstraintJSON { + #[allow(clippy::result_unit_err)] pub fn new(file: &str) -> Result { let file_constraints = File::create(file).map_err(|_err| {})?; let mut writer_constraints = BufWriter::new(file_constraints); @@ -18,6 +19,7 @@ impl ConstraintJSON { Result::Ok(ConstraintJSON { writer_constraints, constraints_flag: false }) } + #[allow(clippy::result_unit_err)] pub fn write_constraint(&mut self, constraint: &str) -> Result<(), ()> { if !self.constraints_flag { self.constraints_flag = true; @@ -31,6 +33,7 @@ impl ConstraintJSON { self.writer_constraints.flush().map_err(|_err| {})?; Result::Ok(()) } + #[allow(clippy::result_unit_err)] pub fn end(mut self) -> Result<(), ()> { self.writer_constraints.write_all(b"\n]\n}").map_err(|_err| {})?; self.writer_constraints.flush().map_err(|_err| {})?; @@ -42,6 +45,7 @@ pub struct SignalsJSON { writer_signals: BufWriter, } impl SignalsJSON { + #[allow(clippy::result_unit_err)] pub fn new(file: &str) -> Result { let file_signals = File::create(file).map_err(|_err| {})?; let mut writer_signals = BufWriter::new(file_signals); @@ -53,12 +57,14 @@ impl SignalsJSON { writer_signals.flush().map_err(|_err| {})?; Result::Ok(SignalsJSON { writer_signals }) } + #[allow(clippy::result_unit_err)] pub fn write_correspondence(&mut self, signal: String, data: String) -> Result<(), ()> { self.writer_signals .write_all(format!(",\n\"{}\" : {}", signal, data).as_bytes()) .map_err(|_err| {})?; self.writer_signals.flush().map_err(|_err| {}) } + #[allow(clippy::result_unit_err)] pub fn end(mut self) -> Result<(), ()> { self.writer_signals.write_all(b"\n}\n}").map_err(|_err| {})?; self.writer_signals.flush().map_err(|_err| {}) @@ -70,6 +76,7 @@ pub struct SubstitutionJSON { first: bool, } impl SubstitutionJSON { + #[allow(clippy::result_unit_err)] pub fn new(file: &str) -> Result { let first = true; let file_substitutions = File::create(file).map_err(|_err| {})?; @@ -78,6 +85,7 @@ impl SubstitutionJSON { writer_substitutions.flush().map_err(|_err| {})?; Result::Ok(SubstitutionJSON { writer_substitutions, first }) } + #[allow(clippy::result_unit_err)] pub fn write_substitution(&mut self, signal: &str, substitution: &str) -> Result<(), ()> { if self.first { self.first = false; @@ -91,6 +99,7 @@ impl SubstitutionJSON { self.writer_substitutions.flush().map_err(|_err| {})?; Result::Ok(()) } + #[allow(clippy::result_unit_err)] pub fn end(mut self) -> Result<(), ()> { self.writer_substitutions.write_all(b"\n}").map_err(|_err| {})?; self.writer_substitutions.flush().map_err(|_err| {}) diff --git a/constraint_writers/src/lib.rs b/constraint_writers/src/lib.rs index 976673087..b144da677 100644 --- a/constraint_writers/src/lib.rs +++ b/constraint_writers/src/lib.rs @@ -5,7 +5,10 @@ pub mod r1cs_writer; pub mod sym_writer; pub trait ConstraintExporter { + #[allow(clippy::result_unit_err)] fn r1cs(&self, out: &str, custom_gates: bool) -> Result<(), ()>; + #[allow(clippy::result_unit_err)] fn json_constraints(&self, writer: &debug_writer::DebugWriter) -> Result<(), ()>; + #[allow(clippy::result_unit_err)] fn sym(&self, out: &str) -> Result<(), ()>; } diff --git a/constraint_writers/src/log_writer.rs b/constraint_writers/src/log_writer.rs index ef15e62ff..7d8b780e7 100644 --- a/constraint_writers/src/log_writer.rs +++ b/constraint_writers/src/log_writer.rs @@ -9,6 +9,12 @@ pub struct Log { pub no_public_outputs: usize, } +impl Default for Log { + fn default() -> Self { + Self::new() + } +} + impl Log { pub fn new() -> Log { Log { diff --git a/constraint_writers/src/r1cs_writer.rs b/constraint_writers/src/r1cs_writer.rs index 7bc0fd7bc..4a0236faa 100644 --- a/constraint_writers/src/r1cs_writer.rs +++ b/constraint_writers/src/r1cs_writer.rs @@ -30,14 +30,14 @@ fn bigint_as_bytes(number: &BigInt, with_bytes: usize) -> (Vec, usize) { fn initialize_section(writer: &mut BufWriter, header: &[u8]) -> Result { writer.write_all(header).map_err(|_err| {})?; //writer.flush().map_err(|_err| {})?; - let go_back = writer.seek(SeekFrom::Current(0)).map_err(|_err| {})?; + let go_back = writer.stream_position().map_err(|_err| {})?; writer.write_all(PLACE_HOLDER).map_err(|_| {})?; //writer.flush().map_err(|_err| {})?; Result::Ok(go_back) } fn end_section(writer: &mut BufWriter, go_back: u64, size: usize) -> Result<(), ()> { - let go_back_1 = writer.seek(SeekFrom::Current(0)).map_err(|_err| {})?; + let go_back_1 = writer.stream_position().map_err(|_err| {})?; writer.seek(SeekFrom::Start(go_back)).map_err(|_err| {})?; let (stream, _) = bigint_as_bytes(&BigInt::from(size), 8); writer.write_all(&stream).map_err(|_err| {})?; @@ -153,6 +153,7 @@ pub struct CustomGatesAppliedSection { } impl R1CSWriter { + #[allow(clippy::result_unit_err)] pub fn new( output_file: String, field_size: usize, @@ -161,11 +162,12 @@ impl R1CSWriter { let sections = [false; SECTIONS as usize]; let num_sections: u8 = if custom_gates { 5 } else { 3 }; let mut writer = - File::create(&output_file).map_err(|_err| {}).map(|f| BufWriter::new(f))?; + File::create(output_file).map_err(|_err| {}).map(BufWriter::new)?; initialize_file(&mut writer, num_sections)?; Result::Ok(R1CSWriter { writer, sections, field_size }) } + #[allow(clippy::result_unit_err)] pub fn start_header_section(mut r1cs: R1CSWriter) -> Result { let start = initialize_section(&mut r1cs.writer, HEADER_TYPE)?; Result::Ok(HeaderSection { @@ -178,6 +180,7 @@ impl R1CSWriter { }) } + #[allow(clippy::result_unit_err)] pub fn start_constraints_section(mut r1cs: R1CSWriter) -> Result { let start = initialize_section(&mut r1cs.writer, CONSTRAINT_TYPE)?; Result::Ok(ConstraintSection { @@ -191,6 +194,7 @@ impl R1CSWriter { }) } + #[allow(clippy::result_unit_err)] pub fn start_signal_section(mut r1cs: R1CSWriter) -> Result { let start = initialize_section(&mut r1cs.writer, WIRE2LABEL_TYPE)?; Result::Ok(SignalSection { @@ -203,6 +207,7 @@ impl R1CSWriter { }) } + #[allow(clippy::result_unit_err)] pub fn start_custom_gates_used_section(mut r1cs: R1CSWriter) -> Result { let start = initialize_section(&mut r1cs.writer, CUSTOM_GATES_USED_TYPE)?; Result::Ok(CustomGatesUsedSection { @@ -215,6 +220,7 @@ impl R1CSWriter { }) } + #[allow(clippy::result_unit_err)] pub fn start_custom_gates_applied_section(mut r1cs: R1CSWriter) -> Result { let start = initialize_section(&mut r1cs.writer, CUSTOM_GATES_APPLIED_TYPE)?; Result::Ok(CustomGatesAppliedSection { @@ -227,8 +233,9 @@ impl R1CSWriter { }) } + #[allow(clippy::result_unit_err)] pub fn finish_writing(mut r1cs: R1CSWriter) -> Result<(), ()> { - r1cs.writer.flush().map_err(|_err| {}) + r1cs.writer.flush().map_err(|_err| {}) } } @@ -243,6 +250,7 @@ pub struct HeaderData { } impl HeaderSection { + #[allow(clippy::result_unit_err)] pub fn write_section(&mut self, data: HeaderData) -> Result<(), ()> { let (field_stream, bytes_field) = bigint_as_bytes(&data.field, self.field_size); let (length_stream, bytes_size) = bigint_as_bytes(&BigInt::from(self.field_size), 4); @@ -268,6 +276,7 @@ impl HeaderSection { Result::Ok(()) } + #[allow(clippy::result_unit_err)] pub fn end_section(mut self) -> Result { end_section(&mut self.writer, self.go_back, self.size)?; let mut sections = self.sections; @@ -279,6 +288,7 @@ impl HeaderSection { type Constraint = HashMap; impl ConstraintSection { + #[allow(clippy::result_unit_err)] pub fn write_constraint_usize( &mut self, a: &Constraint, @@ -307,6 +317,7 @@ impl ConstraintSection { Result::Ok(()) } + #[allow(clippy::result_unit_err)] pub fn end_section(mut self) -> Result { end_section(&mut self.writer, self.go_back, self.size)?; let mut sections = self.sections; @@ -325,6 +336,7 @@ impl ConstraintSection { } impl SignalSection { + #[allow(clippy::result_unit_err)] pub fn write_signal( &mut self, bytes: &T @@ -335,11 +347,13 @@ impl SignalSection { //self.writer.flush().map_err(|_err| {}) } + #[allow(clippy::result_unit_err)] pub fn write_signal_usize(&mut self, signal: usize) -> Result<(), ()> { let (_, as_bytes) = BigInt::from(signal).to_bytes_le(); SignalSection::write_signal(self, &as_bytes) } + #[allow(clippy::result_unit_err)] pub fn end_section(mut self) -> Result { end_section(&mut self.writer, self.go_back, self.size)?; let mut sections = self.sections; @@ -355,6 +369,7 @@ impl SignalSection { pub type CustomGatesUsedData = Vec<(String, Vec)>; impl CustomGatesUsedSection { + #[allow(clippy::result_unit_err)] pub fn write_custom_gates_usages(&mut self, data: CustomGatesUsedData) -> Result<(), ()> { let no_custom_gates = data.len(); let (no_custom_gates_stream, no_custom_gates_size) = @@ -390,6 +405,7 @@ impl CustomGatesUsedSection { Result::Ok(()) } + #[allow(clippy::result_unit_err)] pub fn end_section(mut self) -> Result { end_section(&mut self.writer, self.go_back, self.size)?; let mut sections = self.sections; @@ -405,6 +421,7 @@ impl CustomGatesUsedSection { pub type CustomGatesAppliedData = Vec<(usize, Vec)>; impl CustomGatesAppliedSection { + #[allow(clippy::result_unit_err)] pub fn write_custom_gates_applications(&mut self, data: CustomGatesAppliedData) -> Result<(), ()> { let no_custom_gate_applications = data.len(); let (no_custom_gate_applications_stream, no_custom_gate_applications_size) = @@ -440,6 +457,7 @@ impl CustomGatesAppliedSection { Result::Ok(()) } + #[allow(clippy::result_unit_err)] pub fn end_section(mut self) -> Result { end_section(&mut self.writer, self.go_back, self.size)?; let mut sections = self.sections; diff --git a/constraint_writers/src/sym_writer.rs b/constraint_writers/src/sym_writer.rs index 8299c07e9..9f6af507e 100644 --- a/constraint_writers/src/sym_writer.rs +++ b/constraint_writers/src/sym_writer.rs @@ -18,20 +18,23 @@ pub struct SymFile { } impl SymFile { + #[allow(clippy::result_unit_err)] pub fn new(file: &str) -> Result { let file = File::create(file).map_err(|_err| {})?; let writer = BufWriter::new(file); Result::Ok(SymFile { writer }) } + #[allow(clippy::result_unit_err)] pub fn write_sym_elem(sym: &mut SymFile, elem: SymElem) -> Result<(), ()> { sym.writer.write_all(elem.to_string().as_bytes()).map_err(|_err| {})?; sym.writer.write_all(b"\n").map_err(|_err| {}) //?; //sym.writer.flush().map_err(|_err| {}) } + #[allow(clippy::result_unit_err)] pub fn finish_writing(mut sym: SymFile) -> Result<(), ()> { - sym.writer.flush().map_err(|_err| {}) + sym.writer.flush().map_err(|_err| {}) } // pub fn close(_sym: SymFile) {} diff --git a/dag/src/constraint_correctness_analysis.rs b/dag/src/constraint_correctness_analysis.rs index edb216b4f..9a1170318 100644 --- a/dag/src/constraint_correctness_analysis.rs +++ b/dag/src/constraint_correctness_analysis.rs @@ -12,17 +12,14 @@ const UNCONSTRAINED_IOSIGNAL_CODE: ReportCode = ReportCode::UnconstrainedIOSigna struct UnconstrainedSignal; impl UnconstrainedSignal { - pub fn new(signal: &str, template: &str, examples: &Vec) -> Report { - + pub fn report(signal: &str, template: &str, examples: &Vec) -> Report { if examples.len() == 1{ let msg = format!("In template \"{}\": Local signal {} does not appear in any constraint", template, examples[0]); - let report = Report::warning(msg, UNCONSTRAINED_SIGNAL_CODE); - report + Report::warning(msg, UNCONSTRAINED_SIGNAL_CODE) } else{ let msg = format!("In template \"{}\": Array of local signals {} contains a total of {} signals that do not appear in any constraint", template, signal, examples.len()); let mut report = Report::warning(msg, UNCONSTRAINED_SIGNAL_CODE); - let ex = format!("For example: {}, {}.", examples[0], examples[1]); - report.add_note(ex); + report.add_note(format!("For example: {}, {}.", examples[0], examples[1])); report } } @@ -30,17 +27,14 @@ impl UnconstrainedSignal { struct UnconstrainedIOSignal; impl UnconstrainedIOSignal { - pub fn new(signal: &str, template: &str, examples: &Vec) -> Report { - + pub fn report(signal: &str, template: &str, examples: &Vec) -> Report { if examples.len() == 1{ let msg = format!("In template \"{}\": Subcomponent input/output signal {} does not appear in any constraint of the father component", template, examples[0]); - let report = Report::warning(msg, UNCONSTRAINED_IOSIGNAL_CODE); - report + Report::warning(msg, UNCONSTRAINED_IOSIGNAL_CODE) } else{ let msg = format!("In template \"{}\": Array of subcomponent input/output signals {} contains a total of {} signals that do not appear in any constraint of the father component", template, signal, examples.len()); let mut report = Report::warning(msg, UNCONSTRAINED_IOSIGNAL_CODE); - let ex = format!("For example: {}, {}.", examples[0], examples[1]); - report.add_note(ex); + report.add_note(format!("For example: {}, {}.", examples[0], examples[1])); report } } @@ -57,16 +51,15 @@ struct Analysis { signal_stats: Vec<(String, SignalType, usize)>, } -fn split_signal_name_index(name: &String)-> String{ - let split_components:Vec<&str> = name.split(".").collect(); // split the name of components +fn split_signal_name_index(name: &str) -> String { + let split_components: Vec<&str> = name.split('.').collect(); // split the name of components let mut signal_name = "".to_string(); - for i in 0..split_components.len()-1{ - signal_name = signal_name + split_components[i] + "."; // take the index of the components + for item in split_components.iter().take(split_components.len() - 1) { + signal_name = signal_name + item + "."; // take the index of the components } // no take the index of the array position - let aux_last_component = split_components[split_components.len()-1].to_string(); - let split_index_last_component = - aux_last_component.split("[").next().unwrap(); + let aux_last_component = split_components[split_components.len() - 1].to_string(); + let split_index_last_component = aux_last_component.split('[').next().unwrap(); signal_name + split_index_last_component } @@ -92,9 +85,9 @@ fn analysis_interpretation(analysis: Analysis, result: &mut AnalysisResult) { } for (name, (xtype, examples)) in signal2unconstrainedex{ if xtype == SignalType::Local{ - result.warnings.push(UnconstrainedSignal::new(&name, &tmp_name, &examples)); + result.warnings.push(UnconstrainedSignal::report(&name, &tmp_name, &examples)); } else{ - result.warnings.push(UnconstrainedIOSignal::new(&name, &tmp_name, &examples)); + result.warnings.push(UnconstrainedIOSignal::report(&name, &tmp_name, &examples)); } } } @@ -118,7 +111,7 @@ fn visit_node(node: &Node) -> Analysis { } for signal in &node.underscored_signals{ - let prev = constraint_counter.remove(&signal).unwrap(); + let prev = constraint_counter.remove(signal).unwrap(); constraint_counter.insert(*signal, prev + 1); } diff --git a/dag/src/json_porting.rs b/dag/src/json_porting.rs index 44bb2c577..1b0e6269c 100644 --- a/dag/src/json_porting.rs +++ b/dag/src/json_porting.rs @@ -29,7 +29,7 @@ fn hashmap_as_json(values: &HashMap) -> JsonValue { fn visit_tree(tree: &Tree, writer: &mut ConstraintJSON) -> Result<(), ()> { for constraint in &tree.constraints { - let json_value = transform_constraint_to_json(&constraint); + let json_value = transform_constraint_to_json(constraint); writer.write_constraint(&json_value.to_string())?; } for edge in Tree::get_edges(tree) { diff --git a/dag/src/lib.rs b/dag/src/lib.rs index 8c51193c8..b5b14762f 100644 --- a/dag/src/lib.rs +++ b/dag/src/lib.rs @@ -314,9 +314,9 @@ impl ConstraintExporter for DAG { } impl DAG { - pub fn new(prime: &String) -> DAG { - DAG{ - prime : prime.clone(), + pub fn new(prime: &str) -> DAG { + DAG { + prime : prime.to_owned(), one_signal: 0, nodes: Vec::new(), adjacency: Vec::new(), @@ -471,14 +471,17 @@ impl DAG { constraint_correctness_analysis::clean_constraints(&mut self.nodes); } + #[allow(clippy::result_unit_err)] pub fn generate_r1cs_output(&self, output_file: &str, custom_gates: bool) -> Result<(), ()> { r1cs_porting::write(self, output_file, custom_gates) } + #[allow(clippy::result_unit_err)] pub fn generate_sym_output(&self, output_file: &str) -> Result<(), ()> { sym_porting::write(self, output_file) } + #[allow(clippy::result_unit_err)] pub fn generate_json_constraints(&self, debug: &DebugWriter) -> Result<(), ()> { json_porting::port_constraints(self, debug) } diff --git a/dag/src/map_to_constraint_list.rs b/dag/src/map_to_constraint_list.rs index bccec4c09..c975d2356 100644 --- a/dag/src/map_to_constraint_list.rs +++ b/dag/src/map_to_constraint_list.rs @@ -18,7 +18,7 @@ fn map_tree( let mut no_constraints = 0; for signal in &tree.signals { - Vec::push(witness, *signal); + witness.push(*signal); if tree.dag.nodes[tree.node_id].is_custom_gate { forbidden.insert(*signal); } @@ -26,11 +26,11 @@ fn map_tree( for constraint in &tree.constraints { if Constraint::is_constant_equality(constraint) { - LinkedList::push_back(&mut c_holder.constant_equalities, constraint.clone()); + c_holder.constant_equalities.push_back(constraint.clone()); } else if Constraint::is_equality(constraint, &tree.field) { - LinkedList::push_back(&mut c_holder.equalities, constraint.clone()); + c_holder.equalities.push_back(constraint.clone()); } else if Constraint::is_linear(constraint) { - LinkedList::push_back(&mut c_holder.linear, constraint.clone()); + c_holder.linear.push_back(constraint.clone()); } else { no_constraints += 1; } @@ -51,19 +51,17 @@ fn produce_encoding( ) -> DAGEncoding { let mut adjacency = Vec::new(); let mut nodes = Vec::new(); - let mut id = 0; - for node in dag_nodes { + for (id, node) in dag_nodes.into_iter().enumerate() { let encoded = map_node_to_encoding(id, node); - Vec::push(&mut nodes, encoded); - id += 1; + nodes.push(encoded); } for edges in dag_edges { let mut encoded = Vec::new(); for edge in edges { let new = map_edge_to_encoding(edge); - Vec::push(&mut encoded, new); + encoded.push(new); } - Vec::push(&mut adjacency, encoded); + adjacency.push(encoded); } DAGEncoding { init, no_constraints, nodes, adjacency } } @@ -75,7 +73,7 @@ fn map_node_to_encoding(id: usize, node: Node) -> EncodingNode { let mut non_linear = LinkedList::new(); for c in node.constraints { if !Constraint::is_linear(&c) { - LinkedList::push_back(&mut non_linear, c); + non_linear.push_back(c); } } @@ -85,9 +83,9 @@ fn map_node_to_encoding(id: usize, node: Node) -> EncodingNode { } for (name, id) in node.signal_correspondence { - if HashSet::contains(&locals, &id) { + if locals.contains(&id) { let new_signal = SignalInfo { name, id }; - Vec::push(&mut signals, new_signal); + signals.push(new_signal); } } signals.sort_by(|a, b| a.id.cmp(&b.id)); @@ -121,7 +119,7 @@ pub fn map(dag: DAG, flags: SimplificationFlags) -> ConstraintList { let mut c_holder = CHolder::default(); let mut signal_map = vec![0]; let no_constraints = map_tree(&Tree::new(&dag), &mut signal_map, &mut c_holder, &mut forbidden); - let max_signal = Vec::len(&signal_map); + let max_signal = signal_map.len(); let name_encoding = produce_encoding(no_constraints, init_id, dag.nodes, dag.adjacency); let _dur = now.elapsed().unwrap().as_millis(); // println!("End of dag to list mapping: {} ms", dur); diff --git a/parser/src/include_logic.rs b/parser/src/include_logic.rs index 0b6b91052..3028060d2 100644 --- a/parser/src/include_logic.rs +++ b/parser/src/include_logic.rs @@ -17,6 +17,7 @@ impl FileStack { FileStack { current_location: location, black_paths: HashSet::new(), stack: vec![src] } } + #[allow(clippy::ptr_arg, clippy::result_large_err)] pub fn add_include( f_stack: &mut FileStack, name: String, @@ -87,12 +88,13 @@ impl IncludesGraph { } } + #[allow(clippy::result_large_err)] pub fn add_edge(&mut self, old_path: String) -> Result<(), Report> { let mut crr = PathBuf::new(); crr.push(old_path.clone()); let path = std::fs::canonicalize(crr) .map_err(|_e| produce_report_with_message(ReportCode::FileOs, old_path))?; - let edges = self.adjacency.entry(path).or_insert(vec![]); + let edges = self.adjacency.entry(path).or_default(); edges.push(self.nodes.len() - 1); Ok(()) } @@ -144,15 +146,15 @@ impl IncludesGraph { problematic_paths } + #[allow(clippy::ptr_arg)] pub fn display_path(path: &Vec) -> String { let mut res = String::new(); let mut sep = ""; for file in path.iter().map(|file| file.display().to_string()) { res.push_str(sep); - let result_split = file.rsplit_once("/"); - if result_split.is_some(){ - res.push_str(result_split.unwrap().1); - } else{ + if let Some((_, s)) = file.rsplit_once('/') { + res.push_str(s); + } else { res.push_str(&file); } sep = " -> "; diff --git a/parser/src/lib.rs b/parser/src/lib.rs index 825e385fd..281c30b02 100644 --- a/parser/src/lib.rs +++ b/parser/src/lib.rs @@ -5,7 +5,7 @@ extern crate serde_derive; #[macro_use] extern crate lalrpop_util; -lalrpop_mod!(pub lang); +lalrpop_mod!(#[allow(clippy::all)] pub lang); mod include_logic; mod parser_logic; @@ -14,12 +14,11 @@ mod syntax_sugar_remover; use include_logic::{FileStack, IncludesGraph}; use program_structure::ast::{produce_compiler_version_report, produce_report, produce_report_with_message, produce_version_warning_report, Expression}; use program_structure::error_code::ReportCode; -use program_structure::error_definition::ReportCollection; -use program_structure::error_definition::Report; -use program_structure::file_definition::{FileLibrary}; +use program_structure::error_definition::{Report, ReportCollection}; +use program_structure::file_definition::FileLibrary; use program_structure::program_archive::ProgramArchive; use std::path::{PathBuf, Path}; -use syntax_sugar_remover::{apply_syntactic_sugar}; +use syntax_sugar_remover::apply_syntactic_sugar; use std::str::FromStr; @@ -48,8 +47,8 @@ pub fn find_file( found = true; } Err(e) => { - reports.push(e); - i = i + 1; + reports.push(*e); + i += 1; } } } @@ -97,7 +96,7 @@ pub fn run_parser( program.compiler_version, parse_number_version(version), ) - .map_err(|e| (file_library.clone(), vec![e]))?, + .map_err(|e| (file_library.clone(), vec![*e]))?, ); if program.custom_gates { check_custom_gates_version( @@ -105,11 +104,11 @@ pub fn run_parser( program.compiler_version, parse_number_version(version), ) - .map_err(|e| (file_library.clone(), vec![e]))? + .map_err(|e| (file_library.clone(), vec![*e]))? } } - if main_components.len() == 0 { + if main_components.is_empty() { let report = produce_report(ReportCode::NoMainFoundInProject,0..0, 0); warnings.push(report); Err((file_library, warnings)) @@ -128,7 +127,7 @@ pub fn run_parser( ReportCode::CustomGatesPragmaError ) ).collect(); - if errors.len() > 0 { + if !errors.is_empty() { warnings.append(& mut errors); Err((file_library, warnings)) } else { @@ -147,11 +146,12 @@ pub fn run_parser( } Ok(mut program_archive) => { let lib = program_archive.get_file_library().clone(); - let program_archive_result = apply_syntactic_sugar( &mut program_archive); + let program_archive_result = apply_syntactic_sugar(&mut program_archive); match program_archive_result { Result::Err(v) => { - warnings.push(v); - Result::Err((lib,warnings))}, + warnings.push(*v); + Result::Err((lib, warnings)) + } Result::Ok(_) => Ok((program_archive, warnings)), } } @@ -161,30 +161,26 @@ pub fn run_parser( } fn produce_report_with_main_components(main_components: Vec<(usize, (Vec, Expression), bool)>) -> Report { - let mut j = 0; let mut r = produce_report(ReportCode::MultipleMain, 0..0, 0); - for (i,exp,_) in main_components{ + for (j, (i, (_, e), _)) in main_components.into_iter().enumerate() { if j > 0 { - r.add_secondary(exp.1.get_meta().location.clone(), i, Option::Some("Here it is another main component".to_string())); - } - else { - r.add_primary(exp.1.get_meta().location.clone(), i, "This is a main component".to_string()); + r.add_secondary(e.get_meta().location.clone(), i, Option::Some("Here it is another main component".to_string())); + } else { + r.add_primary(e.get_meta().location.clone(), i, "This is a main component".to_string()); } - j+=1; } r } -fn open_file(path: PathBuf) -> Result<(String, String), Report> /* path, src */ { - use std::fs::read_to_string; +fn open_file(path: PathBuf) -> Result<(String, String), Box> /* path, src */ { let path_str = format!("{:?}", path); - read_to_string(path) + std::fs::read_to_string(path) .map(|contents| (path_str.clone(), contents)) - .map_err(|_| produce_report_with_message(ReportCode::FileOs, path_str.clone())) + .map_err(|_| Box::new(produce_report_with_message(ReportCode::FileOs, path_str))) } fn parse_number_version(version: &str) -> Version { - let version_splitted: Vec<&str> = version.split(".").collect(); + let version_splitted: Vec<&str> = version.split('.').collect(); ( usize::from_str(version_splitted[0]).unwrap(), usize::from_str(version_splitted[1]).unwrap(), @@ -196,7 +192,7 @@ fn check_number_version( file_path: String, version_file: Option, version_compiler: Version, -) -> Result { +) -> Result> { if let Some(required_version) = version_file { if required_version.0 == version_compiler.0 && (required_version.1 < version_compiler.1 @@ -205,11 +201,10 @@ fn check_number_version( { Ok(vec![]) } else { - Err(produce_compiler_version_report(file_path, required_version, version_compiler)) + Err(Box::new(produce_compiler_version_report(file_path, required_version, version_compiler))) } } else { - let report = - produce_version_warning_report(file_path, version_compiler); + let report = produce_version_warning_report(file_path, version_compiler); Ok(vec![report]) } } @@ -218,7 +213,7 @@ fn check_custom_gates_version( file_path: String, version_file: Option, version_compiler: Version, -) -> Result<(), Report> { +) -> Result<(), Box> { let custom_gates_version: Version = (2, 0, 6); if let Some(required_version) = version_file { if required_version.0 < custom_gates_version.0 @@ -228,7 +223,7 @@ fn check_custom_gates_version( && required_version.1 == custom_gates_version.1 && required_version.2 < custom_gates_version.2) { - let report = Report::error( + let report =Box::new(Report::error( format!( "File {} requires at least version {:?} to use custom templates (currently {:?})", file_path, @@ -236,28 +231,26 @@ fn check_custom_gates_version( required_version ), ReportCode::CustomGatesVersionError - ); - return Err(report); - } - } else { - if version_compiler.0 < custom_gates_version.0 - || (version_compiler.0 == custom_gates_version.0 - && version_compiler.1 < custom_gates_version.1) - || (version_compiler.0 == custom_gates_version.0 - && version_compiler.1 == custom_gates_version.1 - && version_compiler.2 < custom_gates_version.2) - { - let report = Report::error( - format!( - "File {} does not include pragma version and the compiler version (currently {:?}) should be at least {:?} to use custom templates", - file_path, - version_compiler, - custom_gates_version - ), - ReportCode::CustomGatesVersionError - ); + )); return Err(report); } + } else if version_compiler.0 < custom_gates_version.0 + || (version_compiler.0 == custom_gates_version.0 + && version_compiler.1 < custom_gates_version.1) + || (version_compiler.0 == custom_gates_version.0 + && version_compiler.1 == custom_gates_version.1 + && version_compiler.2 < custom_gates_version.2) + { + let report = Box::new(Report::error( + format!( + "File {} does not include pragma version and the compiler version (currently {:?}) should be at least {:?} to use custom templates", + file_path, + version_compiler, + custom_gates_version + ), + ReportCode::CustomGatesVersionError + )); + return Err(report); } Ok(()) } \ No newline at end of file diff --git a/parser/src/parser_logic.rs b/parser/src/parser_logic.rs index a572c53e7..0ea4bc48f 100644 --- a/parser/src/parser_logic.rs +++ b/parser/src/parser_logic.rs @@ -1,5 +1,5 @@ use super::lang; -use program_structure::ast::{AST}; +use program_structure::ast::AST; use program_structure::ast::produce_report; use program_structure::error_code::ReportCode; use program_structure::error_definition::{ReportCollection, Report}; diff --git a/parser/src/syntax_sugar_remover.rs b/parser/src/syntax_sugar_remover.rs index fb9462b80..fe4578c17 100644 --- a/parser/src/syntax_sugar_remover.rs +++ b/parser/src/syntax_sugar_remover.rs @@ -9,19 +9,17 @@ use program_structure::template_data::TemplateData; use std::collections::{HashMap, BTreeMap}; use num_bigint::BigInt; - - -pub fn apply_syntactic_sugar(program_archive : &mut ProgramArchive) -> Result<(), Report> { +pub fn apply_syntactic_sugar(program_archive: &mut ProgramArchive) -> Result<(), Box> { if program_archive.get_main_expression().is_anonymous_comp() { - return Result::Err(anonymous_general_error(program_archive.get_main_expression().get_meta().clone(),"The main component cannot contain an anonymous call ".to_string())); - + return Result::Err(Box::new(anonymous_general_error(program_archive.get_main_expression().get_meta().clone(), "The main component cannot contain an anonymous call ".to_string()))); } - let old_templates = program_archive.templates.clone(); - for (_name, t) in &mut program_archive.templates { + let old_templates = program_archive.templates.clone(); + for t in program_archive.templates.values_mut() { let old_body = t.get_body().clone(); check_anonymous_components_statement(&old_body)?; - let (new_body, component_decs, variable_decs, mut substitutions) = remove_anonymous_from_statement(&old_templates, &program_archive.file_library, old_body, &None)?; + let (new_body, component_decs, variable_decs, mut substitutions) + = remove_anonymous_from_statement(&old_templates, &program_archive.file_library, old_body, &None)?; if let Statement::Block { meta, mut stmts } = new_body { let mut init_block = vec![ build_initialization_block(meta.clone(), VariableType::Var, variable_decs), @@ -32,17 +30,16 @@ pub fn apply_syntactic_sugar(program_archive : &mut ProgramArchive) -> Result<( check_tuples_statement(&new_body_with_inits)?; let new_body = remove_tuples_from_statement(new_body_with_inits)?; t.set_body(new_body); - } else{ + } else { unreachable!() } } - - for (_, t) in &mut program_archive.functions { + for t in program_archive.functions.values_mut() { let old_body = t.get_body().clone(); - if old_body.contains_anonymous_comp(){ - return Result::Err(anonymous_general_error(old_body.get_meta().clone(),"Functions cannot contain calls to anonymous templates".to_string())); - } else{ + if old_body.contains_anonymous_comp() { + return Result::Err(Box::new(anonymous_general_error(old_body.get_meta().clone(), "Functions cannot contain calls to anonymous templates".to_string()))); + } else { check_tuples_statement(&old_body)?; let new_body = remove_tuples_from_statement(old_body)?; t.set_body(new_body); @@ -51,42 +48,36 @@ pub fn apply_syntactic_sugar(program_archive : &mut ProgramArchive) -> Result<( Result::Ok(()) } - -fn check_anonymous_components_statement( - stm : &Statement, -) -> Result<(), Report>{ +fn check_anonymous_components_statement(stm: &Statement) -> Result<(), Box> { match stm { Statement::MultSubstitution {meta, lhe, rhe, op, ..} => { if lhe.contains_anonymous_comp() { - Result::Err(anonymous_general_error( + Result::Err(Box::new(anonymous_general_error( meta.clone(), "An anonymous component cannot be used in the left side of an assignment".to_string()) - ) - } else{ - if rhe.contains_anonymous_comp() && *op == AssignOp::AssignSignal{ - let error = format!("Anonymous components only admit the use of the operator <=="); - Result::Err(anonymous_general_error(meta.clone(),error)) - } else{ - check_anonymous_components_expression(rhe) - } + )) + } else if rhe.contains_anonymous_comp() && *op == AssignOp::AssignSignal { + let error = "Anonymous components only admit the use of the operator <==".to_string(); + Result::Err(Box::new(anonymous_general_error(meta.clone(), error))) + } else { + check_anonymous_components_expression(rhe) } }, - Statement::IfThenElse { meta, cond, if_case, else_case, .. } - => { + Statement::IfThenElse { meta, cond, if_case, else_case, .. } => { if cond.contains_anonymous_comp() { - Result::Err(anonymous_inside_condition_error(meta.clone())) - } else{ + Result::Err(Box::new(anonymous_inside_condition_error(meta.clone()))) + } else { check_anonymous_components_statement(if_case)?; - if else_case.is_some(){ - check_anonymous_components_statement(else_case.as_ref().unwrap())?; + if let Some(stm) = else_case { + check_anonymous_components_statement(stm)?; } Result::Ok(()) } } - Statement::While { meta, cond, stmt, .. } => { + Statement::While { meta, cond, stmt, .. } => { if cond.contains_anonymous_comp() { - Result::Err(anonymous_inside_condition_error(meta.clone())) - } else{ + Result::Err(Box::new(anonymous_inside_condition_error(meta.clone()))) + } else { check_anonymous_components_statement(stmt) } } @@ -94,51 +85,48 @@ fn check_anonymous_components_statement( for arg in args { if let program_structure::ast::LogArgument::LogExp( exp ) = arg { if exp.contains_anonymous_comp() { - return Result::Err(anonymous_general_error(meta.clone() ,"An anonymous component cannot be used inside a log".to_string())) + return Result::Err(Box::new(anonymous_general_error(meta.clone() , "An anonymous component cannot be used inside a log".to_string()))) } } } Result::Ok(()) } - Statement::Assert { meta, arg} => { + Statement::Assert { meta, arg} => { if arg.contains_anonymous_comp() { - Result::Err(anonymous_general_error(meta.clone(), "An anonymous component cannot be used inside an assert".to_string())) - } else{ + Result::Err(Box::new(anonymous_general_error(meta.clone(), "An anonymous component cannot be used inside an assert".to_string()))) + } else { Result::Ok(()) } } Statement::Return { meta, value: arg}=> { - if arg.contains_anonymous_comp(){ - Result::Err(anonymous_general_error(meta.clone(), "An anonymous component cannot be used inside a function ".to_string())) - } else{ + if arg.contains_anonymous_comp() { + Result::Err(Box::new(anonymous_general_error(meta.clone(), "An anonymous component cannot be used inside a function ".to_string()))) + } else { Result::Ok(()) } } Statement::ConstraintEquality {meta, lhe, rhe } => { if lhe.contains_anonymous_comp() || rhe.contains_anonymous_comp() { - Result::Err(anonymous_general_error(meta.clone(), "An anonymous component cannot be used with operator === ".to_string())) - } - else{ + Result::Err(Box::new(anonymous_general_error(meta.clone(), "An anonymous component cannot be used with operator === ".to_string()))) + } else { Result::Ok(()) } } Statement::Declaration { meta, dimensions, .. } => { - for exp in dimensions{ - if exp.contains_anonymous_comp(){ - return Result::Err(anonymous_general_error(meta.clone(),"An anonymous component cannot be used to define a dimension of an array".to_string())); + for exp in dimensions { + if exp.contains_anonymous_comp() { + return Result::Err(Box::new(anonymous_general_error(meta.clone(), "An anonymous component cannot be used to define a dimension of an array".to_string()))); } } Result::Ok(()) } - Statement::InitializationBlock { initializations, .. } => - { + Statement::InitializationBlock { initializations, .. } => { for stmt in initializations { check_anonymous_components_statement(stmt)?; } Result::Ok(()) } - Statement::Block {stmts, .. } => { - + Statement::Block {stmts, .. } => { for stmt in stmts { check_anonymous_components_statement(stmt)?; } @@ -147,21 +135,21 @@ fn check_anonymous_components_statement( Statement::Substitution { meta, rhe, access, op, ..} => { use program_structure::ast::Access::ComponentAccess; use program_structure::ast::Access::ArrayAccess; - for acc in access{ - match acc{ - ArrayAccess(exp) =>{ - if exp.contains_anonymous_comp(){ - return Result::Err(anonymous_general_error(meta.clone(),"An anonymous component cannot be used to define a dimension of an array".to_string())); + for acc in access { + match acc { + ArrayAccess(exp) => { + if exp.contains_anonymous_comp() { + return Result::Err(Box::new(anonymous_general_error(meta.clone(), "An anonymous component cannot be used to define a dimension of an array".to_string()))); } }, - ComponentAccess(_)=>{}, + ComponentAccess(_) => {}, } } - if rhe.contains_anonymous_comp() && *op == AssignOp::AssignSignal{ - let error = format!("Anonymous components only admit the use of the operator <=="); - Result::Err(anonymous_general_error(meta.clone(),error)) - } else{ + if rhe.contains_anonymous_comp() && *op == AssignOp::AssignSignal { + let error = "Anonymous components only admit the use of the operator <==".to_string(); + Result::Err(Box::new(anonymous_general_error(meta.clone(), error))) + } else { check_anonymous_components_expression(rhe) } } @@ -169,23 +157,21 @@ fn check_anonymous_components_statement( } } -pub fn check_anonymous_components_expression( - exp : &Expression, -) -> Result<(),Report>{ +pub fn check_anonymous_components_expression(exp: &Expression) -> Result<(), Box> { use Expression::*; match exp { ArrayInLine { meta, values, .. } => { for value in values{ if value.contains_anonymous_comp() { - return Result::Err(anonymous_general_error(meta.clone(),"An anonymous component cannot be used to define a dimension of an array".to_string())); + return Result::Err(Box::new(anonymous_general_error(meta.clone(), "An anonymous component cannot be used to define a dimension of an array".to_string()))); } } Result::Ok(()) }, UniformArray { meta, value, dimension } => { if value.contains_anonymous_comp() || dimension.contains_anonymous_comp() { - Result::Err(anonymous_general_error(meta.clone(),"An anonymous component cannot be used to define a dimension of an array".to_string())) - } else{ + Result::Err(Box::new(anonymous_general_error(meta.clone(), "An anonymous component cannot be used to define a dimension of an array".to_string()))) + } else { Result::Ok(()) } }, @@ -195,78 +181,77 @@ pub fn check_anonymous_components_expression( Variable { meta, access, .. } => { use program_structure::ast::Access::ComponentAccess; use program_structure::ast::Access::ArrayAccess; - for acc in access{ - match acc{ - ArrayAccess(exp) =>{ - if exp.contains_anonymous_comp(){ - return Result::Err(anonymous_general_error(meta.clone(),"An anonymous component cannot be used to define a dimension of an array".to_string())); + for acc in access { + match acc { + ArrayAccess(exp) => { + if exp.contains_anonymous_comp() { + return Result::Err(Box::new(anonymous_general_error(meta.clone(), "An anonymous component cannot be used to define a dimension of an array".to_string()))); } }, - ComponentAccess(_)=>{}, + ComponentAccess(_) => {}, } } Result::Ok(()) }, InfixOp { meta, lhe, rhe, .. } => { if lhe.contains_anonymous_comp() || rhe.contains_anonymous_comp() { - Result::Err(anonymous_general_error(meta.clone(),"An anonymous component cannot be used in the middle of an operation ".to_string())) - } else{ + Result::Err(Box::new(anonymous_general_error(meta.clone(), "An anonymous component cannot be used in the middle of an operation ".to_string()))) + } else { Result::Ok(()) } }, PrefixOp { meta, rhe, .. } => { - if rhe.contains_anonymous_comp() { - Result::Err(anonymous_general_error(meta.clone(),"An anonymous component cannot be used in the middle of an operation ".to_string())) - } else{ + if rhe.contains_anonymous_comp() { + Result::Err(Box::new(anonymous_general_error(meta.clone(), "An anonymous component cannot be used in the middle of an operation ".to_string()))) + } else { Result::Ok(()) } }, - InlineSwitchOp { meta, cond, if_true, if_false } => { + InlineSwitchOp { meta, cond, if_true, if_false } => { if cond.contains_anonymous_comp() || if_true.contains_anonymous_comp() || if_false.contains_anonymous_comp() { - Result::Err(anonymous_general_error(meta.clone(),"An anonymous component cannot be used inside an inline switch ".to_string())) - } else{ + Result::Err(Box::new(anonymous_general_error(meta.clone(), "An anonymous component cannot be used inside an inline switch ".to_string()))) + } else { Result::Ok(()) } }, Call { meta, args, .. } => { - for value in args{ + for value in args { if value.contains_anonymous_comp() { - return Result::Err(anonymous_general_error(meta.clone(),"An anonymous component cannot be used as a parameter in a template call ".to_string())); + return Result::Err(Box::new(anonymous_general_error(meta.clone(), "An anonymous component cannot be used as a parameter in a template call ".to_string()))); } } Result::Ok(()) }, AnonymousComp {meta, params, signals, .. } => { - for value in params{ + for value in params { if value.contains_anonymous_comp() { - return Result::Err(anonymous_general_error(meta.clone(),"An anonymous component cannot be used as a parameter in a template call ".to_string())); + return Result::Err(Box::new(anonymous_general_error(meta.clone(), "An anonymous component cannot be used as a parameter in a template call ".to_string()))); } } - for value in signals{ + for value in signals { check_anonymous_components_expression(value)?; } Result::Ok(()) }, Tuple {values, .. } => { - for val in values{ check_anonymous_components_expression(val)?; } Result::Ok(()) }, ParallelOp { meta, rhe } => { - if !rhe.is_call() && !rhe.is_anonymous_comp() && rhe.contains_anonymous_comp() { - return Result::Err(anonymous_general_error(meta.clone(),"Bad use of parallel operator in combination with anonymous components ".to_string())); - } - else if rhe.is_call() && rhe.contains_anonymous_comp() { - return Result::Err(anonymous_general_error(meta.clone(),"An anonymous component cannot be used as a parameter in a template call ".to_string())); + if rhe.contains_anonymous_comp() { + if rhe.is_call() { + return Result::Err(Box::new(anonymous_general_error(meta.clone(), "An anonymous component cannot be used as a parameter in a template call ".to_string()))); + } else if !rhe.is_anonymous_comp() { + return Result::Err(Box::new(anonymous_general_error(meta.clone(), "Bad use of parallel operator in combination with anonymous components ".to_string()))); + } } Result::Ok(()) }, } } - // (Body, init_components, init_variables, substitutions) pub type UpdatedStatement = (Statement, Vec, Vec, Vec); @@ -274,47 +259,46 @@ pub type UpdatedStatement = (Statement, Vec, Vec, Vec, Vec, Expression); fn remove_anonymous_from_statement( - templates : &HashMap, - file_lib : &FileLibrary, - stm : Statement, - var_access: &Option -) -> Result< UpdatedStatement, Report>{ + templates: &HashMap, + file_lib: &FileLibrary, + stm: Statement, + var_access: &Option, +) -> Result< UpdatedStatement, Box>{ match stm { Statement::MultSubstitution { meta, lhe, op, rhe } => { - - let (comp_declarations, mut substitutions, new_rhe) = remove_anonymous_from_expression(templates, file_lib, rhe, var_access)?; - let subs = Statement::MultSubstitution { meta: meta.clone(), lhe: lhe, op: op, rhe: new_rhe }; - if substitutions.is_empty(){ + let (comp_declarations, mut substitutions, new_rhe) + = remove_anonymous_from_expression(templates, file_lib, rhe, var_access)?; + let subs = Statement::MultSubstitution { meta: meta.clone(), lhe, op, rhe: new_rhe }; + if substitutions.is_empty() { Result::Ok((subs, comp_declarations, Vec::new(), Vec::new())) - }else{ + } else { substitutions.push(subs); - Result::Ok((Statement::Block { meta : meta, stmts : substitutions}, comp_declarations, Vec::new(), Vec::new())) + Result::Ok((Statement::Block { meta, stmts: substitutions}, comp_declarations, Vec::new(), Vec::new())) } }, - Statement::IfThenElse { meta, cond, if_case, else_case } - => { - - let (if_body, mut if_comp_dec, mut if_var_dec, mut if_subs) = remove_anonymous_from_statement(templates, file_lib, *if_case, var_access)?; - let b_if = Box::new(if_body); - if else_case.is_none(){ - Result::Ok((Statement::IfThenElse { meta : meta, cond : cond, if_case: b_if, else_case: Option::None}, if_comp_dec, if_var_dec, if_subs)) - }else { - let else_c = *(else_case.unwrap()); - let (else_body, mut else_comp_dec, mut else_var_dec, mut else_subs) = remove_anonymous_from_statement(templates, file_lib, else_c, var_access)?; - let b_else = Box::new(else_body); + Statement::IfThenElse { meta, cond, if_case, else_case } => { + let (if_body, mut if_comp_dec, mut if_var_dec, mut if_subs) + = remove_anonymous_from_statement(templates, file_lib, *if_case, var_access)?; + let b_else = if let Some(else_c) = else_case { + let (else_body, mut else_comp_dec, mut else_var_dec, mut else_subs) + = remove_anonymous_from_statement(templates, file_lib, *else_c, var_access)?; if_comp_dec.append(&mut else_comp_dec); if_var_dec.append(&mut else_var_dec); if_subs.append(&mut else_subs); - Result::Ok((Statement::IfThenElse { meta : meta, cond : cond, if_case: b_if, else_case: Option::Some(b_else)}, if_comp_dec, if_var_dec, if_subs)) - } + Option::Some(Box::new(else_body)) + } else { + Option::None + }; + Result::Ok((Statement::IfThenElse { meta, cond, if_case: Box::new(if_body), else_case: b_else}, if_comp_dec, if_var_dec, if_subs)) } - Statement::While { meta, cond, stmt } => { + Statement::While { meta, cond, stmt } => { let id_var_while = "anon_var_".to_string() + &file_lib.get_line(meta.start, meta.get_file_id()).unwrap().to_string() + "_" + &meta.start.to_string(); - let var_access = Expression::Variable{meta: meta.clone(), name: id_var_while.clone(), access: Vec::new()}; + let var_access = Expression::Variable{ meta: meta.clone(), name: id_var_while.clone(), access: Vec::new() }; let mut var_declarations = vec![]; let mut subs_out = vec![]; - let (body, comp_dec, mut var_dec, mut subs) = remove_anonymous_from_statement(templates, file_lib, *stmt, &Some(var_access.clone()))?; - let b_while = if !comp_dec.is_empty(){ + let (body, comp_dec, mut var_dec, mut subs) + = remove_anonymous_from_statement(templates, file_lib, *stmt, &Some(var_access.clone()))?; + let b_while = if !comp_dec.is_empty() { var_declarations.push( build_declaration( meta.clone(), @@ -334,46 +318,44 @@ fn remove_anonymous_from_statement( ); var_declarations.append(&mut var_dec); subs_out.append(&mut subs); - let next_access = Expression::InfixOp{ + let next_access = Expression::InfixOp { meta: meta.clone(), infix_op: ExpressionInfixOpcode::Add, lhe: Box::new(var_access), - rhe: Box::new(Expression::Number(meta.clone(), BigInt::from(1))), + rhe: Box::new(Expression::Number(meta.clone(), BigInt::from(1))), }; - let subs_access = Statement::Substitution{ + let subs_access = Statement::Substitution { meta: meta.clone(), var: id_var_while, access: Vec::new(), op: AssignOp::AssignVar, rhe: next_access, }; - - let new_block = Statement::Block{ + let new_block = Statement::Block { meta: meta.clone(), stmts: vec![body, subs_access], }; Box::new(new_block) - } else{ + } else { Box::new(body) }; - Result::Ok((Statement::While { meta: meta, cond: cond, stmt: b_while}, comp_dec, var_declarations, subs_out)) - }, - - Statement::InitializationBlock { meta, xtype, initializations } => - { + Result::Ok((Statement::While { meta, cond, stmt: b_while}, comp_dec, var_declarations, subs_out)) + }, + Statement::InitializationBlock { meta, xtype, initializations } => { let mut new_inits = Vec::new(); let mut comp_inits = Vec::new(); let mut var_inits = Vec::new(); let mut subs = Vec::new(); for stmt in initializations { - let (stmt_ok, mut comps, mut vars, mut sub) = remove_anonymous_from_statement(templates, file_lib, stmt, var_access)?; + let (stmt_ok, mut comps, mut vars, mut sub) + = remove_anonymous_from_statement(templates, file_lib, stmt, var_access)?; new_inits.push(stmt_ok); comp_inits.append(&mut comps); var_inits.append(&mut vars); subs.append(&mut sub); } - Result::Ok((Statement::InitializationBlock { meta: meta, xtype: xtype, initializations: new_inits }, comp_inits, var_inits, subs)) + Result::Ok((Statement::InitializationBlock { meta, xtype, initializations: new_inits }, comp_inits, var_inits, subs)) } Statement::Block { meta, stmts } => { let mut new_stmts = Vec::new(); @@ -381,7 +363,8 @@ fn remove_anonymous_from_statement( let mut var_inits = Vec::new(); let mut subs = Vec::new(); for stmt in stmts { - let (stmt_ok, mut comps, mut vars, mut sub) = remove_anonymous_from_statement(templates, file_lib, stmt, var_access)?; + let (stmt_ok, mut comps, mut vars, mut sub) + = remove_anonymous_from_statement(templates, file_lib, stmt, var_access)?; new_stmts.push(stmt_ok); comp_inits.append(&mut comps); var_inits.append(&mut vars); @@ -390,27 +373,27 @@ fn remove_anonymous_from_statement( Result::Ok((Statement::Block { meta, stmts: new_stmts}, comp_inits, var_inits, subs)) } Statement::Substitution { meta, var, op, rhe, access} => { - let (comp_declarations, mut stmts, new_rhe) = remove_anonymous_from_expression(templates, file_lib, rhe, var_access)?; - let subs = Statement::Substitution { meta: meta.clone(), var: var, access: access, op: op, rhe: new_rhe }; - if stmts.is_empty(){ + let (comp_declarations, mut stmts, new_rhe) + = remove_anonymous_from_expression(templates, file_lib, rhe, var_access)?; + let subs = Statement::Substitution { meta: meta.clone(), var, access, op, rhe: new_rhe }; + if stmts.is_empty() { Result::Ok((subs, comp_declarations, Vec::new(), Vec::new())) - }else{ + } else { stmts.push(subs); Result::Ok((Statement::Block { meta, stmts}, comp_declarations, Vec::new(), Vec::new())) } } Statement::UnderscoreSubstitution { .. } => unreachable!(), - _ => { - Result::Ok((stm, Vec::new(), Vec::new(), Vec::new())) - } + _ => Result::Ok((stm, Vec::new(), Vec::new(), Vec::new())), } } // returns a block with the component declarations, the substitutions and finally the output expression +#[allow(clippy::result_large_err)] pub fn remove_anonymous_from_expression( - templates : &HashMap, - file_lib : &FileLibrary, - exp : Expression, + templates: &HashMap, + file_lib: &FileLibrary, + exp: Expression, var_access: &Option, // in case the call is inside a loop, variable used to control the access ) -> Result{ use Expression::*; @@ -420,26 +403,27 @@ pub fn remove_anonymous_from_expression( let mut seq_substs = Vec::new(); // get the template we are calling to - let template = templates.get(&id); - if template.is_none(){ - return Result::Err(anonymous_general_error(meta.clone(),format!("The template {} does not exist", id))); - } + let template = match templates.get(&id) { + Some(t) => t, + None => return Result::Err(anonymous_general_error(meta.clone(),format!("The template {} does not exist", id))), + }; let id_anon_temp = id.to_string() + "_" + &file_lib.get_line(meta.start, meta.get_file_id()).unwrap().to_string() + "_" + &meta.start.to_string(); // in case we are not inside a loop, we can automatically convert into a component - if var_access.is_none(){ + if let Some(va) = var_access { + // we generate an anonymous component, it depends on the var_access indicating the loop declarations.push(build_declaration( - meta.clone(), - VariableType::Component, + meta.clone(), + VariableType::AnonymousComponent, id_anon_temp.clone(), - Vec::new(), + vec![va.clone()], )); - } else{ // we generate an anonymous component, it depends on the var_access indicating the loop + } else { declarations.push(build_declaration( - meta.clone(), - VariableType::AnonymousComponent, + meta.clone(), + VariableType::Component, id_anon_temp.clone(), - vec![var_access.as_ref().unwrap().clone()], + vec![], )); } @@ -451,17 +435,17 @@ pub fn remove_anonymous_from_expression( call }; // in case we are in a loop in only generates a position, needs the var_access reference - let access = if var_access.is_none(){ - Vec::new() - } else{ - vec![build_array_access(var_access.as_ref().unwrap().clone())] + let access = if let Some(va) = var_access { + vec![build_array_access(va.clone())] + } else { + vec![] }; // in loop: id_anon_temp[var_access] = (parallel) Template(params); // out loop: id_anon_temp = (parallel) Template(params) let sub = build_substitution( meta.clone(), id_anon_temp.clone(), - access.clone(), + access, AssignOp::AssignVar, exp_with_call ); @@ -472,94 +456,76 @@ pub fn remove_anonymous_from_expression( let mut inputs_to_assignments = BTreeMap::new(); if let Some(m) = names { // in case we have a list of names and assignments - let inputs = template.unwrap().get_inputs(); - let mut n_expr = 0; - for (operator, name) in m{ - if operator != AssignOp::AssignConstraintSignal{ - let error = format!("Anonymous components only admit the use of the operator <=="); - return Result::Err(anonymous_general_error(meta.clone(),error)); + let inputs = template.get_inputs(); + for (n_expr, (operator, name)) in m.into_iter().enumerate() { + if operator != AssignOp::AssignConstraintSignal { + let error = "Anonymous components only admit the use of the operator <==".to_string(); + return Result::Err(anonymous_general_error(meta.clone(), error)); } - if inputs.contains_key(&name){ + if inputs.contains_key(&name) { inputs_to_assignments.insert(name, (operator, signals[n_expr].clone())); - } else{ - let error = format!("The template {} does not have an input signal named {}", template.unwrap().get_name(), name); - return Result::Err(anonymous_general_error(meta.clone(),error)); + } else { + let error = format!("The template {} does not have an input signal named {}", template.get_name(), name); + return Result::Err(anonymous_general_error(meta.clone(), error)); } - n_expr += 1; - } + } if inputs.len() != inputs_to_assignments.len() { - return Result::Err(anonymous_general_error(meta.clone(),"The number of template input signals must coincide with the number of input parameters ".to_string())); - } - } - else{ - let inputs = template.unwrap().get_declaration_inputs(); - let mut n_expr = 0; - for value in signals { + return Result::Err(anonymous_general_error(meta.clone(), "The number of template input signals must coincide with the number of input parameters ".to_string())); + } + } else { + let inputs = template.get_declaration_inputs(); + for (n_expr, value) in signals.into_iter().enumerate() { inputs_to_assignments.insert(inputs[n_expr].0.clone(), (AssignOp::AssignConstraintSignal, value)); - n_expr += 1; } - if inputs.len() != inputs_to_assignments.len() { - return Result::Err(anonymous_general_error(meta.clone(),"The number of template input signals must coincide with the number of input parameters ".to_string())); + return Result::Err(anonymous_general_error(meta.clone(), "The number of template input signals must coincide with the number of input parameters ".to_string())); } } - // generate the substitutions for the inputs - for (name_signal, (operator, expr)) in inputs_to_assignments{ - let mut acc = if var_access.is_none(){ - Vec::new() - } else{ - vec![build_array_access(var_access.as_ref().unwrap().clone())] + for (name, (op, exp)) in inputs_to_assignments { + let access = if let Some(va) = var_access { + vec![build_array_access(va.clone()), Access::ComponentAccess(name)] + } else { + vec![Access::ComponentAccess(name)] }; - acc.push(Access::ComponentAccess(name_signal.clone())); - let (mut declarations2, mut stmts,new_exp) = remove_anonymous_from_expression( - templates, - file_lib, - expr, - var_access - )?; - + let (mut decs, mut stmts, rhe) = + remove_anonymous_from_expression(templates, file_lib, exp, var_access)?; seq_substs.append(&mut stmts); - declarations.append(&mut declarations2); - let subs = Statement::Substitution { meta: meta.clone(), var: id_anon_temp.clone(), access: acc, op: operator, rhe: new_exp }; + declarations.append(&mut decs); + let subs = Statement::Substitution { meta: meta.clone(), var: id_anon_temp.clone(), access, op, rhe }; seq_substs.push(subs); } - // generate the expression for the outputs -> return as expression (if single out) or tuple - let outputs = template.unwrap().get_declaration_outputs(); - if outputs.len() == 1 { - let output = outputs.get(0).unwrap().0.clone(); - let mut acc = if var_access.is_none(){ - Vec::new() - } else{ - vec![build_array_access(var_access.as_ref().unwrap().clone())] - }; - - acc.push(Access::ComponentAccess(output.clone())); - let out_exp = Expression::Variable { meta: meta.clone(), name: id_anon_temp, access: acc }; - Result::Ok((declarations, vec![Statement::Block { meta: meta.clone(), stmts: seq_substs }], out_exp)) - } else{ - let mut new_values = Vec::new(); - for output in outputs { - let mut acc = if var_access.is_none(){ - Vec::new() - } else{ - vec![build_array_access(var_access.as_ref().unwrap().clone())] + // generate the expression for the outputs -> return as expression (if single out) or tuple + let out_exp = match &template.get_declaration_outputs()[..] { + [(name, _)] => { + let access = if let Some(va) = var_access { + vec![build_array_access(va.clone()), Access::ComponentAccess(name.clone())] + } else { + vec![Access::ComponentAccess(name.clone())] }; - acc.push(Access::ComponentAccess(output.0.clone())); - let out_exp = Expression::Variable { meta: meta.clone(), name: id_anon_temp.clone(), access: acc }; - new_values.push(out_exp); + Expression::Variable { meta: meta.clone(), name: id_anon_temp, access } } - let out_exp = Tuple {meta : meta.clone(), values : new_values}; - Result::Ok((declarations, vec![Statement::Block { meta: meta.clone(), stmts: seq_substs }], out_exp)) - - } + outputs => { + let mut values = Vec::new(); + for (name, _) in outputs { + let access = if let Some(va) = var_access { + vec![build_array_access(va.clone()), Access::ComponentAccess(name.clone())] + } else { + vec![Access::ComponentAccess(name.clone())] + }; + values.push(Expression::Variable { meta: meta.clone(), name: id_anon_temp.clone(), access }); + } + Tuple { meta: meta.clone(), values } + } + }; + Result::Ok((declarations, vec![Statement::Block { meta: meta.clone(), stmts: seq_substs }], out_exp)) }, Tuple { meta, values } => { let mut new_values = Vec::new(); - let mut new_stmts : Vec = Vec::new(); - let mut declarations : Vec = Vec::new(); + let mut new_stmts: Vec = Vec::new(); + let mut declarations: Vec = Vec::new(); for val in values{ let result = remove_anonymous_from_expression(templates, file_lib, val, var_access); match result { @@ -574,44 +540,41 @@ pub fn remove_anonymous_from_expression( Result::Ok((declarations, new_stmts, build_tuple(meta.clone(), new_values))) }, ParallelOp { meta, rhe } => { - if rhe.is_anonymous_comp(){ + if rhe.is_anonymous_comp() { let rhe2 = rhe.make_anonymous_parallel(); remove_anonymous_from_expression(templates, file_lib, rhe2, var_access) - } else{ + } else { Result::Ok((Vec::new(),Vec::new(), ParallelOp { meta, rhe })) } }, - _ =>{ - Result::Ok((Vec::new(),Vec::new(),exp)) + _ => { + Result::Ok((Vec::new(),Vec::new(), exp)) } } } - -fn check_tuples_statement(stm: &Statement)-> Result<(), Report>{ - match stm{ +fn check_tuples_statement(stm: &Statement)-> Result<(), Box> { + match stm { Statement::MultSubstitution { lhe, rhe, .. } => { check_tuples_expression(lhe)?; check_tuples_expression(rhe)?; Result::Ok(()) }, - Statement::IfThenElse { cond, if_case, else_case, meta, .. } - => { + Statement::IfThenElse { cond, if_case, else_case, meta, .. } => { if cond.contains_tuple() { - Result::Err(tuple_general_error(meta.clone(),"A tuple cannot be used inside a condition ".to_string())) - } else{ + Result::Err(Box::new(tuple_general_error(meta.clone(), "A tuple cannot be used inside a condition ".to_string()))) + } else { check_tuples_statement(if_case)?; - if else_case.is_some(){ - check_tuples_statement(else_case.as_ref().unwrap())?; + if let Some(stm) = else_case { + check_tuples_statement(stm)?; } Result::Ok(()) } } - - Statement::While { meta, cond, stmt } => { + Statement::While { meta, cond, stmt } => { if cond.contains_tuple() { - Result::Err(tuple_general_error(meta.clone(),"A tuple cannot be used inside a condition ".to_string())) - } else{ + Result::Err(Box::new(tuple_general_error(meta.clone(), "A tuple cannot be used inside a condition ".to_string()))) + } else { check_tuples_statement(stmt) } } @@ -620,48 +583,42 @@ fn check_tuples_statement(stm: &Statement)-> Result<(), Report>{ match arg { LogArgument::LogStr(_) => {}, LogArgument::LogExp(exp) => { - check_tuples_expression(&exp)?; + check_tuples_expression(exp)?; }, } } Result::Ok(()) } - Statement::Assert { meta, arg} => { - if arg.contains_tuple(){ - Result::Err(tuple_general_error(meta.clone(),"A tuple cannot be used in a return ".to_string())) - } - else{ + Statement::Assert { meta, arg} => { + if arg.contains_tuple() { + Result::Err(Box::new(tuple_general_error(meta.clone(), "A tuple cannot be used in a return ".to_string()))) + } else { Result::Ok(()) } } Statement::Return { meta, value: arg}=> { - if arg.contains_tuple(){ - Result::Err(tuple_general_error(meta.clone(),"A tuple cannot be used inside a function ".to_string())) - } - else{ + if arg.contains_tuple() { + Result::Err(Box::new(tuple_general_error(meta.clone(), "A tuple cannot be used inside a function ".to_string()))) + } else { Result::Ok(()) } } Statement::ConstraintEquality {meta, lhe, rhe } => { if lhe.contains_tuple() || rhe.contains_tuple() { - Result::Err(tuple_general_error(meta.clone(),"A tuple cannot be used with the operator === ".to_string())) - } - else{ + Result::Err(Box::new(tuple_general_error(meta.clone(), "A tuple cannot be used with the operator === ".to_string()))) + } else { Result::Ok(()) } } - Statement::Declaration { meta, - dimensions, .. } => - { - for exp in dimensions.clone(){ - if exp.contains_tuple(){ - return Result::Err(tuple_general_error(meta.clone(),"A tuple cannot be used to define a dimension of an array ".to_string())); + Statement::Declaration { meta, dimensions, .. } => { + for exp in dimensions { + if exp.contains_tuple() { + return Result::Err(Box::new(tuple_general_error(meta.clone(), "A tuple cannot be used to define a dimension of an array ".to_string()))); } } Result::Ok(()) } - Statement::InitializationBlock {initializations, ..} => - { + Statement::InitializationBlock {initializations, ..} => { for stmt in initializations { check_tuples_statement(stmt)?; } @@ -677,36 +634,36 @@ fn check_tuples_statement(stm: &Statement)-> Result<(), Report>{ use program_structure::ast::Access::ComponentAccess; use program_structure::ast::Access::ArrayAccess; for acc in access{ - match acc{ - ArrayAccess(exp) =>{ - if exp.contains_tuple(){ - return Result::Err(tuple_general_error(meta.clone(),"A tuple cannot be used to define a dimension of an array".to_string())); + match acc { + ArrayAccess(exp) => { + if exp.contains_tuple() { + return Result::Err(Box::new(tuple_general_error(meta.clone(), "A tuple cannot be used to define a dimension of an array".to_string()))); } }, - ComponentAccess(_)=>{}, + ComponentAccess(_) => {}, } } - check_tuples_expression(rhe) + check_tuples_expression(rhe).map_err(Box::new) } Statement::UnderscoreSubstitution { .. } => unreachable!(), } } - -pub fn check_tuples_expression(exp: &Expression) -> Result<(), Report>{ +#[allow(clippy::result_large_err)] +pub fn check_tuples_expression(exp: &Expression) -> Result<(), Report> { use Expression::*; match exp{ ArrayInLine { meta, values } => { for value in values{ if value.contains_tuple() { - return Result::Err(tuple_general_error(meta.clone(),"A tuple cannot be used to define a dimension of an array ".to_string())); + return Result::Err(tuple_general_error(meta.clone(), "A tuple cannot be used to define a dimension of an array ".to_string())); } } Result::Ok(()) }, UniformArray { meta, value, dimension } => { if value.contains_tuple() || dimension.contains_tuple() { - return Result::Err(tuple_general_error(meta.clone(),"A tuple cannot be used to define a dimension of an array ".to_string())); + return Result::Err(tuple_general_error(meta.clone(), "A tuple cannot be used to define a dimension of an array ".to_string())); } Result::Ok(()) }, @@ -716,42 +673,42 @@ pub fn check_tuples_expression(exp: &Expression) -> Result<(), Report>{ Variable { access, meta, .. } => { use program_structure::ast::Access::*; for acc in access{ - match acc{ - ArrayAccess(exp) =>{ - if exp.contains_tuple(){ - return Result::Err(tuple_general_error(meta.clone(),"A tuple cannot be used to define a dimension of an array".to_string())); + match acc { + ArrayAccess(exp) => { + if exp.contains_tuple() { + return Result::Err(tuple_general_error(meta.clone(), "A tuple cannot be used to define a dimension of an array".to_string())); } }, - ComponentAccess(_)=>{}, + ComponentAccess(_) => {}, } } Result::Ok(()) }, InfixOp { meta, lhe, rhe, .. } => { if lhe.contains_tuple() || rhe.contains_tuple() { - Result::Err(tuple_general_error(meta.clone(),"A tuple cannot be used in the middle of an operation".to_string())) - } else{ + Result::Err(tuple_general_error(meta.clone(), "A tuple cannot be used in the middle of an operation".to_string())) + } else { Result::Ok(()) } }, PrefixOp { meta, rhe, .. } => { if rhe.contains_tuple() { - Result::Err(tuple_general_error(meta.clone(),"A tuple cannot be used in the middle of an operation".to_string())) - } else{ + Result::Err(tuple_general_error(meta.clone(), "A tuple cannot be used in the middle of an operation".to_string())) + } else { Result::Ok(()) } }, InlineSwitchOp { meta, cond, if_true, if_false } => { if cond.contains_tuple() || if_true.contains_tuple() || if_false.contains_tuple() { - Result::Err(tuple_general_error(meta.clone(),"A tuple cannot be used inside an inline switch".to_string())) - } else{ + Result::Err(tuple_general_error(meta.clone(), "A tuple cannot be used inside an inline switch".to_string())) + } else { Result::Ok(()) } }, Call { meta, args, .. } => { - for value in args{ + for value in args { if value.contains_tuple() { - return Result::Err(tuple_general_error(meta.clone(),"A tuple cannot be used as a parameter of a function call".to_string())); + return Result::Err(tuple_general_error(meta.clone(), "A tuple cannot be used as a parameter of a function call".to_string())); } } Result::Ok(()) @@ -767,16 +724,16 @@ pub fn check_tuples_expression(exp: &Expression) -> Result<(), Report>{ }, ParallelOp { meta, rhe} => { if rhe.contains_tuple() { - Result::Err(tuple_general_error(meta.clone(),"A tuple cannot be used in a parallel operator ".to_string())) - } else{ + Result::Err(tuple_general_error(meta.clone(), "A tuple cannot be used in a parallel operator ".to_string())) + } else { Result::Ok(()) } }, } } -fn remove_tuples_from_statement(stm: Statement) -> Result { - match stm{ +fn remove_tuples_from_statement(stm: Statement) -> Result> { + match stm { Statement::MultSubstitution { meta, lhe, op, rhe } => { let new_exp_lhe = remove_tuple_from_expression(lhe); let new_exp_rhe = remove_tuple_from_expression(rhe); @@ -785,53 +742,49 @@ fn remove_tuples_from_statement(stm: Statement) -> Result { Expression::Tuple { values: mut values2, .. }) => { if values1.len() == values2.len() { let mut substs = Vec::new(); - while values1.len() > 0 { + while !values1.is_empty() { let lhe = values1.remove(0); if let Expression::Variable { meta, name, access } = lhe { let rhe = values2.remove(0); if name != "_" { substs.push(build_substitution(meta, name, access, op, rhe)); - } else{ - substs.push(Statement::UnderscoreSubstitution { meta: meta, op, rhe: rhe }); + } else { + substs.push(Statement::UnderscoreSubstitution { meta, op, rhe }); } - } else{ - return Result::Err(tuple_general_error(meta.clone(),"The elements of the receiving tuple must be signals or variables.".to_string())); + } else { + return Result::Err(Box::new(tuple_general_error(meta.clone(), "The elements of the receiving tuple must be signals or variables.".to_string()))); } } - return Result::Ok(build_block(meta.clone(),substs)); - } else if values1.len() > 0 { - return Result::Err(tuple_general_error(meta.clone(),"The number of elements in both tuples does not coincide".to_string())); + Result::Ok(build_block(meta.clone(),substs)) + } else if !values1.is_empty() { + return Result::Err(Box::new(tuple_general_error(meta.clone(), "The number of elements in both tuples does not coincide".to_string()))); } else { - return Result::Err(tuple_general_error(meta.clone(),"This expression must be in the right side of an assignment".to_string())); + return Result::Err(Box::new(tuple_general_error(meta.clone(), "This expression must be in the right side of an assignment".to_string()))); } }, (lhe, rhe) => { - if lhe.is_tuple() || lhe.is_variable(){ - return Result::Err(tuple_general_error(rhe.get_meta().clone(),"This expression must be a tuple or an anonymous component".to_string())); + if lhe.is_tuple() || lhe.is_variable() { + return Result::Err(Box::new(tuple_general_error(rhe.get_meta().clone(), "This expression must be a tuple or an anonymous component".to_string()))); } else { - return Result::Err(tuple_general_error(lhe.get_meta().clone(),"This expression must be a tuple, a component, a signal or a variable ".to_string())); + return Result::Err(Box::new(tuple_general_error(lhe.get_meta().clone(), "This expression must be a tuple, a component, a signal or a variable ".to_string()))); } } } }, - Statement::IfThenElse { meta, cond, if_case, else_case } - => { + Statement::IfThenElse { meta, cond, if_case, else_case } => { let if_ok = remove_tuples_from_statement(*if_case)?; - let b_if = Box::new(if_ok); - if else_case.is_none(){ - Result::Ok(Statement::IfThenElse { meta : meta, cond : cond, if_case: b_if, else_case: Option::None}) - }else { - let else_c = *(else_case.unwrap()); - let else_ok = remove_tuples_from_statement(else_c)?; - let b_else = Box::new(else_ok); - Result::Ok(Statement::IfThenElse { meta : meta, cond : cond, if_case: b_if, else_case: Option::Some(b_else)}) - } + let b_else = if let Some(stm) = else_case { + let else_ok = remove_tuples_from_statement(*stm)?; + Option::Some(Box::new(else_ok)) + } else { + Option::None + }; + Result::Ok(Statement::IfThenElse { meta, cond, if_case: Box::new(if_ok), else_case: b_else}) } - - Statement::While { meta, cond, stmt } => { + Statement::While { meta, cond, stmt } => { let while_ok = remove_tuples_from_statement(*stmt)?; let b_while = Box::new(while_ok); - Result::Ok(Statement::While { meta : meta, cond : cond, stmt : b_while}) + Result::Ok(Statement::While { meta, cond, stmt: b_while}) } Statement::LogCall {meta, args } => { let mut newargs = Vec::new(); @@ -848,14 +801,13 @@ fn remove_tuples_from_statement(stm: Statement) -> Result { } Result::Ok(build_log_call(meta, newargs)) } - Statement::InitializationBlock { meta, xtype, initializations } => - { + Statement::InitializationBlock { meta, xtype, initializations } => { let mut new_inits = Vec::new(); for stmt in initializations { let stmt_ok = remove_tuples_from_statement(stmt)?; new_inits.push(stmt_ok); } - Result::Ok(Statement::InitializationBlock { meta: meta, xtype: xtype, initializations: new_inits }) + Result::Ok(Statement::InitializationBlock { meta, xtype, initializations: new_inits }) } Statement::Block { meta, stmts } => { let mut new_stmts = Vec::new(); @@ -863,18 +815,17 @@ fn remove_tuples_from_statement(stm: Statement) -> Result { let stmt_ok = remove_tuples_from_statement(stmt)?; new_stmts.push(stmt_ok); } - Result::Ok(Statement::Block { meta : meta, stmts: new_stmts}) + Result::Ok(Statement::Block { meta, stmts: new_stmts}) } Statement::Substitution { meta, var, op, rhe, access} => { let new_rhe = remove_tuple_from_expression(rhe); if new_rhe.is_tuple() { - return Result::Err(tuple_general_error(meta.clone(),"Left-side of the statement is not a tuple".to_string())); + return Result::Err(Box::new(tuple_general_error(meta.clone(), "Left-side of the statement is not a tuple".to_string()))); } if var != "_" { - Result::Ok(Statement::Substitution { meta: meta.clone(), var: var, access: access, op: op, rhe: new_rhe }) - } - else { - Result::Ok(Statement::UnderscoreSubstitution { meta: meta, op, rhe: new_rhe }) + Result::Ok(Statement::Substitution { meta: meta.clone(), var, access, op, rhe: new_rhe }) + } else { + Result::Ok(Statement::UnderscoreSubstitution { meta, op, rhe: new_rhe }) } } Statement::UnderscoreSubstitution { .. } => unreachable!(), @@ -885,7 +836,7 @@ fn remove_tuples_from_statement(stm: Statement) -> Result { fn separate_tuple_for_logcall(values: Vec) -> Vec { let mut new_values = Vec::new(); for val in values { - if let Expression::Tuple { values : values2, .. } = val { + if let Expression::Tuple { values: values2, .. } = val { new_values.push(LogArgument::LogStr("(".to_string())); let mut new_values2 = separate_tuple_for_logcall(values2); new_values.append(&mut new_values2); @@ -898,8 +849,7 @@ fn separate_tuple_for_logcall(values: Vec) -> Vec { new_values } - -pub fn remove_tuple_from_expression(exp : Expression) -> Expression{ +pub fn remove_tuple_from_expression(exp: Expression) -> Expression{ use Expression::*; match exp { AnonymousComp { .. } => { diff --git a/program_structure/src/abstract_syntax_tree/assign_op_impl.rs b/program_structure/src/abstract_syntax_tree/assign_op_impl.rs index 125b527e1..6ee7f02b9 100644 --- a/program_structure/src/abstract_syntax_tree/assign_op_impl.rs +++ b/program_structure/src/abstract_syntax_tree/assign_op_impl.rs @@ -3,9 +3,6 @@ use super::ast::AssignOp; impl AssignOp { pub fn is_signal_operator(self) -> bool { use AssignOp::*; - match self { - AssignConstraintSignal | AssignSignal => true, - _ => false, - } + matches!(self, AssignConstraintSignal | AssignSignal) } } diff --git a/program_structure/src/abstract_syntax_tree/ast.rs b/program_structure/src/abstract_syntax_tree/ast.rs index 7f2dffb8d..a7219fe87 100644 --- a/program_structure/src/abstract_syntax_tree/ast.rs +++ b/program_structure/src/abstract_syntax_tree/ast.rs @@ -1,4 +1,4 @@ -use crate::{file_definition::{FileLocation, FileID}, error_definition::Report, error_code::{ReportCode}}; +use crate::{file_definition::{FileLocation, FileID}, error_definition::Report, error_code::ReportCode}; use num_bigint::BigInt; use serde_derive::{Deserialize, Serialize}; @@ -483,7 +483,7 @@ impl MemoryKnowledge { ) } MissingSemicolon => { - let mut report = Report::error(format!("Missing semicolon"), + let mut report = Report::error("Missing semicolon".to_string(), ReportCode::MissingSemicolon); report.add_primary(location, file_id, "A semicolon is needed here".to_string()); report @@ -565,20 +565,20 @@ pub fn produce_report_with_message(error_code : ReportCode, msg : String) -> Rep } pub fn produce_compiler_version_report(path : String, required_version : Version, version : Version) -> Report { - let report = Report::error( + + Report::error( format!("File {} requires pragma version {:?} that is not supported by the compiler (version {:?})", path, required_version, version ), ReportCode::CompilerVersionError, - ); - report + ) } pub fn anonymous_inside_condition_error(meta : Meta) -> Report { let msg = "An anonymous component cannot be used inside a condition ".to_string(); let mut report = Report::error( - format!("{}", msg), + msg.to_string(), ReportCode::AnonymousCompError, ); - let file_id = meta.get_file_id().clone(); + let file_id = meta.get_file_id(); report.add_primary( meta.location, file_id, @@ -589,10 +589,10 @@ pub fn anonymous_inside_condition_error(meta : Meta) -> Report { pub fn anonymous_general_error(meta : Meta, msg : String) -> Report { let mut report = Report::error( - format!("{}", msg), + msg.to_string(), ReportCode::AnonymousCompError, ); - let file_id = meta.get_file_id().clone(); + let file_id = meta.get_file_id(); report.add_primary( meta.location, file_id, @@ -603,10 +603,10 @@ pub fn anonymous_general_error(meta : Meta, msg : String) -> Report { pub fn tuple_general_error(meta : Meta, msg : String) -> Report { let mut report = Report::error( - format!("{}", msg), + msg.to_string(), ReportCode::TupleError, ); - let file_id = meta.get_file_id().clone(); + let file_id = meta.get_file_id(); report.add_primary( meta.location, file_id, diff --git a/program_structure/src/abstract_syntax_tree/ast_shortcuts.rs b/program_structure/src/abstract_syntax_tree/ast_shortcuts.rs index 2041797d0..005ae20e7 100644 --- a/program_structure/src/abstract_syntax_tree/ast_shortcuts.rs +++ b/program_structure/src/abstract_syntax_tree/ast_shortcuts.rs @@ -114,7 +114,7 @@ pub fn split_declaration_into_single_nodes_and_multisubstitution( build_substitution(meta.clone(), symbol.name, vec![], AssignOp::AssignVar, value); initializations.push(substitution); } - values.push(Expression::Variable { meta: with_meta.clone(), name: name, access: Vec::new() }) + values.push(Expression::Variable { meta: with_meta.clone(), name, access: Vec::new() }) } if let Some( tuple) = init { let (op,expression) = tuple.tuple_init; diff --git a/program_structure/src/abstract_syntax_tree/expression_impl.rs b/program_structure/src/abstract_syntax_tree/expression_impl.rs index 900827e6f..11775cc2b 100644 --- a/program_structure/src/abstract_syntax_tree/expression_impl.rs +++ b/program_structure/src/abstract_syntax_tree/expression_impl.rs @@ -38,93 +38,51 @@ impl Expression { pub fn is_array(&self) -> bool { use Expression::*; - if let ArrayInLine { .. } = self { - true - } else if let UniformArray { .. } = self{ - true - } else { - false - } + matches!(self, ArrayInLine { .. } | UniformArray { .. }) } pub fn is_infix(&self) -> bool { use Expression::*; - if let InfixOp { .. } = self { - true - } else { - false - } + matches!(self, InfixOp { .. }) } pub fn is_prefix(&self) -> bool { use Expression::*; - if let PrefixOp { .. } = self { - true - } else { - false - } + matches!(self, PrefixOp { .. }) } - + pub fn is_tuple(&self) -> bool { use Expression::*; - if let Tuple { .. } = self { - true - } else { - false - } + matches!(self, Tuple { .. }) } pub fn is_switch(&self) -> bool { use Expression::*; - if let InlineSwitchOp { .. } = self { - true - } else { - false - } + matches!(self, InlineSwitchOp { .. }) } pub fn is_parallel(&self) -> bool { use Expression::*; - if let ParallelOp { .. } = self { - true - } else { - false - } + matches!(self, ParallelOp { .. }) } pub fn is_variable(&self) -> bool { use Expression::*; - if let Variable { .. } = self { - true - } else { - false - } + matches!(self, Variable { .. }) } pub fn is_number(&self) -> bool { use Expression::*; - if let Number(..) = self { - true - } else { - false - } + matches!(self, Number(..)) } pub fn is_call(&self) -> bool { use Expression::*; - if let Call { .. } = self { - true - } else { - false - } + matches!(self, Call { .. }) } pub fn is_anonymous_comp(&self) -> bool { use Expression::*; - if let AnonymousComp { .. } = self { - true - } else { - false - } + matches!(self, AnonymousComp { .. }) } pub fn make_anonymous_parallel(self) -> Expression { diff --git a/program_structure/src/abstract_syntax_tree/statement_builders.rs b/program_structure/src/abstract_syntax_tree/statement_builders.rs index aebcbc04c..72ab5e00f 100644 --- a/program_structure/src/abstract_syntax_tree/statement_builders.rs +++ b/program_structure/src/abstract_syntax_tree/statement_builders.rs @@ -7,7 +7,7 @@ pub fn build_conditional_block( if_case: Statement, else_case: Option, ) -> Statement { - IfThenElse { meta, cond, else_case: else_case.map(|s| Box::new(s)), if_case: Box::new(if_case) } + IfThenElse { meta, cond, else_case: else_case.map(Box::new), if_case: Box::new(if_case) } } pub fn build_while_block(meta: Meta, cond: Expression, stmt: Statement) -> Statement { diff --git a/program_structure/src/abstract_syntax_tree/statement_impl.rs b/program_structure/src/abstract_syntax_tree/statement_impl.rs index 7b8463e72..995740008 100644 --- a/program_structure/src/abstract_syntax_tree/statement_impl.rs +++ b/program_structure/src/abstract_syntax_tree/statement_impl.rs @@ -38,92 +38,48 @@ impl Statement { pub fn is_if_then_else(&self) -> bool { use Statement::IfThenElse; - if let IfThenElse { .. } = self { - true - } else { - false - } + matches!(self, IfThenElse { .. }) } pub fn is_while(&self) -> bool { use Statement::While; - if let While { .. } = self { - true - } else { - false - } + matches!(self, While { .. }) } pub fn is_return(&self) -> bool { use Statement::Return; - if let Return { .. } = self { - true - } else { - false - } + matches!(self, Return { .. }) } pub fn is_initialization_block(&self) -> bool { use Statement::InitializationBlock; - if let InitializationBlock { .. } = self { - true - } else { - false - } + matches!(self, InitializationBlock { .. }) } pub fn is_declaration(&self) -> bool { use Statement::Declaration; - if let Declaration { .. } = self { - true - } else { - false - } + matches!(self, Declaration { .. }) } pub fn is_substitution(&self) -> bool { use Statement::Substitution; - if let Substitution { .. } = self { - true - } else { - false - } + matches!(self, Substitution { .. }) } pub fn is_underscore_substitution(&self) -> bool { use Statement::UnderscoreSubstitution; - if let UnderscoreSubstitution { .. } = self { - true - } else { - false - } + matches!(self, UnderscoreSubstitution { .. }) } pub fn is_constraint_equality(&self) -> bool { use Statement::ConstraintEquality; - if let ConstraintEquality { .. } = self { - true - } else { - false - } + matches!(self, ConstraintEquality { .. }) } pub fn is_log_call(&self) -> bool { use Statement::LogCall; - if let LogCall { .. } = self { - true - } else { - false - } + matches!(self, LogCall { .. }) } pub fn is_block(&self) -> bool { use Statement::Block; - if let Block { .. } = self { - true - } else { - false - } + matches!(self, Block { .. }) } pub fn is_assert(&self) -> bool { use Statement::Assert; - if let Assert { .. } = self { - true - } else { - false - } + matches!(self, Assert { .. }) } pub fn contains_anonymous_comp(&self) -> bool { diff --git a/program_structure/src/program_library/error_definition.rs b/program_structure/src/program_library/error_definition.rs index 1edc6b14a..fba190454 100644 --- a/program_structure/src/program_library/error_definition.rs +++ b/program_structure/src/program_library/error_definition.rs @@ -16,17 +16,11 @@ pub enum MessageCategory { impl MessageCategory { fn is_error(&self) -> bool { use MessageCategory::*; - match self { - Error => true, - _ => false, - } + matches!(self, Error) } fn is_warning(&self) -> bool { use MessageCategory::*; - match self { - Warning => true, - _ => false, - } + matches!(self, Warning) } } @@ -60,7 +54,7 @@ impl Report { diagnostics.push(report.to_diagnostic()); } for diagnostic in diagnostics.iter() { - let print_result = term::emit(&mut writer.lock(), &config, files, &diagnostic); + let print_result = term::emit(&mut writer.lock(), &config, files, diagnostic); if print_result.is_err() { panic!("Error printing reports") } diff --git a/program_structure/src/program_library/file_definition.rs b/program_structure/src/program_library/file_definition.rs index e372b3034..e8e652cd8 100644 --- a/program_structure/src/program_library/file_definition.rs +++ b/program_structure/src/program_library/file_definition.rs @@ -26,13 +26,10 @@ impl FileLibrary { self.get_mut_files().add(file_name, file_source) } pub fn get_line(&self, start: usize, file_id: FileID) -> Option { - match self.files.line_index(file_id, start) { - Some(lines) => Some(lines + 1), - None => None, - } + self.files.line_index(file_id, start).map(|lines| lines + 1) } pub fn to_storage(&self) -> &FileStorage { - &self.get_files() + self.get_files() } fn get_files(&self) -> &FileStorage { &self.files diff --git a/program_structure/src/program_library/program_merger.rs b/program_structure/src/program_library/program_merger.rs index 7e44cac09..6cd009f82 100644 --- a/program_structure/src/program_library/program_merger.rs +++ b/program_structure/src/program_library/program_merger.rs @@ -5,20 +5,13 @@ use super::file_definition::FileID; use super::function_data::{FunctionData, FunctionInfo}; use super::template_data::{TemplateData, TemplateInfo}; +#[derive(Default)] pub struct Merger { fresh_id: usize, function_info: FunctionInfo, template_info: TemplateInfo, } -impl Default for Merger { - fn default() -> Self { - Merger { - fresh_id: 0, - function_info: FunctionInfo::new(), - template_info: TemplateInfo::new(), - } - } -} + impl Merger { pub fn new() -> Merger { diff --git a/program_structure/src/program_library/template_data.rs b/program_structure/src/program_library/template_data.rs index 125bf7ab8..8b3fda8b7 100644 --- a/program_structure/src/program_library/template_data.rs +++ b/program_structure/src/program_library/template_data.rs @@ -27,6 +27,7 @@ pub struct TemplateData { } impl TemplateData { + #[allow(clippy::too_many_arguments)] pub fn new( name: String, file_id: FileID, @@ -60,6 +61,7 @@ impl TemplateData { } } + #[allow(clippy::too_many_arguments)] pub fn copy( name: String, file_id: FileID, @@ -136,7 +138,7 @@ impl TemplateData { &self.output_signals } pub fn get_declaration_inputs(&self) -> &SignalDeclarationOrder { - &&self.input_declarations + &self.input_declarations } pub fn get_declaration_outputs(&self) -> &SignalDeclarationOrder { &self.output_declarations @@ -179,26 +181,23 @@ fn fill_inputs_and_outputs( fill_inputs_and_outputs(initialization, input_signals, output_signals, input_declarations, output_declarations); } } - Statement::Declaration { xtype, name, dimensions, .. } => { - if let ast::VariableType::Signal(stype, tag_list) = xtype { - let signal_name = name.clone(); - let dim = dimensions.len(); - let mut tag_info = HashSet::new(); - for tag in tag_list{ - tag_info.insert(tag.clone()); + Statement::Declaration { xtype: ast::VariableType::Signal(stype, tag_list), name, dimensions, .. } => { + let signal_name = name.clone(); + let dim = dimensions.len(); + let mut tag_info = HashSet::new(); + for tag in tag_list { + tag_info.insert(tag.clone()); + } + match stype { + ast::SignalType::Input => { + input_signals.insert(signal_name.clone(), (dim, tag_info)); + input_declarations.push((signal_name, dim)); } - - match stype { - ast::SignalType::Input => { - input_signals.insert(signal_name.clone(), (dim, tag_info)); - input_declarations.push((signal_name,dim)); - } - ast::SignalType::Output => { - output_signals.insert(signal_name.clone(), (dim, tag_info)); - output_declarations.push((signal_name,dim)); - } - _ => {} //no need to deal with intermediate signals + ast::SignalType::Output => { + output_signals.insert(signal_name.clone(), (dim, tag_info)); + output_declarations.push((signal_name, dim)); } + _ => {} //no need to deal with intermediate signals } } _ => {} diff --git a/program_structure/src/utils/environment.rs b/program_structure/src/utils/environment.rs index 0215dce61..9acfdc16e 100644 --- a/program_structure/src/utils/environment.rs +++ b/program_structure/src/utils/environment.rs @@ -218,7 +218,7 @@ where self.components.get_mut(symbol) } pub fn get_component_res(&self, symbol: &str) -> Result<&CC, CircomEnvironmentError> { - self.components.get(symbol).ok_or_else(|| CircomEnvironmentError::NonExistentSymbol) + self.components.get(symbol).ok_or(CircomEnvironmentError::NonExistentSymbol) } pub fn get_component_or_break(&self, symbol: &str, file: &str, line: u32) -> &CC { assert!(self.has_component(symbol), "Method call in file {} line {}", file, line); @@ -228,7 +228,7 @@ where &mut self, symbol: &str, ) -> Result<&mut CC, CircomEnvironmentError> { - self.components.get_mut(symbol).ok_or_else(|| CircomEnvironmentError::NonExistentSymbol) + self.components.get_mut(symbol).ok_or(CircomEnvironmentError::NonExistentSymbol) } pub fn get_mut_component_or_break(&mut self, symbol: &str, file: &str, line: u32) -> &mut CC { assert!(self.has_component(symbol), "Method call in file {} line {}", file, line); @@ -280,14 +280,14 @@ where self.inputs.get_mut(symbol) } pub fn get_input_res(&self, symbol: &str) -> Result<&SC, CircomEnvironmentError> { - self.inputs.get(symbol).ok_or_else(|| CircomEnvironmentError::NonExistentSymbol) + self.inputs.get(symbol).ok_or(CircomEnvironmentError::NonExistentSymbol) } pub fn get_input_or_break(&self, symbol: &str, file: &str, line: u32) -> &SC { assert!(self.has_input(symbol), "Method call in file {} line {}", file, line); self.inputs.get(symbol).unwrap() } pub fn get_mut_input_res(&mut self, symbol: &str) -> Result<&mut SC, CircomEnvironmentError> { - self.inputs.get_mut(symbol).ok_or_else(|| CircomEnvironmentError::NonExistentSymbol) + self.inputs.get_mut(symbol).ok_or(CircomEnvironmentError::NonExistentSymbol) } pub fn get_mut_input_or_break(&mut self, symbol: &str, file: &str, line: u32) -> &mut SC { assert!(self.has_input(symbol), "Method call in file {} line {}", file, line); @@ -301,14 +301,14 @@ where self.outputs.get_mut(symbol) } pub fn get_output_res(&self, symbol: &str) -> Result<&SC, CircomEnvironmentError> { - self.outputs.get(symbol).ok_or_else(|| CircomEnvironmentError::NonExistentSymbol) + self.outputs.get(symbol).ok_or(CircomEnvironmentError::NonExistentSymbol) } pub fn get_output_or_break(&self, symbol: &str, file: &str, line: u32) -> &SC { assert!(self.has_output(symbol), "Method call in file {} line {}", file, line); self.outputs.get(symbol).unwrap() } pub fn get_mut_output_res(&mut self, symbol: &str) -> Result<&mut SC, CircomEnvironmentError> { - self.outputs.get_mut(symbol).ok_or_else(|| CircomEnvironmentError::NonExistentSymbol) + self.outputs.get_mut(symbol).ok_or(CircomEnvironmentError::NonExistentSymbol) } pub fn get_mut_output_or_break(&mut self, symbol: &str, file: &str, line: u32) -> &mut SC { assert!(self.has_output(symbol), "Method call in file {} line {}", file, line); @@ -322,7 +322,7 @@ where self.intermediates.get_mut(symbol) } pub fn get_intermediate_res(&self, symbol: &str) -> Result<&SC, CircomEnvironmentError> { - self.intermediates.get(symbol).ok_or_else(|| CircomEnvironmentError::NonExistentSymbol) + self.intermediates.get(symbol).ok_or(CircomEnvironmentError::NonExistentSymbol) } pub fn get_intermediate_or_break(&self, symbol: &str, file: &str, line: u32) -> &SC { assert!(self.has_intermediate(symbol), "Method call in file {} line {}", file, line); @@ -332,7 +332,7 @@ where &mut self, symbol: &str, ) -> Result<&mut SC, CircomEnvironmentError> { - self.intermediates.get_mut(symbol).ok_or_else(|| CircomEnvironmentError::NonExistentSymbol) + self.intermediates.get_mut(symbol).ok_or(CircomEnvironmentError::NonExistentSymbol) } pub fn get_mut_intermediate_or_break( &mut self, diff --git a/program_structure/src/utils/memory_slice.rs b/program_structure/src/utils/memory_slice.rs index 3b9d6fc74..d598016fe 100644 --- a/program_structure/src/utils/memory_slice.rs +++ b/program_structure/src/utils/memory_slice.rs @@ -64,7 +64,7 @@ impl Display for MemorySlice { for i in 1..self.values.len() { msg.push_str(&format!(",{}", self.values[i])); } - msg.push_str("]"); + msg.push(']'); f.write_str(&msg) } } @@ -239,7 +239,7 @@ impl MemorySlice { } Result::Err(MemoryError::MismatchedDimensionsWeak(dim_1, dim_2)) } - Result::Err(error) => return Err(error), + Result::Err(error) => Err(error), } } @@ -253,7 +253,7 @@ impl MemorySlice { } memory_slice.number_inserts += 1; memory_slice.values[index] = new_value; - return Result::Ok(()); + Result::Ok(()) } pub fn get_access_index( @@ -262,16 +262,16 @@ impl MemorySlice { ) -> Result, MemoryError> { let mut number_cells = MemorySlice::get_number_of_cells(memory_slice); if index > number_cells { - return Result::Err(MemoryError::OutOfBoundsError); + Result::Err(MemoryError::OutOfBoundsError) } else { let mut access = vec![]; let mut index_aux = index; for pos in &memory_slice.route { - number_cells = number_cells / pos; + number_cells /= pos; access.push(index_aux / number_cells); - index_aux = index_aux % number_cells; + index_aux %= number_cells; } - return Result::Ok(access); + Result::Ok(access) } } @@ -288,7 +288,7 @@ impl MemorySlice { if index > MemorySlice::get_number_of_cells(memory_slice) { return Result::Err(MemoryError::OutOfBoundsError); } - return Result::Ok(memory_slice.values[index].clone()); + Result::Ok(memory_slice.values[index].clone()) } pub fn get_reference_to_single_value<'a>( @@ -299,19 +299,19 @@ impl MemorySlice { let cell = MemorySlice::get_initial_cell(memory_slice, access)?; Result::Ok(&memory_slice.values[cell]) } - pub fn get_reference_to_single_value_by_index<'a>( - memory_slice: &'a MemorySlice, + pub fn get_reference_to_single_value_by_index( + memory_slice: &MemorySlice, index: usize, - ) -> Result<&'a C, MemoryError> { + ) -> Result<&C, MemoryError> { if index > MemorySlice::get_number_of_cells(memory_slice) { return Result::Err(MemoryError::OutOfBoundsError); } Result::Ok(&memory_slice.values[index]) } - pub fn get_reference_to_single_value_by_index_or_break<'a>( - memory_slice: &'a MemorySlice, + pub fn get_reference_to_single_value_by_index_or_break( + memory_slice: &MemorySlice, index: usize, - ) -> &'a C { + ) -> &C { if index > MemorySlice::get_number_of_cells(memory_slice) { unreachable!("The index is too big for the slice"); } @@ -373,7 +373,7 @@ mod tests { if let Result::Ok(v) = result { assert_eq!(*v, 0); } else { - assert!(false); + unreachable!(); } } } @@ -386,7 +386,7 @@ mod tests { if let Result::Ok(val) = memory_response { assert_eq!(*val, 4); } else { - assert!(false); + unreachable!(); } } #[test] @@ -396,17 +396,17 @@ mod tests { let new_row = U32Slice::new_with_route(&[4], &4); let res = U32Slice::insert_values(&mut slice, &[2], &new_row, false); - if let Result::Ok(_) = res { + if res.is_ok() { for c in 0..4 { let memory_result = U32Slice::get_reference_to_single_value(&slice, &[2, c]); if let Result::Ok(val) = memory_result { assert_eq!(*val, 4); } else { - assert!(false); + unreachable!(); } } } else { - assert!(false); + unreachable!(); } } } diff --git a/type_analysis/src/analyzers/custom_gate_analysis.rs b/type_analysis/src/analyzers/custom_gate_analysis.rs index d829d6d2f..721af0356 100644 --- a/type_analysis/src/analyzers/custom_gate_analysis.rs +++ b/type_analysis/src/analyzers/custom_gate_analysis.rs @@ -68,20 +68,17 @@ pub fn custom_gate_analysis( } Substitution { meta, op, .. } => { use AssignOp::*; - match op { - AssignConstraintSignal => { - let mut error = Report::error( - String::from("Added constraint inside custom template"), - ReportCode::CustomGateConstraintError - ); - error.add_primary( - meta.location.clone(), - meta.file_id.unwrap(), - String::from("Added constraint") - ); - errors.push(error); - } - _ => {} + if op == &AssignConstraintSignal { + let mut error = Report::error( + String::from("Added constraint inside custom template"), + ReportCode::CustomGateConstraintError, + ); + error.add_primary( + meta.location.clone(), + meta.file_id.unwrap(), + String::from("Added constraint"), + ); + errors.push(error); } } ConstraintEquality { meta, .. } => { @@ -103,20 +100,17 @@ pub fn custom_gate_analysis( } UnderscoreSubstitution { meta, op, .. } => { use AssignOp::*; - match op { - AssignConstraintSignal => { - let mut error = Report::error( - String::from("Added constraint inside custom template"), - ReportCode::CustomGateConstraintError - ); - error.add_primary( - meta.location.clone(), - meta.file_id.unwrap(), - String::from("Added constraint") - ); - errors.push(error); - } - _ => {} + if op == &AssignConstraintSignal { + let mut error = Report::error( + String::from("Added constraint inside custom template"), + ReportCode::CustomGateConstraintError, + ); + error.add_primary( + meta.location.clone(), + meta.file_id.unwrap(), + String::from("Added constraint"), + ); + errors.push(error); } } _ => {} diff --git a/type_analysis/src/analyzers/functions_all_paths_with_return_statement.rs b/type_analysis/src/analyzers/functions_all_paths_with_return_statement.rs index 6d90448e6..3f4d41258 100644 --- a/type_analysis/src/analyzers/functions_all_paths_with_return_statement.rs +++ b/type_analysis/src/analyzers/functions_all_paths_with_return_statement.rs @@ -3,14 +3,14 @@ use program_structure::error_code::ReportCode; use program_structure::error_definition::Report; use program_structure::function_data::FunctionData; -pub fn all_paths_with_return_check(function_data: &FunctionData) -> Result<(), Report> { +pub fn all_paths_with_return_check(function_data: &FunctionData) -> Result<(), Box> { let function_body = function_data.get_body(); let function_name = function_data.get_name(); if !analyse_statement(function_body) { - return Result::Err(Report::error( + return Result::Err(Box::new(Report::error( format!("In {} there are paths without return", function_name), ReportCode::FunctionReturnError, - )); + ))); } Result::Ok(()) } @@ -31,7 +31,7 @@ fn analyse_statement(stmt: &Statement) -> bool { } } -fn analyse_block(block: &Vec) -> bool { +fn analyse_block(block: &[Statement]) -> bool { let mut has_return_path = false; for stmt in block.iter() { has_return_path = has_return_path || analyse_statement(stmt); diff --git a/type_analysis/src/analyzers/functions_free_of_template_elements.rs b/type_analysis/src/analyzers/functions_free_of_template_elements.rs index b5330864c..023060dde 100644 --- a/type_analysis/src/analyzers/functions_free_of_template_elements.rs +++ b/type_analysis/src/analyzers/functions_free_of_template_elements.rs @@ -92,12 +92,12 @@ fn analyse_statement( } ConstraintEquality { meta, lhe, rhe, .. } => { let mut report = Report::error( - format!("Function uses template operators"), + "Function uses template operators".to_string(), ReportCode::UndefinedFunction, ); let location = file_definition::generate_file_location(meta.get_start(), meta.get_end()); - report.add_primary(location, file_id.clone(), format!("Template operator found")); + report.add_primary(location, file_id, "Template operator found".to_string()); reports.push(report); analyse_expression(lhe, function_names, reports); analyse_expression(rhe, function_names, reports); @@ -132,7 +132,7 @@ fn analyse_statement( } fn analyse_access( - access: &Vec, + access: &[Access], meta: &Meta, function_names: &HashSet, reports: &mut ReportCollection, @@ -143,12 +143,12 @@ fn analyse_access( analyse_expression(index, function_names, reports); } else { let mut report = Report::error( - format!("Function uses component operators"), + "Function uses component operators".to_string(), ReportCode::UndefinedFunction, ); let location = file_definition::generate_file_location(meta.get_start(), meta.get_end()); - report.add_primary(location, file_id.clone(), format!("Template operator found")); + report.add_primary(location, file_id, "Template operator found".to_string()); reports.push(report); } } @@ -182,12 +182,12 @@ fn analyse_expression( Call { meta, id, args, .. } => { if !function_names.contains(id) { let mut report = Report::error( - format!("Unknown call in function"), + "Unknown call in function".to_string(), ReportCode::UndefinedFunction, ); let location = file_definition::generate_file_location(meta.get_start(), meta.get_end()); - report.add_primary(location, file_id.clone(), format!("Is not a function call")); + report.add_primary(location, file_id, "Is not a function call".to_string()); reports.push(report); } for arg in args.iter() { diff --git a/type_analysis/src/analyzers/no_returns_in_template.rs b/type_analysis/src/analyzers/no_returns_in_template.rs index 89fea7027..ec0d094aa 100644 --- a/type_analysis/src/analyzers/no_returns_in_template.rs +++ b/type_analysis/src/analyzers/no_returns_in_template.rs @@ -8,7 +8,7 @@ pub fn free_of_returns(template_data: &TemplateData) -> Result<(), ReportCollect let file_id = template_data.get_file_id(); let template_body = template_data.get_body(); let mut reports = ReportCollection::new(); - look_for_return(&template_body, file_id, &mut reports); + look_for_return(template_body, file_id, &mut reports); if reports.is_empty() { Result::Ok(()) } else { diff --git a/type_analysis/src/analyzers/signal_declaration_analysis.rs b/type_analysis/src/analyzers/signal_declaration_analysis.rs index aa63f7a60..7040c91dd 100644 --- a/type_analysis/src/analyzers/signal_declaration_analysis.rs +++ b/type_analysis/src/analyzers/signal_declaration_analysis.rs @@ -51,7 +51,7 @@ fn treat_statement( file_definition::generate_file_location(meta.get_start(), meta.get_end()); report.add_primary( location, - template_id.clone(), + template_id, "Is outside the initial scope".to_string(), ); reports.push(report); diff --git a/type_analysis/src/analyzers/symbol_analysis.rs b/type_analysis/src/analyzers/symbol_analysis.rs index 1d92ce25e..b3e5f7840 100644 --- a/type_analysis/src/analyzers/symbol_analysis.rs +++ b/type_analysis/src/analyzers/symbol_analysis.rs @@ -14,7 +14,7 @@ pub fn check_naming_correctness(program_archive: &ProgramArchive) -> Result<(), let function_info = program_archive.get_functions(); let mut reports = ReportCollection::new(); let mut instances = Vec::new(); - for (_, data) in template_info { + for data in template_info.values() { let instance = ( data.get_file_id(), data.get_param_location(), @@ -23,7 +23,7 @@ pub fn check_naming_correctness(program_archive: &ProgramArchive) -> Result<(), ); instances.push(instance); } - for (_, data) in function_info { + for data in function_info.values() { let instance = ( data.get_file_id(), data.get_param_location(), @@ -68,7 +68,7 @@ fn analyze_main(program: &ProgramArchive) -> Result<(), Vec> { for signal in signals { if !inputs.contains_key(signal) { let mut report = Report::error( - format!("Invalid public list"), + "Invalid public list".to_string(), ReportCode::SameSymbolDeclaredTwice, ); report.add_primary( @@ -112,11 +112,11 @@ pub fn analyze_symbols( } if param_name_collision { let mut report = - Report::error(format!("Symbol declared twice"), ReportCode::SameSymbolDeclaredTwice); + Report::error("Symbol declared twice".to_string(), ReportCode::SameSymbolDeclaredTwice); report.add_primary( param_location.clone(), - file_id.clone(), - format!("Declaring same symbol twice"), + file_id, + "Declaring same symbol twice".to_string(), ); reports.push(report); } @@ -213,13 +213,13 @@ fn analyze_statement( } if !add_symbol_to_block(environment, name) { let mut report = Report::error( - format!("Symbol declared twice"), + "Symbol declared twice".to_string(), ReportCode::SameSymbolDeclaredTwice, ); report.add_primary( meta.location.clone(), - file_id.clone(), - format!("Declaring same symbol twice"), + file_id, + "Declaring same symbol twice".to_string(), ); reports.push(report); } @@ -269,10 +269,11 @@ fn analyze_statement( } } +#[allow(clippy::too_many_arguments)] fn treat_variable( meta: &Meta, name: &String, - access: &Vec, + access: &[Access], file_id: FileID, function_info: &FunctionInfo, template_info: &TemplateInfo, @@ -280,11 +281,11 @@ fn treat_variable( environment: &Environment, ) { if !symbol_in_environment(environment, name) { - let mut report = Report::error(format!("Undeclared symbol"), ReportCode::NonExistentSymbol); + let mut report = Report::error("Undeclared symbol".to_string(), ReportCode::NonExistentSymbol); report.add_primary( file_definition::generate_file_location(meta.get_start(), meta.get_end()), - file_id.clone(), - format!("Using unknown symbol"), + file_id, + "Using unknown symbol".to_string(), ); reports.push(report); } @@ -346,11 +347,11 @@ fn analyze_expression( Expression::Call { meta, id, args, .. } => { if !function_info.contains_key(id) && !template_info.contains_key(id) { let mut report = - Report::error(format!("Calling symbol"), ReportCode::NonExistentSymbol); + Report::error("Calling symbol".to_string(), ReportCode::NonExistentSymbol); report.add_primary( file_definition::generate_file_location(meta.get_start(), meta.get_end()), - file_id.clone(), - format!("Calling unknown symbol"), + file_id, + "Calling unknown symbol".to_string(), ); reports.push(report); return; @@ -362,12 +363,12 @@ fn analyze_expression( }; if args.len() != expected_num_of_params { let mut report = Report::error( - format!("Calling function with wrong number of arguments"), + "Calling function with wrong number of arguments".to_string(), ReportCode::FunctionWrongNumberOfArguments, ); report.add_primary( file_definition::generate_file_location(meta.get_start(), meta.get_end()), - file_id.clone(), + file_id, format!("Got {} params, {} where expected", args.len(), expected_num_of_params), ); reports.push(report); diff --git a/type_analysis/src/analyzers/type_check.rs b/type_analysis/src/analyzers/type_check.rs index c1bd56a3f..8236eebb8 100644 --- a/type_analysis/src/analyzers/type_check.rs +++ b/type_analysis/src/analyzers/type_check.rs @@ -344,7 +344,7 @@ fn type_statement( LogCall { args, meta } => { for arglog in args { if let LogArgument::LogExp(arg) = arglog{ - let arg_response = type_expression(&arg, program_archive, analysis_information); + let arg_response = type_expression(arg, program_archive, analysis_information); let arg_type = if let Result::Ok(t) = arg_response { t } else { @@ -395,7 +395,7 @@ fn type_statement( } else { return; }; - let ret_type = analysis_information.return_type.clone().unwrap(); + let ret_type = analysis_information.return_type.unwrap(); debug_assert!(!value_type.is_template()); if ret_type != value_type.dim() { add_report( @@ -523,13 +523,7 @@ fn type_expression( ); }; let dim_type = type_expression(dimension, program_archive, analysis_information)?; - if dim_type.is_template() { - add_report( - ReportCode::InvalidArrayType, - expression.get_meta(), - &mut analysis_information.reports, - ); - } else if dim_type.dim() != 0 { + if dim_type.is_template() || dim_type.dim() != 0{ add_report( ReportCode::InvalidArrayType, expression.get_meta(), @@ -702,7 +696,7 @@ fn type_expression( std::mem::replace(&mut analysis_information.environment, new_environment); let returned_type = if program_archive.contains_function(id) { type_function(id, &concrete_types, meta, analysis_information, program_archive) - .map(|val| FoldedType::arithmetic_type(val)) + .map(FoldedType::arithmetic_type) } else { let r_val = type_template(id, &concrete_types, analysis_information, program_archive); @@ -743,7 +737,7 @@ fn treat_access( for access in accesses { match access { ArrayAccess(index) => { - let index_response = type_expression(&index, program_archive, analysis_information); + let index_response = type_expression(index, program_archive, analysis_information); if access_info.2.is_some(){ add_report( @@ -847,7 +841,7 @@ fn apply_access_to_symbol( }; if access_information.2.is_some(){ // tag of io signal of component if dims_accessed > 0{ - return add_report_and_end(ReportCode::InvalidTagAccessAfterArray, meta, reports); + add_report_and_end(ReportCode::InvalidTagAccessAfterArray, meta, reports) } else if !tags.contains(&access_information.2.unwrap()){ return add_report_and_end(ReportCode::InvalidTagAccess, meta, reports); @@ -856,9 +850,9 @@ fn apply_access_to_symbol( } } else{ // io signal of component if dims_accessed > current_dim { - return add_report_and_end(ReportCode::InvalidArrayAccess(current_dim, dims_accessed), meta, reports); + add_report_and_end(ReportCode::InvalidArrayAccess(current_dim, dims_accessed), meta, reports) } else { - return Result::Ok(SymbolInformation::Signal(current_dim - dims_accessed)); + Result::Ok(SymbolInformation::Signal(current_dim - dims_accessed)) } } } else{ // we are in template @@ -1035,10 +1029,10 @@ fn add_report(error_code: ReportCode, meta: &Meta, reports: &mut ReportCollectio InvalidPartialArray => "Only variable arrays can be accessed partially".to_string(), UninitializedSymbolInExpression => "The type of this symbol is not known".to_string(), WrongTypesInAssignOperationOperatorSignal => { - format!("The operator does not match the types of the assigned elements.\n Assignments to signals do not allow the operator =, try using <== or <-- instead") + "The operator does not match the types of the assigned elements.\n Assignments to signals do not allow the operator =, try using <== or <-- instead".to_string() } WrongTypesInAssignOperationOperatorNoSignal => { - format!("The operator does not match the types of the assigned elements.\n Only assignments to signals allow the operators <== and <--, try using = instead") + "The operator does not match the types of the assigned elements.\n Only assignments to signals allow the operators <== and <--, try using = instead".to_string() } WrongTypesInAssignOperationArrayTemplates => "Assignee and assigned types do not match.\n All components of an array must be instances of the same template.".to_string(), WrongTypesInAssignOperationTemplate => "Assignee and assigned types do not match.\n Expected template found expression.".to_string(), @@ -1053,7 +1047,7 @@ fn add_report(error_code: ReportCode, meta: &Meta, reports: &mut ReportCollectio format!("Must be a single arithmetic expression.\n Found expression of {} dimensions", dim) } MustBeSingleArithmeticT => { - format!("Must be a single arithmetic expression.\n Found component") + "Must be a single arithmetic expression.\n Found component".to_string() } MustBeArithmetic => "Must be a single arithmetic expression or an array of arithmetic expressions. \n Found component".to_string(), OutputTagCannotBeModifiedOutside => "Output tag from a subcomponent cannot be modified".to_string(), diff --git a/type_analysis/src/analyzers/type_given_function.rs b/type_analysis/src/analyzers/type_given_function.rs index 427d11bcd..0c51585a3 100644 --- a/type_analysis/src/analyzers/type_given_function.rs +++ b/type_analysis/src/analyzers/type_given_function.rs @@ -23,7 +23,7 @@ fn add_variable_to_environment( has_type: &Type, ) { let last = environment.last_mut().unwrap(); - last.insert(var_name.to_string(), has_type.clone()); + last.insert(var_name.to_string(), *has_type); } fn get_type(function_name: &str, environment: &Environment, var_name: &str) -> Type { @@ -34,7 +34,7 @@ fn get_type(function_name: &str, environment: &Environment, var_name: &str) -> T } } match var_type { - Option::Some(v) => v.clone(), + Option::Some(v) => *v, Option::None => panic!( "in get_type variable {:?} not found in the environment of the function {:?}", var_name, function_name @@ -53,7 +53,7 @@ fn start( let mut initial_block = Block::new(); explored_functions.insert(function_name.to_string()); for (name, t) in function_data.get_name_of_params().iter().zip(params_types.iter()) { - initial_block.insert(name.clone(), t.clone()); + initial_block.insert(name.clone(), *t); } environment.push(initial_block); look_for_return_value( @@ -109,7 +109,8 @@ fn look_for_return_in_statement( if ret1.is_some() { return ret1; } - let ret2 = match else_case { + + match else_case { Option::Some(s) => look_for_return_in_statement( function_name, environment, @@ -119,8 +120,7 @@ fn look_for_return_in_statement( s, ), Option::None => Option::None, - }; - ret2 + } } Statement::While { stmt, .. } => look_for_return_in_statement( function_name, @@ -134,7 +134,6 @@ fn look_for_return_in_statement( function_name, environment, explored_functions, - function_data, function_info, value, ), @@ -173,7 +172,7 @@ fn look_for_return_in_block( explored_functions: &mut NodeRegister, function_data: &FunctionData, function_info: &HashMap, - stmts: &Vec, + stmts: &[Statement], ) -> Option { environment.push(Block::new()); for stmt in stmts.iter() { @@ -198,7 +197,6 @@ fn look_for_type_in_expression( function_name: &str, environment: &mut Environment, explored_functions: &mut NodeRegister, - function_data: &FunctionData, function_info: &HashMap, expression: &Expression, ) -> Option { @@ -208,28 +206,25 @@ fn look_for_type_in_expression( function_name, environment, explored_functions, - function_data, function_info, lhe, ); if lhe_type.is_some() { return lhe_type; } - let rhe_type = look_for_type_in_expression( + + look_for_type_in_expression( function_name, environment, explored_functions, - function_data, function_info, rhe, - ); - rhe_type + ) } Expression::PrefixOp { rhe, .. } => look_for_type_in_expression( function_name, environment, explored_functions, - function_data, function_info, rhe, ), @@ -237,7 +232,6 @@ fn look_for_type_in_expression( function_name, environment, explored_functions, - function_data, function_info, rhe, ), @@ -246,22 +240,20 @@ fn look_for_type_in_expression( function_name, environment, explored_functions, - function_data, function_info, if_true, ); if if_true_type.is_some() { return if_true_type; } - let if_false_type = look_for_type_in_expression( + + look_for_type_in_expression( function_name, environment, explored_functions, - function_data, function_info, if_false, - ); - if_false_type + ) } Expression::Variable { name, access, .. } => { let var_type = get_type(function_name, environment, name); @@ -276,7 +268,6 @@ fn look_for_type_in_expression( function_name, environment, explored_functions, - function_data, function_info, &values[0], ) @@ -286,17 +277,10 @@ fn look_for_type_in_expression( function_name, environment, explored_functions, - function_data, function_info, value, ); - if value_type.is_some(){ - Option::Some(value_type.unwrap() + 1) - } - else{ - None - } - + value_type.map(|x| x + 1) } Expression::Call { id, args, .. } => { if explored_functions.contains(id) { @@ -308,14 +292,13 @@ fn look_for_type_in_expression( function_name, environment, explored_functions, - function_data, function_info, arg, )?; params_types.push(arg_type); } - let has_type = start(id, explored_functions, function_info, ¶ms_types); - has_type + + start(id, explored_functions, function_info, ¶ms_types) } _ => {unreachable!("Anonymous calls should not be reachable at this point."); } } diff --git a/type_analysis/src/analyzers/type_register.rs b/type_analysis/src/analyzers/type_register.rs index 893f91ae9..e7c33d41e 100644 --- a/type_analysis/src/analyzers/type_register.rs +++ b/type_analysis/src/analyzers/type_register.rs @@ -29,12 +29,7 @@ impl TypeRegister { return Option::None; } let instances = self.id_to_instances.get(id).unwrap(); - for instance in instances { - if instance.arguments() == look_for { - return Option::Some(&instance); - } - } - Option::None + instances.iter().find(|&instance| instance.arguments() == look_for) } pub fn add_instance( &mut self, diff --git a/type_analysis/src/analyzers/unknown_known_analysis.rs b/type_analysis/src/analyzers/unknown_known_analysis.rs index 5cb5541f2..0c09c57c3 100644 --- a/type_analysis/src/analyzers/unknown_known_analysis.rs +++ b/type_analysis/src/analyzers/unknown_known_analysis.rs @@ -338,12 +338,10 @@ fn tag(expression: &Expression, environment: &Environment) -> Tag { *environment.get_variable_or_break(name, file!(), line!()) } else if environment.has_component(name) { *environment.get_component_or_break(name, file!(), line!()) - } else { - if environment.has_intermediate(name) && !all_array_are_accesses(access) { - Known /* In this case, it is a tag. */ - } else{ - *environment.get_intermediate_or_break(name, file!(), line!()) - } + } else if environment.has_intermediate(name) && !all_array_are_accesses(access) { + Known /* In this case, it is a tag. */ + } else{ + *environment.get_intermediate_or_break(name, file!(), line!()) }; let mut index = 0; loop { @@ -416,7 +414,7 @@ fn all_array_are_accesses(accesses: &[Access]) -> bool { if let Access::ComponentAccess(_) = aux { all_array_accesses = false; } - i = i + 1; + i += 1; } all_array_accesses } @@ -518,7 +516,7 @@ fn unknown_index(exp: &Expression, environment: &Environment) -> bool { if index == rec.len() || has_unknown_index { break has_unknown_index; } - has_unknown_index = unknown_index(&rec[index], environment); + has_unknown_index = unknown_index(rec[index], environment); index += 1; } } diff --git a/type_analysis/src/check_types.rs b/type_analysis/src/check_types.rs index 5cc3c5682..6a4d4a37a 100644 --- a/type_analysis/src/check_types.rs +++ b/type_analysis/src/check_types.rs @@ -108,7 +108,7 @@ fn function_level_analyses(program_archive: &ProgramArchive, reports: &mut Repor reports.append(&mut functions_free_of_template_elements_reports); } if let Result::Err(functions_all_paths_with_return_statement_report) = result_1 { - reports.push(functions_all_paths_with_return_statement_report); + reports.push(*functions_all_paths_with_return_statement_report); } } }