Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Fix aztec library after nargo fmt #3014

Merged
merged 2 commits into from
Oct 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 58 additions & 43 deletions compiler/noirc_frontend/src/hir/aztec_library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,17 @@
use crate::hir_def::expr::{HirExpression, HirLiteral};
use crate::hir_def::stmt::HirStatement;
use crate::node_interner::{NodeInterner, StructId};
use crate::parser::SortedModule;
use crate::token::SecondaryAttribute;
use crate::{
hir::Context, BlockExpression, CallExpression, CastExpression, Distinctness, Expression,
ExpressionKind, FunctionReturnType, Ident, ImportStatement, IndexExpression, LetStatement,
Literal, MemberAccessExpression, MethodCallExpression, NoirFunction, ParsedModule, Path,
PathKind, Pattern, Statement, UnresolvedType, UnresolvedTypeData, Visibility,
ExpressionKind, FunctionReturnType, Ident, IndexExpression, LetStatement, Literal,
MemberAccessExpression, MethodCallExpression, NoirFunction, Path, PathKind, Pattern, Statement,
UnresolvedType, UnresolvedTypeData, Visibility,
};
use crate::{
ForLoopStatement, FunctionDefinition, NoirStruct, PrefixExpression, Signedness, StructType,
Type, TypeImpl, UnaryOp,
ForLoopStatement, FunctionDefinition, ImportStatement, NoirStruct, PrefixExpression,
Signedness, StatementKind, StructType, Type, TypeImpl, UnaryOp,
};
use fm::FileId;

Expand Down Expand Up @@ -74,11 +75,11 @@
}

fn mutable_assignment(name: &str, assigned_to: Expression) -> Statement {
Statement::Let(LetStatement {
make_statement(StatementKind::Let(LetStatement {
pattern: mutable(name),
r#type: make_type(UnresolvedTypeData::Unspecified),
expression: assigned_to,
})
}))
}

fn mutable_reference(variable_name: &str) -> Expression {
Expand All @@ -89,11 +90,11 @@
}

fn assignment(name: &str, assigned_to: Expression) -> Statement {
Statement::Let(LetStatement {
make_statement(StatementKind::Let(LetStatement {
pattern: pattern(name),
r#type: make_type(UnresolvedTypeData::Unspecified),
expression: assigned_to,
})
}))
}

