From 013631db7da120b7759edd1f7394b5acd55f5db0 Mon Sep 17 00:00:00 2001 From: AztecBot Date: Thu, 22 Aug 2024 10:42:28 +0000 Subject: [PATCH 1/9] chore: apply sync fixes --- .aztec-sync-commit | 2 +- .github/workflows/gates_report.yml | 2 +- .github/workflows/gates_report_brillig.yml | 92 + .gitignore | 1 + Cargo.lock | 1 + Cargo.toml | 6 + acvm-repo/acir/Cargo.toml | 3 + acvm-repo/acir/codegen/acir.cpp | 4 + acvm-repo/acir/src/circuit/mod.rs | 8 +- acvm-repo/acir/src/circuit/opcodes.rs | 6 +- .../opcodes/black_box_function_call.rs | 2 + .../acir/src/circuit/opcodes/function_id.rs | 17 + .../acir/tests/test_program_serialization.rs | 8 +- acvm-repo/acir_field/Cargo.toml | 3 + acvm-repo/acir_field/src/field_element.rs | 4 +- acvm-repo/acir_field/src/generic_ark.rs | 4 +- acvm-repo/acvm/Cargo.toml | 3 + acvm-repo/acvm/src/pwg/mod.rs | 6 +- acvm-repo/acvm_js/Cargo.toml | 3 + acvm-repo/acvm_js/src/execute.rs | 4 +- acvm-repo/acvm_js/src/js_execution_error.rs | 8 +- acvm-repo/blackbox_solver/Cargo.toml | 3 + acvm-repo/bn254_blackbox_solver/Cargo.toml | 3 + .../src/generator/generators.rs | 2 +- acvm-repo/brillig/Cargo.toml | 3 + acvm-repo/brillig_vm/Cargo.toml | 3 + aztec_macros/Cargo.toml | 3 + aztec_macros/src/transforms/functions.rs | 6 +- aztec_macros/src/transforms/note_interface.rs | 59 +- aztec_macros/src/transforms/storage.rs | 2 +- aztec_macros/src/utils/ast_utils.rs | 9 +- aztec_macros/src/utils/parse_utils.rs | 5 +- compiler/fm/Cargo.toml | 3 + compiler/noirc_arena/Cargo.toml | 3 + compiler/noirc_driver/Cargo.toml | 3 + compiler/noirc_driver/src/abi_gen.rs | 2 +- compiler/noirc_driver/src/lib.rs | 11 +- compiler/noirc_driver/src/program.rs | 2 + compiler/noirc_errors/Cargo.toml | 3 + compiler/noirc_errors/src/position.rs | 2 +- compiler/noirc_evaluator/Cargo.toml | 3 + .../src/brillig/brillig_gen.rs | 11 +- .../brillig/brillig_gen/brillig_black_box.rs | 9 +- .../src/brillig/brillig_gen/brillig_block.rs | 146 +- .../brillig_gen/brillig_block_variables.rs | 13 +- .../brillig/brillig_gen/brillig_directive.rs | 2 + .../src/brillig/brillig_gen/brillig_fn.rs | 7 +- .../brillig/brillig_gen/brillig_slice_ops.rs | 35 +- .../noirc_evaluator/src/brillig/brillig_ir.rs | 74 +- .../src/brillig/brillig_ir/artifact.rs | 87 +- .../src/brillig/brillig_ir/codegen_binary.rs | 19 +- .../src/brillig/brillig_ir/codegen_calls.rs | 15 +- .../brillig_ir/codegen_control_flow.rs | 229 +- .../brillig/brillig_ir/codegen_intrinsic.rs | 52 +- .../src/brillig/brillig_ir/codegen_memory.rs | 49 +- .../src/brillig/brillig_ir/codegen_stack.rs | 4 +- .../src/brillig/brillig_ir/entry_point.rs | 207 +- .../src/brillig/brillig_ir/instructions.rs | 59 +- .../brillig_ir/procedures/array_copy.rs | 98 + .../brillig_ir/procedures/array_reverse.rs | 37 + .../brillig/brillig_ir/procedures/mem_copy.rs | 45 + .../src/brillig/brillig_ir/procedures/mod.rs | 42 + .../src/brillig/brillig_ir/registers.rs | 202 +- compiler/noirc_evaluator/src/brillig/mod.rs | 30 +- compiler/noirc_evaluator/src/ssa.rs | 9 +- .../src/ssa/acir_gen/acir_ir/acir_variable.rs | 30 +- .../ssa/acir_gen/acir_ir/generated_acir.rs | 1 + .../noirc_evaluator/src/ssa/acir_gen/mod.rs | 91 +- compiler/noirc_evaluator/src/ssa/ir/dfg.rs | 9 +- .../noirc_evaluator/src/ssa/ir/instruction.rs | 72 +- compiler/noirc_evaluator/src/ssa/ir/map.rs | 2 +- .../noirc_evaluator/src/ssa/opt/mem2reg.rs | 47 +- .../src/ssa/ssa_gen/context.rs | 8 +- .../noirc_evaluator/src/ssa/ssa_gen/mod.rs | 12 +- compiler/noirc_frontend/src/ast/expression.rs | 26 +- compiler/noirc_frontend/src/ast/function.rs | 4 +- compiler/noirc_frontend/src/ast/mod.rs | 25 +- compiler/noirc_frontend/src/ast/statement.rs | 16 +- compiler/noirc_frontend/src/debug/mod.rs | 30 +- .../noirc_frontend/src/elaborator/comptime.rs | 8 + .../src/elaborator/expressions.rs | 23 +- compiler/noirc_frontend/src/elaborator/mod.rs | 47 +- .../src/elaborator/statements.rs | 4 +- .../src/elaborator/trait_impls.rs | 7 +- .../noirc_frontend/src/elaborator/traits.rs | 13 +- .../noirc_frontend/src/elaborator/types.rs | 130 +- .../src/hir/comptime/hir_to_display_ast.rs | 9 +- .../src/hir/comptime/interpreter.rs | 3 + .../src/hir/comptime/interpreter/builtin.rs | 326 ++- .../interpreter/builtin/builtin_helpers.rs | 86 +- .../src/hir/def_collector/dc_mod.rs | 48 +- .../src/hir/def_map/module_def.rs | 2 +- .../src/hir/type_check/errors.rs | 12 +- compiler/noirc_frontend/src/hir_def/expr.rs | 1 + .../noirc_frontend/src/hir_def/function.rs | 4 +- compiler/noirc_frontend/src/hir_def/traits.rs | 11 +- compiler/noirc_frontend/src/hir_def/types.rs | 132 +- compiler/noirc_frontend/src/lexer/token.rs | 3 + compiler/noirc_frontend/src/locations.rs | 76 +- .../src/monomorphization/ast.rs | 13 +- .../src/monomorphization/mod.rs | 45 +- compiler/noirc_frontend/src/node_interner.rs | 39 +- compiler/noirc_frontend/src/parser/errors.rs | 10 + compiler/noirc_frontend/src/parser/parser.rs | 104 +- .../src/parser/parser/function.rs | 35 +- .../src/parser/parser/lambdas.rs | 10 +- .../src/parser/parser/traits.rs | 108 +- .../noirc_frontend/src/parser/parser/types.rs | 14 +- compiler/noirc_frontend/src/tests.rs | 195 ++ compiler/noirc_printable_type/Cargo.toml | 3 + compiler/noirc_printable_type/src/lib.rs | 1 + compiler/wasm/Cargo.toml | 4 +- cspell.json | 3 +- .../docs/explainers/explainer-writing-noir.md | 8 +- docs/docs/how_to/how-to-solidity-verifier.md | 8 +- docs/docs/noir/concepts/unconstrained.md | 9 +- .../how_to/how-to-solidity-verifier.md | 8 +- noir_stdlib/src/array.nr | 20 +- noir_stdlib/src/cmp.nr | 26 + noir_stdlib/src/collections/bounded_vec.nr | 4 +- noir_stdlib/src/collections/map.nr | 4 +- noir_stdlib/src/collections/umap.nr | 6 +- noir_stdlib/src/default.nr | 3 + noir_stdlib/src/field/bn254.nr | 50 +- noir_stdlib/src/hash/mod.nr | 22 +- noir_stdlib/src/lib.nr | 41 +- noir_stdlib/src/{unsafe.nr => mem.nr} | 1 + noir_stdlib/src/meta/expr.nr | 222 ++ noir_stdlib/src/meta/mod.nr | 8 +- noir_stdlib/src/meta/op.nr | 92 + noir_stdlib/src/meta/trait_impl.nr | 7 + noir_stdlib/src/ops/arith.nr | 5 + noir_stdlib/src/ops/bit.nr | 3 + noir_stdlib/src/option.nr | 2 +- noir_stdlib/src/slice.nr | 2 +- noir_stdlib/src/uint128.nr | 62 +- test_programs/.gitignore | 1 + .../array_length_defaulting/src/main.nr | 2 +- .../brillig_mut_ref_from_acir/src/main.nr | 4 +- .../regression_5008/src/main.nr | 4 +- .../turbofish_generic_count/src/main.nr | 2 +- .../unconstrained_ref/src/main.nr | 4 +- .../arithmetic_generics/src/main.nr | 4 +- .../brillig_cast/src/main.nr | 12 +- .../src/main.nr | 14 +- .../src/main.nr | 34 +- .../brillig_modulo/src/main.nr | 28 +- .../brillig_slice_input/src/main.nr | 12 +- .../comptime_exp/src/main.nr | 8 - .../comptime_fmt_strings/src/main.nr | 2 +- .../Nargo.toml | 2 +- .../comptime_trait_impl/src/main.nr | 32 + .../macros_in_comptime/src/main.nr | 6 +- .../zeroed_slice/src/main.nr | 2 +- .../check_uncostrained_regression/src/main.nr | 4 +- .../brillig_assert_fail/src/main.nr | 6 +- .../brillig_assert_msg_runtime/src/main.nr | 6 +- .../src/main.nr | 4 +- .../regression_5202/src/main.nr | 8 +- .../acir_inside_brillig_recursion/src/main.nr | 4 +- .../aes128_encrypt/src/main.nr | 21 +- .../src/main.nr | 6 +- .../execution_success/bigint/src/main.nr | 4 +- .../brillig_acir_as_brillig/src/main.nr | 8 +- .../brillig_array_to_slice/src/main.nr | 10 +- .../brillig_arrays/src/main.nr | 6 +- .../brillig_assert/src/main.nr | 4 +- .../brillig_blake2s/src/main.nr | 4 +- .../src/main.nr | 4 +- .../brillig_calls/src/main.nr | 10 +- .../brillig_calls_array/src/main.nr | 6 +- .../brillig_calls_conditionals/src/main.nr | 10 +- .../brillig_conditional/src/main.nr | 4 +- .../brillig_ecdsa_secp256k1/src/main.nr | 4 +- .../brillig_ecdsa_secp256r1/src/main.nr | 4 +- .../brillig_fns_as_values/src/main.nr | 20 +- .../brillig_hash_to_field/src/main.nr | 4 +- .../brillig_identity_function/src/main.nr | 22 +- .../brillig_keccak/src/main.nr | 26 +- .../brillig_loop/src/main.nr | 6 +- .../brillig_loop_size_regression/Nargo.toml | 7 + .../brillig_loop_size_regression/Prover.toml | 0 .../brillig_loop_size_regression/src/main.nr | 16 + .../brillig_nested_arrays/src/main.nr | 16 +- .../execution_success/brillig_not/src/main.nr | 6 +- .../brillig_oracle/src/main.nr | 30 +- .../brillig_recursion/src/main.nr | 4 +- .../brillig_sha256/src/main.nr | 4 +- .../brillig_unitialised_arrays/src/main.nr | 6 +- .../execution_success/databus/src/main.nr | 4 +- .../execution_success/generics/src/main.nr | 2 +- .../global_consts/src/main.nr | 2 +- .../is_unconstrained/src/main.nr | 4 +- .../nested_arrays_from_brillig/src/main.nr | 4 +- .../regression_4124/src/main.nr | 2 +- .../regression_5435/src/main.nr | 4 +- .../execution_success/slice_regex/src/main.nr | 8 +- .../execution_success/u16_support/src/main.nr | 4 +- .../execution_success/uhashmap/src/main.nr | 8 +- .../execution_success/unit_value/src/main.nr | 2 +- test_programs/gates_report_brillig.sh | 33 + .../noir_test_success/mock_oracle/src/main.nr | 112 +- .../out_of_bounds_alignment/src/main.nr | 4 +- .../regression_4561/src/main.nr | 8 +- test_programs/rebuild.sh | 115 +- tooling/acvm_cli/Cargo.toml | 3 + tooling/debugger/Cargo.toml | 3 + tooling/debugger/src/context.rs | 15 +- tooling/fuzzer/Cargo.toml | 3 + tooling/lsp/Cargo.toml | 4 + tooling/lsp/src/lib.rs | 24 +- tooling/lsp/src/notifications/mod.rs | 8 +- tooling/lsp/src/requests/completion.rs | 2176 ++--------------- .../src/requests/completion/auto_import.rs | 210 ++ .../lsp/src/requests/completion/builtins.rs | 62 + .../requests/completion/completion_items.rs | 391 +++ tooling/lsp/src/requests/completion/kinds.rs | 42 + .../lsp/src/requests/completion/sort_text.rs | 39 + tooling/lsp/src/requests/completion/tests.rs | 1641 +++++++++++++ .../lsp/src/requests/completion/traversal.rs | 132 + tooling/lsp/src/requests/document_symbol.rs | 18 +- tooling/lsp/src/requests/hover.rs | 56 +- tooling/lsp/src/requests/inlay_hint.rs | 16 +- tooling/lsp/src/requests/mod.rs | 13 +- tooling/lsp/src/requests/signature_help.rs | 291 +++ .../lsp/src/requests/signature_help/tests.rs | 196 ++ .../src/requests/signature_help/traversal.rs | 304 +++ tooling/lsp/src/types.rs | 6 +- tooling/nargo/Cargo.toml | 3 + tooling/nargo/src/lib.rs | 31 +- tooling/nargo/src/ops/execute.rs | 6 +- tooling/nargo_cli/Cargo.toml | 3 + tooling/nargo_cli/build.rs | 2 +- tooling/nargo_cli/src/cli/info_cmd.rs | 57 +- tooling/nargo_fmt/Cargo.toml | 3 + tooling/nargo_fmt/src/rewrite/expr.rs | 3 + tooling/nargo_fmt/src/rewrite/typ.rs | 10 +- tooling/nargo_fmt/src/visitor/item.rs | 13 +- tooling/nargo_fmt/tests/expected/fn.nr | 2 + tooling/nargo_fmt/tests/expected/unsafe.nr | 8 + tooling/nargo_fmt/tests/input/fn.nr | 2 + tooling/nargo_fmt/tests/input/unsafe.nr | 8 + tooling/nargo_toml/Cargo.toml | 3 + tooling/noirc_abi/Cargo.toml | 3 + tooling/noirc_abi/src/arbitrary.rs | 8 +- tooling/noirc_abi_wasm/src/lib.rs | 5 +- tooling/noirc_artifacts/Cargo.toml | 3 + tooling/noirc_artifacts/src/program.rs | 4 + tooling/profiler/Cargo.toml | 3 + .../profiler/src/cli/gates_flamegraph_cmd.rs | 3 +- .../src/cli/opcodes_flamegraph_cmd.rs | 2 + tooling/profiler/src/opcode_formatter.rs | 2 +- 252 files changed, 7587 insertions(+), 3359 deletions(-) create mode 100644 .github/workflows/gates_report_brillig.yml create mode 100644 acvm-repo/acir/src/circuit/opcodes/function_id.rs create mode 100644 compiler/noirc_evaluator/src/brillig/brillig_ir/procedures/array_copy.rs create mode 100644 compiler/noirc_evaluator/src/brillig/brillig_ir/procedures/array_reverse.rs create mode 100644 compiler/noirc_evaluator/src/brillig/brillig_ir/procedures/mem_copy.rs create mode 100644 compiler/noirc_evaluator/src/brillig/brillig_ir/procedures/mod.rs rename noir_stdlib/src/{unsafe.nr => mem.nr} (99%) create mode 100644 noir_stdlib/src/meta/op.nr create mode 100644 noir_stdlib/src/meta/trait_impl.nr delete mode 100644 test_programs/compile_success_empty/comptime_exp/src/main.nr rename test_programs/compile_success_empty/{comptime_exp => comptime_trait_impl}/Nargo.toml (74%) create mode 100644 test_programs/compile_success_empty/comptime_trait_impl/src/main.nr create mode 100644 test_programs/execution_success/brillig_loop_size_regression/Nargo.toml create mode 100644 test_programs/execution_success/brillig_loop_size_regression/Prover.toml create mode 100644 test_programs/execution_success/brillig_loop_size_regression/src/main.nr create mode 100644 test_programs/gates_report_brillig.sh create mode 100644 tooling/lsp/src/requests/completion/auto_import.rs create mode 100644 tooling/lsp/src/requests/completion/completion_items.rs create mode 100644 tooling/lsp/src/requests/completion/kinds.rs create mode 100644 tooling/lsp/src/requests/completion/sort_text.rs create mode 100644 tooling/lsp/src/requests/completion/tests.rs create mode 100644 tooling/lsp/src/requests/completion/traversal.rs create mode 100644 tooling/lsp/src/requests/signature_help.rs create mode 100644 tooling/lsp/src/requests/signature_help/tests.rs create mode 100644 tooling/lsp/src/requests/signature_help/traversal.rs create mode 100644 tooling/nargo_fmt/tests/expected/unsafe.nr create mode 100644 tooling/nargo_fmt/tests/input/unsafe.nr diff --git a/.aztec-sync-commit b/.aztec-sync-commit index 5e6d9f5f197..85aa86dabc0 100644 --- a/.aztec-sync-commit +++ b/.aztec-sync-commit @@ -1 +1 @@ -91042c7bcebfebeb4e629162f44988e2cda1ed41 +37492116a70d6f26b24d53c90858888da3c2d8f4 diff --git a/.github/workflows/gates_report.yml b/.github/workflows/gates_report.yml index 0cc94a1a04d..0b0a527b69e 100644 --- a/.github/workflows/gates_report.yml +++ b/.github/workflows/gates_report.yml @@ -80,7 +80,7 @@ jobs: - name: Compare gates reports id: gates_diff - uses: vezenovm/noir-gates-diff@acf12797860f237117e15c0d6e08d64253af52b6 + uses: noir-lang/noir-gates-diff@1931aaaa848a1a009363d6115293f7b7fc72bb87 with: report: gates_report.json summaryQuantile: 0.9 # only display the 10% most significant circuit size diffs in the summary (defaults to 20%) diff --git a/.github/workflows/gates_report_brillig.yml b/.github/workflows/gates_report_brillig.yml new file mode 100644 index 00000000000..4e12a6fcbca --- /dev/null +++ b/.github/workflows/gates_report_brillig.yml @@ -0,0 +1,92 @@ +name: Report Brillig bytecode size diff + +on: + push: + branches: + - master + pull_request: + +jobs: + build-nargo: + runs-on: ubuntu-latest + strategy: + matrix: + target: [x86_64-unknown-linux-gnu] + + steps: + - name: Checkout Noir repo + uses: actions/checkout@v4 + + - name: Setup toolchain + uses: dtolnay/rust-toolchain@1.74.1 + + - uses: Swatinem/rust-cache@v2 + with: + key: ${{ matrix.target }} + cache-on-failure: true + save-if: ${{ github.event_name != 'merge_group' }} + + - name: Build Nargo + run: cargo build --package nargo_cli --release + + - name: Package artifacts + run: | + mkdir dist + cp ./target/release/nargo ./dist/nargo + 7z a -ttar -so -an ./dist/* | 7z a -si ./nargo-x86_64-unknown-linux-gnu.tar.gz + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: nargo + path: ./dist/* + retention-days: 3 + + compare_brillig_bytecode_size_reports: + needs: [build-nargo] + runs-on: ubuntu-latest + permissions: + pull-requests: write + + steps: + - uses: actions/checkout@v4 + + - name: Download nargo binary + uses: actions/download-artifact@v4 + with: + name: nargo + path: ./nargo + + - name: Set nargo on PATH + run: | + nargo_binary="${{ github.workspace }}/nargo/nargo" + chmod +x $nargo_binary + echo "$(dirname $nargo_binary)" >> $GITHUB_PATH + export PATH="$PATH:$(dirname $nargo_binary)" + nargo -V + + - name: Generate Brillig bytecode size report + working-directory: ./test_programs + run: | + chmod +x gates_report_brillig.sh + ./gates_report_brillig.sh + mv gates_report_brillig.json ../gates_report_brillig.json + + - name: Compare Brillig bytecode size reports + id: brillig_bytecode_diff + uses: noir-lang/noir-gates-diff@3fb844067b25d1b59727ea600b614503b33503f4 + with: + report: gates_report_brillig.json + header: | + # Changes to Brillig bytecode sizes + brillig_report: true + summaryQuantile: 0.9 # only display the 10% most significant bytecode size diffs in the summary (defaults to 20%) + + - name: Add bytecode size diff to sticky comment + if: github.event_name == 'pull_request' || github.event_name == 'pull_request_target' + uses: marocchino/sticky-pull-request-comment@v2 + with: + header: brillig + # delete the comment in case changes no longer impact brillig bytecode sizes + delete: ${{ !steps.brillig_bytecode_diff.outputs.markdown }} + message: ${{ steps.brillig_bytecode_diff.outputs.markdown }} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 2c877a4d02c..aeb7d8757c4 100644 --- a/.gitignore +++ b/.gitignore @@ -33,6 +33,7 @@ tooling/noir_js/lib !compiler/wasm/noir-script/target gates_report.json +gates_report_brillig.json # Github Actions scratch space # This gives a location to download artifacts into the repository in CI without making git dirty. diff --git a/Cargo.lock b/Cargo.lock index bacbf939786..e1159c71201 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2722,6 +2722,7 @@ dependencies = [ "acvm", "async-lsp", "codespan-lsp", + "convert_case 0.6.0", "fm", "fxhash", "lsp-types 0.94.1", diff --git a/Cargo.toml b/Cargo.toml index 63509170057..7d9b3254c53 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,6 +50,12 @@ rust-version = "1.74.1" license = "MIT OR Apache-2.0" repository = "https://github.com/noir-lang/noir/" +[workspace.lints.rust] +trivial_casts = "warn" +trivial_numeric_casts = "warn" +unused_import_braces = "warn" +unused_qualifications = "warn" + [workspace.dependencies] # ACVM workspace dependencies diff --git a/acvm-repo/acir/Cargo.toml b/acvm-repo/acir/Cargo.toml index 88616ccffb5..860b565544b 100644 --- a/acvm-repo/acir/Cargo.toml +++ b/acvm-repo/acir/Cargo.toml @@ -10,6 +10,9 @@ license.workspace = true rust-version.workspace = true repository.workspace = true +[lints] +workspace = true + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] diff --git a/acvm-repo/acir/codegen/acir.cpp b/acvm-repo/acir/codegen/acir.cpp index b16baf14d06..2f883502869 100644 --- a/acvm-repo/acir/codegen/acir.cpp +++ b/acvm-repo/acir/codegen/acir.cpp @@ -933,6 +933,7 @@ namespace Program { std::vector proof; std::vector public_inputs; Program::FunctionInput key_hash; + uint32_t proof_type; friend bool operator==(const RecursiveAggregation&, const RecursiveAggregation&); std::vector bincodeSerialize() const; @@ -3149,6 +3150,7 @@ namespace Program { if (!(lhs.proof == rhs.proof)) { return false; } if (!(lhs.public_inputs == rhs.public_inputs)) { return false; } if (!(lhs.key_hash == rhs.key_hash)) { return false; } + if (!(lhs.proof_type == rhs.proof_type)) { return false; } return true; } @@ -3176,6 +3178,7 @@ void serde::Serializable::seria serde::Serializable::serialize(obj.proof, serializer); serde::Serializable::serialize(obj.public_inputs, serializer); serde::Serializable::serialize(obj.key_hash, serializer); + serde::Serializable::serialize(obj.proof_type, serializer); } template <> @@ -3186,6 +3189,7 @@ Program::BlackBoxFuncCall::RecursiveAggregation serde::Deserializable::deserialize(deserializer); obj.public_inputs = serde::Deserializable::deserialize(deserializer); obj.key_hash = serde::Deserializable::deserialize(deserializer); + obj.proof_type = serde::Deserializable::deserialize(deserializer); return obj; } diff --git a/acvm-repo/acir/src/circuit/mod.rs b/acvm-repo/acir/src/circuit/mod.rs index 00d0933a3aa..43984e4a922 100644 --- a/acvm-repo/acir/src/circuit/mod.rs +++ b/acvm-repo/acir/src/circuit/mod.rs @@ -103,7 +103,7 @@ impl ErrorSelector { impl Serialize for ErrorSelector { fn serialize(&self, serializer: S) -> Result where - S: serde::Serializer, + S: Serializer, { self.0.to_string().serialize(serializer) } @@ -112,7 +112,7 @@ impl Serialize for ErrorSelector { impl<'de> Deserialize<'de> for ErrorSelector { fn deserialize(deserializer: D) -> Result where - D: serde::Deserializer<'de>, + D: Deserializer<'de>, { let s: String = Deserialize::deserialize(deserializer)?; let as_u64 = s.parse().map_err(serde::de::Error::custom)?; @@ -224,7 +224,7 @@ impl Circuit { } impl Program { - fn write(&self, writer: W) -> std::io::Result<()> { + fn write(&self, writer: W) -> std::io::Result<()> { let buf = bincode::serialize(self).unwrap(); let mut encoder = flate2::write::GzEncoder::new(writer, Compression::default()); encoder.write_all(&buf)?; @@ -250,7 +250,7 @@ impl Program { } impl Deserialize<'a>> Program { - fn read(reader: R) -> std::io::Result { + fn read(reader: R) -> std::io::Result { let mut gz_decoder = flate2::read::GzDecoder::new(reader); let mut buf_d = Vec::new(); gz_decoder.read_to_end(&mut buf_d)?; diff --git a/acvm-repo/acir/src/circuit/opcodes.rs b/acvm-repo/acir/src/circuit/opcodes.rs index b1fdc5e0080..d7f0f5f6f1f 100644 --- a/acvm-repo/acir/src/circuit/opcodes.rs +++ b/acvm-repo/acir/src/circuit/opcodes.rs @@ -2,6 +2,10 @@ use super::{ brillig::{BrilligFunctionId, BrilligInputs, BrilligOutputs}, directives::Directive, }; + +pub mod function_id; +pub use function_id::AcirFunctionId; + use crate::native_types::{Expression, Witness}; use acir_field::AcirField; use serde::{Deserialize, Serialize}; @@ -125,7 +129,7 @@ pub enum Opcode { Call { /// Id for the function being called. It is the responsibility of the executor /// to fetch the appropriate circuit from this id. - id: u32, + id: AcirFunctionId, /// Inputs to the function call inputs: Vec, /// Outputs of the function call diff --git a/acvm-repo/acir/src/circuit/opcodes/black_box_function_call.rs b/acvm-repo/acir/src/circuit/opcodes/black_box_function_call.rs index 6a301ec5115..333bab419c8 100644 --- a/acvm-repo/acir/src/circuit/opcodes/black_box_function_call.rs +++ b/acvm-repo/acir/src/circuit/opcodes/black_box_function_call.rs @@ -159,6 +159,7 @@ pub enum BlackBoxFuncCall { /// The circuit implementing this opcode can use this hash to ensure that the /// key provided to the circuit matches the key produced by the circuit creator key_hash: FunctionInput, + proof_type: u32, }, BigIntAdd { lhs: u32, @@ -350,6 +351,7 @@ impl BlackBoxFuncCall { proof, public_inputs, key_hash, + proof_type: _, } => { let mut inputs = Vec::new(); inputs.extend(key.iter().copied()); diff --git a/acvm-repo/acir/src/circuit/opcodes/function_id.rs b/acvm-repo/acir/src/circuit/opcodes/function_id.rs new file mode 100644 index 00000000000..b5abb1b3942 --- /dev/null +++ b/acvm-repo/acir/src/circuit/opcodes/function_id.rs @@ -0,0 +1,17 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize, Hash)] +#[serde(transparent)] +pub struct AcirFunctionId(pub u32); + +impl AcirFunctionId { + pub fn as_usize(&self) -> usize { + self.0 as usize + } +} + +impl std::fmt::Display for AcirFunctionId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} diff --git a/acvm-repo/acir/tests/test_program_serialization.rs b/acvm-repo/acir/tests/test_program_serialization.rs index 1a634eeea9c..ce28d47021c 100644 --- a/acvm-repo/acir/tests/test_program_serialization.rs +++ b/acvm-repo/acir/tests/test_program_serialization.rs @@ -14,7 +14,7 @@ use std::collections::BTreeSet; use acir::{ circuit::{ brillig::{BrilligBytecode, BrilligFunctionId, BrilligInputs, BrilligOutputs}, - opcodes::{BlackBoxFuncCall, BlockId, FunctionInput, MemOp}, + opcodes::{AcirFunctionId, BlackBoxFuncCall, BlockId, FunctionInput, MemOp}, Circuit, Opcode, Program, PublicInputs, }, native_types::{Expression, Witness}, @@ -381,13 +381,13 @@ fn nested_acir_call_circuit() { // x // } let nested_call = Opcode::Call { - id: 1, + id: AcirFunctionId(1), inputs: vec![Witness(0), Witness(1)], outputs: vec![Witness(2)], predicate: None, }; let nested_call_two = Opcode::Call { - id: 1, + id: AcirFunctionId(1), inputs: vec![Witness(0), Witness(1)], outputs: vec![Witness(3)], predicate: None, @@ -419,7 +419,7 @@ fn nested_acir_call_circuit() { q_c: FieldElement::one() + FieldElement::one(), }); let call = Opcode::Call { - id: 2, + id: AcirFunctionId(2), inputs: vec![Witness(2), Witness(1)], outputs: vec![Witness(3)], predicate: None, diff --git a/acvm-repo/acir_field/Cargo.toml b/acvm-repo/acir_field/Cargo.toml index a037a453348..c1cffc1334e 100644 --- a/acvm-repo/acir_field/Cargo.toml +++ b/acvm-repo/acir_field/Cargo.toml @@ -10,6 +10,9 @@ license.workspace = true rust-version.workspace = true repository.workspace = true +[lints] +workspace = true + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] diff --git a/acvm-repo/acir_field/src/field_element.rs b/acvm-repo/acir_field/src/field_element.rs index 92ccbc4e5f6..2323f008dbe 100644 --- a/acvm-repo/acir_field/src/field_element.rs +++ b/acvm-repo/acir_field/src/field_element.rs @@ -115,7 +115,7 @@ impl From for FieldElement { } } -impl Serialize for FieldElement { +impl Serialize for FieldElement { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, @@ -124,7 +124,7 @@ impl Serialize for FieldElement { } } -impl<'de, T: ark_ff::PrimeField> Deserialize<'de> for FieldElement { +impl<'de, T: PrimeField> Deserialize<'de> for FieldElement { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, diff --git a/acvm-repo/acir_field/src/generic_ark.rs b/acvm-repo/acir_field/src/generic_ark.rs index f7228e66314..74927c07a36 100644 --- a/acvm-repo/acir_field/src/generic_ark.rs +++ b/acvm-repo/acir_field/src/generic_ark.rs @@ -2,7 +2,7 @@ use num_bigint::BigUint; /// This trait is extremely unstable and WILL have breaking changes. pub trait AcirField: - std::marker::Sized + Sized + std::fmt::Display + std::fmt::Debug + Default @@ -24,7 +24,7 @@ pub trait AcirField: // + From + From + std::hash::Hash - + std::cmp::Eq + + Eq { fn one() -> Self; fn zero() -> Self; diff --git a/acvm-repo/acvm/Cargo.toml b/acvm-repo/acvm/Cargo.toml index 2ee4d529e5a..bf1170ce073 100644 --- a/acvm-repo/acvm/Cargo.toml +++ b/acvm-repo/acvm/Cargo.toml @@ -10,6 +10,9 @@ license.workspace = true rust-version.workspace = true repository.workspace = true +[lints] +workspace = true + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] diff --git a/acvm-repo/acvm/src/pwg/mod.rs b/acvm-repo/acvm/src/pwg/mod.rs index 83c5aeb6296..647c11bd3c3 100644 --- a/acvm-repo/acvm/src/pwg/mod.rs +++ b/acvm-repo/acvm/src/pwg/mod.rs @@ -6,7 +6,7 @@ use acir::{ brillig::ForeignCallResult, circuit::{ brillig::{BrilligBytecode, BrilligFunctionId}, - opcodes::{BlockId, ConstantOrWitnessEnum, FunctionInput}, + opcodes::{AcirFunctionId, BlockId, ConstantOrWitnessEnum, FunctionInput}, AssertionPayload, ErrorSelector, ExpressionOrMemory, Opcode, OpcodeLocation, RawAssertionPayload, ResolvedAssertionPayload, STRING_ERROR_SELECTOR, }, @@ -575,7 +575,7 @@ impl<'a, F: AcirField, B: BlackBoxFunctionSolver> ACVM<'a, F, B> { else { unreachable!("Not executing a Call opcode"); }; - if *id == 0 { + if *id == AcirFunctionId(0) { return Err(OpcodeResolutionError::AcirMainCallAttempted { opcode_location: ErrorLocation::Resolved(OpcodeLocation::Acir( self.instruction_pointer(), @@ -716,7 +716,7 @@ pub(crate) fn is_predicate_false( #[derive(Debug, Clone, PartialEq)] pub struct AcirCallWaitInfo { /// Index in the list of ACIR function's that should be called - pub id: u32, + pub id: AcirFunctionId, /// Initial witness for the given circuit to be called pub initial_witness: WitnessMap, } diff --git a/acvm-repo/acvm_js/Cargo.toml b/acvm-repo/acvm_js/Cargo.toml index 0d90b9ba54f..6b457a8f5f8 100644 --- a/acvm-repo/acvm_js/Cargo.toml +++ b/acvm-repo/acvm_js/Cargo.toml @@ -10,6 +10,9 @@ license.workspace = true rust-version.workspace = true repository.workspace = true +[lints] +workspace = true + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [lib] diff --git a/acvm-repo/acvm_js/src/execute.rs b/acvm-repo/acvm_js/src/execute.rs index c596dcf9614..98a0c4c3abe 100644 --- a/acvm-repo/acvm_js/src/execute.rs +++ b/acvm-repo/acvm_js/src/execute.rs @@ -250,7 +250,7 @@ impl<'a, B: BlackBoxFunctionSolver> ProgramExecutor<'a, B> { acvm.resolve_pending_foreign_call(result); } ACVMStatus::RequiresAcirCall(call_info) => { - let acir_to_call = &self.functions[call_info.id as usize]; + let acir_to_call = &self.functions[call_info.id.as_usize()]; let initial_witness = call_info.initial_witness; let call_solved_witness = self .execute_circuit(acir_to_call, initial_witness, witness_stack) @@ -267,7 +267,7 @@ impl<'a, B: BlackBoxFunctionSolver> ProgramExecutor<'a, B> { } } acvm.resolve_pending_acir_call(call_resolved_outputs); - witness_stack.push(call_info.id, call_solved_witness.clone()); + witness_stack.push(call_info.id.0, call_solved_witness.clone()); } } } diff --git a/acvm-repo/acvm_js/src/js_execution_error.rs b/acvm-repo/acvm_js/src/js_execution_error.rs index 23da88247fc..f6a00af7942 100644 --- a/acvm-repo/acvm_js/src/js_execution_error.rs +++ b/acvm-repo/acvm_js/src/js_execution_error.rs @@ -54,16 +54,14 @@ impl JsExecutionError { None => JsValue::UNDEFINED, }; let assertion_payload = match assertion_payload { - Some(raw) => ::from_serde(&raw) + Some(raw) => ::from_serde(&raw) .expect("Cannot serialize assertion payload"), None => JsValue::UNDEFINED, }; let brillig_function_id = match brillig_function_id { - Some(function_id) => { - ::from_serde(&function_id) - .expect("Cannot serialize Brillig function id") - } + Some(function_id) => ::from_serde(&function_id) + .expect("Cannot serialize Brillig function id"), None => JsValue::UNDEFINED, }; diff --git a/acvm-repo/blackbox_solver/Cargo.toml b/acvm-repo/blackbox_solver/Cargo.toml index 10b491c7f67..d0473857e1c 100644 --- a/acvm-repo/blackbox_solver/Cargo.toml +++ b/acvm-repo/blackbox_solver/Cargo.toml @@ -10,6 +10,9 @@ license.workspace = true rust-version.workspace = true repository.workspace = true +[lints] +workspace = true + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] diff --git a/acvm-repo/bn254_blackbox_solver/Cargo.toml b/acvm-repo/bn254_blackbox_solver/Cargo.toml index ab677396c22..9a23f503a06 100644 --- a/acvm-repo/bn254_blackbox_solver/Cargo.toml +++ b/acvm-repo/bn254_blackbox_solver/Cargo.toml @@ -10,6 +10,9 @@ license.workspace = true rust-version.workspace = true repository.workspace = true +[lints] +workspace = true + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] diff --git a/acvm-repo/bn254_blackbox_solver/src/generator/generators.rs b/acvm-repo/bn254_blackbox_solver/src/generator/generators.rs index bb51426b33b..a4125014d56 100644 --- a/acvm-repo/bn254_blackbox_solver/src/generator/generators.rs +++ b/acvm-repo/bn254_blackbox_solver/src/generator/generators.rs @@ -91,7 +91,7 @@ mod test { fn test_derive_generators() { let res = derive_generators("test domain".as_bytes(), 128, 0); - let is_unique = |y: Affine, j: usize| -> bool { + let is_unique = |y: Affine, j: usize| -> bool { for (i, res) in res.iter().enumerate() { if i != j && *res == y { return false; diff --git a/acvm-repo/brillig/Cargo.toml b/acvm-repo/brillig/Cargo.toml index 631acbd55d8..9f5a5ce0ee2 100644 --- a/acvm-repo/brillig/Cargo.toml +++ b/acvm-repo/brillig/Cargo.toml @@ -10,6 +10,9 @@ license.workspace = true rust-version.workspace = true repository.workspace = true +[lints] +workspace = true + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] diff --git a/acvm-repo/brillig_vm/Cargo.toml b/acvm-repo/brillig_vm/Cargo.toml index ebd35f1579f..cd9f754ebc0 100644 --- a/acvm-repo/brillig_vm/Cargo.toml +++ b/acvm-repo/brillig_vm/Cargo.toml @@ -10,6 +10,9 @@ license.workspace = true rust-version.workspace = true repository.workspace = true +[lints] +workspace = true + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] diff --git a/aztec_macros/Cargo.toml b/aztec_macros/Cargo.toml index a99a654aeed..c9d88e36e28 100644 --- a/aztec_macros/Cargo.toml +++ b/aztec_macros/Cargo.toml @@ -7,6 +7,9 @@ rust-version.workspace = true license.workspace = true repository.workspace = true +[lints] +workspace = true + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] diff --git a/aztec_macros/src/transforms/functions.rs b/aztec_macros/src/transforms/functions.rs index cd3fdd1fc62..dcd4fdc76f6 100644 --- a/aztec_macros/src/transforms/functions.rs +++ b/aztec_macros/src/transforms/functions.rs @@ -267,7 +267,7 @@ fn create_inputs(ty: &str) -> Param { let path_snippet = ty.to_case(Case::Snake); // e.g. private_context_inputs let type_path = chained_dep!("aztec", "context", "inputs", &path_snippet, ty); - let context_type = make_type(UnresolvedTypeData::Named(type_path, vec![], true)); + let context_type = make_type(UnresolvedTypeData::Named(type_path, Default::default(), true)); let visibility = Visibility::Private; Param { pattern: context_pattern, typ: context_type, visibility, span: Span::default() } @@ -396,7 +396,7 @@ fn serialize_to_hasher( Signedness::Unsigned, ast::IntegerBitSize::ThirtyTwo, ), - span: None, + span: Span::default(), }, hasher_name, )) @@ -595,7 +595,7 @@ fn abstract_return_values(func: &NoirFunction) -> Result>, serialize_to_hasher(&ident(return_value_name), ¤t_return_type, hasher_name) .ok_or_else(|| AztecMacroError::UnsupportedFunctionReturnType { typ: current_return_type.clone(), - span: func.return_type().span.unwrap_or_default(), + span: func.return_type().span, })?; replacement_statements.extend(serialization_statements); diff --git a/aztec_macros/src/transforms/note_interface.rs b/aztec_macros/src/transforms/note_interface.rs index 7f5c0e8b48b..46ed75620a7 100644 --- a/aztec_macros/src/transforms/note_interface.rs +++ b/aztec_macros/src/transforms/note_interface.rs @@ -62,8 +62,9 @@ pub fn generate_note_interface_impl( note_struct.name.0.contents )), })?; - let note_interface_impl_span: Option = - if empty_spans { None } else { trait_impl.object_type.span }; + let note_interface_impl_span = + if empty_spans { Span::default() } else { trait_impl.object_type.span }; + // Look for the note struct implementation, generate a default one if it doesn't exist (in order to append methods to it) let existing_impl = module.impls.iter_mut().find(|r#impl| match &r#impl.object_type.typ { UnresolvedTypeData::Named(path, _, _) => path.last_ident().eq(¬e_struct.name), @@ -94,7 +95,7 @@ pub fn generate_note_interface_impl( Ok(val.to_string()) } _ => Err(AztecMacroError::CouldNotImplementNoteInterface { - span: trait_impl.object_type.span, + span: Some(trait_impl.object_type.span), secondary_message: Some(format!( "NoteInterface must be generic over NOTE_LEN and NOTE_BYTES_LEN: {}", note_type @@ -231,7 +232,7 @@ fn generate_note_to_be_bytes( note_type: &String, byte_length: &str, serialized_length: &str, - impl_span: Option, + impl_span: Span, empty_spans: bool, ) -> Result { let function_source = format!( @@ -268,13 +269,13 @@ fn generate_note_to_be_bytes( dbg!(errors); return Err(AztecMacroError::CouldNotImplementNoteInterface { secondary_message: Some("Failed to parse Noir macro code (fn to_be_bytes). This is either a bug in the compiler or the Noir macro code".to_string()), - span: impl_span + span: Some(impl_span) }); } let mut function_ast = function_ast.into_sorted(); let mut noir_fn = function_ast.functions.remove(0); - noir_fn.def.span = impl_span.unwrap_or_default(); + noir_fn.def.span = impl_span; noir_fn.def.visibility = ItemVisibility::Public; Ok(noir_fn) } @@ -282,7 +283,7 @@ fn generate_note_to_be_bytes( fn generate_note_get_header( note_type: &String, note_header_field_name: &String, - impl_span: Option, + impl_span: Span, empty_spans: bool, ) -> Result { let function_source = format!( @@ -300,13 +301,13 @@ fn generate_note_get_header( dbg!(errors); return Err(AztecMacroError::CouldNotImplementNoteInterface { secondary_message: Some("Failed to parse Noir macro code (fn get_header). This is either a bug in the compiler or the Noir macro code".to_string()), - span: impl_span + span: Some(impl_span) }); } let mut function_ast = function_ast.into_sorted(); let mut noir_fn = function_ast.functions.remove(0); - noir_fn.def.span = impl_span.unwrap_or_default(); + noir_fn.def.span = impl_span; noir_fn.def.visibility = ItemVisibility::Public; Ok(noir_fn) } @@ -314,7 +315,7 @@ fn generate_note_get_header( fn generate_note_set_header( note_type: &String, note_header_field_name: &String, - impl_span: Option, + impl_span: Span, empty_spans: bool, ) -> Result { let function_source = format!( @@ -331,13 +332,13 @@ fn generate_note_set_header( dbg!(errors); return Err(AztecMacroError::CouldNotImplementNoteInterface { secondary_message: Some("Failed to parse Noir macro code (fn set_header). This is either a bug in the compiler or the Noir macro code".to_string()), - span: impl_span + span: Some(impl_span) }); } let mut function_ast = function_ast.into_sorted(); let mut noir_fn = function_ast.functions.remove(0); - noir_fn.def.span = impl_span.unwrap_or_default(); + noir_fn.def.span = impl_span; noir_fn.def.visibility = ItemVisibility::Public; Ok(noir_fn) } @@ -346,7 +347,7 @@ fn generate_note_set_header( // of the conversion of the characters in the note's struct name to unsigned integers. fn generate_get_note_type_id( note_type_id: u32, - impl_span: Option, + impl_span: Span, empty_spans: bool, ) -> Result { // TODO(#7165): replace {} with dep::aztec::protocol_types::abis::note_selector::compute_note_selector(\"{}\") in the function source below @@ -365,13 +366,13 @@ fn generate_get_note_type_id( dbg!(errors); return Err(AztecMacroError::CouldNotImplementNoteInterface { secondary_message: Some("Failed to parse Noir macro code (fn get_note_type_id). This is either a bug in the compiler or the Noir macro code".to_string()), - span: impl_span + span: Some(impl_span) }); } let mut function_ast = function_ast.into_sorted(); let mut noir_fn = function_ast.functions.remove(0); - noir_fn.def.span = impl_span.unwrap_or_default(); + noir_fn.def.span = impl_span; noir_fn.def.visibility = ItemVisibility::Public; Ok(noir_fn) } @@ -389,7 +390,7 @@ fn generate_note_properties_struct( note_type: &str, note_fields: &[(String, String)], note_header_field_name: &String, - impl_span: Option, + impl_span: Span, empty_spans: bool, ) -> Result { let struct_source = @@ -400,7 +401,7 @@ fn generate_note_properties_struct( dbg!(errors); return Err(AztecMacroError::CouldNotImplementNoteInterface { secondary_message: Some(format!("Failed to parse Noir macro code (struct {}Properties). This is either a bug in the compiler or the Noir macro code", note_type)), - span: impl_span + span: Some(impl_span) }); } @@ -423,7 +424,7 @@ fn generate_note_deserialize_content( note_fields: &[(String, String)], note_serialize_len: &String, note_header_field_name: &String, - impl_span: Option, + impl_span: Span, empty_spans: bool, ) -> Result { let function_source = generate_note_deserialize_content_source( @@ -438,13 +439,13 @@ fn generate_note_deserialize_content( dbg!(errors); return Err(AztecMacroError::CouldNotImplementNoteInterface { secondary_message: Some("Failed to parse Noir macro code (fn deserialize_content). This is either a bug in the compiler or the Noir macro code".to_string()), - span: impl_span + span: Some(impl_span) }); } let mut function_ast = function_ast.into_sorted(); let mut noir_fn = function_ast.functions.remove(0); - noir_fn.def.span = impl_span.unwrap_or_default(); + noir_fn.def.span = impl_span; noir_fn.def.visibility = ItemVisibility::Public; Ok(noir_fn) } @@ -461,7 +462,7 @@ fn generate_note_serialize_content( note_fields: &[(String, String)], note_serialize_len: &String, note_header_field_name: &String, - impl_span: Option, + impl_span: Span, empty_spans: bool, ) -> Result { let function_source = generate_note_serialize_content_source( @@ -476,13 +477,13 @@ fn generate_note_serialize_content( dbg!(errors); return Err(AztecMacroError::CouldNotImplementNoteInterface { secondary_message: Some("Failed to parse Noir macro code (fn serialize_content). This is either a bug in the compiler or the Noir macro code".to_string()), - span: impl_span + span: Some(impl_span) }); } let mut function_ast = function_ast.into_sorted(); let mut noir_fn = function_ast.functions.remove(0); - noir_fn.def.span = impl_span.unwrap_or_default(); + noir_fn.def.span = impl_span; noir_fn.def.visibility = ItemVisibility::Public; Ok(noir_fn) } @@ -492,7 +493,7 @@ fn generate_note_properties_fn( note_type: &str, note_fields: &[(String, String)], note_header_field_name: &String, - impl_span: Option, + impl_span: Span, empty_spans: bool, ) -> Result { let function_source = @@ -502,12 +503,12 @@ fn generate_note_properties_fn( dbg!(errors); return Err(AztecMacroError::CouldNotImplementNoteInterface { secondary_message: Some("Failed to parse Noir macro code (fn properties). This is either a bug in the compiler or the Noir macro code".to_string()), - span: impl_span + span: Some(impl_span) }); } let mut function_ast = function_ast.into_sorted(); let mut noir_fn = function_ast.functions.remove(0); - noir_fn.def.span = impl_span.unwrap_or_default(); + noir_fn.def.span = impl_span; noir_fn.def.visibility = ItemVisibility::Public; Ok(noir_fn) } @@ -519,7 +520,7 @@ fn generate_note_properties_fn( // fn generate_compute_note_hiding_point( note_type: &String, - impl_span: Option, + impl_span: Span, empty_spans: bool, ) -> Result { // TODO(#7771): update this to do only 1 MSM call @@ -541,12 +542,12 @@ fn generate_compute_note_hiding_point( dbg!(errors); return Err(AztecMacroError::CouldNotImplementNoteInterface { secondary_message: Some("Failed to parse Noir macro code (fn compute_note_hiding_point). This is either a bug in the compiler or the Noir macro code".to_string()), - span: impl_span + span: Some(impl_span) }); } let mut function_ast = function_ast.into_sorted(); let mut noir_fn = function_ast.functions.remove(0); - noir_fn.def.span = impl_span.unwrap_or_default(); + noir_fn.def.span = impl_span; noir_fn.def.visibility = ItemVisibility::Public; Ok(noir_fn) } diff --git a/aztec_macros/src/transforms/storage.rs b/aztec_macros/src/transforms/storage.rs index dacea1a95e3..ce82b4d4b6d 100644 --- a/aztec_macros/src/transforms/storage.rs +++ b/aztec_macros/src/transforms/storage.rs @@ -238,7 +238,7 @@ pub fn generate_storage_implementation( vec![generic_context_type.clone()], true, ), - span: Some(Span::default()), + span: Span::default(), }, type_span: Span::default(), generics: vec![generic_context_ident.into()], diff --git a/aztec_macros/src/utils/ast_utils.rs b/aztec_macros/src/utils/ast_utils.rs index a74ec5b777a..955e4111bb3 100644 --- a/aztec_macros/src/utils/ast_utils.rs +++ b/aztec_macros/src/utils/ast_utils.rs @@ -108,17 +108,14 @@ pub fn assignment_with_type( } pub fn return_type(path: Path) -> FunctionReturnType { - let ty = make_type(UnresolvedTypeData::Named(path, vec![], true)); + let ty = make_type(UnresolvedTypeData::Named(path, Default::default(), true)); FunctionReturnType::Ty(ty) } pub fn lambda(parameters: Vec<(Pattern, UnresolvedType)>, body: Expression) -> Expression { expression(ExpressionKind::Lambda(Box::new(Lambda { parameters, - return_type: UnresolvedType { - typ: UnresolvedTypeData::Unspecified, - span: Some(Span::default()), - }, + return_type: UnresolvedType { typ: UnresolvedTypeData::Unspecified, span: Span::default() }, body, }))) } @@ -179,7 +176,7 @@ pub fn cast(lhs: Expression, ty: UnresolvedTypeData) -> Expression { } pub fn make_type(typ: UnresolvedTypeData) -> UnresolvedType { - UnresolvedType { typ, span: Some(Span::default()) } + UnresolvedType { typ, span: Span::default() } } pub fn index_array(array: Ident, index: &str) -> Expression { diff --git a/aztec_macros/src/utils/parse_utils.rs b/aztec_macros/src/utils/parse_utils.rs index 3b3813da6ee..6b5db103c0b 100644 --- a/aztec_macros/src/utils/parse_utils.rs +++ b/aztec_macros/src/utils/parse_utils.rs @@ -267,6 +267,9 @@ fn empty_expression(expression: &mut Expression) { ExpressionKind::Comptime(block_expression, _span) => { empty_block_expression(block_expression); } + ExpressionKind::Unsafe(block_expression, _span) => { + empty_block_expression(block_expression); + } ExpressionKind::Quote(..) | ExpressionKind::Resolved(_) | ExpressionKind::Error => (), ExpressionKind::AsTraitPath(path) => { empty_unresolved_type(&mut path.typ); @@ -325,7 +328,7 @@ fn empty_unresolved_type(unresolved_type: &mut UnresolvedType) { empty_unresolved_type(unresolved_type) } UnresolvedTypeData::Tuple(unresolved_types) => empty_unresolved_types(unresolved_types), - UnresolvedTypeData::Function(args, ret, _env) => { + UnresolvedTypeData::Function(args, ret, _env, _) => { empty_unresolved_types(args); empty_unresolved_type(ret); } diff --git a/compiler/fm/Cargo.toml b/compiler/fm/Cargo.toml index b48f445be36..c367333a6f4 100644 --- a/compiler/fm/Cargo.toml +++ b/compiler/fm/Cargo.toml @@ -6,6 +6,9 @@ edition.workspace = true rust-version.workspace = true license.workspace = true +[lints] +workspace = true + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] diff --git a/compiler/noirc_arena/Cargo.toml b/compiler/noirc_arena/Cargo.toml index b94f997b7b9..68fc4d1c920 100644 --- a/compiler/noirc_arena/Cargo.toml +++ b/compiler/noirc_arena/Cargo.toml @@ -5,3 +5,6 @@ authors.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true + +[lints] +workspace = true \ No newline at end of file diff --git a/compiler/noirc_driver/Cargo.toml b/compiler/noirc_driver/Cargo.toml index a9949f5093a..b244018cc71 100644 --- a/compiler/noirc_driver/Cargo.toml +++ b/compiler/noirc_driver/Cargo.toml @@ -6,6 +6,9 @@ edition.workspace = true rust-version.workspace = true license.workspace = true +[lints] +workspace = true + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [build-dependencies] diff --git a/compiler/noirc_driver/src/abi_gen.rs b/compiler/noirc_driver/src/abi_gen.rs index 87181b285de..e2692349baa 100644 --- a/compiler/noirc_driver/src/abi_gen.rs +++ b/compiler/noirc_driver/src/abi_gen.rs @@ -107,7 +107,7 @@ pub(super) fn abi_type_from_hir_type(context: &Context, typ: &Type) -> AbiType { | Type::Forall(..) | Type::Quoted(_) | Type::Slice(_) - | Type::Function(_, _, _) => unreachable!("{typ} cannot be used in the abi"), + | Type::Function(_, _, _, _) => unreachable!("{typ} cannot be used in the abi"), Type::FmtString(_, _) => unreachable!("format strings cannot be used in the abi"), Type::MutableReference(_) => unreachable!("&mut cannot be used in the abi"), } diff --git a/compiler/noirc_driver/src/lib.rs b/compiler/noirc_driver/src/lib.rs index 72c95823553..467bda2ca88 100644 --- a/compiler/noirc_driver/src/lib.rs +++ b/compiler/noirc_driver/src/lib.rs @@ -274,11 +274,8 @@ pub fn check_crate( crate_id: CrateId, options: &CompileOptions, ) -> CompilationResult<()> { - let macros: &[&dyn MacroProcessor] = if options.disable_macros { - &[] - } else { - &[&aztec_macros::AztecMacro as &dyn MacroProcessor] - }; + let macros: &[&dyn MacroProcessor] = + if options.disable_macros { &[] } else { &[&aztec_macros::AztecMacro] }; let mut errors = vec![]; let diagnostics = CrateDefMap::collect_defs( @@ -557,6 +554,7 @@ pub fn compile_no_check( let force_compile = force_compile || options.print_acir || options.show_brillig + || options.force_brillig || options.show_ssa || options.emit_ssa; @@ -578,7 +576,7 @@ pub fn compile_no_check( emit_ssa: if options.emit_ssa { Some(context.package_build_path.clone()) } else { None }, }; - let SsaProgramArtifact { program, debug, warnings, names, error_types, .. } = + let SsaProgramArtifact { program, debug, warnings, names, brillig_names, error_types, .. } = create_program(program, &ssa_evaluator_options)?; let abi = abi_gen::gen_abi(context, &main_function, return_visibility, error_types); @@ -593,5 +591,6 @@ pub fn compile_no_check( noir_version: NOIR_ARTIFACT_VERSION_STRING.to_string(), warnings, names, + brillig_names, }) } diff --git a/compiler/noirc_driver/src/program.rs b/compiler/noirc_driver/src/program.rs index 8e02de0b8b3..88460482928 100644 --- a/compiler/noirc_driver/src/program.rs +++ b/compiler/noirc_driver/src/program.rs @@ -29,4 +29,6 @@ pub struct CompiledProgram { pub warnings: Vec, /// Names of the functions in the program. These are used for more informative debugging and benchmarking. pub names: Vec, + /// Names of the unconstrained functions in the program. + pub brillig_names: Vec, } diff --git a/compiler/noirc_errors/Cargo.toml b/compiler/noirc_errors/Cargo.toml index 41b1cd0ff58..61b274c605f 100644 --- a/compiler/noirc_errors/Cargo.toml +++ b/compiler/noirc_errors/Cargo.toml @@ -6,6 +6,9 @@ edition.workspace = true rust-version.workspace = true license.workspace = true +[lints] +workspace = true + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] diff --git a/compiler/noirc_errors/src/position.rs b/compiler/noirc_errors/src/position.rs index 02b242e8b4d..1792197eab7 100644 --- a/compiler/noirc_errors/src/position.rs +++ b/compiler/noirc_errors/src/position.rs @@ -16,7 +16,7 @@ pub struct Spanned { /// This is important for tests. Two Spanned objects are equal if their content is equal /// They may not have the same span. Use into_span to test for Span being equal specifically -impl PartialEq> for Spanned { +impl PartialEq> for Spanned { fn eq(&self, other: &Spanned) -> bool { self.contents == other.contents } diff --git a/compiler/noirc_evaluator/Cargo.toml b/compiler/noirc_evaluator/Cargo.toml index 66c770b5064..81feb0b7154 100644 --- a/compiler/noirc_evaluator/Cargo.toml +++ b/compiler/noirc_evaluator/Cargo.toml @@ -6,6 +6,9 @@ edition.workspace = true rust-version.workspace = true license.workspace = true +[lints] +workspace = true + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] diff --git a/compiler/noirc_evaluator/src/brillig/brillig_gen.rs b/compiler/noirc_evaluator/src/brillig/brillig_gen.rs index ee61a9d13d3..b256c2b85ab 100644 --- a/compiler/noirc_evaluator/src/brillig/brillig_gen.rs +++ b/compiler/noirc_evaluator/src/brillig/brillig_gen.rs @@ -9,7 +9,10 @@ mod variable_liveness; use acvm::FieldElement; use self::{brillig_block::BrilligBlock, brillig_fn::FunctionContext}; -use super::brillig_ir::{artifact::BrilligArtifact, BrilligContext}; +use super::brillig_ir::{ + artifact::{BrilligArtifact, Label}, + BrilligContext, +}; use crate::ssa::ir::function::Function; /// Converting an SSA function into Brillig bytecode. @@ -21,11 +24,13 @@ pub(crate) fn convert_ssa_function( let mut function_context = FunctionContext::new(func); - brillig_context.enter_context(FunctionContext::function_id_to_function_label(func.id())); + brillig_context.enter_context(Label::function(func.id())); for block in function_context.blocks.clone() { BrilligBlock::compile(&mut function_context, &mut brillig_context, block, &func.dfg); } - brillig_context.artifact() + let mut artifact = brillig_context.artifact(); + artifact.name = func.name().to_string(); + artifact } diff --git a/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_black_box.rs b/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_black_box.rs index 8e2b2fb7a29..802d442885f 100644 --- a/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_black_box.rs +++ b/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_black_box.rs @@ -6,14 +6,15 @@ use acvm::{ use crate::brillig::brillig_ir::{ brillig_variable::{BrilligVariable, BrilligVector, SingleAddrVariable}, debug_show::DebugToString, + registers::RegisterAllocator, BrilligContext, }; /// Transforms SSA's black box function calls into the corresponding brillig instructions /// Extracting arguments and results from the SSA function call /// And making any necessary type conversions to adapt noir's blackbox calls to brillig's -pub(crate) fn convert_black_box_call( - brillig_context: &mut BrilligContext, +pub(crate) fn convert_black_box_call( + brillig_context: &mut BrilligContext, bb_func: &BlackBoxFunc, function_arguments: &[BrilligVariable], function_results: &[BrilligVariable], @@ -397,8 +398,8 @@ pub(crate) fn convert_black_box_call( } } -fn convert_array_or_vector( - brillig_context: &mut BrilligContext, +fn convert_array_or_vector( + brillig_context: &mut BrilligContext, array_or_vector: &BrilligVariable, bb_func: &BlackBoxFunc, ) -> BrilligVector { diff --git a/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block.rs b/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block.rs index 76ab613ed1f..74fdbfcdce6 100644 --- a/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block.rs +++ b/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block.rs @@ -1,8 +1,10 @@ +use crate::brillig::brillig_ir::artifact::Label; use crate::brillig::brillig_ir::brillig_variable::{ type_to_heap_value_type, BrilligArray, BrilligVariable, BrilligVector, SingleAddrVariable, }; +use crate::brillig::brillig_ir::registers::Stack; use crate::brillig::brillig_ir::{ - BrilligBinaryOp, BrilligContext, BRILLIG_MEMORY_ADDRESSING_BIT_SIZE, + BrilligBinaryOp, BrilligContext, ReservedRegisters, BRILLIG_MEMORY_ADDRESSING_BIT_SIZE, }; use crate::ssa::ir::dfg::CallStack; use crate::ssa::ir::instruction::ConstrainError; @@ -34,7 +36,7 @@ pub(crate) struct BrilligBlock<'block> { /// The basic block that is being converted pub(crate) block_id: BasicBlockId, /// Context for creating brillig opcodes - pub(crate) brillig_context: &'block mut BrilligContext, + pub(crate) brillig_context: &'block mut BrilligContext, /// Tracks the available variable during the codegen of the block pub(crate) variables: BlockVariables, /// For each instruction, the set of values that are not used anymore after it. @@ -45,7 +47,7 @@ impl<'block> BrilligBlock<'block> { /// Converts an SSA Basic block into a sequence of Brillig opcodes pub(crate) fn compile( function_context: &'block mut FunctionContext, - brillig_context: &'block mut BrilligContext, + brillig_context: &'block mut BrilligContext, block_id: BasicBlockId, dfg: &DataFlowGraph, ) { @@ -93,7 +95,7 @@ impl<'block> BrilligBlock<'block> { /// This uses the current functions's function ID and the block ID /// Making the assumption that the block ID passed in belongs to this /// function. - fn create_block_label_for_current_function(&self, block_id: BasicBlockId) -> String { + fn create_block_label_for_current_function(&self, block_id: BasicBlockId) -> Label { Self::create_block_label(self.function_context.function_id, block_id) } /// Creates a unique label for a block using the function Id and the block ID. @@ -102,8 +104,8 @@ impl<'block> BrilligBlock<'block> { /// for us to create a unique label across functions and blocks. /// /// This is so that during linking there are no duplicates or labels being overwritten. - fn create_block_label(function_id: FunctionId, block_id: BasicBlockId) -> String { - format!("{function_id}-{block_id}") + fn create_block_label(function_id: FunctionId, block_id: BasicBlockId) -> Label { + Label::block(function_id, block_id) } /// Converts an SSA terminator instruction into the necessary opcodes. @@ -468,13 +470,21 @@ impl<'block> BrilligBlock<'block> { result_ids[1], dfg, ); - let source_size_as_register = - self.convert_ssa_array_set(source_variable, destination_variable, None); - // we need to explicitly set the destination_len_variable self.brillig_context - .mov_instruction(destination_len_variable.address, source_size_as_register); - self.brillig_context.deallocate_register(source_size_as_register); + .call_array_copy_procedure(source_variable, destination_variable); + + let BrilligVariable::BrilligArray(BrilligArray { size: source_size, .. }) = + source_variable + else { + unreachable!("ICE: AsSlice on non-array") + }; + + // we need to explicitly set the destination_len_variable + self.brillig_context.usize_const_instruction( + destination_len_variable.address, + source_size.into(), + ); } Value::Intrinsic( Intrinsic::SlicePushBack @@ -660,12 +670,12 @@ impl<'block> BrilligBlock<'block> { dfg, ); self.validate_array_index(source_variable, index_register); - let source_size_as_register = self.convert_ssa_array_set( + self.convert_ssa_array_set( source_variable, destination_variable, - Some((index_register.address, value_variable)), + index_register, + value_variable, ); - self.brillig_context.deallocate_register(source_size_as_register); } Instruction::RangeCheck { value, max_bit_size, assert_message } => { let value = self.convert_ssa_single_addr_value(*value, dfg); @@ -761,9 +771,6 @@ impl<'block> BrilligBlock<'block> { .flat_map(|argument_id| self.convert_ssa_value(*argument_id, dfg).extract_registers()) .collect(); - // Create label for the function that will be called - let label_of_function_to_call = FunctionContext::function_id_to_function_label(func_id); - let variables_to_save = self.variables.get_available_variables(self.function_context); let saved_registers = self @@ -774,7 +781,7 @@ impl<'block> BrilligBlock<'block> { self.variables.dump_constants(); // Call instruction, which will interpret above registers 0..num args - self.brillig_context.add_external_call_instruction(label_of_function_to_call); + self.brillig_context.add_external_call_instruction(func_id); // Important: resolve after pre_call_save_registers_prep_args // This ensures we don't save the results to registers unnecessarily. @@ -870,88 +877,23 @@ impl<'block> BrilligBlock<'block> { &mut self, source_variable: BrilligVariable, destination_variable: BrilligVariable, - opt_index_and_value: Option<(MemoryAddress, BrilligVariable)>, - ) -> MemoryAddress { + index_register: SingleAddrVariable, + value_variable: BrilligVariable, + ) { + assert!(index_register.bit_size == BRILLIG_MEMORY_ADDRESSING_BIT_SIZE); let destination_pointer = match destination_variable { BrilligVariable::BrilligArray(BrilligArray { pointer, .. }) => pointer, BrilligVariable::BrilligVector(BrilligVector { pointer, .. }) => pointer, _ => unreachable!("ICE: array_set SSA returns non-array"), }; - let reference_count = match source_variable { - BrilligVariable::BrilligArray(BrilligArray { rc, .. }) - | BrilligVariable::BrilligVector(BrilligVector { rc, .. }) => rc, - _ => unreachable!("ICE: array_set SSA on non-array"), - }; - - let (source_pointer, source_size_as_register) = match source_variable { - BrilligVariable::BrilligArray(BrilligArray { size, pointer, rc: _ }) => { - let source_size_register = self.brillig_context.allocate_register(); - self.brillig_context.usize_const_instruction(source_size_register, size.into()); - (pointer, source_size_register) - } - BrilligVariable::BrilligVector(BrilligVector { size, pointer, rc: _ }) => { - let source_size_register = self.brillig_context.allocate_register(); - self.brillig_context.mov_instruction(source_size_register, size); - (pointer, source_size_register) - } - _ => unreachable!("ICE: array_set SSA on non-array"), - }; - - // Here we want to compare the reference count against 1. - let one = self.brillig_context.make_usize_constant_instruction(1_usize.into()); - let condition = self.brillig_context.allocate_register(); - self.brillig_context.memory_op_instruction( - reference_count, - one.address, - condition, - BrilligBinaryOp::Equals, + self.brillig_context.call_array_copy_procedure(source_variable, destination_variable); + // Then set the value in the newly created array + self.brillig_context.codegen_store_variable_in_array( + destination_pointer, + index_register, + value_variable, ); - self.brillig_context.codegen_branch(condition, |ctx, cond| { - if cond { - // Reference count is 1, we can mutate the array directly - ctx.mov_instruction(destination_pointer, source_pointer); - } else { - // First issue a array copy to the destination - ctx.codegen_allocate_array(destination_pointer, source_size_as_register); - - ctx.codegen_copy_array( - source_pointer, - destination_pointer, - SingleAddrVariable::new( - source_size_as_register, - BRILLIG_MEMORY_ADDRESSING_BIT_SIZE, - ), - ); - } - }); - - match destination_variable { - BrilligVariable::BrilligArray(BrilligArray { rc: target_rc, .. }) => { - self.brillig_context.usize_const_instruction(target_rc, 1_usize.into()); - } - BrilligVariable::BrilligVector(BrilligVector { - size: target_size, - rc: target_rc, - .. - }) => { - self.brillig_context.mov_instruction(target_size, source_size_as_register); - self.brillig_context.usize_const_instruction(target_rc, 1_usize.into()); - } - _ => unreachable!("ICE: array_set SSA on non-array"), - } - - if let Some((index_register, value_variable)) = opt_index_and_value { - // Then set the value in the newly created array - self.brillig_context.codegen_store_variable_in_array( - destination_pointer, - SingleAddrVariable::new_usize(index_register), - value_variable, - ); - } - - self.brillig_context.deallocate_register(condition); - source_size_as_register } /// Convert the SSA slice operations to brillig slice operations @@ -1733,11 +1675,9 @@ impl<'block> BrilligBlock<'block> { let subitem_pointer = SingleAddrVariable::new_usize(self.brillig_context.allocate_register()); - let one = self.brillig_context.make_usize_constant_instruction(1_usize.into()); - // Initializes a single subitem let initializer_fn = - |ctx: &mut BrilligContext<_>, subitem_start_pointer: SingleAddrVariable| { + |ctx: &mut BrilligContext<_, _>, subitem_start_pointer: SingleAddrVariable| { ctx.mov_instruction(subitem_pointer.address, subitem_start_pointer.address); for (subitem_index, subitem) in subitem_to_repeat_variables.into_iter().enumerate() @@ -1746,7 +1686,7 @@ impl<'block> BrilligBlock<'block> { if subitem_index != item_types.len() - 1 { ctx.memory_op_instruction( subitem_pointer.address, - one.address, + ReservedRegisters::usize_one(), subitem_pointer.address, BrilligBinaryOp::Add, ); @@ -1764,13 +1704,13 @@ impl<'block> BrilligBlock<'block> { self.brillig_context.deallocate_single_addr(step_variable); self.brillig_context.deallocate_single_addr(subitem_pointer); - self.brillig_context.deallocate_single_addr(one); } else { let subitem = subitem_to_repeat_variables.into_iter().next().unwrap(); - let initializer_fn = |ctx: &mut BrilligContext<_>, item_pointer: SingleAddrVariable| { - ctx.codegen_store_variable_in_pointer(item_pointer.address, subitem); - }; + let initializer_fn = + |ctx: &mut BrilligContext<_, _>, item_pointer: SingleAddrVariable| { + ctx.codegen_store_variable_in_pointer(item_pointer.address, subitem); + }; // for (let item_pointer = pointer; item_pointer < pointer + data_length; item_pointer += 1) { initializer_fn(iterator) } self.brillig_context.codegen_for_loop( @@ -1791,7 +1731,6 @@ impl<'block> BrilligBlock<'block> { ) { // Allocate a register for the iterator let write_pointer_register = self.brillig_context.allocate_register(); - let one = self.brillig_context.make_usize_constant_instruction(1_usize.into()); self.brillig_context.mov_instruction(write_pointer_register, pointer); @@ -1804,7 +1743,7 @@ impl<'block> BrilligBlock<'block> { // Increment the write_pointer_register self.brillig_context.memory_op_instruction( write_pointer_register, - one.address, + ReservedRegisters::usize_one(), write_pointer_register, BrilligBinaryOp::Add, ); @@ -1812,7 +1751,6 @@ impl<'block> BrilligBlock<'block> { } self.brillig_context.deallocate_register(write_pointer_register); - self.brillig_context.deallocate_single_addr(one); } /// Converts an SSA `ValueId` into a `MemoryAddress`. Initializes if necessary. diff --git a/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block_variables.rs b/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block_variables.rs index ffbca256d28..63b2073c654 100644 --- a/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block_variables.rs +++ b/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block_variables.rs @@ -7,6 +7,7 @@ use crate::{ get_bit_size_from_ssa_type, BrilligArray, BrilligVariable, BrilligVector, SingleAddrVariable, }, + registers::{RegisterAllocator, Stack}, BrilligContext, }, ssa::ir::{ @@ -51,7 +52,7 @@ impl BlockVariables { pub(crate) fn define_variable( &mut self, function_context: &mut FunctionContext, - brillig_context: &mut BrilligContext, + brillig_context: &mut BrilligContext, value_id: ValueId, dfg: &DataFlowGraph, ) -> BrilligVariable { @@ -71,7 +72,7 @@ impl BlockVariables { pub(crate) fn define_single_addr_variable( &mut self, function_context: &mut FunctionContext, - brillig_context: &mut BrilligContext, + brillig_context: &mut BrilligContext, value: ValueId, dfg: &DataFlowGraph, ) -> SingleAddrVariable { @@ -84,7 +85,7 @@ impl BlockVariables { &mut self, value_id: &ValueId, function_context: &mut FunctionContext, - brillig_context: &mut BrilligContext, + brillig_context: &mut BrilligContext, ) { assert!(self.available_variables.remove(value_id), "ICE: Variable is not available"); let variable = function_context @@ -123,7 +124,7 @@ impl BlockVariables { /// We keep constants block-local. pub(crate) fn allocate_constant( &mut self, - brillig_context: &mut BrilligContext, + brillig_context: &mut BrilligContext, value_id: ValueId, dfg: &DataFlowGraph, ) -> BrilligVariable { @@ -155,9 +156,9 @@ pub(crate) fn compute_array_length(item_typ: &CompositeType, elem_count: usize) } /// For a given value_id, allocates the necessary registers to hold it. -pub(crate) fn allocate_value( +pub(crate) fn allocate_value( value_id: ValueId, - brillig_context: &mut BrilligContext, + brillig_context: &mut BrilligContext, dfg: &DataFlowGraph, ) -> BrilligVariable { let typ = dfg.type_of_value(value_id); diff --git a/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_directive.rs b/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_directive.rs index dff4da56c1e..fca1f60544d 100644 --- a/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_directive.rs +++ b/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_directive.rs @@ -55,6 +55,7 @@ pub(crate) fn directive_invert() -> GeneratedBrillig { ], assert_messages: Default::default(), locations: Default::default(), + name: "directive_invert".to_string(), } } @@ -109,5 +110,6 @@ pub(crate) fn directive_quotient() -> GeneratedBrillig { ], assert_messages: Default::default(), locations: Default::default(), + name: "directive_integer_quotient".to_string(), } } diff --git a/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_fn.rs b/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_fn.rs index f0752c80c46..c1abad17a8f 100644 --- a/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_fn.rs +++ b/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_fn.rs @@ -2,7 +2,7 @@ use iter_extended::vecmap; use crate::{ brillig::brillig_ir::{ - artifact::{BrilligParameter, Label}, + artifact::BrilligParameter, brillig_variable::{get_bit_size_from_ssa_type, BrilligVariable}, }, ssa::ir::{ @@ -44,11 +44,6 @@ impl FunctionContext { } } - /// Creates a function label from a given SSA function id. - pub(crate) fn function_id_to_function_label(function_id: FunctionId) -> Label { - function_id.to_string() - } - pub(crate) fn ssa_type_to_parameter(typ: &Type) -> BrilligParameter { match typ { Type::Numeric(_) | Type::Reference(_) => { diff --git a/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_slice_ops.rs b/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_slice_ops.rs index 55679432b1f..9dbf0ee9bb6 100644 --- a/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_slice_ops.rs +++ b/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_slice_ops.rs @@ -24,7 +24,7 @@ impl<'block> BrilligBlock<'block> { self.brillig_context.usize_const_instruction(target_vector.rc, 1_usize.into()); // Now we copy the source vector into the target vector - self.brillig_context.codegen_copy_array( + self.brillig_context.codegen_mem_copy( source_vector.pointer, target_vector.pointer, SingleAddrVariable::new_usize(source_vector.size), @@ -74,7 +74,7 @@ impl<'block> BrilligBlock<'block> { ); // Now we copy the source vector into the target vector starting at index variables_to_insert.len() - self.brillig_context.codegen_copy_array( + self.brillig_context.codegen_mem_copy( source_vector.pointer, destination_copy_pointer, SingleAddrVariable::new_usize(source_vector.size), @@ -121,7 +121,7 @@ impl<'block> BrilligBlock<'block> { ); // Now we copy the source vector starting at index removed_items.len() into the target vector - self.brillig_context.codegen_copy_array( + self.brillig_context.codegen_mem_copy( source_copy_pointer, target_vector.pointer, SingleAddrVariable::new_usize(target_vector.size), @@ -154,7 +154,7 @@ impl<'block> BrilligBlock<'block> { self.brillig_context.usize_const_instruction(target_vector.rc, 1_usize.into()); // Now we copy all elements except the last items into the target vector - self.brillig_context.codegen_copy_array( + self.brillig_context.codegen_mem_copy( source_vector.pointer, target_vector.pointer, SingleAddrVariable::new_usize(target_vector.size), @@ -192,11 +192,7 @@ impl<'block> BrilligBlock<'block> { self.brillig_context.usize_const_instruction(target_vector.rc, 1_usize.into()); // Copy the elements to the left of the index - self.brillig_context.codegen_copy_array( - source_vector.pointer, - target_vector.pointer, - index, - ); + self.brillig_context.codegen_mem_copy(source_vector.pointer, target_vector.pointer, index); // Compute the source pointer just at the index let source_pointer_at_index = self.brillig_context.allocate_register(); @@ -231,7 +227,7 @@ impl<'block> BrilligBlock<'block> { ); // Copy the elements to the right of the index - self.brillig_context.codegen_copy_array( + self.brillig_context.codegen_mem_copy( source_pointer_at_index, target_pointer_after_index, SingleAddrVariable::new_usize(item_count), @@ -279,11 +275,7 @@ impl<'block> BrilligBlock<'block> { self.brillig_context.usize_const_instruction(target_vector.rc, 1_usize.into()); // Copy the elements to the left of the index - self.brillig_context.codegen_copy_array( - source_vector.pointer, - target_vector.pointer, - index, - ); + self.brillig_context.codegen_mem_copy(source_vector.pointer, target_vector.pointer, index); // Compute the source pointer after the removed items let source_pointer_after_index = self.brillig_context.allocate_register(); @@ -323,7 +315,7 @@ impl<'block> BrilligBlock<'block> { ); // Copy the elements to the right of the index - self.brillig_context.codegen_copy_array( + self.brillig_context.codegen_mem_copy( source_pointer_after_index, target_pointer_at_index, SingleAddrVariable::new_usize(item_count), @@ -371,10 +363,11 @@ mod tests { use crate::brillig::brillig_gen::brillig_block::BrilligBlock; use crate::brillig::brillig_gen::brillig_block_variables::BlockVariables; use crate::brillig::brillig_gen::brillig_fn::FunctionContext; - use crate::brillig::brillig_ir::artifact::BrilligParameter; + use crate::brillig::brillig_ir::artifact::{BrilligParameter, Label}; use crate::brillig::brillig_ir::brillig_variable::{ BrilligArray, BrilligVariable, BrilligVector, SingleAddrVariable, }; + use crate::brillig::brillig_ir::registers::Stack; use crate::brillig::brillig_ir::tests::{ create_and_run_vm, create_context, create_entry_point_bytecode, }; @@ -384,12 +377,14 @@ mod tests { use crate::ssa::ir::map::Id; use crate::ssa::ssa_gen::Ssa; - fn create_test_environment() -> (Ssa, FunctionContext, BrilligContext) { + fn create_test_environment() -> (Ssa, FunctionContext, BrilligContext) { let mut builder = FunctionBuilder::new("main".to_string(), Id::test_new(0)); builder.set_runtime(RuntimeType::Brillig); let ssa = builder.finish(); - let brillig_context = create_context(); + let mut brillig_context = create_context(ssa.main_id); + brillig_context.enter_context(Label::block(ssa.main_id, Id::test_new(0))); + brillig_context.disable_procedures(); let function_context = FunctionContext::new(ssa.main()); (ssa, function_context, brillig_context) @@ -397,7 +392,7 @@ mod tests { fn create_brillig_block<'a>( function_context: &'a mut FunctionContext, - brillig_context: &'a mut BrilligContext, + brillig_context: &'a mut BrilligContext, ) -> BrilligBlock<'a> { let variables = BlockVariables::default(); BrilligBlock { diff --git a/compiler/noirc_evaluator/src/brillig/brillig_ir.rs b/compiler/noirc_evaluator/src/brillig/brillig_ir.rs index 21f8722c116..05117b96c5d 100644 --- a/compiler/noirc_evaluator/src/brillig/brillig_ir.rs +++ b/compiler/noirc_evaluator/src/brillig/brillig_ir.rs @@ -12,6 +12,7 @@ pub(crate) mod artifact; pub(crate) mod brillig_variable; pub(crate) mod debug_show; +pub(crate) mod procedures; pub(crate) mod registers; mod codegen_binary; @@ -23,11 +24,11 @@ mod codegen_stack; mod entry_point; mod instructions; +use artifact::Label; pub(crate) use instructions::BrilligBinaryOp; +use registers::{RegisterAllocator, ScratchSpace}; -use self::{ - artifact::BrilligArtifact, debug_show::DebugToString, registers::BrilligRegistersContext, -}; +use self::{artifact::BrilligArtifact, debug_show::DebugToString, registers::Stack}; use crate::ssa::ir::dfg::CallStack; use acvm::{ acir::brillig::{MemoryAddress, Opcode as BrilligOpcode}, @@ -46,6 +47,8 @@ pub(crate) enum ReservedRegisters { FreeMemoryPointer = 0, /// This register stores the previous stack pointer. The registers of the caller are stored here. PreviousStackPointer = 1, + /// This register stores a 1_usize constant. + UsizeOne = 2, } impl ReservedRegisters { @@ -53,7 +56,7 @@ impl ReservedRegisters { /// /// This is used to offset the general registers /// which should not overwrite the special register - const NUM_RESERVED_REGISTERS: usize = 2; + const NUM_RESERVED_REGISTERS: usize = 3; /// Returns the length of the reserved registers pub(crate) fn len() -> usize { @@ -70,42 +73,67 @@ impl ReservedRegisters { MemoryAddress::from(ReservedRegisters::PreviousStackPointer as usize) } - /// Returns a user defined (non-reserved) register index. - fn user_register_index(index: usize) -> MemoryAddress { - MemoryAddress::from(index + ReservedRegisters::len()) + /// Returns the usize one register. This will be used to perform arithmetic operations. + pub(crate) fn usize_one() -> MemoryAddress { + MemoryAddress::from(ReservedRegisters::UsizeOne as usize) } } /// Brillig context object that is used while constructing the /// Brillig bytecode. -pub(crate) struct BrilligContext { +pub(crate) struct BrilligContext { obj: BrilligArtifact, /// Tracks register allocations - registers: BrilligRegistersContext, + registers: Registers, /// Context label, must be unique with respect to the function /// being linked. - context_label: String, + context_label: Label, /// Section label, used to separate sections of code - section_label: usize, + current_section: usize, /// Stores the next available section next_section: usize, /// IR printer debug_show: DebugShow, + /// Whether this context can call procedures or not. + /// This is used to prevent a procedure from calling another procedure. + can_call_procedures: bool, } -impl BrilligContext { - /// Initial context state - pub(crate) fn new(enable_debug_trace: bool) -> BrilligContext { +/// Regular brillig context to codegen user defined functions +impl BrilligContext { + pub(crate) fn new(enable_debug_trace: bool) -> BrilligContext { BrilligContext { obj: BrilligArtifact::default(), - registers: BrilligRegistersContext::new(), - context_label: String::default(), - section_label: 0, + registers: Stack::new(), + context_label: Label::entrypoint(), + current_section: 0, next_section: 1, debug_show: DebugShow::new(enable_debug_trace), + can_call_procedures: true, } } + /// Allows disabling procedures so tests don't need a linking pass + pub(crate) fn disable_procedures(&mut self) { + self.can_call_procedures = false; + } +} + +/// Special brillig context to codegen compiler intrinsic shared procedures +impl BrilligContext { + pub(crate) fn new_for_procedure(enable_debug_trace: bool) -> BrilligContext { + BrilligContext { + obj: BrilligArtifact::default(), + registers: ScratchSpace::new(), + context_label: Label::entrypoint(), + current_section: 0, + next_section: 1, + debug_show: DebugShow::new(enable_debug_trace), + can_call_procedures: false, + } + } +} +impl BrilligContext { /// Adds a brillig instruction to the brillig byte code fn push_opcode(&mut self, opcode: BrilligOpcode) { self.obj.push_opcode(opcode); @@ -135,8 +163,10 @@ pub(crate) mod tests { use acvm::{BlackBoxFunctionSolver, BlackBoxResolutionError, FieldElement}; use crate::brillig::brillig_ir::{BrilligBinaryOp, BrilligContext}; + use crate::ssa::ir::function::FunctionId; - use super::artifact::{BrilligParameter, GeneratedBrillig}; + use super::artifact::{BrilligParameter, GeneratedBrillig, Label}; + use super::registers::Stack; use super::{BrilligOpcode, ReservedRegisters}; pub(crate) struct DummyBlackBoxSolver; @@ -195,20 +225,20 @@ pub(crate) mod tests { } } - pub(crate) fn create_context() -> BrilligContext { + pub(crate) fn create_context(id: FunctionId) -> BrilligContext { let mut context = BrilligContext::new(true); - context.enter_context("test"); + context.enter_context(Label::function(id)); context } pub(crate) fn create_entry_point_bytecode( - context: BrilligContext, + context: BrilligContext, arguments: Vec, returns: Vec, ) -> GeneratedBrillig { let artifact = context.artifact(); let mut entry_point_artifact = - BrilligContext::new_entry_point_artifact(arguments, returns, "test".to_string()); + BrilligContext::new_entry_point_artifact(arguments, returns, FunctionId::test_new(0)); entry_point_artifact.link_with(&artifact); entry_point_artifact.finish() } diff --git a/compiler/noirc_evaluator/src/brillig/brillig_ir/artifact.rs b/compiler/noirc_evaluator/src/brillig/brillig_ir/artifact.rs index 2d0bdb5955c..d0bd91e185c 100644 --- a/compiler/noirc_evaluator/src/brillig/brillig_ir/artifact.rs +++ b/compiler/noirc_evaluator/src/brillig/brillig_ir/artifact.rs @@ -1,7 +1,8 @@ use acvm::acir::brillig::Opcode as BrilligOpcode; use std::collections::{BTreeMap, HashMap}; -use crate::ssa::ir::dfg::CallStack; +use crate::brillig::brillig_ir::procedures::ProcedureId; +use crate::ssa::ir::{basic_block::BasicBlockId, dfg::CallStack, function::FunctionId}; /// Represents a parameter or a return value of an entry point function. #[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)] @@ -22,6 +23,7 @@ pub(crate) struct GeneratedBrillig { pub(crate) byte_code: Vec>, pub(crate) locations: BTreeMap, pub(crate) assert_messages: BTreeMap, + pub(crate) name: String, } #[derive(Default, Debug, Clone)] @@ -44,20 +46,85 @@ pub(crate) struct BrilligArtifact { /// which are defined in other bytecode, that this bytecode has called. /// TODO: perhaps we should combine this with the `unresolved_jumps` field /// TODO: and have an enum which indicates whether the jump is internal or external - unresolved_external_call_labels: Vec<(JumpInstructionPosition, UnresolvedJumpLocation)>, + unresolved_external_call_labels: Vec<(JumpInstructionPosition, Label)>, /// Maps the opcodes that are associated with a callstack to it. locations: BTreeMap, /// The current call stack. All opcodes that are pushed will be associated with this call stack. call_stack: CallStack, + /// Name of the function, only used for debugging purposes. + pub(crate) name: String, } /// A pointer to a location in the opcode. pub(crate) type OpcodeLocation = usize; + +#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] +pub(crate) enum LabelType { + /// Labels for the entry point bytecode + Entrypoint, + /// Labels for user defined functions + Function(FunctionId, Option), + /// Labels for intrinsic procedures + Procedure(ProcedureId), +} + +impl std::fmt::Display for LabelType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + LabelType::Function(function_id, block_id) => { + if let Some(block_id) = block_id { + write!(f, "Function({:?}, {:?})", function_id, block_id) + } else { + write!(f, "Function({:?})", function_id) + } + } + LabelType::Entrypoint => write!(f, "Entrypoint"), + LabelType::Procedure(procedure_id) => write!(f, "Procedure({:?})", procedure_id), + } + } +} + /// An identifier for a location in the code. /// /// It is assumed that an entity will keep a map /// of labels to Opcode locations. -pub(crate) type Label = String; +#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] +pub(crate) struct Label { + pub(crate) label_type: LabelType, + pub(crate) section: Option, +} + +impl Label { + pub(crate) fn add_section(&self, section: usize) -> Self { + Label { label_type: self.label_type, section: Some(section) } + } + + pub(crate) fn function(func_id: FunctionId) -> Self { + Label { label_type: LabelType::Function(func_id, None), section: None } + } + + pub(crate) fn block(func_id: FunctionId, block_id: BasicBlockId) -> Self { + Label { label_type: LabelType::Function(func_id, Some(block_id)), section: None } + } + + pub(crate) fn entrypoint() -> Self { + Label { label_type: LabelType::Entrypoint, section: None } + } + + pub(crate) fn procedure(procedure_id: ProcedureId) -> Self { + Label { label_type: LabelType::Procedure(procedure_id), section: None } + } +} + +impl std::fmt::Display for Label { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + if let Some(section) = self.section { + write!(f, "{:?} - {}", self.label_type, section) + } else { + write!(f, "{:?}", self.label_type) + } + } +} /// Pointer to a unresolved Jump instruction in /// the bytecode. pub(crate) type JumpInstructionPosition = OpcodeLocation; @@ -81,12 +148,13 @@ impl BrilligArtifact { byte_code: self.byte_code, locations: self.locations, assert_messages: self.assert_messages, + name: self.name, } } /// Gets the first unresolved function call of this artifact. pub(crate) fn first_unresolved_function_call(&self) -> Option