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 attributes #5888

Merged
merged 22 commits into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from 15 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
1 change: 1 addition & 0 deletions compiler/noirc_frontend/src/ast/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ pub trait Recoverable {
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct ModuleDeclaration {
pub ident: Ident,
pub outer_attributes: Vec<SecondaryAttribute>,
}

impl std::fmt::Display for ModuleDeclaration {
Expand Down
49 changes: 49 additions & 0 deletions compiler/noirc_frontend/src/elaborator/comptime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use crate::{
},
dc_mod,
},
def_map::{LocalModuleId, ModuleId},
resolution::errors::ResolverError,
},
hir_def::expr::HirIdent,
Expand Down Expand Up @@ -380,6 +381,8 @@ impl<'context> Elaborator<'context> {
) -> CollectedItems {
let mut generated_items = CollectedItems::default();

self.run_attributes_on_modules(&mut generated_items);

for (trait_id, trait_) in traits {
let attributes = &trait_.trait_def.attributes;
let item = Value::TraitDefinition(*trait_id);
Expand All @@ -399,9 +402,55 @@ impl<'context> Elaborator<'context> {
}

self.run_attributes_on_functions(functions, &mut generated_items);

generated_items
}

fn run_attributes_on_modules(&mut self, generated_items: &mut CollectedItems) {
if self.ran_module_attributes {
return;
}
self.ran_module_attributes = true;

let def_map = &self.def_maps[&self.crate_id];
let mut data = Vec::new();

for (index, module_data) in def_map.modules.iter() {
let local_id = LocalModuleId(index);

if !module_data.outer_attributes.is_empty() {
// When resolving an outer attribute we need to do it as if we are located in the parent module
let parent = def_map.modules()[index].parent.unwrap();
let parent_module_data = &def_map.modules()[parent.0];
let attributes = module_data.outer_attributes.clone();
data.push((local_id, parent, parent_module_data.location, attributes));
}

if !module_data.inner_attributes.is_empty() {
let attributes = module_data.inner_attributes.clone();
data.push((local_id, local_id, module_data.location, attributes));
}
}

for (local_id, attribute_module, location, attributes) in data {
let module_id = ModuleId { krate: self.crate_id, local_id };
let item = Value::ModuleDefinition(module_id);
let span = location.span;

self.local_module = attribute_module;
self.file = location.file;

for name in attributes {
let item = item.clone();
if let Err(error) =
self.run_comptime_attribute_on_item(&name, item, span, generated_items)
{
self.errors.push(error);
}
}
}
}

fn run_attributes_on_functions(
&mut self,
function_sets: &[UnresolvedFunctions],
Expand Down
4 changes: 4 additions & 0 deletions compiler/noirc_frontend/src/elaborator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,9 @@ pub struct Elaborator<'context> {
enable_arithmetic_generics: bool,

pub(crate) interpreter_call_stack: im::Vector<Location>,

/// Did we already run module attributes?
ran_module_attributes: bool,
}

#[derive(Default)]
Expand Down Expand Up @@ -218,6 +221,7 @@ impl<'context> Elaborator<'context> {
enable_arithmetic_generics,
current_trait: None,
interpreter_call_stack,
ran_module_attributes: false,
}
}

