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

feat: Module::add_item #5947

Merged
merged 7 commits into from
Sep 6, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
35 changes: 34 additions & 1 deletion compiler/noirc_frontend/src/elaborator/comptime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,39 @@ impl<'context> Elaborator<'context> {
result
}

pub fn elaborate_item_in_module<'a, T>(
&'a mut self,
module: ModuleId,
f: impl FnOnce(&mut Elaborator<'a>) -> T,
) -> T {
// Create a fresh elaborator to ensure no state is changed from
// this elaborator
let mut elaborator = Elaborator::new(
asterite marked this conversation as resolved.
Show resolved Hide resolved
self.interner,
self.def_maps,
module.krate,
self.debug_comptime_in_file,
self.enable_arithmetic_generics,
self.interpreter_call_stack.clone(),
);

elaborator.function_context.push(FunctionContext::default());
elaborator.scopes.start_function();

elaborator.current_item = None;
elaborator.crate_id = module.krate;
elaborator.local_module = module.local_id;
// TODO: elaborator.file = meta.source_file;

elaborator.populate_scope_from_comptime_scopes();

let result = f(&mut elaborator);
elaborator.check_and_pop_function_context();

self.errors.append(&mut elaborator.errors);
result
}

fn populate_scope_from_comptime_scopes(&mut self) {
// Take the comptime scope to be our runtime scope.
// Iterate from global scope to the most local scope so that the
Expand Down Expand Up @@ -352,7 +385,7 @@ impl<'context> Elaborator<'context> {
}
}

fn add_item(
pub(crate) fn add_item(
&mut self,
item: TopLevelStatement,
generated_items: &mut CollectedItems,
Expand Down
2 changes: 1 addition & 1 deletion compiler/noirc_frontend/src/elaborator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
DefinitionKind, DependencyId, ExprId, FuncId, FunctionModifiers, GlobalId, ReferenceId,
TraitId, TypeAliasId,
},
token::CustomAtrribute,

Check warning on line 32 in compiler/noirc_frontend/src/elaborator/mod.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (Atrribute)
Shared, Type, TypeVariable,
};
use crate::{
Expand Down Expand Up @@ -274,7 +274,7 @@
this
}

fn elaborate_items(&mut self, mut items: CollectedItems) {
pub(crate) fn elaborate_items(&mut self, mut items: CollectedItems) {
// We must first resolve and intern the globals before we can resolve any stmts inside each function.
// Each function uses its own resolver with a newly created ScopeForest, and must be resolved again to be within a function's scope
//
Expand Down Expand Up @@ -816,7 +816,7 @@
let attributes = func.secondary_attributes().iter();
let attributes =
attributes.filter_map(|secondary_attribute| secondary_attribute.as_custom());
let attributes: Vec<CustomAtrribute> = attributes.cloned().collect();

Check warning on line 819 in compiler/noirc_frontend/src/elaborator/mod.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (Atrribute)

let meta = FuncMeta {
name: name_ident,
Expand Down
12 changes: 12 additions & 0 deletions compiler/noirc_frontend/src/hir/comptime/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use crate::ast::{BinaryOpKind, FunctionKind, IntegerBitSize, Signedness};
use crate::elaborator::Elaborator;
use crate::graph::CrateId;
use crate::hir::def_map::ModuleId;
use crate::hir_def::expr::ImplKind;
use crate::hir_def::function::FunctionBody;
use crate::macros_api::UnaryOp;
Expand Down Expand Up @@ -194,6 +195,17 @@
result
}

fn elaborate_in_module<T>(
&mut self,
module: ModuleId,
f: impl FnOnce(&mut Elaborator) -> T,
) -> T {
self.unbind_generics_from_previous_function();
let result = self.elaborator.elaborate_item_in_module(module, f);
self.rebind_generics_from_previous_function();
result
}

fn call_special(
&mut self,
function: FuncId,
Expand Down Expand Up @@ -223,7 +235,7 @@
}
} else {
let name = self.elaborator.interner.function_name(&function);
unreachable!("Non-builtin, lowlevel or oracle builtin fn '{name}'")

Check warning on line 238 in compiler/noirc_frontend/src/hir/comptime/interpreter.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (lowlevel)
}
}

