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: add some Module comptime functions #5684

Merged
merged 9 commits into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
26 changes: 25 additions & 1 deletion compiler/noirc_frontend/src/elaborator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -623,6 +623,21 @@ impl<'context> Elaborator<'context> {
}
}

pub fn resolve_module_by_path(&self, path: Path) -> Option<ModuleId> {
let path_resolver = StandardPathResolver::new(self.module_id());

match path_resolver.resolve(self.def_maps, path.clone(), &mut None) {
Ok(PathResolution { module_def_id: ModuleDefId::ModuleId(module_id), error }) => {
if error.is_some() {
None
} else {
Some(module_id)
}
}
_ => None,
}
}

fn resolve_trait_by_path(&mut self, path: Path) -> Option<TraitId> {
let path_resolver = StandardPathResolver::new(self.module_id());

Expand Down Expand Up @@ -870,7 +885,11 @@ impl<'context> Elaborator<'context> {
/// Since they should be within a child module, they should be elaborated as if
/// `in_contract` is `false` so we can still resolve them in the parent module without them being in a contract.
fn in_contract(&self) -> bool {
self.module_id().module(self.def_maps).is_contract
self.module_is_contract(self.module_id())
}

pub(crate) fn module_is_contract(&self, module_id: ModuleId) -> bool {
module_id.module(self.def_maps).is_contract
}

fn is_entry_point_function(&self, func: &NoirFunction, in_contract: bool) -> bool {
Expand Down Expand Up @@ -1069,6 +1088,11 @@ impl<'context> Elaborator<'context> {
self.self_type = None;
}

pub fn get_module(&self, module: ModuleId) -> &ModuleData {
let message = "A crate should always be present for a given crate id";
&self.def_maps.get(&module.krate).expect(message).modules[module.local_id.0]
}

fn get_module_mut(def_maps: &mut DefMaps, module: ModuleId) -> &mut ModuleData {
let message = "A crate should always be present for a given crate id";
&mut def_maps.get_mut(&module.krate).expect(message).modules[module.local_id.0]
Expand Down
99 changes: 96 additions & 3 deletions compiler/noirc_frontend/src/hir/comptime/interpreter/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
use acvm::{AcirField, FieldElement};
use builtin_helpers::{
check_argument_count, check_one_argument, check_three_arguments, check_two_arguments,
get_function_def, get_quoted, get_slice, get_trait_constraint, get_trait_def, get_type,
get_u32, hir_pattern_to_tokens,
get_function_def, get_module, get_quoted, get_slice, get_trait_constraint, get_trait_def,
get_type, get_u32, hir_pattern_to_tokens,
};
use chumsky::Parser;
use iter_extended::{try_vecmap, vecmap};
Expand All @@ -17,7 +17,7 @@
use crate::{
ast::IntegerBitSize,
hir::comptime::{errors::IResult, value::add_token_spans, InterpreterError, Value},
macros_api::{NodeInterner, Signedness},
macros_api::{ModuleDefId, NodeInterner, Signedness},
parser,
token::Token,
QuotedType, Shared, Type,
Expand All @@ -40,13 +40,18 @@
"array_len" => array_len(interner, arguments, location),
"as_slice" => as_slice(interner, arguments, location),
"is_unconstrained" => Ok(Value::Bool(true)),
"function_def_name" => function_def_name(interner, arguments, location),
"function_def_parameters" => function_def_parameters(interner, arguments, location),
"function_def_return_type" => function_def_return_type(interner, arguments, location),
"module_functions" => module_functions(self, arguments, location),
"module_is_contract" => module_is_contract(self, arguments, location),
"module_name" => module_name(interner, arguments, location),
"modulus_be_bits" => modulus_be_bits(interner, arguments, location),
"modulus_be_bytes" => modulus_be_bytes(interner, arguments, location),
"modulus_le_bits" => modulus_le_bits(interner, arguments, location),
"modulus_le_bytes" => modulus_le_bytes(interner, arguments, location),
"modulus_num_bits" => modulus_num_bits(interner, arguments, location),
"quoted_as_module" => quoted_as_module(self, arguments, return_type, location),
"quoted_as_trait_constraint" => quoted_as_trait_constraint(self, arguments, location),
"quoted_as_type" => quoted_as_type(self, arguments, location),
"quoted_eq" => quoted_eq(arguments, location),
Expand Down Expand Up @@ -307,6 +312,31 @@
Ok(Value::Slice(values, typ))
}

// fn as_module(quoted: Quoted) -> Option<Module>
fn quoted_as_module(
interpreter: &mut Interpreter,
arguments: Vec<(Value, Location)>,
return_type: Type,
location: Location,
) -> IResult<Value> {
let argument = check_one_argument(arguments, location)?;

let tokens = get_quoted(argument, location)?;
let quoted = add_token_spans(tokens.clone(), location.span);

let option_value = parser::path_no_turbofish()
.parse(quoted)
.ok()
.and_then(|path| {
interpreter.elaborate_item(interpreter.current_function, |elaborator| {
elaborator.resolve_module_by_path(path)
})
})
.map(Value::ModuleDefinition);
asterite marked this conversation as resolved.
Show resolved Hide resolved

option(return_type, option_value)
}

// fn as_trait_constraint(quoted: Quoted) -> TraitConstraint
fn quoted_as_trait_constraint(
interpreter: &mut Interpreter,
Expand Down Expand Up @@ -351,7 +381,7 @@
})?;

let typ =
interpreter.elaborate_item(interpreter.current_function, |elab| elab.resolve_type(typ));

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

View workflow job for this annotation

GitHub Actions / Code

Unknown word (elab)

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

View workflow job for this annotation

GitHub Actions / Code

Unknown word (elab)

Ok(Value::Type(typ))
}
Expand Down Expand Up @@ -652,6 +682,20 @@
}
}

