Skip to content

Commit

Permalink
Merge branch 'master' into kw/add-package-version
Browse files Browse the repository at this point in the history
  • Loading branch information
kevaundray authored Nov 21, 2023
2 parents df98c09 + 008a431 commit d449a1d
Show file tree
Hide file tree
Showing 356 changed files with 3,106 additions and 1,948 deletions.
20 changes: 11 additions & 9 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ noirc_abi = { path = "tooling/noirc_abi" }
bb_abstraction_leaks = { path = "tooling/bb_abstraction_leaks" }

# LSP
async-lsp = { version = "0.0.5", default-features = false }
lsp-types = "0.94"
async-lsp = { version = "0.1.0", default-features = false }
lsp-types = "0.94.1"
tower = "0.4"

# Wasm
Expand Down
16 changes: 16 additions & 0 deletions acvm-repo/acvm/src/pwg/brillig.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,22 @@ impl<'b, B: BlackBoxFunctionSolver> BrilligSolver<'b, B> {
Ok(Self { vm, acir_index })
}

pub fn get_registers(&self) -> &Registers {
self.vm.get_registers()
}

pub fn set_register(&mut self, register_index: usize, value: Value) {
self.vm.set_register(RegisterIndex(register_index), value);
}

pub fn get_memory(&self) -> &[Value] {
self.vm.get_memory()
}

pub fn write_memory_at(&mut self, ptr: usize, value: Value) {
self.vm.write_memory_at(ptr, value);
}

