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_let #5964

Merged
merged 6 commits into from
Sep 9, 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
1 change: 1 addition & 0 deletions aztec_macros/src/utils/parse_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,7 @@ fn empty_pattern(pattern: &mut Pattern) {
empty_pattern(pattern);
}
}
Pattern::Interned(_, _) => (),
}
}

Expand Down
48 changes: 43 additions & 5 deletions compiler/noirc_frontend/src/ast/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ use iter_extended::vecmap;
use noirc_errors::{Span, Spanned};

use super::{
BlockExpression, Expression, ExpressionKind, GenericTypeArgs, IndexExpression, ItemVisibility,
MemberAccessExpression, MethodCallExpression, UnresolvedType,
BlockExpression, ConstructorExpression, Expression, ExpressionKind, GenericTypeArgs,
IndexExpression, ItemVisibility, MemberAccessExpression, MethodCallExpression, UnresolvedType,
};
use crate::elaborator::types::SELF_TYPE_NAME;
use crate::lexer::token::SpannedToken;
use crate::macros_api::{SecondaryAttribute, UnresolvedTypeData};
use crate::node_interner::{InternedExpressionKind, InternedStatementKind};
use crate::macros_api::{NodeInterner, SecondaryAttribute, UnresolvedTypeData};
use crate::node_interner::{InternedExpressionKind, InternedPattern, InternedStatementKind};
use crate::parser::{ParserError, ParserErrorReason};
use crate::token::Token;

Expand Down Expand Up @@ -565,6 +565,7 @@ pub enum Pattern {
Mutable(Box<Pattern>, Span, /*is_synthesized*/ bool),
Tuple(Vec<Pattern>, Span),
Struct(Path, Vec<(Ident, Pattern)>, Span),
Interned(InternedPattern, Span),
}

impl Pattern {
Expand All @@ -577,7 +578,8 @@ impl Pattern {
Pattern::Identifier(ident) => ident.span(),
Pattern::Mutable(_, span, _)
| Pattern::Tuple(_, span)
| Pattern::Struct(_, _, span) => *span,
| Pattern::Struct(_, _, span)
| Pattern::Interned(_, span) => *span,
}
}
pub fn name_ident(&self) -> &Ident {
Expand All @@ -595,6 +597,39 @@ impl Pattern {
other => panic!("Pattern::into_ident called on {other} pattern with no identifier"),
}
}

pub(crate) fn try_as_expression(&self, interner: &NodeInterner) -> Option<Expression> {
match self {
Pattern::Identifier(ident) => Some(Expression {
kind: ExpressionKind::Variable(Path::from_ident(ident.clone())),
span: ident.span(),
}),
Pattern::Mutable(_, _, _) => None,
Pattern::Tuple(patterns, span) => {
let mut expressions = Vec::new();
for pattern in patterns {
expressions.push(pattern.try_as_expression(interner)?);
}
Some(Expression { kind: ExpressionKind::Tuple(expressions), span: *span })
}
Pattern::Struct(path, patterns, span) => {
let mut fields = Vec::new();
for (field, pattern) in patterns {
let expression = pattern.try_as_expression(interner)?;
fields.push((field.clone(), expression));
}
Some(Expression {
kind: ExpressionKind::Constructor(Box::new(ConstructorExpression {
type_name: path.clone(),
fields,
struct_type: None,
})),
span: *span,
})
}
Pattern::Interned(id, _) => interner.get_pattern(*id).try_as_expression(interner),
}
}
}

impl Recoverable for Pattern {
Expand Down Expand Up @@ -905,6 +940,9 @@ impl Display for Pattern {
let fields = vecmap(fields, |(name, pattern)| format!("{name}: {pattern}"));
write!(f, "{} {{ {} }}", typename, fields.join(", "))
}
Pattern::Interned(_, _) => {
write!(f, "?Interned")
}
}
}
}
Expand Down
9 changes: 7 additions & 2 deletions compiler/noirc_frontend/src/ast/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@
UseTreeKind,
},
node_interner::{
ExprId, InternedExpressionKind, InternedStatementKind, InternedUnresolvedTypeData,
QuotedTypeId,
ExprId, InternedExpressionKind, InternedPattern, InternedStatementKind,
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 @@ -440,6 +440,8 @@
true
}