Expand Down
33 changes: 33 additions & 0 deletions compiler/noirc_frontend/src/hir/comptime/interpreter/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ impl<'local, 'context> Interpreter<'local, 'context> {
function_def_set_return_type(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),
"module_name" => module_name(interner, arguments, location),
"modulus_be_bits" => modulus_be_bits(interner, arguments, location),
Expand Down Expand Up @@ -1799,6 +1800,38 @@ fn module_functions(
Ok(Value::Slice(func_ids, slice_type))
}

// fn has_named_attribute(self, name: Quoted) -> bool
fn module_has_named_attribute(
interpreter: &Interpreter,
arguments: Vec<(Value, Location)>,
location: Location,
) -> IResult<Value> {
let (self_argument, name) = check_two_arguments(arguments, location)?;
let module_id = get_module(self_argument)?;
let module_data = interpreter.elaborator.get_module(module_id);
let name = get_quoted(name)?;

let name = name.iter().map(|token| token.to_string()).collect::<Vec<_>>().join("");

let attributes = module_data.outer_attributes.iter().chain(&module_data.inner_attributes);
for attribute in attributes {
let parse_result = Elaborator::parse_attribute(attribute, location.file);
let Ok(Some((function, _arguments))) = parse_result else {
continue;
};

let ExpressionKind::Variable(path) = function.kind else {
continue;
};

if path.last_name() == name {
return Ok(Value::Bool(true));
}
}

Ok(Value::Bool(false))
}

// fn is_contract(self) -> bool
fn module_is_contract(
interpreter: &Interpreter,
Expand Down
8 changes: 7 additions & 1 deletion compiler/noirc_frontend/src/hir/comptime/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,13 @@ fn interpret_helper(src: &str) -> Result<Value, InterpreterError> {
let module_id = LocalModuleId(Index::unsafe_zeroed());
let mut modules = noirc_arena::Arena::default();
let location = Location::new(Default::default(), file);
let root = LocalModuleId(modules.insert(ModuleData::new(None, location, false)));
let root = LocalModuleId(modules.insert(ModuleData::new(
None,
location,
Vec::new(),
Vec::new(),
false,
)));
assert_eq!(root, module_id);

let file_manager = FileManager::new(&PathBuf::new());
Expand Down
19 changes: 16 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 @@ -17,6 +17,7 @@
use crate::hir::resolution::errors::ResolverError;
use crate::macros_api::{Expression, NodeInterner, UnresolvedType, UnresolvedTypeData};
use crate::node_interner::ModuleAttributes;
use crate::token::SecondaryAttribute;
use crate::{
graph::CrateId,
hir::def_collector::dc_crate::{UnresolvedStruct, UnresolvedTrait},
Expand Down Expand Up @@ -63,7 +64,7 @@
for decl in ast.module_decls {
errors.extend(collector.parse_module_declaration(
context,
&decl,
decl,
crate_id,
macro_processors,
));
Expand Down Expand Up @@ -304,6 +305,8 @@
context,
&name,
Location::new(name.span(), self.file_id),
Vec::new(),
Vec::new(),
false,
false,
) {
Expand Down Expand Up @@ -436,6 +439,8 @@
context,
&name,
Location::new(name.span(), self.file_id),
Vec::new(),
Vec::new(),
false,
false,
) {
Expand Down Expand Up @@ -629,6 +634,8 @@
context,
&submodule.name,
Location::new(submodule.name.span(), file_id),
submodule.outer_attributes,
submodule.contents.inner_attributes.clone(),
true,
submodule.is_contract,
) {
Expand Down Expand Up @@ -657,7 +664,7 @@
fn parse_module_declaration(
&mut self,
context: &mut Context,
mod_decl: &ModuleDeclaration,
mod_decl: ModuleDeclaration,
crate_id: CrateId,
macro_processors: &[&dyn MacroProcessor],
) -> Vec<(CompilationError, FileId)> {
Expand Down Expand Up @@ -720,6 +727,8 @@
context,
&mod_decl.ident,
Location::new(Span::empty(0), child_file_id),
mod_decl.outer_attributes,
ast.inner_attributes.clone(),
true,
false,
) {
Expand All @@ -746,11 +755,14 @@

/// Add a child module to the current def_map.
/// On error this returns None and pushes to `errors`
#[allow(clippy::too_many_arguments)]
fn push_child_module(
&mut self,
context: &mut Context,
mod_name: &Ident,
mod_location: Location,
outer_attributes: Vec<SecondaryAttribute>,
inner_attributes: Vec<SecondaryAttribute>,
add_to_parent_scope: bool,
is_contract: bool,
) -> Result<ModuleId, DefCollectorErrorKind> {
Expand All @@ -761,10 +773,11 @@
// if it's an inline module, or the first char of a the file if it's an external module.
// - `location` will always point to the token "foo" in `mod foo` regardless of whether
// it's inline or external.
// Eventually the location put in `ModuleData` is used for codelenses about `contract`s,

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

View workflow job for this annotation

GitHub Actions / Code

Unknown word (codelenses)
// so we keep using `location` so that it continues to work as usual.
let location = Location::new(mod_name.span(), mod_location.file);
let new_module = ModuleData::new(parent, location, is_contract);
let new_module =
ModuleData::new(parent, location, outer_attributes, inner_attributes, is_contract);
let module_id = self.def_collector.def_map.modules.insert(new_module);

let modules = &mut self.def_collector.def_map.modules;
Expand Down
8 changes: 7 additions & 1 deletion compiler/noirc_frontend/src/hir/def_map/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,13 @@ impl CrateDefMap {
// Allocate a default Module for the root, giving it a ModuleId
let mut modules: Arena<ModuleData> = Arena::default();
let location = Location::new(Default::default(), root_file_id);
let root = modules.insert(ModuleData::new(None, location, false));
let root = modules.insert(ModuleData::new(
None,
location,
Vec::new(),
ast.inner_attributes.clone(),
false,
));

let def_map = CrateDefMap {
root: LocalModuleId(root),
Expand Down
20 changes: 19 additions & 1 deletion compiler/noirc_frontend/src/hir/def_map/module_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use noirc_errors::Location;
use super::{ItemScope, LocalModuleId, ModuleDefId, ModuleId, PerNs};
use crate::ast::{Ident, ItemVisibility};
use crate::node_interner::{FuncId, GlobalId, StructId, TraitId, TypeAliasId};
use crate::token::SecondaryAttribute;

/// Contains the actual contents of a module: its parent (if one exists),
/// children, and scope with all definitions defined within the scope.
Expand All @@ -24,17 +25,34 @@ pub struct ModuleData {

/// True if this module is a `contract Foo { ... }` module containing contract functions
pub is_contract: bool,

pub outer_attributes: Vec<String>,
pub inner_attributes: Vec<String>,
}

impl ModuleData {
pub fn new(parent: Option<LocalModuleId>, location: Location, is_contract: bool) -> ModuleData {
pub fn new(
parent: Option<LocalModuleId>,
location: Location,
outer_attributes: Vec<SecondaryAttribute>,
inner_attributes: Vec<SecondaryAttribute>,
is_contract: bool,
) -> ModuleData {
let outer_attributes = outer_attributes.iter().filter_map(|attr| attr.as_custom());
let outer_attributes = outer_attributes.map(|attr| attr.to_string()).collect();

let inner_attributes = inner_attributes.iter().filter_map(|attr| attr.as_custom());
let inner_attributes = inner_attributes.map(|attr| attr.to_string()).collect();

ModuleData {
parent,
children: HashMap::new(),
scope: ItemScope::default(),
definitions: ItemScope::default(),
location,
is_contract,
outer_attributes,
inner_attributes,
}
}

Expand Down
8 changes: 8 additions & 0 deletions compiler/noirc_frontend/src/lexer/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ pub enum LexerErrorKind {
IntegerLiteralTooLarge { span: Span, limit: String },
#[error("{:?} is not a valid attribute", found)]
MalformedFuncAttribute { span: Span, found: String },
#[error("{:?} is not a valid inner attribute", found)]
InvalidInnerAttribute { span: Span, found: String },
#[error("Logical and used instead of bitwise and")]
LogicalAnd { span: Span },
#[error("Unterminated block comment")]
Expand Down Expand Up @@ -57,6 +59,7 @@ impl LexerErrorKind {
LexerErrorKind::InvalidIntegerLiteral { span, .. } => *span,
LexerErrorKind::IntegerLiteralTooLarge { span, .. } => *span,
LexerErrorKind::MalformedFuncAttribute { span, .. } => *span,
LexerErrorKind::InvalidInnerAttribute { span, .. } => *span,
LexerErrorKind::LogicalAnd { span } => *span,
LexerErrorKind::UnterminatedBlockComment { span } => *span,
LexerErrorKind::UnterminatedStringLiteral { span } => *span,
Expand Down Expand Up @@ -103,6 +106,11 @@ impl LexerErrorKind {
format!(" {found} is not a valid attribute"),
*span,
),
LexerErrorKind::InvalidInnerAttribute { span, found } => (
"Invalid inner attribute".to_string(),
format!(" {found} is not a valid inner attribute"),
*span,
),
LexerErrorKind::LogicalAnd { span } => (
"Noir has no logical-and (&&) operator since short-circuiting is much less efficient when compiling to circuits".to_string(),
"Try `&` instead, or use `if` only if you require short-circuiting".to_string(),
Expand Down
34 changes: 32 additions & 2 deletions compiler/noirc_frontend/src/lexer/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
position: Position,
done: bool,
skip_comments: bool,
skip_whitespaces: bool,

Check warning on line 23 in compiler/noirc_frontend/src/lexer/lexer.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (whitespaces)
max_integer: BigInt,
}

Expand Down Expand Up @@ -63,8 +63,8 @@
position: 0,
done: false,
skip_comments: true,
skip_whitespaces: true,

Check warning on line 66 in compiler/noirc_frontend/src/lexer/lexer.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (whitespaces)
max_integer: BigInt::from_biguint(num_bigint::Sign::Plus, FieldElement::modulus())

Check warning on line 67 in compiler/noirc_frontend/src/lexer/lexer.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (biguint)
- BigInt::one(),
}
}
Expand All @@ -74,8 +74,8 @@
self
}

pub fn skip_whitespaces(mut self, flag: bool) -> Self {

Check warning on line 77 in compiler/noirc_frontend/src/lexer/lexer.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (whitespaces)
self.skip_whitespaces = flag;

Check warning on line 78 in compiler/noirc_frontend/src/lexer/lexer.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (whitespaces)
self
}

Expand Down Expand Up @@ -118,7 +118,7 @@
match self.next_char() {
Some(x) if Self::is_code_whitespace(x) => {
let spanned = self.eat_whitespace(x);
if self.skip_whitespaces {

Check warning on line 121 in compiler/noirc_frontend/src/lexer/lexer.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (whitespaces)
self.next_token()
} else {
Ok(spanned)
Expand Down Expand Up @@ -286,6 +286,13 @@
fn eat_attribute(&mut self) -> SpannedTokenResult {
let start = self.position;

let is_inner = if self.peek_char_is('!') {
self.next_char();
true
} else {
false
};

if !self.peek_char_is('[') {
return Err(LexerErrorKind::UnexpectedCharacter {
span: Span::single_char(self.position),
Expand All @@ -309,8 +316,19 @@
let end = self.position;

let attribute = Attribute::lookup_attribute(&word, Span::inclusive(start, end))?;

Ok(attribute.into_span(start, end))
if is_inner {
match attribute {
Attribute::Function(attribute) => Err(LexerErrorKind::InvalidInnerAttribute {
span: Span::from(start..end),
found: attribute.to_string(),
}),
Attribute::Secondary(attribute) => {
Ok(Token::InnerAttribute(attribute).into_span(start, end))
}
}
} else {
Ok(Token::Attribute(attribute).into_span(start, end))
}
}

//XXX(low): Can increase performance if we use iterator semantic and utilize some of the methods on String. See below
Expand Down Expand Up @@ -898,6 +916,18 @@
assert_eq!(sub_string, "test(invalid_scope)");
}

#[test]
fn test_inner_attribute() {
let input = r#"#![something]"#;
let mut lexer = Lexer::new(input);

let token = lexer.next_token().unwrap();
assert_eq!(
token.token(),
&Token::InnerAttribute(SecondaryAttribute::Custom("something".to_string()))
);
}

#[test]
fn test_int_type() {
let input = "u16 i16 i108 u104.5";
Expand Down
Loading
Loading