Expand Down
32 changes: 32 additions & 0 deletions compiler/noirc_frontend/src/hir/comptime/interpreter/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use crate::{
value::{ExprValue, TypedExpr},
InterpreterError, Value,
},
hir::def_collector::dc_crate::CollectedItems,
hir_def::function::FunctionBody,
lexer::Lexer,
macros_api::{HirExpression, HirLiteral, Ident, ModuleDefId, NodeInterner, Signedness},
Expand Down Expand Up @@ -112,6 +113,7 @@ impl<'local, 'context> Interpreter<'local, 'context> {
"function_def_set_return_public" => {
function_def_set_return_public(self, arguments, location)
}
"module_add_item" => module_add_item(self, arguments, location),
"module_functions" => module_functions(self, arguments, location),
"module_has_named_attribute" => module_has_named_attribute(self, arguments, location),
"module_is_contract" => module_is_contract(self, arguments, location),
Expand Down Expand Up @@ -2007,6 +2009,36 @@ fn function_def_set_return_public(
Ok(Value::Unit)
}

// fn add_item(self, item: Quoted)
fn module_add_item(
interpreter: &mut Interpreter,
arguments: Vec<(Value, Location)>,
location: Location,
) -> IResult<Value> {
let (self_argument, item) = check_two_arguments(arguments, location)?;
let module_id = get_module(self_argument)?;

let parser = parser::top_level_statement(parser::module());
let top_level_statement = parse(item, parser, "a top-level item")?;
asterite marked this conversation as resolved.
Show resolved Hide resolved

// TODO: we need to type-check the top-level statement relative to the current function
// (interpreter.current_function) but we need to add it to the given module (module_id).
// How to do this?
asterite marked this conversation as resolved.
Show resolved Hide resolved

let mut generated_items = CollectedItems::default();
interpreter.elaborate_in_module(module_id, |elaborator| {
elaborator.add_item(top_level_statement, &mut generated_items, location);
});

if !generated_items.is_empty() {
interpreter.elaborate_item(interpreter.current_function, |elaborator| {
elaborator.elaborate_items(generated_items);
});
}

Ok(Value::Unit)
}

// fn functions(self) -> [FunctionDefinition]
fn module_functions(
interpreter: &Interpreter,
Expand Down
4 changes: 2 additions & 2 deletions compiler/noirc_frontend/src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ use noirc_errors::Span;
pub use parser::path::path_no_turbofish;
pub use parser::traits::trait_bound;
pub use parser::{
block, expression, fresh_statement, lvalue, parse_program, parse_type, pattern,
top_level_items, visibility,
block, expression, fresh_statement, lvalue, module, parse_program, parse_type, pattern,
top_level_items, top_level_statement, visibility,
};

#[derive(Debug, Clone)]
Expand Down
4 changes: 2 additions & 2 deletions compiler/noirc_frontend/src/parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@

use chumsky::prelude::*;
use iter_extended::vecmap;
use lalrpop_util::lalrpop_mod;

Check warning on line 57 in compiler/noirc_frontend/src/parser/parser.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (lalrpop)

Check warning on line 57 in compiler/noirc_frontend/src/parser/parser.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (lalrpop)
use noirc_errors::{Span, Spanned};

mod assertion;
Expand All @@ -69,8 +69,8 @@
mod types;
mod visibility;

// synthesized by LALRPOP

Check warning on line 72 in compiler/noirc_frontend/src/parser/parser.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (LALRPOP)
lalrpop_mod!(pub noir_parser);

Check warning on line 73 in compiler/noirc_frontend/src/parser/parser.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (lalrpop)

#[cfg(test)]
mod test_helpers;
Expand All @@ -97,12 +97,12 @@

if cfg!(feature = "experimental_parser") {
for parsed_item in &parsed_module.items {
if lalrpop_parser_supports_kind(&parsed_item.kind) {

Check warning on line 100 in compiler/noirc_frontend/src/parser/parser.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (lalrpop)
match &parsed_item.kind {
ItemKind::Import(parsed_use_tree, _visibility) => {
prototype_parse_use_tree(Some(parsed_use_tree), source_program);
}
// other kinds prevented by lalrpop_parser_supports_kind

Check warning on line 105 in compiler/noirc_frontend/src/parser/parser.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (lalrpop)
_ => unreachable!(),
}
}
Expand All @@ -119,7 +119,7 @@
}

let mut lexer = Lexer::new(input);
lexer = lexer.skip_whitespaces(false);

Check warning on line 122 in compiler/noirc_frontend/src/parser/parser.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (whitespaces)
let mut errors = Vec::new();

// NOTE: this is a hack to get the references working
Expand Down Expand Up @@ -175,7 +175,7 @@

/// module: top_level_statement module
/// | %empty
fn module() -> impl NoirParser<ParsedModule> {
pub fn module() -> impl NoirParser<ParsedModule> {
recursive(|module_parser| {
empty()
.to(ParsedModule::default())
Expand All @@ -202,7 +202,7 @@
/// | module_declaration
/// | use_statement
/// | global_declaration
fn top_level_statement<'a>(
pub fn top_level_statement<'a>(
module_parser: impl NoirParser<ParsedModule> + 'a,
) -> impl NoirParser<TopLevelStatement> + 'a {
choice((
Expand Down
6 changes: 6 additions & 0 deletions docs/docs/noir/standard_library/meta/module.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ declarations in the source program.

## Methods

### add_item

#include_code add_item noir_stdlib/src/meta/module.nr rust

Adds a top-level item to the module.
asterite marked this conversation as resolved.
Show resolved Hide resolved

### name

#include_code name noir_stdlib/src/meta/module.nr rust
Expand Down
5 changes: 5 additions & 0 deletions noir_stdlib/src/meta/module.nr
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
impl Module {
#[builtin(module_add_item)]
// docs:start:add_item
fn add_item(self, item: Quoted) {}
// docs:end:add_item

#[builtin(module_has_named_attribute)]
// docs:start:has_named_attribute
fn has_named_attribute(self, name: Quoted) -> bool {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@ fn outer_attribute_separate_module(m: Module) {
increment_counter();
}

#[add_function]
mod add_to_me {}

fn add_function(m: Module) {
m.add_item(quote { pub fn added_function() {} });
}

fn main() {
comptime
{
Expand Down Expand Up @@ -73,6 +80,8 @@ fn main() {

yet_another_module::generated_outer_function();
yet_another_module::generated_inner_function();

add_to_me::added_function();
}

// docs:start:as_module_example
Expand Down
Loading