Skip to content

Commit

Permalink
chore(experimental): Add scan pass and into_expression for comptime…
Browse files Browse the repository at this point in the history
… interpreter (#4884)

# Description

## Problem\*

Resolves #4590

## Summary\*

This PR links up the comptime interpreter with the rest of the codebase.
It does so by adding a scanning step where the Hir is scanned for
`comptime` expressions to execute. When one of these is found, the
interpreter switches to evaluation mode and evaluates the expression.
Afterward, the result of the expression is inlined into the Hir via
`Value::into_expression`. For `Code` values, this means the entire code
block is spliced in (a macro expansion).

You can now run simple programs at compile-time now as long as they
don't have expansion of `quote`d values (macros) since those would
require the full loop back to name resolution again. Anyway, here's an
example that works now:

```rs
fn main() {
    let x = comptime { 2 * 4 };
    println(x);
}
```
By monomorphization the compiler sees
```rs
fn main() {
    let x = 8;
    println(x);
}
```
More complex expressions within the `comptime` block should also work.
Just note that this scanning + evaluation is currently only within
functions. So comptime globals won't be evaluated.

## Additional Context

I may try splitting out this PR into several smaller ones but need to
look into where to make the split more. Leaving this up for now in case
people find it useful or it's not as big as I expected.

Future changes:

Architecture-wise we're only missing the ability to make the full loop
and go back to name resolution after a macro expansion now. Since we
already have the Hir -> Ast pass (although it can be considerably
improved since it is rather broken still), we only need to call it after
the comptime interpreter and run name resolution again.

## 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\*

- [ ] I have tested the changes locally.
- [ ] I have formatted the changes with [Prettier](https://prettier.io/)
and/or `cargo fmt` on default settings.
  • Loading branch information
jfecher authored Apr 23, 2024
1 parent 9704bd0 commit ce5e1a5
Show file tree
Hide file tree
Showing 22 changed files with 667 additions and 251 deletions.
2 changes: 2 additions & 0 deletions compiler/noirc_frontend/src/ast/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub enum ExpressionKind {
Lambda(Box<Lambda>),
Parenthesized(Box<Expression>),
Quote(BlockExpression),
Comptime(BlockExpression),
Error,
}

Expand Down Expand Up @@ -504,6 +505,7 @@ impl Display for ExpressionKind {
Lambda(lambda) => lambda.fmt(f),
Parenthesized(sub_expr) => write!(f, "({sub_expr})"),
Quote(block) => write!(f, "quote {block}"),
Comptime(block) => write!(f, "comptime {block}"),
Error => write!(f, "Error"),
}
}
Expand Down
8 changes: 4 additions & 4 deletions compiler/noirc_frontend/src/ast/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pub enum StatementKind {
Break,
Continue,
/// This statement should be executed at compile-time
Comptime(Box<StatementKind>),
CompTime(Box<StatementKind>),
// This is an expression with a trailing semi-colon
Semi(Expression),
// This statement is the result of a recovered parse error.
Expand Down Expand Up @@ -87,10 +87,10 @@ impl StatementKind {
}
self
}
StatementKind::Comptime(mut statement) => {
StatementKind::CompTime(mut statement) => {
*statement =
statement.add_semicolon(semi, span, last_statement_in_block, emit_error);
StatementKind::Comptime(statement)
StatementKind::CompTime(statement)
}
// A semicolon on a for loop is optional and does nothing
StatementKind::For(_) => self,
Expand Down Expand Up @@ -685,7 +685,7 @@ impl Display for StatementKind {
StatementKind::For(for_loop) => for_loop.fmt(f),
StatementKind::Break => write!(f, "break"),
StatementKind::Continue => write!(f, "continue"),
StatementKind::Comptime(statement) => write!(f, "comptime {statement}"),
StatementKind::CompTime(statement) => write!(f, "comptime {statement}"),
StatementKind::Semi(semi) => write!(f, "{semi};"),
StatementKind::Error => write!(f, "Error"),
}
Expand Down
53 changes: 53 additions & 0 deletions compiler/noirc_frontend/src/hir/comptime/errors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use crate::{node_interner::DefinitionId, Type};
use acvm::FieldElement;
use noirc_errors::Location;

use super::value::Value;

/// The possible errors that can halt the interpreter.
#[derive(Debug)]
pub enum InterpreterError {
ArgumentCountMismatch { expected: usize, actual: usize, call_location: Location },
TypeMismatch { expected: Type, value: Value, location: Location },
NoValueForId { id: DefinitionId, location: Location },
IntegerOutOfRangeForType { value: FieldElement, typ: Type, location: Location },
ErrorNodeEncountered { location: Location },
NonFunctionCalled { value: Value, location: Location },
NonBoolUsedInIf { value: Value, location: Location },
NonBoolUsedInConstrain { value: Value, location: Location },
FailingConstraint { message: Option<Value>, location: Location },
NoMethodFound { object: Value, typ: Type, location: Location },
NonIntegerUsedInLoop { value: Value, location: Location },
NonPointerDereferenced { value: Value, location: Location },
NonTupleOrStructInMemberAccess { value: Value, location: Location },
NonArrayIndexed { value: Value, location: Location },
NonIntegerUsedAsIndex { value: Value, location: Location },
NonIntegerIntegerLiteral { typ: Type, location: Location },
NonIntegerArrayLength { typ: Type, location: Location },
NonNumericCasted { value: Value, location: Location },
IndexOutOfBounds { index: usize, length: usize, location: Location },
ExpectedStructToHaveField { value: Value, field_name: String, location: Location },
TypeUnsupported { typ: Type, location: Location },
InvalidValueForUnary { value: Value, operator: &'static str, location: Location },
InvalidValuesForBinary { lhs: Value, rhs: Value, operator: &'static str, location: Location },
CastToNonNumericType { typ: Type, location: Location },
QuoteInRuntimeCode { location: Location },
NonStructInConstructor { typ: Type, location: Location },
CannotInlineMacro { value: Value, location: Location },
UnquoteFoundDuringEvaluation { location: Location },

Unimplemented { item: &'static str, location: Location },

// Perhaps this should be unreachable! due to type checking also preventing this error?
// Currently it and the Continue variant are the only interpreter errors without a Location field
BreakNotInLoop { location: Location },
ContinueNotInLoop { location: Location },

// 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.
Break,
Continue,
}

#[allow(unused)]
pub(super) type IResult<T> = std::result::Result<T, InterpreterError>;
26 changes: 17 additions & 9 deletions compiler/noirc_frontend/src/hir/comptime/hir_to_ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::ast::{
UnresolvedTypeData, UnresolvedTypeExpression,
};
use crate::ast::{ConstrainStatement, Expression, Statement, StatementKind};
use crate::hir_def::expr::{HirArrayLiteral, HirExpression, HirIdent};
use crate::hir_def::expr::{HirArrayLiteral, HirBlockExpression, HirExpression, HirIdent};
use crate::hir_def::stmt::{HirLValue, HirPattern, HirStatement};
use crate::hir_def::types::Type;
use crate::macros_api::HirLiteral;
Expand All @@ -26,7 +26,7 @@ impl StmtId {
#[allow(unused)]
fn to_ast(self, interner: &NodeInterner) -> Statement {
let statement = interner.statement(&self);
let span = interner.statement_span(&self);
let span = interner.statement_span(self);

let kind = match statement {
HirStatement::Let(let_stmt) => {
Expand Down Expand Up @@ -66,8 +66,8 @@ impl StmtId {
HirStatement::Expression(expr) => StatementKind::Expression(expr.to_ast(interner)),
HirStatement::Semi(expr) => StatementKind::Semi(expr.to_ast(interner)),
HirStatement::Error => StatementKind::Error,
HirStatement::Comptime(statement) => {
StatementKind::Comptime(Box::new(statement.to_ast(interner).kind))
HirStatement::CompTime(statement) => {
StatementKind::CompTime(Box::new(statement.to_ast(interner).kind))
}
};

Expand Down Expand Up @@ -108,10 +108,7 @@ impl ExprId {
ExpressionKind::Literal(Literal::FmtStr(string))
}
HirExpression::Literal(HirLiteral::Unit) => ExpressionKind::Literal(Literal::Unit),
HirExpression::Block(expr) => {
let statements = vecmap(expr.statements, |statement| statement.to_ast(interner));
ExpressionKind::Block(BlockExpression { statements })
}
HirExpression::Block(expr) => ExpressionKind::Block(expr.into_ast(interner)),
HirExpression::Prefix(prefix) => ExpressionKind::Prefix(Box::new(PrefixExpression {
operator: prefix.operator,
rhs: prefix.rhs.to_ast(interner),
Expand Down Expand Up @@ -172,8 +169,12 @@ impl ExprId {
let body = lambda.body.to_ast(interner);
ExpressionKind::Lambda(Box::new(Lambda { parameters, return_type, body }))
}
HirExpression::Quote(block) => ExpressionKind::Quote(block),
HirExpression::Error => ExpressionKind::Error,
HirExpression::Comptime(block) => ExpressionKind::Comptime(block.into_ast(interner)),
HirExpression::Quote(block) => ExpressionKind::Quote(block),

// A macro was evaluated here!
HirExpression::Unquote(block) => ExpressionKind::Block(block),
};

Expression::new(kind, span)
Expand Down Expand Up @@ -353,3 +354,10 @@ impl HirArrayLiteral {
}
}
}

impl HirBlockExpression {
fn into_ast(self, interner: &NodeInterner) -> BlockExpression {
let statements = vecmap(self.statements, |statement| statement.to_ast(interner));
BlockExpression { statements }
}
}
Loading

0 comments on commit ce5e1a5

Please sign in to comment.