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 Expr::as_constructor #5980

Merged
merged 16 commits into from
Sep 13, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
8 changes: 5 additions & 3 deletions aztec_macros/src/transforms/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@
///
/// To:
///
/// impl<Context> Storage<Contex> {

Check warning on line 180 in aztec_macros/src/transforms/storage.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (Contex)
/// fn init(context: Context) -> Self {
/// Storage {
/// a_map: Map::new(context, 0, |context, slot| {
Expand Down Expand Up @@ -222,9 +222,11 @@
})
.collect();

let storage_constructor_statement = make_statement(StatementKind::Expression(expression(
ExpressionKind::constructor((chained_path!(storage_struct_name), field_constructors)),
)));
let storage_constructor_statement =
make_statement(StatementKind::Expression(expression(ExpressionKind::constructor((
UnresolvedType::from_path(chained_path!(storage_struct_name)),
field_constructors,
)))));

// This is the type over which the impl is generic.
let generic_context_ident = ident("Context");
Expand Down
2 changes: 1 addition & 1 deletion aztec_macros/src/utils/parse_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,7 @@ fn empty_method_call_expression(method_call_expression: &mut MethodCallExpressio
}

fn empty_constructor_expression(constructor_expression: &mut ConstructorExpression) {
empty_path(&mut constructor_expression.type_name);
empty_unresolved_type(&mut constructor_expression.typ);
for (name, expression) in constructor_expression.fields.iter_mut() {
empty_ident(name);
empty_expression(expression);
Expand Down
10 changes: 6 additions & 4 deletions compiler/noirc_frontend/src/ast/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,9 +200,11 @@ impl ExpressionKind {
ExpressionKind::Literal(Literal::FmtStr(contents))
}

pub fn constructor((type_name, fields): (Path, Vec<(Ident, Expression)>)) -> ExpressionKind {
pub fn constructor(
(typ, fields): (UnresolvedType, Vec<(Ident, Expression)>),
) -> ExpressionKind {
ExpressionKind::Constructor(Box::new(ConstructorExpression {
type_name,
typ,
fields,
struct_type: None,
}))
Expand Down Expand Up @@ -536,7 +538,7 @@ pub struct MethodCallExpression {

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct ConstructorExpression {
pub type_name: Path,
pub typ: UnresolvedType,
pub fields: Vec<(Ident, Expression)>,

/// This may be filled out during macro expansion
Expand Down Expand Up @@ -717,7 +719,7 @@ impl Display for ConstructorExpression {
let fields =
self.fields.iter().map(|(ident, expr)| format!("{ident}: {expr}")).collect::<Vec<_>>();

write!(f, "({} {{ {} }})", self.type_name, fields.join(", "))
write!(f, "({} {{ {} }})", self.typ, fields.join(", "))
}
}

Expand Down
13 changes: 13 additions & 0 deletions compiler/noirc_frontend/src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,19 @@
pub(crate) fn is_type_expression(&self) -> bool {
matches!(&self.typ, UnresolvedTypeData::Expression(_))
}

pub fn from_path(mut path: Path) -> Self {
let span = path.span;
let last_segment = path.segments.last_mut().unwrap();
let generics = std::mem::take(&mut last_segment.generics);
jfecher marked this conversation as resolved.
Show resolved Hide resolved
let generic_type_args = if let Some(generics) = generics {
GenericTypeArgs { ordered_args: generics, named_args: Vec::new() }
} else {
GenericTypeArgs::default()
};
let typ = UnresolvedTypeData::Named(path, generic_type_args, true);
UnresolvedType { typ, span }
}
}

impl UnresolvedTypeData {
Expand Down Expand Up @@ -501,7 +514,7 @@
Self::Public => write!(f, "pub"),
Self::Private => write!(f, "priv"),
Self::CallData(id) => write!(f, "calldata{id}"),
Self::ReturnData => write!(f, "returndata"),

Check warning on line 517 in compiler/noirc_frontend/src/ast/mod.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (returndata)
}
}
}
2 changes: 1 addition & 1 deletion compiler/noirc_frontend/src/ast/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,7 @@ impl Pattern {
}
Some(Expression {
kind: ExpressionKind::Constructor(Box::new(ConstructorExpression {
type_name: path.clone(),
typ: UnresolvedType::from_path(path.clone()),
fields,
struct_type: None,
})),
Expand Down
2 changes: 1 addition & 1 deletion compiler/noirc_frontend/src/ast/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
InternedUnresolvedTypeData, QuotedTypeId,
},
parser::{Item, ItemKind, ParsedSubModule},
token::{CustomAtrribute, SecondaryAttribute, Tokens},

Check warning on line 19 in compiler/noirc_frontend/src/ast/visitor.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (Atrribute)
ParsedModule, QuotedType,
};

Expand Down Expand Up @@ -451,7 +451,7 @@
true
}

fn visit_custom_attribute(&mut self, _: &CustomAtrribute, _target: AttributeTarget) {}

Check warning on line 454 in compiler/noirc_frontend/src/ast/visitor.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (Atrribute)
}

