Skip to content

Commit

Permalink
Merge b4b94ff into 3da86cb
Browse files Browse the repository at this point in the history
  • Loading branch information
AztecBot authored Jul 18, 2024
2 parents 3da86cb + b4b94ff commit 3f147bb
Show file tree
Hide file tree
Showing 85 changed files with 2,464 additions and 6,487 deletions.
2 changes: 1 addition & 1 deletion .noir-sync-commit
Original file line number Diff line number Diff line change
@@ -1 +1 @@
951e821a585fe7e0697291cadd4d3c3aa49fd8e4
a213c15275892581e5d8f7235baf08a6cb137da4
1 change: 1 addition & 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
Expand Up @@ -73,6 +73,7 @@ pub fn generate_note_interface_impl(module: &mut SortedModule) -> Result<(), Azt
generics: vec![],
methods: vec![],
where_clause: vec![],
is_comptime: false,
};
module.impls.push(default_impl.clone());
module.impls.last_mut().unwrap()
Expand Down
1 change: 1 addition & 0 deletions noir/noir-repo/aztec_macros/src/transforms/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@ pub fn generate_storage_implementation(
methods: vec![(init, Span::default())],

where_clause: vec![],
is_comptime: false,
};
module.impls.push(storage_impl);

Expand Down
45 changes: 16 additions & 29 deletions noir/noir-repo/aztec_macros/src/utils/hir_utils.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
use acvm::acir::AcirField;
use iter_extended::vecmap;
use noirc_errors::Location;
use noirc_errors::{CustomDiagnostic, Location};
use noirc_frontend::ast;
use noirc_frontend::elaborator::Elaborator;
use noirc_frontend::hir::def_collector::dc_crate::{
CollectedItems, UnresolvedFunctions, UnresolvedGlobal,
};
use noirc_frontend::macros_api::{HirExpression, HirLiteral};
use noirc_frontend::node_interner::{NodeInterner, TraitImplKind};
use noirc_frontend::{
graph::CrateId,
hir::{
def_map::{LocalModuleId, ModuleId},
resolution::{path_resolver::StandardPathResolver, resolver::Resolver},
type_check::type_check_func,
},
hir::def_map::{LocalModuleId, ModuleId},
macros_api::{FileId, HirContext, MacroError, ModuleDefId, StructId},
node_interner::{FuncId, TraitId},
Shared, StructType, Type,
Expand Down Expand Up @@ -190,24 +190,18 @@ pub fn inject_fn(
span: None,
})?;

let def_maps = &mut context.def_maps;

let path_resolver =
StandardPathResolver::new(ModuleId { local_id: module_id, krate: *crate_id });

let resolver = Resolver::new(&mut context.def_interner, &path_resolver, def_maps, file_id);

let (hir_func, meta, _) = resolver.resolve_function(func, func_id);
let mut items = CollectedItems::default();
let functions = vec![(module_id, func_id, func)];
let trait_id = None;
items.functions.push(UnresolvedFunctions { file_id, functions, trait_id, self_type: None });

context.def_interner.push_fn_meta(meta, func_id);
context.def_interner.update_fn(func_id, hir_func);

let errors = type_check_func(&mut context.def_interner, func_id);
let mut errors = Elaborator::elaborate(context, *crate_id, items, None);
errors.retain(|(error, _)| !CustomDiagnostic::from(error).is_warning());

if !errors.is_empty() {
return Err(MacroError {
primary_message: "Failed to type check autogenerated function".to_owned(),
secondary_message: Some(errors.iter().map(|err| err.to_string()).collect::<String>()),
secondary_message: Some(errors.iter().map(|err| err.0.to_string()).collect::<String>()),
span: None,
});
}
Expand Down Expand Up @@ -243,17 +237,10 @@ pub fn inject_global(
)
});

let def_maps = &mut context.def_maps;

let path_resolver =
StandardPathResolver::new(ModuleId { local_id: module_id, krate: *crate_id });

let mut resolver = Resolver::new(&mut context.def_interner, &path_resolver, def_maps, file_id);

let hir_stmt = resolver.resolve_global_let(global, global_id);
let mut items = CollectedItems::default();
items.globals.push(UnresolvedGlobal { file_id, module_id, global_id, stmt_def: global });

