Skip to content

Commit

Permalink
fix: Error when mutating comptime variables in non-comptime code (#6003)
Browse files Browse the repository at this point in the history
# Description

## Problem\*

Resolves #5982

## Summary\*

Issues an error when mutating comptime globals in a non-comptime
context. Previously we either allowed the code if the method is unused,
or panicked during monomorphization.

## Additional Context



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

- [x] I have tested the changes locally.
- [x] I have formatted the changes with [Prettier](https://prettier.io/)
and/or `cargo fmt` on default settings.
  • Loading branch information
jfecher authored Sep 11, 2024
1 parent d1e52f3 commit e20c44d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
7 changes: 7 additions & 0 deletions compiler/noirc_frontend/src/elaborator/statements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,13 @@ impl<'context> Elaborator<'context> {
} else {
if let Some(definition) = self.interner.try_definition(ident.id) {
mutable = definition.mutable;

if definition.comptime && !self.in_comptime_context() {
self.push_err(ResolverError::MutatingComptimeInNonComptimeContext {
name: definition.name.clone(),
span: ident.location.span,
});
}
}

let typ = self.interner.definition_type(ident.id).instantiate(self.interner).0;
Expand Down
9 changes: 9 additions & 0 deletions compiler/noirc_frontend/src/hir/resolution/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@ pub enum ResolverError {
QuoteInRuntimeCode { span: Span },
#[error("Comptime-only type `{typ}` cannot be used in runtime code")]
ComptimeTypeInRuntimeCode { typ: String, span: Span },
#[error("Comptime variable `{name}` cannot be mutated in a non-comptime context")]
MutatingComptimeInNonComptimeContext { name: String, span: Span },
}

impl ResolverError {
Expand Down Expand Up @@ -522,6 +524,13 @@ impl<'a> From<&'a ResolverError> for Diagnostic {
*span,
)
},
ResolverError::MutatingComptimeInNonComptimeContext { name, span } => {
Diagnostic::simple_error(
format!("Comptime variable `{name}` cannot be mutated in a non-comptime context"),
format!("`{name}` mutated here"),
*span,
)
},
}
}
}

0 comments on commit e20c44d

Please sign in to comment.