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 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
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,8 +12,8 @@ use crate::{
UseTreeKind,
},
node_interner::{
ExprId, InternedExpressionKind, InternedStatementKind, InternedUnresolvedTypeData,
QuotedTypeId,
ExprId, InternedExpressionKind, InternedPattern, InternedStatementKind,
InternedUnresolvedTypeData, QuotedTypeId,
},
parser::{Item, ItemKind, ParsedSubModule},
token::{CustomAtrribute, SecondaryAttribute, Tokens},
Expand Down Expand Up @@ -440,6 +440,8 @@ pub trait Visitor {
true
}

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

fn visit_secondary_attribute(
&mut self,
_: &SecondaryAttribute,
Expand Down Expand Up @@ -1321,6 +1323,9 @@ impl Pattern {
}
}
}
Pattern::Interned(id, span) => {
visitor.visit_interned_pattern(id, *span);
}
}
}
}
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 @@ -675,6 +675,7 @@ fn pattern_vars(pattern: &ast::Pattern) -> Vec<(ast::Ident, bool)> {
stack.extend(pids.iter().map(|(_, pattern)| (pattern, is_mut)));
vars.extend(pids.iter().map(|(id, _)| (id.clone(), false)));
}
ast::Pattern::Interned(_, _) => (),
}
}
vars
Expand All @@ -701,6 +702,7 @@ fn pattern_to_string(pattern: &ast::Pattern) -> String {
.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)
}
}
}
}
99 changes: 77 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 @@ -1500,6 +1501,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 @@ -1777,27 +1813,33 @@ 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) {
let (expr_id, _) = elaborator.elaborate_expression(expression);
Ok(Value::TypedExpr(TypedExpr::ExprId(expr_id)))
} 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 @@ -1819,6 +1861,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 @@ -2031,6 +2076,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