Skip to content

Commit

Permalink
feat: add some Module comptime functions (noir-lang#5684)
Browse files Browse the repository at this point in the history
# Description

## Problem

Part of noir-lang#5668

## Summary

Adds these comptime functions:
- `Quoted::as_module`
- `Module::name`
- `Module::is_contract`
- `Module::functions`
- `FunctionDefinition::name`

## Additional Context

Some notes:
- I made `Quoted::as_module` return `Option<ModuleId>`, while other
`Quoted::as_...` methods currently return a non-Option instead.
Eventually it would be nice to unify these but doing that in this PR
would have made it much bigger and complex, mainly because those methods
rely on methods that are used in many places in the compiler.
- For now I made `Module::name` and `FunctionDefinition::name` return
`Quoted`. Once we have a `String` type we could change them to `String`,
and the logic from going to Quoted -> String is very simple.

I was wondering... would a `String` type be what a Slice is for Arrays?

One more thought: I wonder if instead of returning `Option<ModuleId>` it
wouldn't be better to return some kind of `Result`. That way the caller
would know what the error is, if it happens. But I think we don't have
`Result` yet in Noir, right?

## Documentation\*

Check one:
- [x] No documentation needed.
- [ ] Documentation included in this PR.
- [ ] **[For Experimental Features]** Documentation to be submitted in a
separate PR.

# PR Checklist\*

- [x] I have tested the changes locally.
- [x] I have formatted the changes with [Prettier](https://prettier.io/)
and/or `cargo fmt` on default settings.

---------

Co-authored-by: jfecher <[email protected]>
  • Loading branch information
asterite and jfecher authored Aug 7, 2024
1 parent 325dac5 commit eefd69b
Show file tree
Hide file tree
Showing 14 changed files with 197 additions and 18 deletions.
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 std::{
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 rustc_hash::FxHashMap as HashMap;
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 @@ impl<'local, 'context> Interpreter<'local, 'context> {
"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 @@ fn slice_insert(
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 @@ -652,6 +680,19 @@ fn zeroed(return_type: Type) -> IResult<Value> {
}
}

// 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 @@ fn function_def_return_type(
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 super::{spanned, Item, ItemKind};
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 @@ -58,10 +58,10 @@ mod attributes;
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
Expand All @@ -71,7 +71,7 @@ lalrpop_mod!(pub noir_parser);
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 Down Expand Up @@ -366,10 +366,6 @@ fn function_declaration_parameters() -> impl NoirParser<Vec<(Ident, UnresolvedTy
.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 rename() -> impl NoirParser<Option<Ident>> {

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 });
}
}

0 comments on commit eefd69b

Please sign in to comment.