let statement_id = context.def_interner.get_global(global_id).let_statement;
context.def_interner.replace_statement(statement_id, hir_stmt);
let _errors = Elaborator::elaborate(context, *crate_id, items, None);
}

pub fn fully_qualified_note_path(context: &HirContext, note_id: StructId) -> Option<String> {
Expand Down
10 changes: 1 addition & 9 deletions noir/noir-repo/compiler/noirc_driver/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,6 @@ pub struct CompileOptions {
#[arg(long, hide = true)]
pub force_brillig: bool,

/// Use the deprecated name resolution & type checking passes instead of the elaborator
#[arg(long, hide = true)]
pub use_legacy: bool,

/// Enable printing results of comptime evaluation: provide a path suffix
/// for the module to debug, e.g. "package_name/src/main.nr"
#[arg(long)]
Expand Down Expand Up @@ -262,15 +258,13 @@ pub fn check_crate(
crate_id: CrateId,
deny_warnings: bool,
disable_macros: bool,
use_legacy: bool,
debug_comptime_in_file: Option<&str>,
) -> CompilationResult<()> {
let macros: &[&dyn MacroProcessor] =
if disable_macros { &[] } else { &[&aztec_macros::AztecMacro as &dyn MacroProcessor] };

let mut errors = vec![];
let diagnostics =
CrateDefMap::collect_defs(crate_id, context, use_legacy, debug_comptime_in_file, macros);
let diagnostics = CrateDefMap::collect_defs(crate_id, context, debug_comptime_in_file, macros);
errors.extend(diagnostics.into_iter().map(|(error, file_id)| {
let diagnostic = CustomDiagnostic::from(&error);
diagnostic.in_file(file_id)
Expand Down Expand Up @@ -307,7 +301,6 @@ pub fn compile_main(
crate_id,
options.deny_warnings,
options.disable_macros,
options.use_legacy,
options.debug_comptime_in_file.as_deref(),
)?;

Expand Down Expand Up @@ -349,7 +342,6 @@ pub fn compile_contract(
crate_id,
options.deny_warnings,
options.disable_macros,
options.use_legacy,
options.debug_comptime_in_file.as_deref(),
)?;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ fn stdlib_does_not_produce_constant_warnings() -> Result<(), ErrorsAndWarnings>
let root_crate_id = prepare_crate(&mut context, file_name);

let ((), warnings) =
noirc_driver::check_crate(&mut context, root_crate_id, false, false, false, None)?;
noirc_driver::check_crate(&mut context, root_crate_id, false, false, None)?;

assert_eq!(warnings, Vec::new(), "stdlib is producing {} warnings", warnings.len());

Expand Down
4 changes: 4 additions & 0 deletions noir/noir-repo/compiler/noirc_errors/src/position.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ impl Span {
self.start() <= other.start() && self.end() >= other.end()
}

pub fn intersects(&self, other: &Span) -> bool {
self.end() > other.start() && self.start() < other.end()
}

pub fn is_smaller(&self, other: &Span) -> bool {
let self_distance = self.end() - self.start();
let other_distance = other.end() - other.start();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -294,24 +294,7 @@ impl<F: AcirField> GeneratedAcir<F> {
outputs: (outputs[0], outputs[1], outputs[2]),
},
BlackBoxFunc::Keccak256 => {
let var_message_size = match inputs.to_vec().pop() {
Some(var_message_size) => var_message_size[0],
None => {
return Err(InternalError::MissingArg {
name: "".to_string(),
arg: "message_size".to_string(),
call_stack: self.call_stack.clone(),
});
}
};

BlackBoxFuncCall::Keccak256 {
inputs: inputs[0].clone(),
var_message_size,
outputs: outputs
.try_into()
.expect("Compiler should generate correct size outputs"),
}
unreachable!("unexpected BlackBox {}", func_name.to_string())
}
BlackBoxFunc::Keccakf1600 => BlackBoxFuncCall::Keccakf1600 {
inputs: inputs[0]
Expand Down
12 changes: 12 additions & 0 deletions noir/noir-repo/compiler/noirc_evaluator/src/ssa/ir/instruction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -602,6 +602,18 @@ impl Instruction {
}
}
Instruction::ArrayGet { array, index } => {
if let Value::Instruction { instruction, .. } = &dfg[*array] {
if let Instruction::ArraySet { index: write_index, value, .. } =
dfg[*instruction]
{
// If we're reading from an index of the array which we just wrote to, we can return
// the value which we wrote without performing the read.
if dfg.resolve(write_index) == dfg.resolve(*index) {
return SimplifiedTo(value);
}
}
}

let array = dfg.get_array_constant(*array);
let index = dfg.get_numeric_constant(*index);
if let (Some((array, _)), Some(index)) = (array, index) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -461,28 +461,37 @@ fn simplify_black_box_func(
BlackBoxFunc::SHA256 => simplify_hash(dfg, arguments, acvm::blackbox_solver::sha256),
BlackBoxFunc::Blake2s => simplify_hash(dfg, arguments, acvm::blackbox_solver::blake2s),
BlackBoxFunc::Blake3 => simplify_hash(dfg, arguments, acvm::blackbox_solver::blake3),
BlackBoxFunc::PedersenCommitment
| BlackBoxFunc::PedersenHash
| BlackBoxFunc::Keccakf1600 => SimplifyResult::None, //TODO(Guillaume)
BlackBoxFunc::Keccak256 => {
match (dfg.get_array_constant(arguments[0]), dfg.get_numeric_constant(arguments[1])) {
(Some((input, _)), Some(num_bytes)) if array_is_constant(dfg, &input) => {
let input_bytes: Vec<u8> = to_u8_vec(dfg, input);

let num_bytes = num_bytes.to_u128() as usize;
let truncated_input_bytes = &input_bytes[0..num_bytes];
let hash = acvm::blackbox_solver::keccak256(truncated_input_bytes)
.expect("Rust solvable black box function should not fail");

let hash_values =
vecmap(hash, |byte| FieldElement::from_be_bytes_reduce(&[byte]));

let result_array = make_constant_array(dfg, hash_values, Type::unsigned(8));
BlackBoxFunc::PedersenCommitment | BlackBoxFunc::PedersenHash => SimplifyResult::None,
BlackBoxFunc::Keccakf1600 => {
if let Some((array_input, _)) = dfg.get_array_constant(arguments[0]) {
if array_is_constant(dfg, &array_input) {
let const_input: Vec<u64> = array_input
.iter()
.map(|id| {
let field = dfg
.get_numeric_constant(*id)
.expect("value id from array should point at constant");
field.to_u128() as u64
})
.collect();

let state = acvm::blackbox_solver::keccakf1600(
const_input.try_into().expect("Keccakf1600 input should have length of 25"),
)
.expect("Rust solvable black box function should not fail");
let state_values = vecmap(state, |x| FieldElement::from(x as u128));
let result_array = make_constant_array(dfg, state_values, Type::unsigned(64));
SimplifyResult::SimplifiedTo(result_array)
} else {
SimplifyResult::None
}
_ => SimplifyResult::None,
} else {
SimplifyResult::None
}
}
BlackBoxFunc::Keccak256 => {
unreachable!("Keccak256 should have been replaced by calls to Keccakf1600")
}
BlackBoxFunc::Poseidon2Permutation => SimplifyResult::None, //TODO(Guillaume)
BlackBoxFunc::EcdsaSecp256k1 => {
simplify_signature(dfg, arguments, acvm::blackbox_solver::ecdsa_secp256k1_verify)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1412,7 +1412,7 @@ mod test {
// Tests that it does not simplify a true constraint an always-false constraint
// acir(inline) fn main f1 {
// b0(v0: [u8; 2]):
// v4 = call keccak256(v0, u8 2)
// v4 = call sha256(v0, u8 2)
// v5 = array_get v4, index u8 0
// v6 = cast v5 as u32
// v8 = truncate v6 to 1 bits, max_bit_size: 32
Expand Down Expand Up @@ -1448,7 +1448,7 @@ mod test {
let two = builder.numeric_constant(2_u128, Type::unsigned(8));

let keccak =
builder.import_intrinsic_id(Intrinsic::BlackBox(acvm::acir::BlackBoxFunc::Keccak256));
builder.import_intrinsic_id(Intrinsic::BlackBox(acvm::acir::BlackBoxFunc::SHA256));
let v4 =
builder.insert_call(keccak, vec![array, two], vec![Type::Array(element_type, 32)])[0];
let v5 = builder.insert_array_get(v4, zero, Type::unsigned(8));
Expand Down
23 changes: 9 additions & 14 deletions noir/noir-repo/compiler/noirc_frontend/src/ast/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -800,12 +800,8 @@ impl FunctionDefinition {
return_visibility: Visibility::Private,
}
}
}

impl Display for FunctionDefinition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{:?}", self.attributes)?;

pub fn signature(&self) -> String {
let parameters = vecmap(&self.parameters, |Param { visibility, pattern, typ, span: _ }| {
if *visibility == Visibility::Public {
format!("{pattern}: {visibility} {typ}")
Expand All @@ -827,15 +823,14 @@ impl Display for FunctionDefinition {
format!(" -> {}", self.return_type)
};

write!(
f,
"fn {}({}){}{} {}",
self.name,
parameters.join(", "),
return_type,
where_clause_str,
self.body
)
format!("fn {}({}){}{}", self.name, parameters.join(", "), return_type, where_clause_str)
}
}

impl Display for FunctionDefinition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{:?}", self.attributes)?;
write!(f, "fn {} {}", self.signature(), self.body)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use super::{
BlockExpression, Expression, ExpressionKind, IndexExpression, MemberAccessExpression,
MethodCallExpression, UnresolvedType,
};
use crate::hir::resolution::resolver::SELF_TYPE_NAME;
use crate::elaborator::types::SELF_TYPE_NAME;
use crate::lexer::token::SpannedToken;
use crate::macros_api::SecondaryAttribute;
use crate::parser::{ParserError, ParserErrorReason};
Expand Down
13 changes: 1 addition & 12 deletions noir/noir-repo/compiler/noirc_frontend/src/ast/structure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,7 @@ pub struct NoirStruct {
pub generics: UnresolvedGenerics,
pub fields: Vec<(Ident, UnresolvedType)>,
pub span: Span,
}

impl NoirStruct {
pub fn new(
name: Ident,
attributes: Vec<SecondaryAttribute>,
generics: UnresolvedGenerics,
fields: Vec<(Ident, UnresolvedType)>,
span: Span,
) -> NoirStruct {
NoirStruct { name, attributes, generics, fields, span }
}
pub is_comptime: bool,
}

impl Display for NoirStruct {
Expand Down
5 changes: 4 additions & 1 deletion noir/noir-repo/compiler/noirc_frontend/src/ast/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ pub struct TypeImpl {
pub generics: UnresolvedGenerics,
pub where_clause: Vec<UnresolvedTraitConstraint>,
pub methods: Vec<(NoirFunction, Span)>,
pub is_comptime: bool,
}

/// Ast node for an implementation of a trait for a particular type
Expand All @@ -69,6 +70,8 @@ pub struct NoirTraitImpl {
pub where_clause: Vec<UnresolvedTraitConstraint>,

pub items: Vec<TraitImplItem>,

pub is_comptime: bool,
}

/// Represents a simple trait constraint such as `where Foo: TraitY<U, V>`
Expand All @@ -84,7 +87,7 @@ pub struct UnresolvedTraitConstraint {
}

/// Represents a single trait bound, such as `TraitX` or `TraitY<U, V>`
#[derive(Clone, Debug, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TraitBound {
pub trait_path: Path,
pub trait_id: Option<TraitId>, // initially None, gets assigned during DC
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::{
},
hir::{
comptime::{self, InterpreterError},
resolution::{errors::ResolverError, resolver::LambdaContext},
resolution::errors::ResolverError,
type_check::TypeCheckError,
},
hir_def::{
Expand All @@ -32,7 +32,7 @@ use crate::{
QuotedType, Shared, StructType, Type,
};

use super::Elaborator;
use super::{Elaborator, LambdaContext};

impl<'context> Elaborator<'context> {
pub(super) fn elaborate_expression(&mut self, expr: Expression) -> (ExprId, Type) {
Expand Down
Loading

0 comments on commit 3f147bb

Please sign in to comment.