// fn name(self) -> Quoted
fn function_def_name(
interner: &NodeInterner,
arguments: Vec<(Value, Location)>,
location: Location,
) -> IResult<Value> {
let self_argument = check_one_argument(arguments, location)?;
let func_id = get_function_def(self_argument, location)?;
let func_meta = interner.function_meta(&func_id);
let name = &interner.definition(func_meta.name.id).name;
let tokens = Rc::new(vec![Token::Ident(name.clone())]);
asterite marked this conversation as resolved.
Show resolved Hide resolved
Ok(Value::Quoted(tokens))
}

// fn parameters(self) -> [(Quoted, Type)]
fn function_def_parameters(
interner: &NodeInterner,
Expand Down Expand Up @@ -693,6 +737,55 @@
Ok(Value::Type(func_meta.return_type().follow_bindings()))
}

// fn functions(self) -> [FunctionDefinition]
fn module_functions(
interpreter: &Interpreter,
arguments: Vec<(Value, Location)>,
location: Location,
) -> IResult<Value> {
let self_argument = check_one_argument(arguments, location)?;
let module_id = get_module(self_argument, location)?;
let module_data = interpreter.elaborator.get_module(module_id);
let func_ids = module_data
.value_definitions()
.filter_map(|module_def_id| {
if let ModuleDefId::FunctionId(func_id) = module_def_id {
Some(Value::FunctionDefinition(func_id))
} else {
None
}
})
.collect();

let slice_type = Type::Slice(Box::new(Type::Quoted(QuotedType::FunctionDefinition)));

asterite marked this conversation as resolved.
Show resolved Hide resolved
Ok(Value::Slice(func_ids, slice_type))
}

// fn is_contract(self) -> bool
fn module_is_contract(
interpreter: &Interpreter,
arguments: Vec<(Value, Location)>,
location: Location,
) -> IResult<Value> {
let self_argument = check_one_argument(arguments, location)?;
let module_id = get_module(self_argument, location)?;
Ok(Value::Bool(interpreter.elaborator.module_is_contract(module_id)))
}

// fn name(self) -> Quoted
fn module_name(
interner: &NodeInterner,
arguments: Vec<(Value, Location)>,
location: Location,
) -> IResult<Value> {
let self_argument = check_one_argument(arguments, location)?;
let module_id = get_module(self_argument, location)?;
let name = &interner.module_attributes(&module_id).name;
let tokens = Rc::new(vec![Token::Ident(name.clone())]);
Ok(Value::Quoted(tokens))
}

fn modulus_be_bits(
_interner: &mut NodeInterner,
arguments: Vec<(Value, Location)>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ use noirc_errors::Location;

use crate::{
ast::{IntegerBitSize, Signedness},
hir::comptime::{errors::IResult, InterpreterError, Value},
hir::{
comptime::{errors::IResult, InterpreterError, Value},
def_map::ModuleId,
},
hir_def::stmt::HirPattern,
macros_api::NodeInterner,
node_interner::{FuncId, TraitId},
Expand Down Expand Up @@ -124,6 +127,17 @@ pub(crate) fn get_function_def(value: Value, location: Location) -> IResult<Func
}
}