fn member_access(lhs: &str, rhs: &str) -> Expression {
Expand Down Expand Up @@ -161,10 +162,10 @@
/// Traverses every function in the ast, calling `transform_function` which
/// determines if further processing is required
pub(crate) fn transform(
mut ast: ParsedModule,
mut ast: SortedModule,
crate_id: &CrateId,
context: &Context,
) -> Result<ParsedModule, (DefCollectorErrorKind, FileId)> {
) -> Result<SortedModule, (DefCollectorErrorKind, FileId)> {
// Usage -> mut ast -> aztec_library::transform(&mut ast)

// Covers all functions in the ast
Expand Down Expand Up @@ -193,7 +194,7 @@
}

/// Includes an import to the aztec library if it has not been included yet
fn include_relevant_imports(ast: &mut ParsedModule) {
fn include_relevant_imports(ast: &mut SortedModule) {
// Create the aztec import path using the assumed chained_dep! macro
let aztec_import_path = import(chained_dep!("aztec"));

Expand All @@ -219,7 +220,7 @@
}

// Check to see if the user has defined a storage struct
fn check_for_storage_definition(module: &ParsedModule) -> bool {
fn check_for_storage_definition(module: &SortedModule) -> bool {
module.types.iter().any(|function| function.name.0.contents == "Storage")
}

Expand All @@ -235,10 +236,10 @@
/// Determines if ast nodes are annotated with aztec attributes.
/// For annotated functions it calls the `transform` function which will perform the required transformations.
/// Returns true if an annotated node is found, false otherwise
fn transform_module(module: &mut ParsedModule, storage_defined: bool) -> bool {
fn transform_module(module: &mut SortedModule, storage_defined: bool) -> bool {
let mut has_transformed_module = false;

for structure in module.types.iter_mut() {
for structure in module.types.iter() {
if structure.attributes.iter().any(|attr| matches!(attr, SecondaryAttribute::Event)) {
module.impls.push(generate_selector_impl(structure));
has_transformed_module = true;
Expand Down Expand Up @@ -414,13 +415,13 @@
/// This allows developers to emit events without having to write the signature of the event every time they emit it.
/// The signature cannot be known at this point since types are not resolved yet, so we use a signature placeholder.
/// It'll get resolved after by transforming the HIR.
fn generate_selector_impl(structure: &mut NoirStruct) -> TypeImpl {
fn generate_selector_impl(structure: &NoirStruct) -> TypeImpl {
let struct_type = make_type(UnresolvedTypeData::Named(path(structure.name.clone()), vec![]));

let selector_fun_body = BlockExpression(vec![Statement::Expression(call(
let selector_fun_body = BlockExpression(vec![make_statement(StatementKind::Expression(call(
variable_path(chained_path!("aztec", "selector", "compute_selector")),
vec![expression(ExpressionKind::Literal(Literal::Str(SIGNATURE_PLACEHOLDER.to_string())))],
))]);
)))]);

let mut selector_fn_def = FunctionDefinition::normal(
&ident("selector"),
Expand Down Expand Up @@ -590,22 +591,24 @@
let last_statement = &func.def.body.0[len - 1];

// TODO: (length, type) => We can limit the size of the array returned to be limited by kernel size
// Doesnt need done until we have settled on a kernel size

Check warning on line 594 in compiler/noirc_frontend/src/hir/aztec_library.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (Doesnt)
// TODO: support tuples here and in inputs -> convert into an issue

// Check if the return type is an expression, if it is, we can handle it
match last_statement {
Statement::Expression(expression) => match current_return_type {
// Call serialize on structs, push the whole array, calling push_array
UnresolvedTypeData::Named(..) => Some(make_struct_return_type(expression.clone())),
UnresolvedTypeData::Array(..) => Some(make_array_return_type(expression.clone())),
// Cast these types to a field before pushing
UnresolvedTypeData::Bool | UnresolvedTypeData::Integer(..) => {
Some(make_castable_return_type(expression.clone()))
Statement { kind: StatementKind::Expression(expression), .. } => {
match current_return_type {
// Call serialize on structs, push the whole array, calling push_array
UnresolvedTypeData::Named(..) => Some(make_struct_return_type(expression.clone())),
UnresolvedTypeData::Array(..) => Some(make_array_return_type(expression.clone())),
// Cast these types to a field before pushing
UnresolvedTypeData::Bool | UnresolvedTypeData::Integer(..) => {
Some(make_castable_return_type(expression.clone()))

Check warning on line 606 in compiler/noirc_frontend/src/hir/aztec_library.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (castable)
}
UnresolvedTypeData::FieldElement => Some(make_return_push(expression.clone())),
_ => None,
}
UnresolvedTypeData::FieldElement => Some(make_return_push(expression.clone())),
_ => None,
},
}
_ => None,
}
}
Expand Down Expand Up @@ -665,20 +668,32 @@
member_access("context", "return_values")
}

fn make_statement(kind: StatementKind) -> Statement {
Statement { span: Span::default(), kind }
}

/// Make return Push
///
/// Translates to:
/// `context.return_values.push({push_value})`
fn make_return_push(push_value: Expression) -> Statement {
Statement::Semi(method_call(context_return_values(), "push", vec![push_value]))
make_statement(StatementKind::Semi(method_call(
context_return_values(),
"push",
vec![push_value],
)))
}

/// Make Return push array
///
/// Translates to:
/// `context.return_values.push_array({push_value})`
fn make_return_push_array(push_value: Expression) -> Statement {
Statement::Semi(method_call(context_return_values(), "push_array", vec![push_value]))
make_statement(StatementKind::Semi(method_call(
context_return_values(),
"push_array",
vec![push_value],
)))
}

/// Make struct return type
Expand Down Expand Up @@ -706,22 +721,22 @@
fn make_array_return_type(expression: Expression) -> Statement {
let inner_cast_expression =
cast(index_array_variable(expression.clone(), "i"), UnresolvedTypeData::FieldElement);
let assignment = Statement::Semi(method_call(
let assignment = make_statement(StatementKind::Semi(method_call(
context_return_values(), // variable
"push", // method name
vec![inner_cast_expression],
));
)));

create_loop_over(expression, vec![assignment])
}

/// Castable return type

Check warning on line 733 in compiler/noirc_frontend/src/hir/aztec_library.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (Castable)
///
/// Translates to:
/// ```noir
/// context.return_values.push({ident} as Field)
/// ```
fn make_castable_return_type(expression: Expression) -> Statement {

Check warning on line 739 in compiler/noirc_frontend/src/hir/aztec_library.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (castable)
// Cast these types to a field before pushing
let cast_expression = cast(expression, UnresolvedTypeData::FieldElement);
make_return_push(cast_expression)
Expand Down Expand Up @@ -780,7 +795,7 @@
"finish", // method name
vec![], // args
);
Statement::Expression(method_call)
make_statement(StatementKind::Expression(method_call))
}

//
Expand All @@ -795,11 +810,11 @@
vec![], // args
);

Statement::Semi(method_call(
make_statement(StatementKind::Semi(method_call(
variable("hasher"), // variable
"add_multiple", // method name
vec![serialized_call], // args
))
)))
}

fn create_loop_over(var: Expression, loop_body: Vec<Statement>) -> Statement {
Expand All @@ -818,14 +833,14 @@
let for_loop_block = expression(ExpressionKind::Block(BlockExpression(loop_body)));

// `for i in 0..{ident}.len()`
Statement::For(ForLoopStatement {
make_statement(StatementKind::For(ForLoopStatement {
identifier: ident("i"),
start_range: expression(ExpressionKind::Literal(Literal::Integer(FieldElement::from(
i128::from(0),
)))),
end_range: end_range_expression,
block: for_loop_block,
})
}))
}

fn add_array_to_hasher(identifier: &Ident) -> Statement {
Expand All @@ -838,23 +853,23 @@
index_array(identifier.clone(), "i"), // lhs - `ident[i]`
UnresolvedTypeData::FieldElement, // cast to - `as Field`
);
let block_statement = Statement::Semi(method_call(
let block_statement = make_statement(StatementKind::Semi(method_call(
variable("hasher"), // variable
"add", // method name
vec![cast_expression],
));
)));

create_loop_over(variable_ident(identifier.clone()), vec![block_statement])
}

fn add_field_to_hasher(identifier: &Ident) -> Statement {
// `hasher.add({ident})`
let iden = variable_path(path(identifier.clone()));

Check warning on line 867 in compiler/noirc_frontend/src/hir/aztec_library.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (iden)
Statement::Semi(method_call(
make_statement(StatementKind::Semi(method_call(
variable("hasher"), // variable
"add", // method name
vec![iden], // args

Check warning on line 871 in compiler/noirc_frontend/src/hir/aztec_library.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (iden)
))
)))
}

fn add_cast_to_hasher(identifier: &Ident) -> Statement {
Expand All @@ -866,11 +881,11 @@
);

// `hasher.add({ident} as Field)`
Statement::Semi(method_call(
make_statement(StatementKind::Semi(method_call(
variable("hasher"), // variable
"add", // method name
vec![cast_operation], // args
))
)))
}

/// Computes the aztec signature for a resolved type.
Expand Down
6 changes: 3 additions & 3 deletions compiler/noirc_frontend/src/hir/def_collector/dc_mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
graph::CrateId,
hir::def_collector::dc_crate::{UnresolvedStruct, UnresolvedTrait},
node_interner::{TraitId, TypeAliasId},
parser::{SortedModule, SubModule},
parser::{SortedModule, SortedSubModule},
FunctionDefinition, Ident, LetStatement, NoirFunction, NoirStruct, NoirTrait, NoirTraitImpl,
NoirTypeAlias, TraitImplItem, TraitItem, TypeImpl,
};
Expand Down Expand Up @@ -243,7 +243,7 @@
types: Vec<NoirStruct>,
krate: CrateId,
) -> Vec<(CompilationError, FileId)> {
let mut definiton_errors = vec![];

Check warning on line 246 in compiler/noirc_frontend/src/hir/def_collector/dc_mod.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (definiton)
for struct_definition in types {
let name = struct_definition.name.clone();

Expand All @@ -257,7 +257,7 @@
let id = match self.push_child_module(&name, self.file_id, false, false) {
Ok(local_id) => context.def_interner.new_struct(&unresolved, krate, local_id),
Err(error) => {
definiton_errors.push((error.into(), self.file_id));

Check warning on line 260 in compiler/noirc_frontend/src/hir/def_collector/dc_mod.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (definiton)
continue;
}
};
Expand All @@ -272,13 +272,13 @@
first_def,
second_def,
};
definiton_errors.push((error.into(), self.file_id));

Check warning on line 275 in compiler/noirc_frontend/src/hir/def_collector/dc_mod.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (definiton)
}

// And store the TypeId -> StructType mapping somewhere it is reachable
self.def_collector.collected_types.insert(id, unresolved);
}
definiton_errors

Check warning on line 281 in compiler/noirc_frontend/src/hir/def_collector/dc_mod.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (definiton)
}

/// Collect any type aliases definitions declared within the ast.
Expand Down Expand Up @@ -451,7 +451,7 @@
&mut self,
context: &mut Context,
crate_id: CrateId,
submodules: Vec<SubModule>,
submodules: Vec<SortedSubModule>,
file_id: FileId,
) -> Vec<(CompilationError, FileId)> {
let mut errors: Vec<(CompilationError, FileId)> = vec![];
Expand All @@ -460,7 +460,7 @@
Ok(child) => {
errors.extend(collect_defs(
self.def_collector,
submodule.contents.into_sorted(),
submodule.contents,
file_id,
child,
crate_id,
Expand Down
Loading