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: detect cycles in globals #6859

Merged
merged 4 commits into from
Dec 18, 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
6 changes: 3 additions & 3 deletions compiler/noirc_frontend/src/elaborator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use std::{
};

use crate::{
ast::ItemVisibility, hir_def::traits::ResolvedTraitBound, usage_tracker::UsageTracker,
StructField, StructType, TypeBindings,
ast::ItemVisibility, hir_def::traits::ResolvedTraitBound, node_interner::GlobalValue,
usage_tracker::UsageTracker, StructField, StructType, TypeBindings,
};
use crate::{
ast::{
Expand Down Expand Up @@ -1689,7 +1689,7 @@ impl<'context> Elaborator<'context> {

self.debug_comptime(location, |interner| value.display(interner).to_string());

self.interner.get_global_mut(global_id).value = Some(value);
self.interner.get_global_mut(global_id).value = GlobalValue::Resolved(value);
}
}

Expand Down
7 changes: 4 additions & 3 deletions compiler/noirc_frontend/src/elaborator/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ use crate::{
traits::{NamedType, ResolvedTraitBound, Trait, TraitConstraint},
},
node_interner::{
DependencyId, ExprId, ImplSearchErrorKind, NodeInterner, TraitId, TraitImplKind,
TraitMethodId,
DependencyId, ExprId, GlobalValue, ImplSearchErrorKind, NodeInterner, TraitId,
TraitImplKind, TraitMethodId,
},
token::SecondaryAttribute,
Generics, Kind, ResolvedGeneric, Type, TypeBinding, TypeBindings, UnificationError,
Expand Down Expand Up @@ -426,7 +426,8 @@ impl<'context> Elaborator<'context> {
let rhs = stmt.expression;
let span = self.interner.expr_span(&rhs);

let Some(global_value) = &self.interner.get_global(id).value else {
let GlobalValue::Resolved(global_value) = &self.interner.get_global(id).value
else {
self.push_err(ResolverError::UnevaluatedGlobalType { span });
return None;
};
Expand Down
11 changes: 10 additions & 1 deletion compiler/noirc_frontend/src/hir/comptime/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,9 @@
CannotInterpretFormatStringWithErrors {
location: Location,
},
GlobalsDependencyCycle {
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.
Expand Down Expand Up @@ -319,7 +322,8 @@
| InterpreterError::CannotResolveExpression { location, .. }
| InterpreterError::CannotSetFunctionBody { location, .. }
| InterpreterError::UnknownArrayLength { location, .. }
| InterpreterError::CannotInterpretFormatStringWithErrors { location } => *location,
| InterpreterError::CannotInterpretFormatStringWithErrors { location }
| InterpreterError::GlobalsDependencyCycle { location } => *location,

InterpreterError::FailedToParseMacro { error, file, .. } => {
Location::new(error.span(), *file)
Expand Down Expand Up @@ -631,7 +635,7 @@
}
InterpreterError::GenericNameShouldBeAnIdent { name, location } => {
let msg =
"Generic name needs to be a valid identifer (one word beginning with a letter)"

Check warning on line 638 in compiler/noirc_frontend/src/hir/comptime/errors.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (identifer)
.to_string();
let secondary = format!("`{name}` is not a valid identifier");
CustomDiagnostic::simple_error(msg, secondary, location.span)
Expand Down Expand Up @@ -674,6 +678,11 @@
"Some of the variables to interpolate could not be evaluated".to_string();
CustomDiagnostic::simple_error(msg, secondary, location.span)
}
InterpreterError::GlobalsDependencyCycle { location } => {
let msg = "This global recursively depends on itself".to_string();
let secondary = String::new();
CustomDiagnostic::simple_error(msg, secondary, location.span)
}
}
}
}
46 changes: 30 additions & 16 deletions compiler/noirc_frontend/src/hir/comptime/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
perform_impl_bindings, perform_instantiation_bindings, resolve_trait_method,
undo_instantiation_bindings,
};
use crate::node_interner::GlobalValue;
use crate::token::{FmtStrFragment, Tokens};
use crate::TypeVariable;
use crate::{
Expand Down Expand Up @@ -251,7 +252,7 @@
}
} else {
let name = self.elaborator.interner.function_name(&function);
unreachable!("Non-builtin, lowlevel or oracle builtin fn '{name}'")

Check warning on line 255 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 @@ -568,26 +569,39 @@
DefinitionKind::Local(_) => self.lookup(&ident),
DefinitionKind::Global(global_id) => {
// Avoid resetting the value if it is already known
if let Some(value) = &self.elaborator.interner.get_global(*global_id).value {
Ok(value.clone())
} else {
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(
|| {
let global_id = *global_id;
let global_info = self.elaborator.interner.get_global(global_id);
let global_crate_id = global_info.crate_id;
match &global_info.value {
GlobalValue::Resolved(value) => Ok(value.clone()),
GlobalValue::Resolving => {
// Note that the error we issue here isn't very informative (it doesn't include the actual cycle)
// but the general dependency cycle detector will give a better error later on during compilation.
let location = self.elaborator.interner.expr_location(&id);
Err(InterpreterError::GlobalsDependencyCycle { location })
}
GlobalValue::Unresolved => {
let let_ = self
.elaborator
.interner
.get_global_let_statement(global_id)
.ok_or_else(|| {
let location = self.elaborator.interner.expr_location(&id);
InterpreterError::VariableNotInScope { location }
},
)?;
})?;

if let_.runs_comptime() || crate_of_global != self.crate_id {
self.evaluate_let(let_.clone())?;
}
self.elaborator.interner.get_global_mut(global_id).value =
GlobalValue::Resolving;

if let_.runs_comptime() || global_crate_id != self.crate_id {
self.evaluate_let(let_.clone())?;
}

let value = self.lookup(&ident)?;
self.elaborator.interner.get_global_mut(global_id).value = Some(value.clone());
Ok(value)
let value = self.lookup(&ident)?;
self.elaborator.interner.get_global_mut(global_id).value =
GlobalValue::Resolved(value.clone());
Ok(value)
}
}
}
DefinitionKind::NumericGeneric(type_variable, numeric_typ) => {
Expand Down Expand Up @@ -1032,7 +1046,7 @@
}

/// Generate matches for bit shifting, which in Noir only accepts `u8` for RHS.
macro_rules! match_bitshift {

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

View workflow job for this annotation

GitHub Actions / Code

Unknown word (bitshift)
(($lhs_value:ident as $lhs:ident $op:literal $rhs_value:ident as $rhs:ident) => $expr:expr) => {
match_values! {
($lhs_value as $lhs $op $rhs_value as $rhs) {
Expand Down Expand Up @@ -1102,10 +1116,10 @@
BinaryOpKind::Xor => match_bitwise! {
(lhs_value as lhs "^" rhs_value as rhs) => lhs ^ rhs
},
BinaryOpKind::ShiftRight => match_bitshift! {

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

View workflow job for this annotation

GitHub Actions / Code

Unknown word (bitshift)
(lhs_value as lhs ">>" rhs_value as rhs) => lhs.checked_shr(rhs.into())
},
BinaryOpKind::ShiftLeft => match_bitshift! {

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

View workflow job for this annotation

GitHub Actions / Code

Unknown word (bitshift)
(lhs_value as lhs "<<" rhs_value as rhs) => lhs.checked_shl(rhs.into())
},
BinaryOpKind::Modulo => match_integer! {
Expand Down
4 changes: 2 additions & 2 deletions compiler/noirc_frontend/src/monomorphization/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
use crate::ast::{FunctionKind, IntegerBitSize, Signedness, UnaryOp, Visibility};
use crate::hir::comptime::InterpreterError;
use crate::hir::type_check::{NoMatchingImplFoundError, TypeCheckError};
use crate::node_interner::{ExprId, ImplSearchErrorKind};
use crate::node_interner::{ExprId, GlobalValue, ImplSearchErrorKind};
use crate::token::FmtStrFragment;
use crate::{
debug::DebugInstrumenter,
Expand Down Expand Up @@ -895,7 +895,7 @@ impl<'interner> Monomorphizer<'interner> {
DefinitionKind::Global(global_id) => {
let global = self.interner.get_global(*global_id);

let expr = if let Some(value) = global.value.clone() {
let expr = if let GlobalValue::Resolved(value) = global.value.clone() {
value
.into_hir_expression(self.interner, global.location)
.map_err(MonomorphizationError::InterpreterError)?
Expand Down
11 changes: 9 additions & 2 deletions compiler/noirc_frontend/src/node_interner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,12 +218,12 @@
interned_statement_kinds: noirc_arena::Arena<StatementKind>,

// Interned `UnresolvedTypeData`s during comptime code.
interned_unresolved_type_datas: noirc_arena::Arena<UnresolvedTypeData>,

Check warning on line 221 in compiler/noirc_frontend/src/node_interner.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (datas)

// Interned `Pattern`s during comptime code.
interned_patterns: noirc_arena::Arena<Pattern>,

/// Determins whether to run in LSP mode. In LSP mode references are tracked.

Check warning on line 226 in compiler/noirc_frontend/src/node_interner.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (Determins)
pub(crate) lsp_mode: bool,

/// Store the location of the references in the graph.
Expand Down Expand Up @@ -609,7 +609,14 @@
pub crate_id: CrateId,
pub location: Location,
pub let_statement: StmtId,
pub value: Option<comptime::Value>,
pub value: GlobalValue,
}

#[derive(Debug, Clone)]
pub enum GlobalValue {
Unresolved,
Resolving,
Resolved(comptime::Value),
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
Expand Down Expand Up @@ -666,7 +673,7 @@
quoted_types: Default::default(),
interned_expression_kinds: Default::default(),
interned_statement_kinds: Default::default(),
interned_unresolved_type_datas: Default::default(),

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

View workflow job for this annotation

GitHub Actions / Code

Unknown word (datas)
interned_patterns: Default::default(),
lsp_mode: false,
location_indices: LocationIndices::default(),
Expand Down Expand Up @@ -861,7 +868,7 @@
crate_id,
let_statement,
location,
value: None,
value: GlobalValue::Unresolved,
});
self.global_attributes.insert(id, attributes);
id
Expand Down Expand Up @@ -2203,11 +2210,11 @@
&mut self,
typ: UnresolvedTypeData,
) -> InternedUnresolvedTypeData {
InternedUnresolvedTypeData(self.interned_unresolved_type_datas.insert(typ))

Check warning on line 2213 in compiler/noirc_frontend/src/node_interner.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (datas)
}

pub fn get_unresolved_type_data(&self, id: InternedUnresolvedTypeData) -> &UnresolvedTypeData {
&self.interned_unresolved_type_datas[id.0]

Check warning on line 2217 in compiler/noirc_frontend/src/node_interner.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (datas)
}

/// Returns the type of an operator (which is always a function), along with its return type.
Expand Down
20 changes: 20 additions & 0 deletions compiler/noirc_frontend/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3855,3 +3855,23 @@ fn disallows_underscore_on_right_hand_side() {

assert_eq!(name, "_");
}

#[test]
fn errors_on_cyclic_globals() {
let src = r#"
pub comptime global A: u32 = B;
pub comptime global B: u32 = A;

fn main() { }
"#;
let errors = get_program_errors(src);

assert!(errors.iter().any(|(error, _)| matches!(
error,
CompilationError::InterpreterError(InterpreterError::GlobalsDependencyCycle { .. })
)));
assert!(errors.iter().any(|(error, _)| matches!(
error,
CompilationError::ResolverError(ResolverError::DependencyCycle { .. })
vezenovm marked this conversation as resolved.
Show resolved Hide resolved
)));
}
Loading