pub(crate) fn get_module(value: Value, location: Location) -> IResult<ModuleId> {
match value {
Value::ModuleDefinition(module_id) => Ok(module_id),
value => {
let expected = Type::Quoted(QuotedType::Module);
let actual = value.get_type().into_owned();
Err(InterpreterError::TypeMismatch { expected, actual, location })
}
}
}

pub(crate) fn get_trait_constraint(
value: Value,
location: Location,
Expand Down
4 changes: 3 additions & 1 deletion compiler/noirc_frontend/src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ use chumsky::primitive::Container;
pub use errors::ParserError;
pub use errors::ParserErrorReason;
use noirc_errors::Span;
pub use parser::{expression, parse_program, parse_type, top_level_items, trait_bound};
pub use parser::{
expression, parse_program, parse_type, path_no_turbofish, top_level_items, trait_bound,
};

#[derive(Debug, Clone)]
pub enum TopLevelStatement {
Expand Down
6 changes: 5 additions & 1 deletion compiler/noirc_frontend/src/parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@

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

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

View workflow job for this annotation

GitHub Actions / Code

Unknown word (lalrpop)

Check warning on line 53 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 @@ -64,14 +64,14 @@
mod traits;
mod types;

// synthesized by LALRPOP

Check warning on line 67 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 68 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;

use literals::literal;
use path::{maybe_empty_path, path, path_no_turbofish};
use path::{maybe_empty_path, path};
use primitives::{dereference, ident, negation, not, nothing, right_shift_operator, token_kind};
use traits::where_clause;

Expand All @@ -90,12 +90,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 93 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) => {
prototype_parse_use_tree(Some(parsed_use_tree), source_program);
}
// other kinds prevented by lalrpop_parser_supports_kind

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

View workflow job for this annotation

GitHub Actions / Code

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

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

Check warning on line 115 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 @@ -370,6 +370,10 @@
traits::trait_bound()
}

pub fn path_no_turbofish() -> impl NoirParser<Path> {
path::path_no_turbofish()
}

asterite marked this conversation as resolved.
Show resolved Hide resolved
fn block_expr<'a>(
statement: impl NoirParser<StatementKind> + 'a,
) -> impl NoirParser<Expression> + 'a {
Expand Down
3 changes: 3 additions & 0 deletions noir_stdlib/src/meta/function_def.nr
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
impl FunctionDefinition {
#[builtin(function_def_name)]
fn name(self) -> Quoted {}

#[builtin(function_def_parameters)]
fn parameters(self) -> [(Quoted, Type)] {}

Expand Down
1 change: 1 addition & 0 deletions noir_stdlib/src/meta/mod.nr
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::hash::BuildHasherDefault;
use crate::hash::poseidon2::Poseidon2Hasher;

mod function_def;
mod module;
mod struct_def;
mod trait_constraint;
mod trait_def;
Expand Down
10 changes: 10 additions & 0 deletions noir_stdlib/src/meta/module.nr
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
impl Module {
#[builtin(module_is_contract)]
fn is_contract(self) -> bool {}

#[builtin(module_functions)]
fn functions(self) -> [FunctionDefinition] {}

#[builtin(module_name)]
fn name(self) -> Quoted {}
}
4 changes: 4 additions & 0 deletions noir_stdlib/src/meta/quoted.nr
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use crate::cmp::Eq;
use crate::option::Option;

impl Quoted {
#[builtin(quoted_as_module)]
fn as_module(self) -> Option<Module> {}

#[builtin(quoted_as_trait_constraint)]
fn as_trait_constraint(self) -> TraitConstraint {}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ comptime fn function_attr(f: FunctionDefinition) {

// Check FunctionDefinition::return_type
assert_eq(f.return_type(), type_of(an_i32));

// Check FunctionDefinition::name
assert_eq(f.name(), quote { foo });
}

fn main() {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "comptime_module"
type = "bin"
authors = [""]
compiler_version = ">=0.31.0"

[dependencies]
26 changes: 26 additions & 0 deletions test_programs/compile_success_empty/comptime_module/src/main.nr
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
mod foo {
fn x() {}
fn y() {}
}

contract bar {}

fn main() {
comptime
{
// Check Module::is_contract
let foo = quote { foo }.as_module().unwrap();
assert(!foo.is_contract());

let bar = quote { bar }.as_module().unwrap();
assert(bar.is_contract());

// Check Module::functions
assert_eq(foo.functions().len(), 2);
assert_eq(bar.functions().len(), 0);

// Check Module::name
assert_eq(foo.name(), quote { foo });
assert_eq(bar.name(), quote { bar });
}
}
Loading