fn visit_interned_pattern(&mut self, _: &InternedPattern, _: Span) {}

fn visit_secondary_attribute(
&mut self,
_: &SecondaryAttribute,
Expand All @@ -448,7 +450,7 @@
true
}

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

Check warning on line 453 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 @@ -1241,8 +1243,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 1246 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 1247 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 @@ -1321,6 +1323,9 @@
}
}
}
Pattern::Interned(id, span) => {
visitor.visit_interned_pattern(id, *span);
}
}
}
}
Expand All @@ -1339,7 +1344,7 @@
}
}

impl CustomAtrribute {

Check warning on line 1347 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
2 changes: 2 additions & 0 deletions compiler/noirc_frontend/src/debug/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@
}
ast::LValue::Dereference(_lv, span) => {
// TODO: this is a dummy statement for now, but we should
// somehow track the derefence and update the pointed to

Check warning on line 288 in compiler/noirc_frontend/src/debug/mod.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (derefence)
// variable
ast::Statement {
kind: ast::StatementKind::Expression(uint_expr(0, *span)),
Expand Down Expand Up @@ -671,10 +671,11 @@
ast::Pattern::Tuple(patterns, _) => {
stack.extend(patterns.iter().map(|pattern| (pattern, false)));
}
ast::Pattern::Struct(_, pids, _) => {

Check warning on line 674 in compiler/noirc_frontend/src/debug/mod.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (pids)
stack.extend(pids.iter().map(|(_, pattern)| (pattern, is_mut)));

Check warning on line 675 in compiler/noirc_frontend/src/debug/mod.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (pids)
vars.extend(pids.iter().map(|(id, _)| (id.clone(), false)));

Check warning on line 676 in compiler/noirc_frontend/src/debug/mod.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (pids)
}
ast::Pattern::Interned(_, _) => (),
}
}
vars
Expand All @@ -701,6 +702,7 @@
.join(", "),
)
}
ast::Pattern::Interned(_, _) => "?Interned".to_string(),
}
}

Expand Down
11 changes: 11 additions & 0 deletions compiler/noirc_frontend/src/elaborator/patterns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,17 @@ impl<'context> Elaborator<'context> {
mutable,
new_definitions,
),
Pattern::Interned(id, _) => {
let pattern = self.interner.get_pattern(id).clone();
self.elaborate_pattern_mut(
pattern,
expected_type,
definition,
mutable,
new_definitions,
global_id,
)
}
}
}

Expand Down
20 changes: 19 additions & 1 deletion compiler/noirc_frontend/src/hir/comptime/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,14 @@ pub enum InterpreterError {
duplicate_location: Location,
existing_location: Location,
},
CannotResolveExpression {
location: Location,
expression: String,
},
CannotSetFunctionBody {
location: Location,
expression: String,
},