impl ParsedModule {
Expand Down Expand Up @@ -920,7 +920,7 @@
}

pub fn accept_children(&self, visitor: &mut impl Visitor) {
self.type_name.accept(visitor);
self.typ.accept(visitor);

for (_field_name, expression) in &self.fields {
expression.accept(visitor);
Expand Down Expand Up @@ -1248,8 +1248,8 @@
UnresolvedTypeData::Unspecified => visitor.visit_unspecified_type(self.span),
UnresolvedTypeData::Quoted(typ) => visitor.visit_quoted_type(typ, self.span),
UnresolvedTypeData::FieldElement => visitor.visit_field_element_type(self.span),
UnresolvedTypeData::Integer(signdness, size) => {

Check warning on line 1251 in compiler/noirc_frontend/src/ast/visitor.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (signdness)
visitor.visit_integer_type(*signdness, *size, self.span);

Check warning on line 1252 in compiler/noirc_frontend/src/ast/visitor.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (signdness)
}
UnresolvedTypeData::Bool => visitor.visit_bool_type(self.span),
UnresolvedTypeData::Unit => visitor.visit_unit_type(self.span),
Expand Down Expand Up @@ -1349,7 +1349,7 @@
}
}

impl CustomAtrribute {

Check warning on line 1352 in compiler/noirc_frontend/src/ast/visitor.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (Atrribute)
pub fn accept(&self, target: AttributeTarget, visitor: &mut impl Visitor) {
visitor.visit_custom_attribute(self, target);
}
Expand Down
33 changes: 27 additions & 6 deletions compiler/noirc_frontend/src/elaborator/expressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use rustc_hash::FxHashSet as HashSet;
use crate::{
ast::{
ArrayLiteral, ConstructorExpression, IfExpression, InfixExpression, Lambda,
UnresolvedTypeExpression,
UnresolvedTypeData, UnresolvedTypeExpression,
},
hir::{
comptime::{self, InterpreterError},
Expand Down Expand Up @@ -436,22 +436,43 @@ impl<'context> Elaborator<'context> {
&mut self,
constructor: ConstructorExpression,
) -> (HirExpression, Type) {
let span = constructor.typ.span;

// A constructor type can either be a Path or an interned UnresolvedType.
// We represent both as UnresolvedType (with Path being a Named UnresolvedType)
// and error if we don't get a Named path.
let mut typ = constructor.typ.typ;
if let UnresolvedTypeData::Interned(id) = typ {
typ = self.interner.get_unresolved_type_data(id).clone();
}
let UnresolvedTypeData::Named(mut path, generics, _) = typ else {
self.push_err(ResolverError::NonStructUsedInConstructor { typ: typ.to_string(), span });
return (HirExpression::Error, Type::Error);
};

let last_segment = path.segments.last_mut().unwrap();
if !generics.ordered_args.is_empty() {
last_segment.generics = Some(generics.ordered_args);
}

let exclude_last_segment = true;
self.check_unsupported_turbofish_usage(&constructor.type_name, exclude_last_segment);
self.check_unsupported_turbofish_usage(&path, exclude_last_segment);

let span = constructor.type_name.span();
let last_segment = constructor.type_name.last_segment();
let last_segment = path.last_segment();
let is_self_type = last_segment.ident.is_self_type_name();

let (r#type, struct_generics) = if let Some(struct_id) = constructor.struct_type {
let typ = self.interner.get_struct(struct_id);
let generics = typ.borrow().instantiate(self.interner);
(typ, generics)
} else {
match self.lookup_type_or_error(constructor.type_name) {
match self.lookup_type_or_error(path) {
Some(Type::Struct(r#type, struct_generics)) => (r#type, struct_generics),
Some(typ) => {
self.push_err(ResolverError::NonStructUsedInConstructor { typ, span });
self.push_err(ResolverError::NonStructUsedInConstructor {
typ: typ.to_string(),
span,
});
return (HirExpression::Error, Type::Error);
}
None => return (HirExpression::Error, Type::Error),
Expand Down
5 changes: 4 additions & 1 deletion compiler/noirc_frontend/src/elaborator/patterns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,10 @@ impl<'context> Elaborator<'context> {
Some(Type::Struct(struct_type, generics)) => (struct_type, generics),
None => return error_identifier(self),
Some(typ) => {
self.push_err(ResolverError::NonStructUsedInConstructor { typ, span });
self.push_err(ResolverError::NonStructUsedInConstructor {
typ: typ.to_string(),
span,
});
jfecher marked this conversation as resolved.
Show resolved Hide resolved
return error_identifier(self);
}
};
Expand Down
3 changes: 1 addition & 2 deletions compiler/noirc_frontend/src/hir/comptime/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,8 +394,7 @@
let mut diagnostic =
CustomDiagnostic::simple_error(primary, secondary, location.span);

// Only take at most 3 frames starting from the top of the stack to avoid producing too much output
for frame in call_stack.iter().rev().take(3) {
for frame in call_stack.iter().rev() {
jfecher marked this conversation as resolved.
Show resolved Hide resolved
diagnostic.add_secondary_with_file("".to_string(), frame.span, frame.file);
}

Expand Down Expand Up @@ -496,7 +495,7 @@
let message = format!("Failed to parse macro's token stream into {rule}");
let tokens = vecmap(tokens.iter(), ToString::to_string).join(" ");

// 10 is an aribtrary number of tokens here chosen to fit roughly onto one line

Check warning on line 498 in compiler/noirc_frontend/src/hir/comptime/errors.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (aribtrary)
let token_stream = if tokens.len() > 10 {
format!("The resulting token stream was: {tokens}")
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ impl HirExpression {
let struct_type = None;

ExpressionKind::Constructor(Box::new(ConstructorExpression {
type_name,
typ: UnresolvedType::from_path(type_name),
fields,
struct_type,
}))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use builtin_helpers::{
get_format_string, get_function_def, get_module, get_quoted, get_slice, get_struct,
get_trait_constraint, get_trait_def, get_trait_impl, get_tuple, get_type, get_typed_expr,
get_u32, get_unresolved_type, has_named_attribute, hir_pattern_to_tokens,
mutate_func_meta_type, parse, quote_ident, quote_path, replace_func_meta_parameters,
mutate_func_meta_type, parse, quote_ident, replace_func_meta_parameters,
replace_func_meta_return_type,
};
use chumsky::{chain::Chain, prelude::choice, Parser};
Expand All @@ -26,13 +26,13 @@ use crate::{
FunctionReturnType, IntegerBitSize, LValue, Literal, Pattern, Statement, StatementKind,
UnaryOp, UnresolvedType, UnresolvedTypeData, Visibility,
},
hir::def_collector::dc_crate::CollectedItems,
hir::{
comptime::{
errors::IResult,
value::{ExprValue, TypedExpr},
InterpreterError, Value,
},
def_collector::dc_crate::CollectedItems,
def_map::ModuleId,
},
hir_def::function::FunctionBody,
Expand Down Expand Up @@ -1421,7 +1421,7 @@ fn expr_as_constructor(

let option_value =
if let ExprValue::Expression(ExpressionKind::Constructor(constructor)) = expr_value {
let typ = quote_path(&constructor.type_name, interner);
let typ = Value::UnresolvedType(constructor.typ.typ);
let fields = constructor.fields.into_iter();
let fields = fields.map(|(name, value)| {
Value::Tuple(vec![quote_ident(&name), Value::expression(value.kind)])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use noirc_errors::Location;

use crate::{
ast::{
BlockExpression, ExpressionKind, Ident, IntegerBitSize, LValue, Path, Pattern, Signedness,
BlockExpression, ExpressionKind, Ident, IntegerBitSize, LValue, Pattern, Signedness,
StatementKind, UnresolvedTypeData,
},
elaborator::Elaborator,
Expand Down Expand Up @@ -479,30 +479,3 @@ pub(super) fn quote_ident(ident: &Ident) -> Value {
pub(super) fn ident_to_tokens(ident: &Ident) -> Rc<Vec<Token>> {
Rc::new(vec![Token::Ident(ident.0.contents.clone())])
}

pub(super) fn quote_path(path: &Path, interner: &mut NodeInterner) -> Value {
Value::Quoted(path_to_tokens(path, interner))
}

pub(super) fn path_to_tokens(path: &Path, interner: &mut NodeInterner) -> Rc<Vec<Token>> {
let mut tokens = Vec::new();
for (index, segment) in path.segments.iter().enumerate() {
if index > 0 {
tokens.push(Token::DoubleColon);
}
tokens.push(Token::Ident(segment.ident.0.contents.clone()));
if let Some(generics) = &segment.generics {
tokens.push(Token::DoubleColon);
tokens.push(Token::Less);
for (index, generic) in generics.iter().enumerate() {
if index > 0 {
tokens.push(Token::Comma);
}
let id = interner.push_unresolved_type_data(generic.typ.clone());
tokens.push(Token::InternedUnresolvedTypeData(id));
}
tokens.push(Token::Greater);
}
}
Rc::new(tokens)
}
2 changes: 1 addition & 1 deletion compiler/noirc_frontend/src/hir/comptime/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ impl Value {
// Since we've provided the struct_type, the path should be ignored.
let type_name = Path::from_single(String::new(), location.span);
ExpressionKind::Constructor(Box::new(ConstructorExpression {
type_name,
typ: UnresolvedType::from_path(type_name),
fields,
struct_type,
}))
Expand Down
2 changes: 1 addition & 1 deletion compiler/noirc_frontend/src/hir/resolution/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub enum ResolverError {
#[error("Test functions are not allowed to have any parameters")]
TestFunctionHasParameters { span: Span },
#[error("Only struct types can be used in constructor expressions")]
NonStructUsedInConstructor { typ: Type, span: Span },
NonStructUsedInConstructor { typ: String, span: Span },
#[error("Only struct types can have generics")]
NonStructWithGenerics { span: Span },
#[error("Cannot apply generics on Self type")]
Expand Down
7 changes: 6 additions & 1 deletion compiler/noirc_frontend/src/parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ use self::primitives::{keyword, macro_quote_marker, mutable_reference, variable}
use self::types::{generic_type_args, maybe_comp_time};
use attributes::{attributes, inner_attribute, validate_secondary_attributes};
use doc_comments::{inner_doc_comments, outer_doc_comments};
use types::interned_unresolved_type;
pub use types::parse_type;
use visibility::item_visibility;
pub use visibility::visibility;
Expand Down Expand Up @@ -1228,7 +1229,11 @@ fn constructor(expr_parser: impl ExprParser) -> impl NoirParser<ExpressionKind>
.allow_trailing()
.delimited_by(just(Token::LeftBrace), just(Token::RightBrace));

path(super::parse_type()).then(args).map(ExpressionKind::constructor)
let path = path(super::parse_type()).map(UnresolvedType::from_path);
let interned_unresolved_type = interned_unresolved_type();
let typ = choice((path, interned_unresolved_type));

typ.then(args).map(ExpressionKind::constructor)
}

fn constructor_field<P>(expr_parser: P) -> impl NoirParser<(Ident, Expression)>
Expand Down
16 changes: 8 additions & 8 deletions noir_stdlib/src/meta/expr.nr
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ impl Expr {
/// expression and the type to cast to.
// docs:start:as_cast
#[builtin(expr_as_cast)]
fn as_cast(self) -> Option<(Expr, UnresolvedType)> {}
comptime fn as_cast(self) -> Option<(Expr, UnresolvedType)> {}
// docs:end:as_cast

/// If this expression is a `comptime { stmt1; stmt2; ...; stmtN }` block,
Expand All @@ -69,7 +69,7 @@ impl Expr {
/// return the type and the fields.
#[builtin(expr_as_constructor)]
// docs:start:as_constructor
fn as_constructor(self) -> Option<(Quoted, [(Quoted, Expr)])> {}
comptime fn as_constructor(self) -> Option<(UnresolvedType, [(Quoted, Expr)])> {}
// docs:end:as_constructor

/// If this expression is a function call `foo(arg1, ..., argN)`, return
Expand Down Expand Up @@ -98,7 +98,7 @@ impl Expr {
/// as well as whether the integer is negative (true) or not (false).
#[builtin(expr_as_integer)]
// docs:start:as_integer
fn as_integer(self) -> Option<(Field, bool)> {}
comptime fn as_integer(self) -> Option<(Field, bool)> {}
// docs:end:as_integer

/// If this expression is a let statement, returns the let pattern as an `Expr`,
Expand Down Expand Up @@ -341,9 +341,9 @@ comptime fn modify_comptime<Env>(expr: Expr, f: fn[Env](Expr) -> Option<Expr>) -
)
}

fn modify_constructor<Env>(expr: Expr, f: fn[Env](Expr) -> Option<Expr>) -> Option<Expr> {
comptime fn modify_constructor<Env>(expr: Expr, f: fn[Env](Expr) -> Option<Expr>) -> Option<Expr> {
expr.as_constructor().map(
|expr: (Quoted, [(Quoted, Expr)])| {
|expr: (UnresolvedType, [(Quoted, Expr)])| {
let (typ, fields) = expr;
let fields = fields.map(|field: (Quoted, Expr)| {
let (name, value) = field;
Expand All @@ -354,7 +354,7 @@ fn modify_constructor<Env>(expr: Expr, f: fn[Env](Expr) -> Option<Expr>) -> Opti
)
}

fn modify_function_call<Env>(expr: Expr, f: fn[Env](Expr) -> Option<Expr>) -> Option<Expr> {
comptime fn modify_function_call<Env>(expr: Expr, f: fn[Env](Expr) -> Option<Expr>) -> Option<Expr> {
expr.as_function_call().map(
|expr: (Expr, [Expr])| {
let (function, arguments) = expr;
Expand Down Expand Up @@ -529,7 +529,7 @@ comptime fn new_comptime(exprs: [Expr]) -> Expr {
quote { comptime { $exprs }}.as_expr().unwrap()
}

fn new_constructor(typ: Quoted, fields: [(Quoted, Expr)]) -> Expr {
comptime fn new_constructor(typ: UnresolvedType, fields: [(Quoted, Expr)]) -> Expr {
let fields = fields.map(
|field: (Quoted, Expr)| {
let (name, value) = field;
Expand All @@ -539,7 +539,7 @@ fn new_constructor(typ: Quoted, fields: [(Quoted, Expr)]) -> Expr {
quote { $typ { $fields }}.as_expr().unwrap()
}

fn new_if(condition: Expr, consequence: Expr, alternative: Option<Expr>) -> Expr {
comptime fn new_if(condition: Expr, consequence: Expr, alternative: Option<Expr>) -> Expr {
if alternative.is_some() {
let alternative = alternative.unwrap();
quote { if $condition { $consequence } else { $alternative }}.as_expr().unwrap()
Expand Down
3 changes: 1 addition & 2 deletions test_programs/noir_test_success/comptime_expr/src/main.nr
Original file line number Diff line number Diff line change
Expand Up @@ -331,8 +331,7 @@ mod tests {
comptime
{
let expr = quote { Foo { a: 1, b: 2 } }.as_expr().unwrap();
let (typ, fields) = expr.as_constructor().unwrap();
assert_eq(typ, quote { Foo });
let (_typ, fields) = expr.as_constructor().unwrap();
assert_eq(fields.len(), 2);
assert_eq(fields[0].0, quote { a });
assert_eq(fields[0].1.as_integer().unwrap(), (1, false));
Expand Down
12 changes: 9 additions & 3 deletions tooling/lsp/src/requests/code_action/fill_struct_fields.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use lsp_types::TextEdit;
use noirc_errors::{Location, Span};
use noirc_frontend::{ast::ConstructorExpression, node_interner::ReferenceId};
use noirc_frontend::{
ast::{ConstructorExpression, UnresolvedTypeData},
node_interner::ReferenceId,
};

use crate::byte_span_to_range;

Expand All @@ -12,8 +15,11 @@ impl<'a> CodeActionFinder<'a> {
return;
}

// Find out which struct this is
let location = Location::new(constructor.type_name.last_ident().span(), self.file);
let UnresolvedTypeData::Named(path, _, _) = &constructor.typ.typ else {
return;
};

let location = Location::new(path.span, self.file);
let Some(ReferenceId::Struct(struct_id)) = self.interner.find_referenced(location) else {
return;
};
Expand Down
Loading
Loading