Skip to content

Commit

Permalink
chore: pull changes out of sync PR (#9966)
Browse files Browse the repository at this point in the history
Please read [contributing guidelines](CONTRIBUTING.md) and remove this
line.
  • Loading branch information
TomAFrench authored Nov 14, 2024
1 parent 9370c91 commit bf4176f
Show file tree
Hide file tree
Showing 23 changed files with 356 additions and 71 deletions.
11 changes: 11 additions & 0 deletions noir/noir-repo/Cargo.lock

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

Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
use noirc_errors::debug_info::ProcedureDebugId;
use serde::{Deserialize, Serialize};

mod array_copy;
mod array_reverse;
mod check_max_stack_depth;
Expand All @@ -14,11 +17,9 @@ use array_copy::compile_array_copy_procedure;
use array_reverse::compile_array_reverse_procedure;
use check_max_stack_depth::compile_check_max_stack_depth_procedure;
use mem_copy::compile_mem_copy_procedure;
use noirc_errors::debug_info::ProcedureDebugId;
use prepare_vector_insert::compile_prepare_vector_insert_procedure;
use prepare_vector_push::compile_prepare_vector_push_procedure;
use revert_with_string::compile_revert_with_string_procedure;
use serde::{Deserialize, Serialize};
use vector_copy::compile_vector_copy_procedure;
use vector_pop_back::compile_vector_pop_back_procedure;
use vector_pop_front::compile_vector_pop_front_procedure;
Expand Down
1 change: 0 additions & 1 deletion noir/noir-repo/compiler/noirc_evaluator/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ pub mod ssa;
pub mod brillig;

pub use ssa::create_program;

pub use ssa::ir::instruction::ErrorType;

/// Trims leading whitespace from each line of the input string, according to
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use acvm::acir::circuit::opcodes::{
};
use acvm::acir::circuit::{AssertionPayload, ExpressionOrMemory, ExpressionWidth, Opcode};
use acvm::brillig_vm::{MemoryValue, VMStatus, VM};
use acvm::BlackBoxFunctionSolver;
use acvm::{
acir::AcirField,
acir::{
Expand Down Expand Up @@ -107,7 +108,9 @@ impl From<NumericType> for AcirType {
/// Context object which holds the relationship between
/// `Variables`(AcirVar) and types such as `Expression` and `Witness`
/// which are placed into ACIR.
pub(crate) struct AcirContext<F: AcirField> {
pub(crate) struct AcirContext<F: AcirField, B: BlackBoxFunctionSolver<F>> {
blackbox_solver: B,

/// Two-way map that links `AcirVar` to `AcirVarData`.
///
/// The vars object is an instance of the `TwoWayMap`, which provides a bidirectional mapping between `AcirVar` and `AcirVarData`.
Expand All @@ -132,7 +135,7 @@ pub(crate) struct AcirContext<F: AcirField> {
pub(crate) warnings: Vec<SsaReport>,
}

impl<F: AcirField> AcirContext<F> {
impl<F: AcirField, B: BlackBoxFunctionSolver<F>> AcirContext<F, B> {
pub(crate) fn set_expression_width(&mut self, expression_width: ExpressionWidth) {
self.expression_width = expression_width;
}
Expand Down Expand Up @@ -1758,8 +1761,8 @@ impl<F: AcirField> AcirContext<F> {
brillig_stdlib_func,
);

fn range_constraint_value<G: AcirField>(
context: &mut AcirContext<G>,
fn range_constraint_value<G: AcirField, C: BlackBoxFunctionSolver<G>>(
context: &mut AcirContext<G, C>,
value: &AcirValue,
) -> Result<(), RuntimeError> {
match value {
Expand Down Expand Up @@ -1878,7 +1881,7 @@ impl<F: AcirField> AcirContext<F> {
inputs: &[BrilligInputs<F>],
outputs_types: &[AcirType],
) -> Option<Vec<AcirValue>> {
let mut memory = (execute_brillig(code, inputs)?).into_iter();
let mut memory = (execute_brillig(code, &self.blackbox_solver, inputs)?).into_iter();

let outputs_var = vecmap(outputs_types.iter(), |output| match output {
AcirType::NumericType(_) => {
Expand Down Expand Up @@ -2171,8 +2174,9 @@ pub(crate) struct AcirVar(usize);
/// Returns the finished state of the Brillig VM if execution can complete.
///
/// Returns `None` if complete execution of the Brillig bytecode is not possible.
fn execute_brillig<F: AcirField>(
fn execute_brillig<F: AcirField, B: BlackBoxFunctionSolver<F>>(
code: &[BrilligOpcode<F>],
blackbox_solver: &B,
inputs: &[BrilligInputs<F>],
) -> Option<Vec<MemoryValue<F>>> {
// Set input values
Expand All @@ -2198,12 +2202,8 @@ fn execute_brillig<F: AcirField>(
}

// Instantiate a Brillig VM given the solved input registers and memory, along with the Brillig bytecode.
//
// We pass a stubbed solver here as a concrete solver implies a field choice which conflicts with this function
// being generic.
let solver = acvm::blackbox_solver::StubbedBlackBoxSolver;
let profiling_active = false;
let mut vm = VM::new(calldata, code, Vec::new(), &solver, profiling_active);
let mut vm = VM::new(calldata, code, Vec::new(), blackbox_solver, profiling_active);

// Run the Brillig VM on these inputs, bytecode, etc!
let vm_status = vm.process_opcodes();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use crate::brillig::{brillig_gen::brillig_fn::FunctionContext as BrilligFunction
use crate::errors::{InternalError, InternalWarning, RuntimeError, SsaReport};
pub(crate) use acir_ir::generated_acir::GeneratedAcir;
use acvm::acir::circuit::opcodes::{AcirFunctionId, BlockType};
use bn254_blackbox_solver::Bn254BlackBoxSolver;
use noirc_frontend::monomorphization::ast::InlineType;

use acvm::acir::circuit::brillig::{BrilligBytecode, BrilligFunctionId};
Expand Down Expand Up @@ -157,7 +158,7 @@ struct Context<'a> {
current_side_effects_enabled_var: AcirVar,

/// Manages and builds the `AcirVar`s to which the converted SSA values refer.
acir_context: AcirContext<FieldElement>,
acir_context: AcirContext<FieldElement, Bn254BlackBoxSolver>,

/// Track initialized acir dynamic arrays
///
Expand Down
4 changes: 2 additions & 2 deletions noir/noir-repo/compiler/noirc_evaluator/src/ssa/opt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ pub(crate) fn assert_normalized_ssa_equals(mut ssa: super::Ssa, expected: &str)
let expected = trim_leading_whitespace_from_lines(expected);

if ssa != expected {
println!("Got:\n~~~\n{}\n~~~\nExpected:\n~~~\n{}\n~~~", ssa, expected);
similar_asserts::assert_eq!(ssa, expected);
println!("Expected:\n~~~\n{expected}\n~~~\nGot:\n~~~\n{ssa}\n~~~");
similar_asserts::assert_eq!(expected, ssa);
}
}
9 changes: 8 additions & 1 deletion noir/noir-repo/compiler/noirc_evaluator/src/ssa/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -735,10 +735,17 @@ impl<'a> Parser<'a> {
}

fn eat_int(&mut self) -> ParseResult<Option<FieldElement>> {
let negative = self.eat(Token::Dash)?;

if matches!(self.token.token(), Token::Int(..)) {
let token = self.bump()?;
match token.into_token() {
Token::Int(int) => Ok(Some(int)),
Token::Int(mut int) => {
if negative {
int = -int;
}
Ok(Some(int))
}
_ => unreachable!(),
}
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ impl<'a> Lexer<'a> {
Some(']') => self.single_char_token(Token::RightBracket),
Some('&') => self.single_char_token(Token::Ampersand),
Some('-') if self.peek_char() == Some('>') => self.double_char_token(Token::Arrow),
Some('-') => self.single_char_token(Token::Dash),
Some(ch) if ch.is_ascii_alphanumeric() || ch == '_' => self.eat_alpha_numeric(ch),
Some(char) => Err(LexerError::UnexpectedCharacter {
char,
Expand Down
11 changes: 11 additions & 0 deletions noir/noir-repo/compiler/noirc_evaluator/src/ssa/parser/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -425,3 +425,14 @@ fn test_slice() {
";
assert_ssa_roundtrip(src);
}

#[test]
fn test_negative() {
let src = "
acir(inline) fn main f0 {
b0():
return Field -1
}
";
assert_ssa_roundtrip(src);
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ pub(crate) enum Token {
Equal,
/// &
Ampersand,
/// -
Dash,
Eof,
}

Expand Down Expand Up @@ -90,6 +92,7 @@ impl Display for Token {
Token::Arrow => write!(f, "->"),
Token::Equal => write!(f, "=="),
Token::Ampersand => write!(f, "&"),
Token::Dash => write!(f, "-"),
Token::Eof => write!(f, "(end of stream)"),
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,14 @@ impl<'context> Elaborator<'context> {
}
ItemKind::Impl(r#impl) => {
let module = self.module_id();
dc_mod::collect_impl(self.interner, generated_items, r#impl, self.file, module);
dc_mod::collect_impl(
self.interner,
generated_items,
r#impl,
self.file,
module,
&mut self.errors,
);
}

ItemKind::ModuleDecl(_)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ use crate::{
};

use self::builtin_helpers::{eq_item, get_array, get_ctstring, get_str, get_u8, hash_item, lex};
use super::Interpreter;
use super::{foreign, Interpreter};

pub(crate) mod builtin_helpers;

Expand All @@ -57,6 +57,7 @@ impl<'local, 'context> Interpreter<'local, 'context> {
let interner = &mut self.elaborator.interner;
let call_stack = &self.elaborator.interpreter_call_stack;
match name {
"apply_range_constraint" => foreign::apply_range_constraint(arguments, location),
"array_as_str_unchecked" => array_as_str_unchecked(interner, arguments, location),
"array_len" => array_len(interner, arguments, location),
"assert_constant" => Ok(Value::Bool(true)),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use acvm::blackbox_solver::BlackBoxFunctionSolver;
use acvm::{
acir::BlackBoxFunc, blackbox_solver::BlackBoxFunctionSolver, AcirField, BlackBoxResolutionError,
};
use bn254_blackbox_solver::Bn254BlackBoxSolver;
use im::Vector;
use iter_extended::try_vecmap;
Expand Down Expand Up @@ -29,6 +31,28 @@ pub(super) fn call_foreign(
}
}

pub(super) fn apply_range_constraint(
arguments: Vec<(Value, Location)>,
location: Location,
) -> IResult<Value> {
let (value, num_bits) = check_two_arguments(arguments, location)?;

let input = get_field(value)?;
let num_bits = get_u32(num_bits)?;

if input.num_bits() < num_bits {
Ok(Value::Unit)
} else {
Err(InterpreterError::BlackBoxError(
BlackBoxResolutionError::Failed(
BlackBoxFunc::RANGE,
"value exceeds range check bounds".to_owned(),
),
location,
))
}
}

// poseidon2_permutation<let N: u32>(_input: [Field; N], _state_length: u32) -> [Field; N]
fn poseidon2_permutation(
interner: &mut NodeInterner,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,9 @@ pub fn collect_defs(

errors.extend(collector.collect_functions(context, ast.functions, crate_id));

collector.collect_trait_impls(context, ast.trait_impls, crate_id);
errors.extend(collector.collect_trait_impls(context, ast.trait_impls, crate_id));

collector.collect_impls(context, ast.impls, crate_id);
errors.extend(collector.collect_impls(context, ast.impls, crate_id));

collector.collect_attributes(
ast.inner_attributes,
Expand Down Expand Up @@ -163,7 +163,13 @@ impl<'a> ModCollector<'a> {
errors
}

fn collect_impls(&mut self, context: &mut Context, impls: Vec<TypeImpl>, krate: CrateId) {
fn collect_impls(
&mut self,
context: &mut Context,
impls: Vec<TypeImpl>,
krate: CrateId,
) -> Vec<(CompilationError, FileId)> {
let mut errors = Vec::new();
let module_id = ModuleId { krate, local_id: self.module_id };

for r#impl in impls {
Expand All @@ -173,16 +179,21 @@ impl<'a> ModCollector<'a> {
r#impl,
self.file_id,
module_id,
&mut errors,
);
}

errors
}

fn collect_trait_impls(
&mut self,
context: &mut Context,
impls: Vec<NoirTraitImpl>,
krate: CrateId,
) {
) -> Vec<(CompilationError, FileId)> {
let mut errors = Vec::new();

for mut trait_impl in impls {
let trait_name = trait_impl.trait_name.clone();

Expand All @@ -198,6 +209,13 @@ impl<'a> ModCollector<'a> {
let module = ModuleId { krate, local_id: self.module_id };

for (_, func_id, noir_function) in &mut unresolved_functions.functions {
if noir_function.def.attributes.is_test_function() {
let error = DefCollectorErrorKind::TestOnAssociatedFunction {
span: noir_function.name_ident().span(),
};
errors.push((error.into(), self.file_id));
}

let location = Location::new(noir_function.def.span, self.file_id);
context.def_interner.push_function(*func_id, &noir_function.def, module, location);
}
Expand All @@ -224,6 +242,8 @@ impl<'a> ModCollector<'a> {

self.def_collector.items.trait_impls.push(unresolved_trait_impl);
}

errors
}

fn collect_functions(
Expand Down Expand Up @@ -1051,13 +1071,23 @@ pub fn collect_impl(
r#impl: TypeImpl,
file_id: FileId,
module_id: ModuleId,
errors: &mut Vec<(CompilationError, FileId)>,
) {
let mut unresolved_functions =
UnresolvedFunctions { file_id, functions: Vec::new(), trait_id: None, self_type: None };

for (method, _) in r#impl.methods {
let doc_comments = method.doc_comments;
let mut method = method.item;

if method.def.attributes.is_test_function() {
let error = DefCollectorErrorKind::TestOnAssociatedFunction {
span: method.name_ident().span(),
};
errors.push((error.into(), file_id));
continue;
}

let func_id = interner.push_empty_fn();
method.def.where_clause.extend(r#impl.where_clause.clone());
let location = Location::new(method.span(), file_id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ pub enum DefCollectorErrorKind {
},
#[error("{0}")]
UnsupportedNumericGenericType(#[from] UnsupportedNumericGenericType),
#[error("The `#[test]` attribute may only be used on a non-associated function")]
TestOnAssociatedFunction { span: Span },
}

impl DefCollectorErrorKind {
Expand Down Expand Up @@ -291,6 +293,12 @@ impl<'a> From<&'a DefCollectorErrorKind> for Diagnostic {
diag
}
DefCollectorErrorKind::UnsupportedNumericGenericType(err) => err.into(),
DefCollectorErrorKind::TestOnAssociatedFunction { span } => Diagnostic::simple_error(
"The `#[test]` attribute is disallowed on `impl` methods".into(),
String::new(),
*span,
),

}
}
}
Loading

0 comments on commit bf4176f

Please sign in to comment.