// These cases are not errors, they are just used to prevent us from running more code
// until the loop can be resumed properly. These cases will never be displayed to users.
Expand Down Expand Up @@ -291,7 +299,9 @@ impl InterpreterError {
| InterpreterError::InvalidAttribute { location, .. }
| InterpreterError::GenericNameShouldBeAnIdent { location, .. }
| InterpreterError::DuplicateGeneric { duplicate_location: location, .. }
| InterpreterError::TypeAnnotationsNeededForMethodCall { location } => *location,
| InterpreterError::TypeAnnotationsNeededForMethodCall { location }
| InterpreterError::CannotResolveExpression { location, .. }
| InterpreterError::CannotSetFunctionBody { location, .. } => *location,

InterpreterError::FailedToParseMacro { error, file, .. } => {
Location::new(error.span(), *file)
Expand Down Expand Up @@ -626,6 +636,14 @@ impl<'a> From<&'a InterpreterError> for CustomDiagnostic {
);
error
}
InterpreterError::CannotResolveExpression { location, expression } => {
let msg = format!("Cannot resolve expression `{expression}`");
CustomDiagnostic::simple_error(msg, String::new(), location.span)
}
InterpreterError::CannotSetFunctionBody { location, expression } => {
let msg = format!("`{expression}` is not a valid function body");
CustomDiagnostic::simple_error(msg, String::new(), location.span)
}
}
}
}
98 changes: 76 additions & 22 deletions compiler/noirc_frontend/src/hir/comptime/interpreter/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ use rustc_hash::FxHashMap as HashMap;
use crate::{
ast::{
ArrayLiteral, BlockExpression, ConstrainKind, Expression, ExpressionKind, FunctionKind,
FunctionReturnType, IntegerBitSize, LValue, Literal, Statement, StatementKind, UnaryOp,
UnresolvedType, UnresolvedTypeData, Visibility,
FunctionReturnType, IntegerBitSize, LValue, Literal, Pattern, Statement, StatementKind,
UnaryOp, UnresolvedType, UnresolvedTypeData, Visibility,
},
hir::def_collector::dc_crate::CollectedItems,
hir::{
Expand Down Expand Up @@ -78,6 +78,7 @@ impl<'local, 'context> Interpreter<'local, 'context> {
"expr_as_if" => expr_as_if(interner, arguments, return_type, location),
"expr_as_index" => expr_as_index(interner, arguments, return_type, location),
"expr_as_integer" => expr_as_integer(interner, arguments, return_type, location),
"expr_as_let" => expr_as_let(interner, arguments, return_type, location),
"expr_as_member_access" => {
expr_as_member_access(interner, arguments, return_type, location)
}
Expand Down Expand Up @@ -1494,6 +1495,41 @@ fn expr_as_integer(
})
}

// fn as_let(self) -> Option<(Expr, Option<UnresolvedType>, Expr)>
fn expr_as_let(
interner: &NodeInterner,
arguments: Vec<(Value, Location)>,
return_type: Type,
location: Location,
) -> IResult<Value> {
expr_as(interner, arguments, return_type.clone(), location, |expr| match expr {
ExprValue::Statement(StatementKind::Let(let_statement)) => {
let option_type = extract_option_generic_type(return_type);
let Type::Tuple(mut tuple_types) = option_type else {
panic!("Expected the return type option generic arg to be a tuple");
};
assert_eq!(tuple_types.len(), 3);
tuple_types.pop().unwrap();
let option_type = tuple_types.pop().unwrap();

let typ = if let_statement.r#type.typ == UnresolvedTypeData::Unspecified {
None
} else {
Some(Value::UnresolvedType(let_statement.r#type.typ))
};

let typ = option(option_type, typ).ok()?;

Some(Value::Tuple(vec![
Value::pattern(let_statement.pattern),
typ,
Value::expression(let_statement.expression.kind),
]))
}
_ => None,
})
}

// fn as_member_access(self) -> Option<(Expr, Quoted)>
fn expr_as_member_access(
interner: &NodeInterner,
Expand Down Expand Up @@ -1771,27 +1807,32 @@ fn expr_resolve(
interpreter.current_function
};

let value =
interpreter.elaborate_in_function(function_to_resolve_in, |elaborator| match expr_value {
ExprValue::Expression(expression_kind) => {
let expr = Expression { kind: expression_kind, span: self_argument_location.span };
let (expr_id, _) = elaborator.elaborate_expression(expr);
Value::TypedExpr(TypedExpr::ExprId(expr_id))
}
ExprValue::Statement(statement_kind) => {
let statement =
Statement { kind: statement_kind, span: self_argument_location.span };
let (stmt_id, _) = elaborator.elaborate_statement(statement);
Value::TypedExpr(TypedExpr::StmtId(stmt_id))
}
ExprValue::LValue(lvalue) => {
let expr = lvalue.as_expression();
let (expr_id, _) = elaborator.elaborate_expression(expr);
Value::TypedExpr(TypedExpr::ExprId(expr_id))
interpreter.elaborate_in_function(function_to_resolve_in, |elaborator| match expr_value {
ExprValue::Expression(expression_kind) => {
let expr = Expression { kind: expression_kind, span: self_argument_location.span };
let (expr_id, _) = elaborator.elaborate_expression(expr);
Ok(Value::TypedExpr(TypedExpr::ExprId(expr_id)))
}
ExprValue::Statement(statement_kind) => {
let statement = Statement { kind: statement_kind, span: self_argument_location.span };
let (stmt_id, _) = elaborator.elaborate_statement(statement);
Ok(Value::TypedExpr(TypedExpr::StmtId(stmt_id)))
}
ExprValue::LValue(lvalue) => {
let expr = lvalue.as_expression();
let (expr_id, _) = elaborator.elaborate_expression(expr);
Ok(Value::TypedExpr(TypedExpr::ExprId(expr_id)))
}
ExprValue::Pattern(pattern) => {
if let Some(expression) = pattern.try_as_expression(elaborator.interner) {
Ok(Value::expression(expression.kind))
jfecher marked this conversation as resolved.
Show resolved Hide resolved
} else {
let expression = Value::pattern(pattern).display(elaborator.interner).to_string();
let location = self_argument_location;
Err(InterpreterError::CannotResolveExpression { location, expression })
}
});

Ok(value)
}
})
}

fn unwrap_expr_value(interner: &NodeInterner, mut expr_value: ExprValue) -> ExprValue {
Expand All @@ -1813,6 +1854,9 @@ fn unwrap_expr_value(interner: &NodeInterner, mut expr_value: ExprValue) -> Expr
ExprValue::LValue(LValue::Interned(id, span)) => {
expr_value = ExprValue::LValue(interner.get_lvalue(id, span).clone());
}
ExprValue::Pattern(Pattern::Interned(id, _)) => {
expr_value = ExprValue::Pattern(interner.get_pattern(id).clone());
}
_ => break,
}
}
Expand Down Expand Up @@ -2013,6 +2057,16 @@ fn function_def_set_body(
}),
ExprValue::Statement(statement_kind) => statement_kind,
ExprValue::LValue(lvalue) => StatementKind::Expression(lvalue.as_expression()),
ExprValue::Pattern(pattern) => {
if let Some(expression) = pattern.try_as_expression(interpreter.elaborator.interner) {
StatementKind::Expression(expression)
} else {
let expression =
Value::pattern(pattern).display(interpreter.elaborator.interner).to_string();
let location = body_location;
return Err(InterpreterError::CannotSetFunctionBody { location, expression });
}
}
};

let statement = Statement { kind: statement_kind, span: body_location.span };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use noirc_errors::Location;

use crate::{
ast::{
BlockExpression, ExpressionKind, IntegerBitSize, LValue, Signedness, StatementKind,
UnresolvedTypeData,
BlockExpression, ExpressionKind, IntegerBitSize, LValue, Pattern, Signedness,
StatementKind, UnresolvedTypeData,
},
elaborator::Elaborator,
hir::{
Expand Down Expand Up @@ -191,6 +191,9 @@ pub(crate) fn get_expr(
ExprValue::LValue(LValue::Interned(id, _)) => {
Ok(ExprValue::LValue(interner.get_lvalue(id, location.span).clone()))
}
ExprValue::Pattern(Pattern::Interned(id, _)) => {
Ok(ExprValue::Pattern(interner.get_pattern(id).clone()))
}
_ => Ok(expr),
},
value => type_mismatch(value, Type::Quoted(QuotedType::Expr), location),
Expand Down
Loading
Loading