Skip to content

Commit

Permalink
fix: Implement .len() in Acir-Gen (#2077)
Browse files Browse the repository at this point in the history
* Start experiment to merge array and slice types

* Finish merger of slices and arrays

* Implement missing try_bind function

* Add missed case for NotConstant

* Fix some tests

* Fix poseidon test

* Fix evaluation of slice length

* Fix tests

* Fix 2070
  • Loading branch information
jfecher authored Aug 1, 2023
1 parent a484a31 commit ab61e3a
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 1 deletion.
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 @@ -996,6 +996,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

0 comments on commit ab61e3a

Please sign in to comment.