Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Implement .len() in Acir-Gen #2077

Merged
merged 12 commits into from
Aug 1, 2023
1 change: 1 addition & 0 deletions crates/nargo_cli/tests/test_data/array_len/Prover.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
len3 = [1, 2, 3]
len4 = [1, 2, 3, 4]
x = 123
7 changes: 6 additions & 1 deletion crates/nargo_cli/tests/test_data/array_len/src/main.nr
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,17 @@ fn nested_call<N>(b: [Field; N]) -> Field {
len_plus_1(b)
}

fn main(len3: [u8; 3], len4: [Field; 4]) {
fn main(x: Field, len3: [u8; 3], len4: [Field; 4]) {
assert(len_plus_1(len3) == 4);
assert(len_plus_1(len4) == 5);
assert(add_lens(len3, len4) == 7);
assert(nested_call(len4) == 5);

// std::array::len returns a comptime value
assert(len4[len3.len()] == 4);

// Regression for #1023, ensure .len still works after calling to_le_bytes on a witness.
// This was needed because normally .len is evaluated before acir-gen where to_le_bytes
// on a witness is only evaluated during/after acir-gen.
assert(x.to_le_bytes(8).len() != 0);
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ impl AcirType {
}
}

/// Returns a field type
pub(crate) fn field() -> Self {
AcirType::NumericType(NumericType::NativeField)
}

/// Returns a boolean type
fn boolean() -> Self {
AcirType::NumericType(NumericType::Unsigned { bit_size: 1 })
Expand Down
8 changes: 8 additions & 0 deletions crates/noirc_evaluator/src/ssa_refactor/acir_gen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -933,6 +933,14 @@ impl Context {

Ok(Self::convert_vars_to_values(out_vars, dfg, result_ids))
}
Intrinsic::ArrayLen => {
let len = match self.convert_value(arguments[0], dfg) {
AcirValue::Var(_, _) => unreachable!("Non-array passed to array.len() method"),
AcirValue::Array(values) => (values.len() as u128).into(),
AcirValue::DynamicArray(array) => (array.len as u128).into(),
};
Ok(vec![AcirValue::Var(self.acir_context.add_constant(len), AcirType::field())])
}
_ => todo!("expected a black box function"),
}
}
Expand Down
Loading