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 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
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
95 changes: 92 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,29 @@
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 path = parser::path_no_turbofish().parse(quoted).ok();
let option_value = path.and_then(|path| {
let module = interpreter.elaborate_item(interpreter.current_function, |elaborator| {
elaborator.resolve_module_by_path(path)
});
module.map(Value::ModuleDefinition)
});

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 +379,7 @@
})?;

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

Check warning on line 382 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 382 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 +680,19 @@
}
}

// 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 name = interner.function_name(&func_id).to_string();
let tokens = Rc::new(vec![Token::Ident(name)]);
Ok(Value::Quoted(tokens))
}

// fn parameters(self) -> [(Quoted, Type)]
fn function_def_parameters(
interner: &NodeInterner,
Expand Down Expand Up @@ -693,6 +734,54 @@
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)));
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::path::path_no_turbofish;
pub use parser::traits::trait_bound;
pub use parser::{expression, parse_program, parse_type, top_level_items};

#[derive(Debug, Clone)]
pub enum TopLevelStatement {
Expand Down
16 changes: 6 additions & 10 deletions compiler/noirc_frontend/src/parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@
use crate::ast::{
BinaryOp, BinaryOpKind, BlockExpression, ForLoopStatement, ForRange, Ident, IfExpression,
InfixExpression, LValue, Literal, ModuleDeclaration, NoirTypeAlias, Param, Path, Pattern,
Recoverable, Statement, TraitBound, TypeImpl, UnaryRhsMemberAccess, UnaryRhsMethodCall,
UseTree, UseTreeKind, Visibility,
Recoverable, Statement, TypeImpl, UnaryRhsMemberAccess, UnaryRhsMethodCall, UseTree,
UseTreeKind, Visibility,
};
use crate::ast::{
Expression, ExpressionKind, LetStatement, StatementKind, UnresolvedType, UnresolvedTypeData,
Expand All @@ -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 @@ -58,20 +58,20 @@
mod function;
mod lambdas;
mod literals;
mod path;
pub(super) mod path;
mod primitives;
mod structs;
mod traits;
pub(super) 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 @@ -366,10 +366,6 @@
.labelled(ParsingRuleLabel::Parameter)
}

pub fn trait_bound() -> impl NoirParser<TraitBound> {
traits::trait_bound()
}

fn block_expr<'a>(
statement: impl NoirParser<StatementKind> + 'a,
) -> impl NoirParser<Expression> + 'a {
Expand Down Expand Up @@ -431,7 +427,7 @@

fn use_tree() -> impl NoirParser<UseTree> {
recursive(|use_tree| {
let simple = path_no_turbofish().then(rename()).map(|(mut prefix, alias)| {
let simple = path::path_no_turbofish().then(rename()).map(|(mut prefix, alias)| {
let ident = prefix.pop().ident;
UseTree { prefix, kind: UseTreeKind::Path(ident, alias) }
});
Expand Down
2 changes: 1 addition & 1 deletion compiler/noirc_frontend/src/parser/parser/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub(super) fn path<'a>(
path_inner(path_segment(type_parser))
}

pub(super) fn path_no_turbofish() -> impl NoirParser<Path> {
pub fn path_no_turbofish() -> impl NoirParser<Path> {
path_inner(path_segment_no_turbofish())
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/noirc_frontend/src/parser/parser/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ fn trait_bounds() -> impl NoirParser<Vec<TraitBound>> {
trait_bound().separated_by(just(Token::Plus)).at_least(1).allow_trailing()
}

pub(super) fn trait_bound() -> impl NoirParser<TraitBound> {
pub fn trait_bound() -> impl NoirParser<TraitBound> {
path_no_turbofish().then(generic_type_args(parse_type())).map(|(trait_path, trait_generics)| {
TraitBound { trait_path, trait_generics, trait_id: None }
})
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