pub(super) fn solve(&mut self) -> Result<BrilligSolverStatus, OpcodeResolutionError> {
let status = self.vm.process_opcodes();
self.handle_vm_status(status)
Expand Down
8 changes: 8 additions & 0 deletions acvm-repo/acvm/src/pwg/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,14 @@ impl<'a, B: BlackBoxFunctionSolver> ACVM<'a, B> {
&self.witness_map
}

pub fn overwrite_witness(
&mut self,
witness: Witness,
value: FieldElement,
) -> Option<FieldElement> {
self.witness_map.insert(witness, value)
}

/// Returns a slice containing the opcodes of the circuit being executed.
pub fn opcodes(&self) -> &[Opcode] {
self.opcodes
Expand Down
8 changes: 8 additions & 0 deletions acvm-repo/brillig_vm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,10 +164,18 @@ impl<'a, B: BlackBoxFunctionSolver> VM<'a, B> {
&self.registers
}

pub fn set_register(&mut self, register_index: RegisterIndex, value: Value) {
self.registers.set(register_index, value);
}

pub fn get_memory(&self) -> &Vec<Value> {
self.memory.values()
}

pub fn write_memory_at(&mut self, ptr: usize, value: Value) {
self.memory.write(ptr, value);
}

/// Process a single opcode and modify the program counter.
pub fn process_opcode(&mut self) -> VMStatus {
let opcode = &self.bytecode[self.program_counter];
Expand Down
2 changes: 1 addition & 1 deletion compiler/integration-tests/circuits/main/src/main.nr
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
fn main(x : Field, y : pub Field) {
fn main(x: Field, y: pub Field) {
assert(x != y);
}
10 changes: 5 additions & 5 deletions compiler/integration-tests/circuits/recursion/src/main.nr
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use dep::std;

fn main(
verification_key : [Field; 114],
proof : [Field; 94],
public_inputs : [Field; 1],
key_hash : Field,
input_aggregation_object : [Field; 16],
verification_key: [Field; 114],
proof: [Field; 94],
public_inputs: [Field; 1],
key_hash: Field,
input_aggregation_object: [Field; 16]
) -> pub [Field; 16] {
let vk : [Field] = verification_key;
let p : [Field] = proof;
Expand Down
3 changes: 0 additions & 3 deletions compiler/noirc_driver/build.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
const GIT_COMMIT: &&str = &"GIT_COMMIT";

fn main() {
// Rebuild if the tests have changed
println!("cargo:rerun-if-changed=tests");

// Only use build_data if the environment variable isn't set
// The environment variable is always set when working via Nix
if std::env::var(GIT_COMMIT).is_err() {
Expand Down
141 changes: 141 additions & 0 deletions compiler/noirc_driver/src/abi_gen.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
use std::collections::BTreeMap;

use acvm::acir::native_types::Witness;
use iter_extended::{btree_map, vecmap};
use noirc_abi::{Abi, AbiParameter, AbiType};
use noirc_frontend::{
hir::Context,
hir_def::{function::Param, stmt::HirPattern},
node_interner::{FuncId, NodeInterner},
};
use std::ops::Range;

/// Arranges a function signature and a generated circuit's return witnesses into a
/// `noirc_abi::Abi`.
pub(super) fn gen_abi(
context: &Context,
func_id: &FuncId,
input_witnesses: Vec<Witness>,
return_witnesses: Vec<Witness>,
) -> Abi {
let (parameters, return_type) = compute_function_abi(context, func_id);
let param_witnesses = param_witnesses_from_abi_param(&parameters, input_witnesses);
Abi { parameters, return_type, param_witnesses, return_witnesses }
}

pub(super) fn compute_function_abi(
context: &Context,
func_id: &FuncId,
) -> (Vec<AbiParameter>, Option<AbiType>) {
let func_meta = context.def_interner.function_meta(func_id);

let (parameters, return_type) = func_meta.into_function_signature();
let parameters = into_abi_params(context, parameters);
let return_type = return_type.map(|typ| AbiType::from_type(context, &typ));
(parameters, return_type)
}

/// Attempts to retrieve the name of this parameter. Returns None
/// if this parameter is a tuple or struct pattern.
fn get_param_name<'a>(pattern: &HirPattern, interner: &'a NodeInterner) -> Option<&'a str> {
match pattern {
HirPattern::Identifier(ident) => Some(interner.definition_name(ident.id)),
HirPattern::Mutable(pattern, _) => get_param_name(pattern, interner),
HirPattern::Tuple(_, _) => None,
HirPattern::Struct(_, _, _) => None,
}
}

fn into_abi_params(context: &Context, params: Vec<Param>) -> Vec<AbiParameter> {
vecmap(params, |(pattern, typ, vis)| {
let param_name = get_param_name(&pattern, &context.def_interner)
.expect("Abi for tuple and struct parameters is unimplemented")
.to_owned();
let as_abi = AbiType::from_type(context, &typ);
AbiParameter { name: param_name, typ: as_abi, visibility: vis.into() }
})
}

// Takes each abi parameter and shallowly maps to the expected witness range in which the
// parameter's constituent values live.
fn param_witnesses_from_abi_param(
abi_params: &Vec<AbiParameter>,
input_witnesses: Vec<Witness>,
) -> BTreeMap<String, Vec<Range<Witness>>> {
let mut idx = 0_usize;
if input_witnesses.is_empty() {
return BTreeMap::new();
}

btree_map(abi_params, |param| {
let num_field_elements_needed = param.typ.field_count() as usize;
let param_witnesses = &input_witnesses[idx..idx + num_field_elements_needed];

// It's likely that `param_witnesses` will consist of mostly incrementing witness indices.
// We then want to collapse these into `Range`s to save space.
let param_witnesses = collapse_ranges(param_witnesses);
idx += num_field_elements_needed;
(param.name.clone(), param_witnesses)
})
}

/// Takes a vector of [`Witnesses`][`Witness`] and collapses it into a vector of [`Range`]s of [`Witnesses`][`Witness`].
fn collapse_ranges(witnesses: &[Witness]) -> Vec<Range<Witness>> {
if witnesses.is_empty() {
return Vec::new();
}
let mut wit = Vec::new();
let mut last_wit: Witness = witnesses[0];

for (i, witness) in witnesses.iter().enumerate() {
if i == 0 {
continue;
};
let witness_index = witness.witness_index();
let prev_witness_index = witnesses[i - 1].witness_index();
if witness_index != prev_witness_index + 1 {
wit.push(last_wit..Witness(prev_witness_index + 1));
last_wit = *witness;
};
}

let last_witness = witnesses.last().unwrap().witness_index();
wit.push(last_wit..Witness(last_witness + 1));

wit
}

#[cfg(test)]
mod test {
use std::ops::Range;

use acvm::acir::native_types::Witness;

use super::collapse_ranges;

#[test]
fn collapses_single_range() {
let witnesses: Vec<_> = vec![1, 2, 3].into_iter().map(Witness::from).collect();

let collapsed_witnesses = collapse_ranges(&witnesses);

assert_eq!(collapsed_witnesses, vec![Range { start: Witness(1), end: Witness(4) },])
}

#[test]
fn collapse_ranges_correctly() {
let witnesses: Vec<_> =
vec![1, 2, 3, 5, 6, 2, 3, 4].into_iter().map(Witness::from).collect();

let collapsed_witnesses = collapse_ranges(&witnesses);

assert_eq!(
collapsed_witnesses,
vec![
Range { start: Witness(1), end: Witness(4) },
Range { start: Witness(5), end: Witness(7) },
Range { start: Witness(2), end: Witness(5) }
]
)
}
}
15 changes: 6 additions & 9 deletions compiler/noirc_driver/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use fm::FileId;
use iter_extended::vecmap;
use noirc_abi::{AbiParameter, AbiType, ContractEvent};
use noirc_errors::{CustomDiagnostic, FileDiagnostic};
use noirc_evaluator::create_circuit;
use noirc_evaluator::errors::RuntimeError;
use noirc_evaluator::{create_circuit, into_abi_params};
use noirc_frontend::graph::{CrateId, CrateName};
use noirc_frontend::hir::def_map::{Contract, CrateDefMap};
use noirc_frontend::hir::Context;
Expand All @@ -18,6 +18,7 @@ use noirc_frontend::node_interner::FuncId;
use serde::{Deserialize, Serialize};
use std::path::Path;

mod abi_gen;
mod contract;
mod debug;
mod program;
Expand Down Expand Up @@ -140,12 +141,7 @@ pub fn compute_function_abi(
) -> Option<(Vec<AbiParameter>, Option<AbiType>)> {
let main_function = context.get_main_function(crate_id)?;

let func_meta = context.def_interner.function_meta(&main_function);

let (parameters, return_type) = func_meta.into_function_signature();
let parameters = into_abi_params(context, parameters);
let return_type = return_type.map(|typ| AbiType::from_type(context, &typ));
Some((parameters, return_type))
Some(abi_gen::compute_function_abi(context, &main_function))
}

/// Run the frontend to check the crate for errors then compile the main function if there were none
Expand Down Expand Up @@ -345,9 +341,10 @@ pub fn compile_no_check(
return Ok(cached_program.expect("cache must exist for hashes to match"));
}

let (circuit, debug, abi, warnings) =
create_circuit(context, program, options.show_ssa, options.show_brillig)?;
let (circuit, debug, input_witnesses, return_witnesses, warnings) =
create_circuit(program, options.show_ssa, options.show_brillig)?;

let abi = abi_gen::gen_abi(context, &main_function, input_witnesses, return_witnesses);
let file_map = filter_relevant_files(&[debug.clone()], &context.file_manager);

Ok(CompiledProgram {
Expand Down
7 changes: 4 additions & 3 deletions compiler/noirc_errors/src/debug_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub struct DebugInfo {

/// Holds OpCodes Counts for Acir and Brillig Opcodes
/// To be printed with `nargo info --profile-info`
#[derive(Default, Debug, Serialize, Deserialize, Clone)]
pub struct OpCodesCount {
pub acir_size: usize,
pub brillig_size: usize,
Expand Down Expand Up @@ -51,12 +52,12 @@ impl DebugInfo {
self.locations.get(loc).cloned()
}

pub fn count_span_opcodes(&self) -> HashMap<&Location, OpCodesCount> {
let mut accumulator: HashMap<&Location, Vec<&OpcodeLocation>> = HashMap::new();
pub fn count_span_opcodes(&self) -> HashMap<Location, OpCodesCount> {
let mut accumulator: HashMap<Location, Vec<&OpcodeLocation>> = HashMap::new();

for (opcode_location, locations) in self.locations.iter() {
for location in locations.iter() {
let opcodes = accumulator.entry(location).or_insert(Vec::new());
let opcodes = accumulator.entry(*location).or_insert(Vec::new());
opcodes.push(opcode_location);
}
}
Expand Down
1 change: 0 additions & 1 deletion compiler/noirc_evaluator/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ license.workspace = true
[dependencies]
noirc_frontend.workspace = true
noirc_errors.workspace = true
noirc_abi.workspace = true
acvm.workspace = true
fxhash.workspace = true
iter-extended.workspace = true
Expand Down
1 change: 0 additions & 1 deletion compiler/noirc_evaluator/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,4 @@ pub mod ssa;

pub mod brillig;

pub use ssa::abi_gen::into_abi_params;
pub use ssa::create_circuit;
Loading

0 comments on commit d449a1d

Please sign in to comment.