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

fix: Fix using lazily elaborated comptime globals #5995

Merged
merged 1 commit into from
Sep 11, 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
9 changes: 0 additions & 9 deletions compiler/noirc_frontend/src/elaborator/patterns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -513,15 +513,6 @@ impl<'context> Elaborator<'context> {
let typ = self.type_check_variable(expr, id, generics);
self.interner.push_expr_type(id, typ.clone());

// Comptime variables must be replaced with their values
if let Some(definition) = self.interner.try_definition(definition_id) {
if definition.comptime && !self.in_comptime_context() {
let mut interpreter = self.setup_interpreter();
let value = interpreter.evaluate(id);
return self.inline_comptime_value(value, span);
}
}

(id, typ)
}

Expand Down
23 changes: 17 additions & 6 deletions compiler/noirc_frontend/src/hir/comptime/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@
}
} else {
let name = self.elaborator.interner.function_name(&function);
unreachable!("Non-builtin, lowlevel or oracle builtin fn '{name}'")

Check warning on line 240 in compiler/noirc_frontend/src/hir/comptime/interpreter.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (lowlevel)
}
}

Expand Down Expand Up @@ -434,7 +434,14 @@

for scope in self.elaborator.interner.comptime_scopes.iter_mut().rev() {
if let Entry::Occupied(mut entry) = scope.entry(id) {
entry.insert(argument);
match entry.get() {
Value::Pointer(reference, true) => {
*reference.borrow_mut() = argument;
}
_ => {
entry.insert(argument);
}
}
return Ok(());
}
}
Expand Down Expand Up @@ -527,12 +534,13 @@
DefinitionKind::Local(_) => self.lookup(&ident),
DefinitionKind::Global(global_id) => {
// Avoid resetting the value if it is already known
if let Ok(value) = self.lookup(&ident) {
Ok(value)
if let Some(value) = &self.elaborator.interner.get_global(*global_id).value {
Ok(value.clone())
} else {
let crate_of_global = self.elaborator.interner.get_global(*global_id).crate_id;
let global_id = *global_id;
let crate_of_global = self.elaborator.interner.get_global(global_id).crate_id;
let let_ =
self.elaborator.interner.get_global_let_statement(*global_id).ok_or_else(
self.elaborator.interner.get_global_let_statement(global_id).ok_or_else(
|| {
let location = self.elaborator.interner.expr_location(&id);
InterpreterError::VariableNotInScope { location }
Expand All @@ -542,7 +550,10 @@
if let_.comptime || crate_of_global != self.crate_id {
self.evaluate_let(let_.clone())?;
}
self.lookup(&ident)

let value = self.lookup(&ident)?;
self.elaborator.interner.get_global_mut(global_id).value = Some(value.clone());
Ok(value)
}
}
DefinitionKind::GenericType(type_variable) => {
Expand Down
5 changes: 5 additions & 0 deletions compiler/noirc_frontend/src/hir/comptime/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@
Value::Expr(ExprValue::Statement(statement))
}

pub(crate) fn lvalue(lvaue: LValue) -> Self {

Check warning on line 99 in compiler/noirc_frontend/src/hir/comptime/value.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (lvaue)
Value::Expr(ExprValue::LValue(lvaue))

Check warning on line 100 in compiler/noirc_frontend/src/hir/comptime/value.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (lvaue)
}

pub(crate) fn pattern(pattern: Pattern) -> Self {
Expand Down Expand Up @@ -405,6 +405,11 @@
}
Value::Quoted(tokens) => HirExpression::Unquote(add_token_spans(tokens, location.span)),
Value::TypedExpr(TypedExpr::ExprId(expr_id)) => interner.expression(&expr_id),
// Only convert pointers with auto_deref = true. These are mutable variables
// and we don't need to wrap them in `&mut`.
Value::Pointer(element, true) => {
return element.unwrap_or_clone().into_hir_expression(interner, location);
}
Value::TypedExpr(TypedExpr::StmtId(..))
| Value::Expr(..)
| Value::Pointer(..)
Expand Down
10 changes: 10 additions & 0 deletions compiler/noirc_frontend/src/hir_def/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,16 @@
pub fn borrow_mut(&self) -> std::cell::RefMut<T> {
self.0.borrow_mut()
}

pub fn unwrap_or_clone(self) -> T
where
T: Clone,
{
match Rc::try_unwrap(self.0) {
Ok(elem) => elem.into_inner(),
Err(rc) => rc.as_ref().clone().into_inner(),
}
}
}

/// A restricted subset of binary operators useable on
Expand Down Expand Up @@ -1965,7 +1975,7 @@
}

let recur_on_binding = |id, replacement: &Type| {
// Prevent recuring forever if there's a `T := T` binding

Check warning on line 1978 in compiler/noirc_frontend/src/hir_def/types.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (recuring)
if replacement.type_variable_id() == Some(id) {
replacement.clone()
} else {
Expand Down Expand Up @@ -2036,7 +2046,7 @@
Type::Tuple(fields)
}
Type::Forall(typevars, typ) => {
// Trying to substitute_helper a variable de, substitute_bound_typevarsfined within a nested Forall

Check warning on line 2049 in compiler/noirc_frontend/src/hir_def/types.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (typevarsfined)
// is usually impossible and indicative of an error in the type checker somewhere.
for var in typevars {
assert!(!type_bindings.contains_key(&var.id()));
Expand Down Expand Up @@ -2203,7 +2213,7 @@

/// Replace any `Type::NamedGeneric` in this type with a `Type::TypeVariable`
/// using to the same inner `TypeVariable`. This is used during monomorphization
/// to bind to named generics since they are unbindable during type checking.

Check warning on line 2216 in compiler/noirc_frontend/src/hir_def/types.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (unbindable)
pub fn replace_named_generics_with_type_variables(&mut self) {
match self {
Type::FieldElement
Expand Down Expand Up @@ -2582,7 +2592,7 @@
len.hash(state);
env.hash(state);
}
Type::Tuple(elems) => elems.hash(state),

Check warning on line 2595 in compiler/noirc_frontend/src/hir_def/types.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (elems)

Check warning on line 2595 in compiler/noirc_frontend/src/hir_def/types.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (elems)
Type::Struct(def, args) => {
def.hash(state);
args.hash(state);
Expand Down Expand Up @@ -2675,7 +2685,7 @@
// Special case: we consider unbound named generics and type variables to be equal to each
// other if their type variable ids match. This is important for some corner cases in
// monomorphization where we call `replace_named_generics_with_type_variables` but
// still want them to be equal for canonicalization checks in arithmetic generics.

Check warning on line 2688 in compiler/noirc_frontend/src/hir_def/types.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (canonicalization)
// Without this we'd fail the `serialize` test.
(
NamedGeneric(lhs_var, _, _) | TypeVariable(lhs_var, _),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "comptime_globals_regression"
type = "bin"
authors = [""]
compiler_version = ">=0.33.0"

[dependencies]
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
comptime mut global COUNTER = 0;

fn main() {
comptime
{
increment()
};
comptime
{
increment()
};

assert_eq(get_counter(), 2);
}

fn get_counter() -> Field {
COUNTER
}

comptime fn increment() {
COUNTER += 1;
assert_eq(get_counter(), COUNTER);
}
Loading