diff --git a/acvm-repo/acir/tests/test_program_serialization.rs b/acvm-repo/acir/tests/test_program_serialization.rs index d4c7a8782ab..dfcb1a8bb86 100644 --- a/acvm-repo/acir/tests/test_program_serialization.rs +++ b/acvm-repo/acir/tests/test_program_serialization.rs @@ -267,7 +267,7 @@ fn complex_brillig_foreign_call() { brillig::Opcode::Const { destination: MemoryAddress(0), value: FieldElement::from(32_usize), - bit_size: 64, + bit_size: 32, }, brillig::Opcode::CalldataCopy { destination_address: MemoryAddress(1), @@ -335,7 +335,6 @@ fn complex_brillig_foreign_call() { Program { functions: vec![circuit], unconstrained_functions: vec![brillig_bytecode] }; let bytes = Program::serialize_program(&program); - let expected_serialization: Vec = vec![ 31, 139, 8, 0, 0, 0, 0, 0, 0, 255, 213, 84, 75, 10, 131, 64, 12, 77, 102, 90, 43, 221, 245, 6, 133, 246, 0, 211, 158, 192, 187, 136, 59, 69, 151, 158, 94, 116, 48, 131, 241, 233, 70, @@ -343,9 +342,9 @@ fn complex_brillig_foreign_call() { 91, 154, 75, 208, 205, 4, 221, 62, 249, 113, 60, 95, 238, 40, 142, 230, 2, 28, 237, 1, 28, 73, 245, 255, 132, 253, 142, 217, 151, 168, 245, 179, 43, 243, 115, 163, 113, 190, 18, 57, 63, 4, 83, 44, 180, 55, 50, 180, 28, 188, 153, 224, 196, 122, 175, 111, 112, 68, 24, 65, - 50, 204, 162, 100, 249, 119, 137, 226, 193, 16, 251, 169, 50, 204, 235, 170, 41, 139, 214, - 130, 42, 82, 253, 168, 253, 23, 222, 25, 236, 58, 176, 237, 20, 234, 207, 107, 45, 78, 184, - 55, 27, 124, 191, 104, 42, 111, 40, 121, 15, 94, 163, 77, 128, 65, 5, 0, 0, + 116, 178, 40, 89, 254, 93, 162, 120, 48, 196, 126, 170, 12, 243, 186, 106, 202, 162, 181, + 160, 138, 84, 63, 106, 255, 133, 119, 6, 187, 14, 108, 59, 133, 250, 243, 90, 139, 19, 238, + 205, 6, 223, 47, 154, 202, 27, 74, 222, 3, 234, 73, 242, 82, 65, 5, 0, 0, ]; assert_eq!(bytes, expected_serialization) diff --git a/acvm-repo/acir_field/src/field_element.rs b/acvm-repo/acir_field/src/field_element.rs index a45e8c9946a..7810578ff73 100644 --- a/acvm-repo/acir_field/src/field_element.rs +++ b/acvm-repo/acir_field/src/field_element.rs @@ -319,6 +319,10 @@ impl AcirField for FieldElement { (self.num_bits() <= 64).then(|| self.to_u128() as u64) } + fn try_to_u32(&self) -> Option { + (self.num_bits() <= 32).then(|| self.to_u128() as u32) + } + /// Computes the inverse or returns zero if the inverse does not exist /// Before using this FieldElement, please ensure that this behavior is necessary fn inverse(&self) -> FieldElement { diff --git a/acvm-repo/acir_field/src/generic_ark.rs b/acvm-repo/acir_field/src/generic_ark.rs index 1e0215223ef..3d93de5a992 100644 --- a/acvm-repo/acir_field/src/generic_ark.rs +++ b/acvm-repo/acir_field/src/generic_ark.rs @@ -60,6 +60,8 @@ pub trait AcirField: fn try_to_u64(&self) -> Option; + fn try_to_u32(&self) -> Option; + /// Computes the inverse or returns zero if the inverse does not exist /// Before using this FieldElement, please ensure that this behavior is necessary fn inverse(&self) -> Self; diff --git a/acvm-repo/acvm_js/test/shared/complex_foreign_call.ts b/acvm-repo/acvm_js/test/shared/complex_foreign_call.ts index 0d6fab0e1f3..8ec2ddd1cb2 100644 --- a/acvm-repo/acvm_js/test/shared/complex_foreign_call.ts +++ b/acvm-repo/acvm_js/test/shared/complex_foreign_call.ts @@ -6,9 +6,9 @@ export const bytecode = Uint8Array.from([ 192, 187, 136, 59, 69, 151, 158, 94, 116, 48, 131, 241, 233, 70, 28, 65, 3, 195, 155, 79, 62, 47, 9, 25, 166, 81, 210, 97, 177, 236, 239, 130, 70, 208, 223, 91, 154, 75, 208, 205, 4, 221, 62, 249, 113, 60, 95, 238, 40, 142, 230, 2, 28, 237, 1, 28, 73, 245, 255, 132, 253, 142, 217, 151, 168, 245, 179, 43, 243, 115, 163, 113, 190, 18, 57, 63, 4, 83, 44, - 180, 55, 50, 180, 28, 188, 153, 224, 196, 122, 175, 111, 112, 68, 24, 65, 50, 204, 162, 100, 249, 119, 137, 226, 193, - 16, 251, 169, 50, 204, 235, 170, 41, 139, 214, 130, 42, 82, 253, 168, 253, 23, 222, 25, 236, 58, 176, 237, 20, 234, - 207, 107, 45, 78, 184, 55, 27, 124, 191, 104, 42, 111, 40, 121, 15, 94, 163, 77, 128, 65, 5, 0, 0, + 180, 55, 50, 180, 28, 188, 153, 224, 196, 122, 175, 111, 112, 68, 24, 65, 116, 178, 40, 89, 254, 93, 162, 120, 48, + 196, 126, 170, 12, 243, 186, 106, 202, 162, 181, 160, 138, 84, 63, 106, 255, 133, 119, 6, 187, 14, 108, 59, 133, 250, + 243, 90, 139, 19, 238, 205, 6, 223, 47, 154, 202, 27, 74, 222, 3, 234, 73, 242, 82, 65, 5, 0, 0, ]); export const initialWitnessMap: WitnessMap = new Map([ [1, '0x0000000000000000000000000000000000000000000000000000000000000001'], diff --git a/acvm-repo/brillig_vm/src/lib.rs b/acvm-repo/brillig_vm/src/lib.rs index 46550fa4994..da9a34f1044 100644 --- a/acvm-repo/brillig_vm/src/lib.rs +++ b/acvm-repo/brillig_vm/src/lib.rs @@ -645,6 +645,7 @@ impl<'a, F: AcirField, B: BlackBoxFunctionSolver> VM<'a, F, B> { mod tests { use acir::{AcirField, FieldElement}; use acvm_blackbox_solver::StubbedBlackBoxSolver; + const BRILLIG_MEMORY_ADDRESSING_BIT_SIZE: u32 = 32; use super::*; @@ -927,7 +928,7 @@ mod tests { #[test] fn cmp_binary_ops() { - let bit_size = 32; + let bit_size = BRILLIG_MEMORY_ADDRESSING_BIT_SIZE; let calldata: Vec = vec![(2u128).into(), (2u128).into(), (0u128).into(), (5u128).into(), (6u128).into()]; let calldata_size = calldata.len(); @@ -1029,7 +1030,7 @@ mod tests { /// i += 1; /// } fn brillig_write_memory(item_count: usize) -> Vec> { - let bit_size = 64; + let bit_size = BRILLIG_MEMORY_ADDRESSING_BIT_SIZE; let r_i = MemoryAddress::from(0); let r_len = MemoryAddress::from(1); let r_tmp = MemoryAddress::from(2); @@ -1083,11 +1084,11 @@ mod tests { let memory = brillig_write_memory(5); let expected = - vec![(0u64).into(), (1u64).into(), (2u64).into(), (3u64).into(), (4u64).into()]; + vec![(0u32).into(), (1u32).into(), (2u32).into(), (3u32).into(), (4u32).into()]; assert_eq!(memory, expected); let memory = brillig_write_memory(1024); - let expected: Vec<_> = (0..1024).map(|i: u64| i.into()).collect(); + let expected: Vec<_> = (0..1024).map(|i: u32| i.into()).collect(); assert_eq!(memory, expected); } @@ -1102,7 +1103,7 @@ mod tests { /// i += 1; /// } fn brillig_sum_memory(memory: Vec) -> FieldElement { - let bit_size = 64; + let bit_size = 32; let r_i = MemoryAddress::from(0); let r_len = MemoryAddress::from(1); let r_sum = MemoryAddress::from(2); @@ -1198,7 +1199,7 @@ mod tests { /// } /// Note we represent a 100% in-stack optimized form in brillig fn brillig_recursive_write_memory(size: usize) -> Vec> { - let bit_size = 64; + let bit_size = BRILLIG_MEMORY_ADDRESSING_BIT_SIZE; let r_i = MemoryAddress::from(0); let r_len = MemoryAddress::from(1); let r_tmp = MemoryAddress::from(2); @@ -1265,11 +1266,11 @@ mod tests { let memory = brillig_recursive_write_memory::(5); let expected = - vec![(0u64).into(), (1u64).into(), (2u64).into(), (3u64).into(), (4u64).into()]; + vec![(0u32).into(), (1u32).into(), (2u32).into(), (3u32).into(), (4u32).into()]; assert_eq!(memory, expected); let memory = brillig_recursive_write_memory::(1024); - let expected: Vec<_> = (0..1024).map(|i: u64| i.into()).collect(); + let expected: Vec<_> = (0..1024).map(|i: u32| i.into()).collect(); assert_eq!(memory, expected); } @@ -1301,7 +1302,11 @@ mod tests { let double_program = vec![ // Load input address with value 5 - Opcode::Const { destination: r_input, value: (5u128).into(), bit_size: 32 }, + Opcode::Const { + destination: r_input, + value: (5u128).into(), + bit_size: BRILLIG_MEMORY_ADDRESSING_BIT_SIZE, + }, // Call foreign function "double" with the input address Opcode::ForeignCall { function: "double".into(), @@ -1362,9 +1367,17 @@ mod tests { offset: 0, }, // input = 0 - Opcode::Const { destination: r_input, value: 2_usize.into(), bit_size: 64 }, + Opcode::Const { + destination: r_input, + value: 2_usize.into(), + bit_size: BRILLIG_MEMORY_ADDRESSING_BIT_SIZE, + }, // output = 0 - Opcode::Const { destination: r_output, value: 2_usize.into(), bit_size: 64 }, + Opcode::Const { + destination: r_output, + value: 2_usize.into(), + bit_size: BRILLIG_MEMORY_ADDRESSING_BIT_SIZE, + }, // *output = matrix_2x2_transpose(*input) Opcode::ForeignCall { function: "matrix_2x2_transpose".into(), @@ -1444,24 +1457,28 @@ mod tests { offset: 0, }, // input_pointer = 4 - Opcode::Const { destination: r_input_pointer, value: (4u128).into(), bit_size: 64 }, + Opcode::Const { + destination: r_input_pointer, + value: (4u128).into(), + bit_size: BRILLIG_MEMORY_ADDRESSING_BIT_SIZE, + }, // input_size = input_string.len() (constant here) Opcode::Const { destination: r_input_size, value: input_string.len().into(), - bit_size: 64, + bit_size: BRILLIG_MEMORY_ADDRESSING_BIT_SIZE, }, // output_pointer = 4 + input_size Opcode::Const { destination: r_output_pointer, value: (4 + input_string.len()).into(), - bit_size: 64, + bit_size: BRILLIG_MEMORY_ADDRESSING_BIT_SIZE, }, // output_size = input_size * 2 Opcode::Const { destination: r_output_size, value: (input_string.len() * 2).into(), - bit_size: 64, + bit_size: BRILLIG_MEMORY_ADDRESSING_BIT_SIZE, }, // output_pointer[0..output_size] = string_double(input_pointer[0...input_size]) Opcode::ForeignCall { @@ -1538,9 +1555,17 @@ mod tests { offset: 0, }, // input = 0 - Opcode::Const { destination: r_input, value: (2u128).into(), bit_size: 64 }, + Opcode::Const { + destination: r_input, + value: (2u128).into(), + bit_size: BRILLIG_MEMORY_ADDRESSING_BIT_SIZE, + }, // output = 0 - Opcode::Const { destination: r_output, value: (6u128).into(), bit_size: 64 }, + Opcode::Const { + destination: r_output, + value: (6u128).into(), + bit_size: BRILLIG_MEMORY_ADDRESSING_BIT_SIZE, + }, // *output = matrix_2x2_transpose(*input) Opcode::ForeignCall { function: "matrix_2x2_transpose".into(), @@ -1629,11 +1654,23 @@ mod tests { offset: 0, }, // input = 3 - Opcode::Const { destination: r_input_a, value: (3u128).into(), bit_size: 64 }, + Opcode::Const { + destination: r_input_a, + value: (3u128).into(), + bit_size: BRILLIG_MEMORY_ADDRESSING_BIT_SIZE, + }, // input = 7 - Opcode::Const { destination: r_input_b, value: (7u128).into(), bit_size: 64 }, + Opcode::Const { + destination: r_input_b, + value: (7u128).into(), + bit_size: BRILLIG_MEMORY_ADDRESSING_BIT_SIZE, + }, // output = 0 - Opcode::Const { destination: r_output, value: (0u128).into(), bit_size: 64 }, + Opcode::Const { + destination: r_output, + value: (0u128).into(), + bit_size: BRILLIG_MEMORY_ADDRESSING_BIT_SIZE, + }, // *output = matrix_2x2_transpose(*input) Opcode::ForeignCall { function: "matrix_2x2_transpose".into(), @@ -1718,28 +1755,28 @@ mod tests { let v2_ptr: usize = 0usize; let mut memory = v2.clone(); let v2_start = memory.len(); - memory.extend(vec![MemoryValue::from(v2_ptr), v2.len().into(), MemoryValue::from(1_usize)]); + memory.extend(vec![MemoryValue::from(v2_ptr), v2.len().into(), MemoryValue::from(1_u32)]); let a4_ptr = memory.len(); memory.extend(a4.clone()); let a4_start = memory.len(); - memory.extend(vec![MemoryValue::from(a4_ptr), MemoryValue::from(1_usize)]); + memory.extend(vec![MemoryValue::from(a4_ptr), MemoryValue::from(1_u32)]); let v6_ptr = memory.len(); memory.extend(v6.clone()); let v6_start = memory.len(); - memory.extend(vec![MemoryValue::from(v6_ptr), v6.len().into(), MemoryValue::from(1_usize)]); + memory.extend(vec![MemoryValue::from(v6_ptr), v6.len().into(), MemoryValue::from(1_u32)]); let a9_ptr = memory.len(); memory.extend(a9.clone()); let a9_start = memory.len(); - memory.extend(vec![MemoryValue::from(a9_ptr), MemoryValue::from(1_usize)]); + memory.extend(vec![MemoryValue::from(a9_ptr), MemoryValue::from(1_u32)]); // finally we add the contents of the outer array let outer_ptr = memory.len(); let outer_array = vec![ MemoryValue::new_field(FieldElement::from(1u128)), - MemoryValue::from(v2.len()), + MemoryValue::from(v2.len() as u32), MemoryValue::from(v2_start), MemoryValue::from(a4_start), MemoryValue::new_field(FieldElement::from(5u128)), - MemoryValue::from(v6.len()), + MemoryValue::from(v6.len() as u32), MemoryValue::from(v6_start), MemoryValue::from(a9_start), ]; @@ -1770,7 +1807,7 @@ mod tests { })) .chain(vec![ // input = 0 - Opcode::Const { destination: r_input, value: (outer_ptr).into(), bit_size: 64 }, + Opcode::Const { destination: r_input, value: (outer_ptr).into(), bit_size: 32 }, // some_function(input) Opcode::ForeignCall { function: "flat_sum".into(), diff --git a/acvm-repo/brillig_vm/src/memory.rs b/acvm-repo/brillig_vm/src/memory.rs index 1435e514eac..95e28f7d863 100644 --- a/acvm-repo/brillig_vm/src/memory.rs +++ b/acvm-repo/brillig_vm/src/memory.rs @@ -2,7 +2,7 @@ use acir::{brillig::MemoryAddress, AcirField}; use num_bigint::BigUint; use num_traits::{One, Zero}; -pub const MEMORY_ADDRESSING_BIT_SIZE: u32 = 64; +pub const MEMORY_ADDRESSING_BIT_SIZE: u32 = 32; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub enum MemoryValue { @@ -167,18 +167,18 @@ impl From for MemoryValue { } } -impl From for MemoryValue { - fn from(value: u64) -> Self { - MemoryValue::new_integer(value.into(), 64) - } -} - impl From for MemoryValue { fn from(value: u32) -> Self { MemoryValue::new_integer(value.into(), 32) } } +impl From for MemoryValue { + fn from(value: u64) -> Self { + MemoryValue::new_integer(value.into(), 64) + } +} + impl From for MemoryValue { fn from(value: u8) -> Self { MemoryValue::new_integer(value.into(), 8) diff --git a/aztec_macros/src/transforms/events.rs b/aztec_macros/src/transforms/events.rs index 9c8cd826360..69cb6ddafc3 100644 --- a/aztec_macros/src/transforms/events.rs +++ b/aztec_macros/src/transforms/events.rs @@ -158,7 +158,7 @@ fn transform_event( // Also update the type! It might have a different length now than the placeholder. interner.push_expr_type( selector_literal_id, - Type::String(Box::new(Type::Constant(signature.len() as u64))), + Type::String(Box::new(Type::Constant(signature.len() as u32))), ); Ok(()) } diff --git a/aztec_macros/src/transforms/storage.rs b/aztec_macros/src/transforms/storage.rs index bd9fff3c3d3..a1c21c7efcf 100644 --- a/aztec_macros/src/transforms/storage.rs +++ b/aztec_macros/src/transforms/storage.rs @@ -257,7 +257,7 @@ pub fn get_storage_serialized_length( traits: &[TraitId], typ: &Type, interner: &NodeInterner, -) -> Result { +) -> Result { let (struct_name, maybe_stored_in_state) = match typ { Type::Struct(struct_type, generics) => { Ok((struct_type.borrow().name.0.contents.clone(), generics.first())) @@ -394,7 +394,7 @@ pub fn assign_storage_slots( )), }?; - let mut storage_slot: u64 = 1; + let mut storage_slot: u32 = 1; for (index, (_, expr_id)) in storage_constructor_expression.fields.iter().enumerate() { let fields = storage_struct .borrow() diff --git a/aztec_macros/src/utils/hir_utils.rs b/aztec_macros/src/utils/hir_utils.rs index 7ce280c4c7f..d4b55e1311f 100644 --- a/aztec_macros/src/utils/hir_utils.rs +++ b/aztec_macros/src/utils/hir_utils.rs @@ -320,7 +320,7 @@ pub fn get_serialized_length( trait_name: &str, typ: &Type, interner: &NodeInterner, -) -> Result { +) -> Result { let serialized_trait_impl_kind = traits .iter() .find_map(|&trait_id| { diff --git a/compiler/noirc_evaluator/src/brillig/brillig_ir.rs b/compiler/noirc_evaluator/src/brillig/brillig_ir.rs index 9341db2ead7..ebccf7a0bf1 100644 --- a/compiler/noirc_evaluator/src/brillig/brillig_ir.rs +++ b/compiler/noirc_evaluator/src/brillig/brillig_ir.rs @@ -34,9 +34,9 @@ use acvm::{ use debug_show::DebugShow; /// The Brillig VM does not apply a limit to the memory address space, -/// As a convention, we take use 64 bits. This means that we assume that -/// memory has 2^64 memory slots. -pub(crate) const BRILLIG_MEMORY_ADDRESSING_BIT_SIZE: u32 = 64; +/// As a convention, we take use 32 bits. This means that we assume that +/// memory has 2^32 memory slots. +pub(crate) const BRILLIG_MEMORY_ADDRESSING_BIT_SIZE: u32 = 32; // Registers reserved in runtime for special purposes. pub(crate) enum ReservedRegisters { diff --git a/compiler/noirc_evaluator/src/brillig/brillig_ir/codegen_control_flow.rs b/compiler/noirc_evaluator/src/brillig/brillig_ir/codegen_control_flow.rs index d9109646338..fee3a450119 100644 --- a/compiler/noirc_evaluator/src/brillig/brillig_ir/codegen_control_flow.rs +++ b/compiler/noirc_evaluator/src/brillig/brillig_ir/codegen_control_flow.rs @@ -162,8 +162,7 @@ impl BrilligContext { let current_revert_data_pointer = ctx.allocate_register(); ctx.mov_instruction(current_revert_data_pointer, revert_data.pointer); - let revert_data_id = - ctx.make_usize_constant_instruction((error_selector as u128).into()); + let revert_data_id = ctx.make_constant_instruction((error_selector as u128).into(), 64); ctx.store_instruction(current_revert_data_pointer, revert_data_id.address); ctx.codegen_usize_op_in_place(current_revert_data_pointer, BrilligBinaryOp::Add, 1); diff --git a/compiler/noirc_evaluator/src/ssa/ir/instruction.rs b/compiler/noirc_evaluator/src/ssa/ir/instruction.rs index 7517b54aac3..e21deb9ef79 100644 --- a/compiler/noirc_evaluator/src/ssa/ir/instruction.rs +++ b/compiler/noirc_evaluator/src/ssa/ir/instruction.rs @@ -580,7 +580,7 @@ impl Instruction { let index = dfg.get_numeric_constant(*index); if let (Some((array, _)), Some(index)) = (array, index) { let index = - index.try_to_u64().expect("Expected array index to fit in u64") as usize; + index.try_to_u32().expect("Expected array index to fit in u32") as usize; if index < array.len() { return SimplifiedTo(array[index]); } @@ -592,7 +592,7 @@ impl Instruction { let index = dfg.get_numeric_constant(*index); if let (Some((array, element_type)), Some(index)) = (array, index) { let index = - index.try_to_u64().expect("Expected array index to fit in u64") as usize; + index.try_to_u32().expect("Expected array index to fit in u32") as usize; if index < array.len() { let new_array = dfg.make_array(array.update(index, *value), element_type); diff --git a/compiler/noirc_evaluator/src/ssa/ir/types.rs b/compiler/noirc_evaluator/src/ssa/ir/types.rs index ded385d2d3c..76b5bc43384 100644 --- a/compiler/noirc_evaluator/src/ssa/ir/types.rs +++ b/compiler/noirc_evaluator/src/ssa/ir/types.rs @@ -3,6 +3,8 @@ use std::rc::Rc; use acvm::{acir::AcirField, FieldElement}; use iter_extended::vecmap; +use crate::ssa::ssa_gen::SSA_WORD_SIZE; + /// A numeric type in the Intermediate representation /// Note: we class NativeField as a numeric type /// though we also apply limitations to it, such as not @@ -92,7 +94,7 @@ impl Type { /// Creates the type of an array's length. pub(crate) fn length_type() -> Type { - Type::unsigned(64) + Type::unsigned(SSA_WORD_SIZE) } /// Returns the bit size of the provided numeric type. diff --git a/compiler/noirc_evaluator/src/ssa/ssa_gen/context.rs b/compiler/noirc_evaluator/src/ssa/ssa_gen/context.rs index df14ee99bd3..a16e0f93c61 100644 --- a/compiler/noirc_evaluator/src/ssa/ssa_gen/context.rs +++ b/compiler/noirc_evaluator/src/ssa/ssa_gen/context.rs @@ -20,6 +20,7 @@ use crate::ssa::ir::types::{NumericType, Type}; use crate::ssa::ir::value::ValueId; use super::value::{Tree, Value, Values}; +use super::SSA_WORD_SIZE; use fxhash::FxHashMap as HashMap; /// The FunctionContext is the main context object for translating a @@ -587,9 +588,9 @@ impl<'a> FunctionContext<'a> { address } - /// Array indexes are u64s. This function casts values used as indexes to u64. + /// Array indexes are u32. This function casts values used as indexes to u32. pub(super) fn make_array_index(&mut self, index: ValueId) -> ValueId { - self.builder.insert_cast(index, Type::unsigned(64)) + self.builder.insert_cast(index, Type::unsigned(SSA_WORD_SIZE)) } /// Define a local variable to be some Values that can later be retrieved @@ -837,12 +838,12 @@ impl<'a> FunctionContext<'a> { ) -> ValueId { let index = self.make_array_index(index); let element_size = - self.builder.numeric_constant(self.element_size(array), Type::unsigned(64)); + self.builder.numeric_constant(self.element_size(array), Type::unsigned(SSA_WORD_SIZE)); // The actual base index is the user's index * the array element type's size let mut index = self.builder.set_location(location).insert_binary(index, BinaryOp::Mul, element_size); - let one = self.builder.numeric_constant(FieldElement::one(), Type::unsigned(64)); + let one = self.builder.numeric_constant(FieldElement::one(), Type::unsigned(SSA_WORD_SIZE)); new_value.for_each(|value| { let value = value.eval(self); diff --git a/compiler/noirc_evaluator/src/ssa/ssa_gen/mod.rs b/compiler/noirc_evaluator/src/ssa/ssa_gen/mod.rs index 698a2b0471a..254e907fb0e 100644 --- a/compiler/noirc_evaluator/src/ssa/ssa_gen/mod.rs +++ b/compiler/noirc_evaluator/src/ssa/ssa_gen/mod.rs @@ -32,6 +32,8 @@ use super::{ }, }; +pub(crate) const SSA_WORD_SIZE: u32 = 32; + /// Generates SSA for the given monomorphized program. /// /// This function will generate the SSA but does not perform any optimizations on it. @@ -244,7 +246,7 @@ impl<'a> FunctionContext<'a> { let elements = vecmap(string.as_bytes(), |byte| { self.builder.numeric_constant(*byte as u128, Type::unsigned(8)).into() }); - let typ = Self::convert_non_tuple_type(&ast::Type::String(elements.len() as u64)); + let typ = Self::convert_non_tuple_type(&ast::Type::String(elements.len() as u32)); self.codegen_array(elements, typ) } @@ -400,7 +402,8 @@ impl<'a> FunctionContext<'a> { // base_index = index * type_size let index = self.make_array_index(index); let type_size = Self::convert_type(element_type).size_of_type(); - let type_size = self.builder.numeric_constant(type_size as u128, Type::unsigned(64)); + let type_size = + self.builder.numeric_constant(type_size as u128, Type::unsigned(SSA_WORD_SIZE)); let base_index = self.builder.set_location(location).insert_binary(index, BinaryOp::Mul, type_size); diff --git a/compiler/noirc_frontend/src/ast/mod.rs b/compiler/noirc_frontend/src/ast/mod.rs index a9d9f232b64..39b23228967 100644 --- a/compiler/noirc_frontend/src/ast/mod.rs +++ b/compiler/noirc_frontend/src/ast/mod.rs @@ -143,7 +143,7 @@ pub(crate) type UnaryRhsMemberAccess = #[derive(Debug, PartialEq, Eq, Clone, Hash)] pub enum UnresolvedTypeExpression { Variable(Path), - Constant(u64, Span), + Constant(u32, Span), BinaryOperation( Box, BinaryTypeOperator, @@ -307,7 +307,7 @@ impl UnresolvedTypeExpression { match expr.kind { ExpressionKind::Literal(Literal::Integer(int, sign)) => { assert!(!sign, "Negative literal is not allowed here"); - match int.try_to_u64() { + match int.try_to_u32() { Some(int) => Ok(UnresolvedTypeExpression::Constant(int, expr.span)), None => Err(expr), } diff --git a/compiler/noirc_frontend/src/elaborator/expressions.rs b/compiler/noirc_frontend/src/elaborator/expressions.rs index abd8781a213..5eee7ee6c7c 100644 --- a/compiler/noirc_frontend/src/elaborator/expressions.rs +++ b/compiler/noirc_frontend/src/elaborator/expressions.rs @@ -114,7 +114,7 @@ impl<'context> Elaborator<'context> { (Lit(int), self.polymorphic_integer_or_field()) } Literal::Str(str) | Literal::RawStr(str, _) => { - let len = Type::Constant(str.len() as u64); + let len = Type::Constant(str.len() as u32); (Lit(HirLiteral::Str(str)), Type::String(Box::new(len))) } Literal::FmtStr(str) => self.elaborate_fmt_string(str, span), @@ -156,7 +156,7 @@ impl<'context> Elaborator<'context> { elem_id }); - let length = Type::Constant(elements.len() as u64); + let length = Type::Constant(elements.len() as u32); (HirArrayLiteral::Standard(elements), first_elem_type, length) } ArrayLiteral::Repeated { repeated_element, length } => { @@ -220,7 +220,7 @@ impl<'context> Elaborator<'context> { } } - let len = Type::Constant(str.len() as u64); + let len = Type::Constant(str.len() as u32); let typ = Type::FmtString(Box::new(len), Box::new(Type::Tuple(capture_types))); (HirExpression::Literal(HirLiteral::FmtStr(str, fmt_str_idents)), typ) } diff --git a/compiler/noirc_frontend/src/elaborator/types.rs b/compiler/noirc_frontend/src/elaborator/types.rs index a106f6687df..5e3ace423e5 100644 --- a/compiler/noirc_frontend/src/elaborator/types.rs +++ b/compiler/noirc_frontend/src/elaborator/types.rs @@ -415,7 +415,7 @@ impl<'context> Elaborator<'context> { .or_else(|| self.resolve_trait_method_by_named_generic(path)) } - fn eval_global_as_array_length(&mut self, global: GlobalId, path: &Path) -> u64 { + fn eval_global_as_array_length(&mut self, global: GlobalId, path: &Path) -> u32 { let Some(stmt) = self.interner.get_global_let_statement(global) else { let path = path.clone(); self.push_err(ResolverError::NoSuchNumericTypeVariable { path }); diff --git a/compiler/noirc_frontend/src/hir/comptime/errors.rs b/compiler/noirc_frontend/src/hir/comptime/errors.rs index 7b38f2fd32e..df4bc941f66 100644 --- a/compiler/noirc_frontend/src/hir/comptime/errors.rs +++ b/compiler/noirc_frontend/src/hir/comptime/errors.rs @@ -171,7 +171,7 @@ impl<'a> From<&'a InterpreterError> for CustomDiagnostic { let typ = value.get_type(); let msg = format!("Non-integer type `{typ}` used in for loop"); let secondary = if matches!(typ.as_ref(), &Type::FieldElement) { - "`field` is not an integer type, try `u64` instead".to_string() + "`field` is not an integer type, try `u32` instead".to_string() } else { String::new() }; diff --git a/compiler/noirc_frontend/src/hir/comptime/interpreter.rs b/compiler/noirc_frontend/src/hir/comptime/interpreter.rs index 314ea26e52c..8809e63d00a 100644 --- a/compiler/noirc_frontend/src/hir/comptime/interpreter.rs +++ b/compiler/noirc_frontend/src/hir/comptime/interpreter.rs @@ -332,7 +332,7 @@ impl<'a> Interpreter<'a> { DefinitionKind::GenericType(type_variable) => { let value = match &*type_variable.borrow() { TypeBinding::Unbound(_) => None, - TypeBinding::Bound(binding) => binding.evaluate_to_u64(), + TypeBinding::Bound(binding) => binding.evaluate_to_u32(), }; if let Some(value) = value { @@ -395,9 +395,11 @@ impl<'a> Interpreter<'a> { } (Signedness::Unsigned, IntegerBitSize::ThirtyTwo) => { let value: u32 = - value.try_to_u64().and_then(|value| value.try_into().ok()).ok_or( - InterpreterError::IntegerOutOfRangeForType { value, typ, location }, - )?; + value.try_to_u32().ok_or(InterpreterError::IntegerOutOfRangeForType { + value, + typ, + location, + })?; let value = if is_negative { 0u32.wrapping_sub(value) } else { value }; Ok(Value::U32(value)) } @@ -485,7 +487,7 @@ impl<'a> Interpreter<'a> { HirArrayLiteral::Repeated { repeated_element, length } => { let element = self.evaluate(repeated_element)?; - if let Some(length) = length.evaluate_to_u64() { + if let Some(length) = length.evaluate_to_u32() { let elements = (0..length).map(|_| element.clone()).collect(); Ok(Value::Array(elements, typ)) } else { diff --git a/compiler/noirc_frontend/src/hir/comptime/value.rs b/compiler/noirc_frontend/src/hir/comptime/value.rs index 6cf0a1d9011..43d461ad043 100644 --- a/compiler/noirc_frontend/src/hir/comptime/value.rs +++ b/compiler/noirc_frontend/src/hir/comptime/value.rs @@ -59,7 +59,7 @@ impl Value { Value::U32(_) => Type::Integer(Signedness::Unsigned, IntegerBitSize::ThirtyTwo), Value::U64(_) => Type::Integer(Signedness::Unsigned, IntegerBitSize::SixtyFour), Value::String(value) => { - let length = Type::Constant(value.len() as u64); + let length = Type::Constant(value.len() as u32); Type::String(Box::new(length)) } Value::Function(_, typ) => return Cow::Borrowed(typ), diff --git a/compiler/noirc_frontend/src/hir/resolution/resolver.rs b/compiler/noirc_frontend/src/hir/resolution/resolver.rs index 8f15d7688de..18e1a5a22ca 100644 --- a/compiler/noirc_frontend/src/hir/resolution/resolver.rs +++ b/compiler/noirc_frontend/src/hir/resolution/resolver.rs @@ -1987,7 +1987,7 @@ impl<'a> Resolver<'a> { self.interner.push_expr(hir_block) } - fn eval_global_as_array_length(&mut self, global: GlobalId, path: &Path) -> u64 { + fn eval_global_as_array_length(&mut self, global: GlobalId, path: &Path) -> u32 { let Some(stmt) = self.interner.get_global_let_statement(global) else { let path = path.clone(); self.push_err(ResolverError::NoSuchNumericTypeVariable { path }); diff --git a/compiler/noirc_frontend/src/hir/type_check/expr.rs b/compiler/noirc_frontend/src/hir/type_check/expr.rs index 6504ead178f..50af9dbf34e 100644 --- a/compiler/noirc_frontend/src/hir/type_check/expr.rs +++ b/compiler/noirc_frontend/src/hir/type_check/expr.rs @@ -54,7 +54,7 @@ impl<'interner> TypeChecker<'interner> { fn check_hir_array_literal( &mut self, hir_array_literal: HirArrayLiteral, - ) -> (Result>, Box) { + ) -> (Result>, Box) { match hir_array_literal { HirArrayLiteral::Standard(arr) => { let elem_types = vecmap(&arr, |arg| self.check_expression(arg)); @@ -81,7 +81,7 @@ impl<'interner> TypeChecker<'interner> { }); } - (Ok(arr.len() as u64), Box::new(first_elem_type.clone())) + (Ok(arr.len() as u32), Box::new(first_elem_type.clone())) } HirArrayLiteral::Repeated { repeated_element, length } => { let elem_type = self.check_expression(&repeated_element); @@ -131,11 +131,11 @@ impl<'interner> TypeChecker<'interner> { HirLiteral::Bool(_) => Type::Bool, HirLiteral::Integer(_, _) => self.polymorphic_integer_or_field(), HirLiteral::Str(string) => { - let len = Type::Constant(string.len() as u64); + let len = Type::Constant(string.len() as u32); Type::String(Box::new(len)) } HirLiteral::FmtStr(string, idents) => { - let len = Type::Constant(string.len() as u64); + let len = Type::Constant(string.len() as u32); let types = vecmap(&idents, |elem| self.check_expression(elem)); Type::FmtString(Box::new(len), Box::new(Type::Tuple(types))) } diff --git a/compiler/noirc_frontend/src/hir_def/types.rs b/compiler/noirc_frontend/src/hir_def/types.rs index cf9aafbb308..ff8b11f3916 100644 --- a/compiler/noirc_frontend/src/hir_def/types.rs +++ b/compiler/noirc_frontend/src/hir_def/types.rs @@ -102,7 +102,7 @@ pub enum Type { /// A type-level integer. Included to let an Array's size type variable /// bind to an integer without special checks to bind it to a non-type. - Constant(u64), + Constant(u32), /// The type of quoted code in macros. This is always a comptime-only type Code, @@ -121,10 +121,10 @@ impl Type { Type::FieldElement | Type::Integer { .. } | Type::Bool => 1, Type::Array(size, typ) => { let length = size - .evaluate_to_u64() + .evaluate_to_u32() .expect("Cannot have variable sized arrays as a parameter to main"); let typ = typ.as_ref(); - (length as u32) * typ.field_count() + length * typ.field_count() } Type::Struct(def, args) => { let struct_type = def.borrow(); @@ -135,12 +135,9 @@ impl Type { Type::Tuple(fields) => { fields.iter().fold(0, |acc, field_typ| acc + field_typ.field_count()) } - Type::String(size) => { - let size = size - .evaluate_to_u64() - .expect("Cannot have variable sized strings as a parameter to main"); - size as u32 - } + Type::String(size) => size + .evaluate_to_u32() + .expect("Cannot have variable sized strings as a parameter to main"), Type::FmtString(_, _) | Type::Unit | Type::TypeVariable(_, _) @@ -457,7 +454,7 @@ pub enum TypeVariableKind { /// A potentially constant array size. This will only bind to itself or /// Type::Constant(n) with a matching size. This defaults to Type::Constant(n) if still unbound /// during monomorphization. - Constant(u64), + Constant(u32), } /// A TypeVariable is a mutable reference that is either @@ -551,7 +548,7 @@ impl Type { } pub fn default_int_type() -> Type { - Type::Integer(Signedness::Unsigned, IntegerBitSize::SixtyFour) + Type::Integer(Signedness::Unsigned, IntegerBitSize::ThirtyTwo) } pub fn type_variable(id: TypeVariableId) -> Type { @@ -561,7 +558,7 @@ impl Type { /// Returns a TypeVariable(_, TypeVariableKind::Constant(length)) to bind to /// a constant integer for e.g. an array length. - pub fn constant_variable(length: u64, interner: &mut NodeInterner) -> Type { + pub fn constant_variable(length: u32, interner: &mut NodeInterner) -> Type { let id = interner.next_type_variable_id(); let kind = TypeVariableKind::Constant(length); let var = TypeVariable::unbound(id); @@ -962,7 +959,7 @@ impl Type { fn try_bind_to_maybe_constant( &self, var: &TypeVariable, - target_length: u64, + target_length: u32, bindings: &mut TypeBindings, ) -> Result<(), UnificationError> { let target_id = match &*var.borrow() { @@ -1383,17 +1380,17 @@ impl Type { } /// If this type is a Type::Constant (used in array lengths), or is bound - /// to a Type::Constant, return the constant as a u64. - pub fn evaluate_to_u64(&self) -> Option { + /// to a Type::Constant, return the constant as a u32. + pub fn evaluate_to_u32(&self) -> Option { if let Some(binding) = self.get_inner_type_variable() { if let TypeBinding::Bound(binding) = &*binding.borrow() { - return binding.evaluate_to_u64(); + return binding.evaluate_to_u32(); } } match self { Type::TypeVariable(_, TypeVariableKind::Constant(size)) => Some(*size), - Type::Array(len, _elem) => len.evaluate_to_u64(), + Type::Array(len, _elem) => len.evaluate_to_u32(), Type::Constant(x) => Some(*x), _ => None, } @@ -1787,7 +1784,7 @@ fn convert_array_expression_to_slice( impl BinaryTypeOperator { /// Return the actual rust numeric function associated with this operator - pub fn function(self) -> fn(u64, u64) -> u64 { + pub fn function(self) -> fn(u32, u32) -> u32 { match self { BinaryTypeOperator::Addition => |a, b| a.wrapping_add(b), BinaryTypeOperator::Subtraction => |a, b| a.wrapping_sub(b), @@ -1824,7 +1821,7 @@ impl From<&Type> for PrintableType { match value { Type::FieldElement => PrintableType::Field, Type::Array(size, typ) => { - let length = size.evaluate_to_u64().expect("Cannot print variable sized arrays"); + let length = size.evaluate_to_u32().expect("Cannot print variable sized arrays"); let typ = typ.as_ref(); PrintableType::Array { length, typ: Box::new(typ.into()) } } @@ -1850,7 +1847,7 @@ impl From<&Type> for PrintableType { } Type::Bool => PrintableType::Boolean, Type::String(size) => { - let size = size.evaluate_to_u64().expect("Cannot print variable sized strings"); + let size = size.evaluate_to_u32().expect("Cannot print variable sized strings"); PrintableType::String { length: size } } Type::FmtString(_, _) => unreachable!("format strings cannot be printed"), diff --git a/compiler/noirc_frontend/src/monomorphization/ast.rs b/compiler/noirc_frontend/src/monomorphization/ast.rs index 15c27ee344c..99ac08ddfc2 100644 --- a/compiler/noirc_frontend/src/monomorphization/ast.rs +++ b/compiler/noirc_frontend/src/monomorphization/ast.rs @@ -278,11 +278,11 @@ pub struct Function { #[derive(Debug, PartialEq, Eq, Clone, Hash)] pub enum Type { Field, - Array(/*len:*/ u64, Box), // Array(4, Field) = [Field; 4] + Array(/*len:*/ u32, Box), // Array(4, Field) = [Field; 4] Integer(Signedness, /*bits:*/ IntegerBitSize), // u32 = Integer(unsigned, ThirtyTwo) Bool, - String(/*len:*/ u64), // String(4) = str[4] - FmtString(/*len:*/ u64, Box), + String(/*len:*/ u32), // String(4) = str[4] + FmtString(/*len:*/ u32, Box), Unit, Tuple(Vec), Slice(Box), diff --git a/compiler/noirc_frontend/src/monomorphization/mod.rs b/compiler/noirc_frontend/src/monomorphization/mod.rs index 2e74eb87e60..b4567bf9af7 100644 --- a/compiler/noirc_frontend/src/monomorphization/mod.rs +++ b/compiler/noirc_frontend/src/monomorphization/mod.rs @@ -573,7 +573,7 @@ impl<'interner> Monomorphizer<'interner> { let location = self.interner.expr_location(&array); let typ = Self::convert_type(&self.interner.id_type(array), location)?; - let length = length.evaluate_to_u64().ok_or_else(|| { + let length = length.evaluate_to_u32().ok_or_else(|| { let location = self.interner.expr_location(&array); MonomorphizationError::UnknownArrayLength { location } })?; @@ -896,7 +896,7 @@ impl<'interner> Monomorphizer<'interner> { TypeBinding::Unbound(_) => { unreachable!("Unbound type variable used in expression") } - TypeBinding::Bound(binding) => binding.evaluate_to_u64().unwrap_or_else(|| { + TypeBinding::Bound(binding) => binding.evaluate_to_u32().unwrap_or_else(|| { panic!("Non-numeric type variable used in expression expecting a value") }), }; @@ -917,16 +917,16 @@ impl<'interner> Monomorphizer<'interner> { HirType::FieldElement => ast::Type::Field, HirType::Integer(sign, bits) => ast::Type::Integer(*sign, *bits), HirType::Bool => ast::Type::Bool, - HirType::String(size) => ast::Type::String(size.evaluate_to_u64().unwrap_or(0)), + HirType::String(size) => ast::Type::String(size.evaluate_to_u32().unwrap_or(0)), HirType::FmtString(size, fields) => { - let size = size.evaluate_to_u64().unwrap_or(0); + let size = size.evaluate_to_u32().unwrap_or(0); let fields = Box::new(Self::convert_type(fields.as_ref(), location)?); ast::Type::FmtString(size, fields) } HirType::Unit => ast::Type::Unit, HirType::Array(length, element) => { let element = Box::new(Self::convert_type(element.as_ref(), location)?); - let length = match length.evaluate_to_u64() { + let length = match length.evaluate_to_u32() { Some(length) => length, None => return Err(MonomorphizationError::TypeAnnotationsNeeded { location }), }; @@ -1304,7 +1304,7 @@ impl<'interner> Monomorphizer<'interner> { Expression::Literal(Literal::Integer((byte as u128).into(), int_type.clone(), location)) }); - let typ = Type::Array(bytes_as_expr.len() as u64, Box::new(int_type)); + let typ = Type::Array(bytes_as_expr.len() as u32, Box::new(int_type)); let arr_literal = ArrayLiteral { typ, contents: bytes_as_expr }; Expression::Literal(Literal::Array(arr_literal)) diff --git a/compiler/noirc_printable_type/src/lib.rs b/compiler/noirc_printable_type/src/lib.rs index a12ecf01b56..d9c9c7f9731 100644 --- a/compiler/noirc_printable_type/src/lib.rs +++ b/compiler/noirc_printable_type/src/lib.rs @@ -11,7 +11,7 @@ use thiserror::Error; pub enum PrintableType { Field, Array { - length: u64, + length: u32, #[serde(rename = "type")] typ: Box, }, @@ -34,7 +34,7 @@ pub enum PrintableType { fields: Vec<(String, PrintableType)>, }, String { - length: u64, + length: u32, }, Function { arguments: Vec, diff --git a/noir_stdlib/src/array.nr b/noir_stdlib/src/array.nr index 8a8a1fad01c..6fba197dd05 100644 --- a/noir_stdlib/src/array.nr +++ b/noir_stdlib/src/array.nr @@ -4,7 +4,7 @@ use crate::cmp::Ord; // by the methods in the `slice` module impl [T; N] { #[builtin(array_len)] - pub fn len(self) -> u64 {} + pub fn len(self) -> u32 {} pub fn sort(self) -> Self where T: Ord { self.sort_via(|a: T, b: T| a <= b) @@ -31,7 +31,7 @@ impl [T; N] { } /// Returns the index of the elements in the array that would sort it, using the provided custom sorting function. - unconstrained fn get_sorting_index(self, ordering: fn[Env](T, T) -> bool) -> [u64; N] { + unconstrained fn get_sorting_index(self, ordering: fn[Env](T, T) -> bool) -> [u32; N] { let mut result = [0; N]; let mut a = self; for i in 0..N { @@ -110,7 +110,7 @@ impl [T; N] { // helper function used to look up the position of a value in an array of Field // Note that function returns 0 if the value is not found -unconstrained fn find_index(a: [u64; N], find: u64) -> u64 { +unconstrained fn find_index(a: [u32; N], find: u32) -> u32 { let mut result = 0; for i in 0..a.len() { if a[i] == find { diff --git a/noir_stdlib/src/collections/bounded_vec.nr b/noir_stdlib/src/collections/bounded_vec.nr index 65f3716dd34..aae96e5943d 100644 --- a/noir_stdlib/src/collections/bounded_vec.nr +++ b/noir_stdlib/src/collections/bounded_vec.nr @@ -2,7 +2,7 @@ use crate::{cmp::Eq, convert::From}; struct BoundedVec { storage: [T; MaxLen], - len: u64, + len: u32, } impl BoundedVec { @@ -11,12 +11,12 @@ impl BoundedVec { BoundedVec { storage: [zeroed; MaxLen], len: 0 } } - pub fn get(mut self: Self, index: u64) -> T { + pub fn get(mut self: Self, index: u32) -> T { assert(index < self.len); self.storage[index] } - pub fn get_unchecked(mut self: Self, index: u64) -> T { + pub fn get_unchecked(mut self: Self, index: u32) -> T { self.storage[index] } @@ -27,11 +27,11 @@ impl BoundedVec { self.len += 1; } - pub fn len(self) -> u64 { + pub fn len(self) -> u32 { self.len } - pub fn max_len(_self: BoundedVec) -> u64 { + pub fn max_len(_self: BoundedVec) -> u32 { MaxLen } diff --git a/noir_stdlib/src/collections/map.nr b/noir_stdlib/src/collections/map.nr index 5f8cc6dab62..84e94166869 100644 --- a/noir_stdlib/src/collections/map.nr +++ b/noir_stdlib/src/collections/map.nr @@ -19,7 +19,7 @@ struct HashMap { _table: [Slot; N], // Amount of valid elements in the map. - _len: u64, + _len: u32, _build_hasher: B } @@ -262,14 +262,14 @@ impl HashMap { // Amount of active key-value entries. // docs:start:len - pub fn len(self) -> u64 { + pub fn len(self) -> u32 { // docs:end:len self._len } // Get the compile-time map capacity. // docs:start:capacity - pub fn capacity(_self: Self) -> u64 { + pub fn capacity(_self: Self) -> u32 { // docs:end:capacity N } @@ -292,7 +292,7 @@ impl HashMap { for attempt in 0..N { if !should_break { - let index = self.quadratic_probe(hash, attempt as u64); + let index = self.quadratic_probe(hash, attempt as u32); let slot = self._table[index]; // Not marked as deleted and has key-value. @@ -328,7 +328,7 @@ impl HashMap { for attempt in 0..N { if !should_break { - let index = self.quadratic_probe(hash, attempt as u64); + let index = self.quadratic_probe(hash, attempt as u32); let mut slot = self._table[index]; let mut insert = false; @@ -368,7 +368,7 @@ impl HashMap { for attempt in 0..N { if !should_break { - let index = self.quadratic_probe(hash, attempt as u64); + let index = self.quadratic_probe(hash, attempt as u32); let mut slot = self._table[index]; // Not marked as deleted and has key-value. @@ -389,21 +389,21 @@ impl HashMap { fn hash( self, key: K - ) -> u64 + ) -> u32 where K: Hash, B: BuildHasher, H: Hasher { let mut hasher = self._build_hasher.build_hasher(); key.hash(&mut hasher); - hasher.finish() as u64 + hasher.finish() as u32 } // Probing scheme: quadratic function. // We use 0.5 constant near variadic attempt and attempt^2 monomials. // This ensures good uniformity of distribution for table sizes // equal to prime numbers or powers of two. - fn quadratic_probe(_self: Self, hash: u64, attempt: u64) -> u64 { + fn quadratic_probe(_self: Self, hash: u32, attempt: u32) -> u32 { (hash + (attempt + attempt * attempt) / 2) % N } diff --git a/noir_stdlib/src/collections/vec.nr b/noir_stdlib/src/collections/vec.nr index 56354438c89..18aaa8b9b3b 100644 --- a/noir_stdlib/src/collections/vec.nr +++ b/noir_stdlib/src/collections/vec.nr @@ -17,7 +17,7 @@ impl Vec { /// Get an element from the vector at the given index. /// Panics if the given index /// points beyond the end of the vector. - pub fn get(self, index: u64) -> T { + pub fn get(self, index: u32) -> T { self.slice[index] } @@ -40,20 +40,20 @@ impl Vec { /// Insert an element at a specified index, shifting all elements /// after it to the right - pub fn insert(&mut self, index: u64, elem: T) { + pub fn insert(&mut self, index: u32, elem: T) { self.slice = self.slice.insert(index, elem); } /// Remove an element at a specified index, shifting all elements /// after it to the left, returning the removed element - pub fn remove(&mut self, index: u64) -> T { + pub fn remove(&mut self, index: u32) -> T { let (new_slice, elem) = self.slice.remove(index); self.slice = new_slice; elem } /// Returns the number of elements in the vector - pub fn len(self) -> u64 { + pub fn len(self) -> u32 { self.slice.len() } } diff --git a/noir_stdlib/src/hash/poseidon.nr b/noir_stdlib/src/hash/poseidon.nr index f40ea2738ed..c4b5f0fcb6f 100644 --- a/noir_stdlib/src/hash/poseidon.nr +++ b/noir_stdlib/src/hash/poseidon.nr @@ -57,14 +57,14 @@ pub fn permute(pos_conf: PoseidonConfig, mut state: [Field; T] for _r in 0..rf / 2 - 1 { state = sigma(state); for i in 0..T { - state[i] += round_constants[T * (_r + 1) as u64 + i]; + state[i] += round_constants[T * (_r + 1) as u32 + i]; } state = apply_matrix(mds, state); } state = sigma(state); for i in 0..T { - state[i] += round_constants[T * (rf / 2) as u64 + i]; + state[i] += round_constants[T * (rf / 2) as u32 + i]; } state = apply_matrix(presparse_mds, state); @@ -74,15 +74,15 @@ pub fn permute(pos_conf: PoseidonConfig, mut state: [Field; T] for _r in 0..rp { state[0] = state[0].pow_32(alpha); - state[0] += round_constants[(rf/2 + 1) as u64 * T + _r as u64]; + state[0] += round_constants[(rf/2 + 1) as u32 * T + _r as u32]; crate::as_witness(state[0]); { let mut newState0 = 0; for j in 0..T { - newState0 += sparse_mds[(T * 2 - 1) * _r as u64 + j as u64] * state[j]; + newState0 += sparse_mds[(T * 2 - 1) * _r as u32 + j as u32] * state[j]; } for k in 1..T { - state[k] += state[0] * sparse_mds[(t * 2 - 1) as u64 * _r as u64 + T + k - 1]; + state[k] += state[0] * sparse_mds[(t * 2 - 1) as u32 * _r as u32 + T + k - 1]; } state[0] = newState0; @@ -97,7 +97,7 @@ pub fn permute(pos_conf: PoseidonConfig, mut state: [Field; T] for _r in 0..rf / 2 - 1 { state = sigma(state); for i in 0..state.len() { - state[i] += round_constants[(rf/2+1) as u64 * T + rp as u64 + (_r as u64) * T + i]; + state[i] += round_constants[(rf/2+1) as u32 * T + rp as u32 + (_r as u32) * T + i]; } state = apply_matrix(mds, state); } diff --git a/noir_stdlib/src/hash/poseidon2.nr b/noir_stdlib/src/hash/poseidon2.nr index e5a82a596c6..04d922b581d 100644 --- a/noir_stdlib/src/hash/poseidon2.nr +++ b/noir_stdlib/src/hash/poseidon2.nr @@ -12,7 +12,7 @@ struct Poseidon2 { impl Poseidon2 { - pub fn hash(input: [Field; N], message_size: u64) -> Field { + pub fn hash(input: [Field; N], message_size: u32) -> Field { if message_size == N { Poseidon2::hash_internal(input, N, false) } else { @@ -95,7 +95,7 @@ impl Poseidon2 { result } - fn hash_internal(input: [Field; N], in_len: u64, is_variable_length: bool) -> Field { + fn hash_internal(input: [Field; N], in_len: u32, is_variable_length: bool) -> Field { let two_pow_64 = 18446744073709551616; let iv : Field = (in_len as Field) * two_pow_64; let mut sponge = Poseidon2::new(iv); diff --git a/noir_stdlib/src/slice.nr b/noir_stdlib/src/slice.nr index ac542a960ed..bf05ae0cf64 100644 --- a/noir_stdlib/src/slice.nr +++ b/noir_stdlib/src/slice.nr @@ -1,6 +1,6 @@ impl [T] { #[builtin(array_len)] - pub fn len(self) -> u64 {} + pub fn len(self) -> u32 {} /// Push a new element to the end of the slice, returning a /// new slice with a length one greater than the @@ -27,13 +27,13 @@ impl [T] { /// Insert an element at a specified index, shifting all elements /// after it to the right #[builtin(slice_insert)] - pub fn insert(self, index: u64, elem: T) -> Self {} + pub fn insert(self, index: u32, elem: T) -> Self {} /// Remove an element at a specified index, shifting all elements /// after it to the left, returning the altered slice and /// the removed element #[builtin(slice_remove)] - pub fn remove(self, index: u64) -> (Self, T) {} + pub fn remove(self, index: u32) -> (Self, T) {} // Append each element of the `other` slice to the end of `self`. // This returns a new slice and leaves both input slices unchanged. diff --git a/test_programs/execution_success/array_len/src/main.nr b/test_programs/execution_success/array_len/src/main.nr index f846cfb9844..45c09b8a282 100644 --- a/test_programs/execution_success/array_len/src/main.nr +++ b/test_programs/execution_success/array_len/src/main.nr @@ -1,12 +1,12 @@ -fn len_plus_1(array: [T; N]) -> u64 { +fn len_plus_1(array: [T; N]) -> u32 { array.len() + 1 } -fn add_lens(a: [T; N], b: [Field; M]) -> u64 { +fn add_lens(a: [T; N], b: [Field; M]) -> u32 { a.len() + b.len() } -fn nested_call(b: [Field; N]) -> u64 { +fn nested_call(b: [Field; N]) -> u32 { len_plus_1(b) } diff --git a/test_programs/execution_success/brillig_array_to_slice/src/main.nr b/test_programs/execution_success/brillig_array_to_slice/src/main.nr index 8f7fcf24bae..262d3b5d86a 100644 --- a/test_programs/execution_success/brillig_array_to_slice/src/main.nr +++ b/test_programs/execution_success/brillig_array_to_slice/src/main.nr @@ -1,4 +1,4 @@ -unconstrained fn brillig_as_slice(x: Field) -> (u64, Field, Field) { +unconstrained fn brillig_as_slice(x: Field) -> (u32, Field, Field) { let mut dynamic: [Field; 1] = [1]; dynamic[x] = 2; assert(dynamic[0] == 2); diff --git a/test_programs/execution_success/regression/src/main.nr b/test_programs/execution_success/regression/src/main.nr index 316c0d6bad6..e60791aface 100644 --- a/test_programs/execution_success/regression/src/main.nr +++ b/test_programs/execution_success/regression/src/main.nr @@ -1,4 +1,4 @@ -global NIBBLE_LENGTH: u64 = 16; +global NIBBLE_LENGTH: u32 = 16; struct U4 { inner: u8, @@ -22,7 +22,7 @@ impl Eq for U4 { fn compact_decode(input: [u8; N], length: Field) -> ([U4; NIBBLE_LENGTH], Field) { assert(2 * input.len() <= NIBBLE_LENGTH); - assert(length as u64 <= input.len()); + assert(length as u32 <= input.len()); let mut nibble = [U4::zero(); NIBBLE_LENGTH]; @@ -32,7 +32,7 @@ fn compact_decode(input: [u8; N], length: Field) -> ([U4; NIBBLE_LENGTH], Fie if parity == 1 { nibble[0] = U4::from_u8(input[0] & 0x0f); for i in 1..input.len() { - if i as u64 < length as u64 { + if i as u32 < length as u32 { let x = input[i]; nibble[2*i - 1] = U4::from_u8(x >> 4); nibble[2*i] = U4::from_u8(x & 0x0f); @@ -40,7 +40,7 @@ fn compact_decode(input: [u8; N], length: Field) -> ([U4; NIBBLE_LENGTH], Fie } } else { for i in 0..2 { - if (i as u64) < length as u64 - 1 { + if (i as u32) < length as u32 - 1 { let x = input[i + 1]; nibble[2*i] = U4::from_u8(x >> 4); nibble[2*i + 1] = U4::from_u8(x & 0x0f); diff --git a/test_programs/execution_success/slice_dynamic_index/src/main.nr b/test_programs/execution_success/slice_dynamic_index/src/main.nr index 9b97c0721bb..2ab633eb98c 100644 --- a/test_programs/execution_success/slice_dynamic_index/src/main.nr +++ b/test_programs/execution_success/slice_dynamic_index/src/main.nr @@ -124,12 +124,12 @@ fn dynamic_slice_merge_if(mut slice: [Field], x: Field) { assert(first_elem == 12); assert(rest_of_slice.len() == 6); - slice = rest_of_slice.insert(x as u64 - 2, 20); + slice = rest_of_slice.insert(x as u32 - 2, 20); assert(slice[2] == 20); assert(slice[6] == 30); assert(slice.len() == 7); - let (removed_slice, removed_elem) = slice.remove(x as u64 - 1); + let (removed_slice, removed_elem) = slice.remove(x as u32 - 1); // The deconstructed tuple assigns to the slice but is not seen outside of the if statement // without a direct assignment slice = removed_slice; diff --git a/tooling/nargo/src/artifacts/debug_vars.rs b/tooling/nargo/src/artifacts/debug_vars.rs index 3695fa47842..d2c0bb3ea00 100644 --- a/tooling/nargo/src/artifacts/debug_vars.rs +++ b/tooling/nargo/src/artifacts/debug_vars.rs @@ -96,10 +96,10 @@ impl DebugVars { PrintableType::Array { length, typ }, ) => { assert!(!*is_slice, "slice has array type"); - if *index as u64 >= *length { + if *index >= *length { panic!("unexpected field index past array length") } - if *length != array_elements.len() as u64 { + if *length != array_elements.len() as u32 { panic!("type/array length mismatch") } (array_elements.get_mut(*index as usize).unwrap(), &*Box::leak(typ.clone())) diff --git a/tooling/noirc_abi/src/lib.rs b/tooling/noirc_abi/src/lib.rs index 0acace71fb3..b1ddba26f15 100644 --- a/tooling/noirc_abi/src/lib.rs +++ b/tooling/noirc_abi/src/lib.rs @@ -51,7 +51,7 @@ pub const MAIN_RETURN_NAME: &str = "return"; pub enum AbiType { Field, Array { - length: u64, + length: u32, #[serde(rename = "type")] typ: Box, }, @@ -72,7 +72,7 @@ pub enum AbiType { fields: Vec, }, String { - length: u64, + length: u32, }, } @@ -137,7 +137,7 @@ impl AbiType { Type::FieldElement => Self::Field, Type::Array(size, typ) => { let length = size - .evaluate_to_u64() + .evaluate_to_u32() .expect("Cannot have variable sized arrays as a parameter to main"); let typ = typ.as_ref(); Self::Array { length, typ: Box::new(Self::from_type(context, typ)) } @@ -160,7 +160,7 @@ impl AbiType { Type::Bool => Self::Boolean, Type::String(size) => { let size = size - .evaluate_to_u64() + .evaluate_to_u32() .expect("Cannot have variable sized strings as a parameter to main"); Self::String { length: size } } @@ -198,14 +198,14 @@ impl AbiType { pub fn field_count(&self) -> u32 { match self { AbiType::Field | AbiType::Integer { .. } | AbiType::Boolean => 1, - AbiType::Array { length, typ } => typ.field_count() * (*length as u32), + AbiType::Array { length, typ } => typ.field_count() * *length, AbiType::Struct { fields, .. } => { fields.iter().fold(0, |acc, (_, field_type)| acc + field_type.field_count()) } AbiType::Tuple { fields } => { fields.iter().fold(0, |acc, field_typ| acc + field_typ.field_count()) } - AbiType::String { length } => *length as u32, + AbiType::String { length } => *length, } } } @@ -600,14 +600,14 @@ fn range_to_vec(ranges: &[Range]) -> Vec { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "error_kind", rename_all = "lowercase")] pub enum AbiErrorType { - FmtString { length: u64, item_types: Vec }, + FmtString { length: u32, item_types: Vec }, Custom(AbiType), } impl AbiErrorType { pub fn from_type(context: &Context, typ: &Type) -> Self { match typ { Type::FmtString(len, item_types) => { - let length = len.evaluate_to_u64().expect("Cannot evaluate fmt length"); + let length = len.evaluate_to_u32().expect("Cannot evaluate fmt length"); let Type::Tuple(item_types) = item_types.as_ref() else { unreachable!("FmtString items must be a tuple") };