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: Evaluate operators in globals in types #4537

Merged
merged 6 commits into from
Mar 14, 2024
Merged
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
65 changes: 60 additions & 5 deletions compiler/noirc_frontend/src/hir/resolution/resolver.rs
Original file line number Diff line number Diff line change
@@ -37,11 +37,11 @@ use crate::{
StatementKind,
};
use crate::{
ArrayLiteral, Distinctness, ForRange, FunctionDefinition, FunctionReturnType, Generics,
ItemVisibility, LValue, NoirStruct, NoirTypeAlias, Param, Path, PathKind, Pattern, Shared,
StructType, Type, TypeAlias, TypeVariable, TypeVariableKind, UnaryOp, UnresolvedGenerics,
UnresolvedTraitConstraint, UnresolvedType, UnresolvedTypeData, UnresolvedTypeExpression,
Visibility, ERROR_IDENT,
ArrayLiteral, BinaryOpKind, Distinctness, ForRange, FunctionDefinition, FunctionReturnType,
Generics, ItemVisibility, LValue, NoirStruct, NoirTypeAlias, Param, Path, PathKind, Pattern,
Shared, StructType, Type, TypeAlias, TypeVariable, TypeVariableKind, UnaryOp,
UnresolvedGenerics, UnresolvedTraitConstraint, UnresolvedType, UnresolvedTypeData,
UnresolvedTypeExpression, Visibility, ERROR_IDENT,
};
use fm::FileId;
use iter_extended::vecmap;
@@ -1943,10 +1943,65 @@ impl<'a> Resolver<'a> {
rhs: ExprId,
span: Span,
) -> Result<u128, Option<ResolverError>> {
// Arbitrary amount of recursive calls to try before giving up
let fuel = 100;
self.try_eval_array_length_id_with_fuel(rhs, span, fuel)
}

fn try_eval_array_length_id_with_fuel(
&self,
rhs: ExprId,
span: Span,
fuel: u32,
) -> Result<u128, Option<ResolverError>> {
if fuel == 0 {
// If we reach here, it is likely from evaluating cyclic globals. We expect an error to
// be issued for them after name resolution so issue no error now.
return Err(None);
}

match self.interner.expression(&rhs) {
HirExpression::Literal(HirLiteral::Integer(int, false)) => {
int.try_into_u128().ok_or(Some(ResolverError::IntegerTooLarge { span }))
}
HirExpression::Ident(ident) => {
let definition = self.interner.definition(ident.id);
match definition.kind {
DefinitionKind::Global(global_id) => {
let let_statement = self.interner.get_global_let_statement(global_id);
if let Some(let_statement) = let_statement {
let expression = let_statement.expression;
self.try_eval_array_length_id_with_fuel(expression, span, fuel - 1)
} else {
Err(Some(ResolverError::InvalidArrayLengthExpr { span }))
}
}
_ => Err(Some(ResolverError::InvalidArrayLengthExpr { span })),
}
}
HirExpression::Infix(infix) => {
let lhs = self.try_eval_array_length_id_with_fuel(infix.lhs, span, fuel - 1)?;
let rhs = self.try_eval_array_length_id_with_fuel(infix.rhs, span, fuel - 1)?;

match infix.operator.kind {
BinaryOpKind::Add => Ok(lhs + rhs),
BinaryOpKind::Subtract => Ok(lhs - rhs),
BinaryOpKind::Multiply => Ok(lhs * rhs),
BinaryOpKind::Divide => Ok(lhs / rhs),
BinaryOpKind::Equal => Ok((lhs == rhs) as u128),
BinaryOpKind::NotEqual => Ok((lhs != rhs) as u128),
BinaryOpKind::Less => Ok((lhs < rhs) as u128),
BinaryOpKind::LessEqual => Ok((lhs <= rhs) as u128),
BinaryOpKind::Greater => Ok((lhs > rhs) as u128),
BinaryOpKind::GreaterEqual => Ok((lhs >= rhs) as u128),
BinaryOpKind::And => Ok(lhs & rhs),
BinaryOpKind::Or => Ok(lhs | rhs),
BinaryOpKind::Xor => Ok(lhs ^ rhs),
BinaryOpKind::ShiftRight => Ok(lhs >> rhs),
BinaryOpKind::ShiftLeft => Ok(lhs << rhs),
BinaryOpKind::Modulo => Ok(lhs % rhs),
}
}
_other => Err(Some(ResolverError::InvalidArrayLengthExpr { span })),
}
}
12 changes: 12 additions & 0 deletions compiler/noirc_frontend/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1214,6 +1214,18 @@ fn lambda$f1(mut env$l1: (Field)) -> Field {
assert_eq!(get_program_errors(src).len(), 0);
}

#[test]
fn operators_in_global_used_in_type() {
let src = r#"
global ONE = 1;
global COUNT = ONE + 2;
fn main() {
let _array: [Field; COUNT] = [1, 2, 3];
}
"#;
assert_eq!(get_program_errors(src).len(), 0);
}

// Regression for #4545
#[test]
fn type_aliases_in_main() {

Unchanged files with check annotations Beta

} else if is_custom_attribute(&secondary_attribute, "aztec(initializer)") {
is_initializer = true;
insert_init_check = false;
} else if is_custom_attribute(&secondary_attribute, "aztec(noinitcheck)") {

Check warning on line 127 in aztec_macros/src/lib.rs

GitHub Actions / Code

Unknown word (noinitcheck)
insert_init_check = false;
} else if is_custom_attribute(&secondary_attribute, "aztec(internal)") {
is_internal = true;
// If compute_note_hash_and_nullifier is already defined by the user, we skip auto-generation in order to provide an
// escape hatch for this mechanism.
// TODO(#4647): improve this diagnosis and error messaging.
if collected_functions.iter().any(|coll_funcs_data| {

Check warning on line 81 in aztec_macros/src/transforms/compute_note_hash_and_nullifier.rs

GitHub Actions / Code

Unknown word (funcs)
check_for_compute_note_hash_and_nullifier_definition(&coll_funcs_data.functions, module_id)

Check warning on line 82 in aztec_macros/src/transforms/compute_note_hash_and_nullifier.rs

GitHub Actions / Code

Unknown word (funcs)
}) {
return Ok(());
}
unresolved_traits_impls: &[UnresolvedTraitImpl],
trait_name: &str,
) -> Vec<String> {
let mut struct_typenames: Vec<String> = Vec::new();

Check warning on line 78 in aztec_macros/src/utils/hir_utils.rs

GitHub Actions / Code

Unknown word (typenames)
// These structs can be declared in either external crates or the current one. External crates that contain
// dependencies have already been processed and resolved, but are available here via the NodeInterner. Note that
if trait_impl.borrow().ident.0.contents == *trait_name {
if let Type::Struct(s, _) = &trait_impl.borrow().typ {
struct_typenames.push(s.borrow().name.0.contents.clone());

Check warning on line 88 in aztec_macros/src/utils/hir_utils.rs

GitHub Actions / Code

Unknown word (typenames)
} else {
panic!("Found impl for {} on non-Struct", trait_name);
}
}
// This crate's traits and impls have not yet been resolved, so we look for impls in unresolved_trait_impls.
struct_typenames.extend(

Check warning on line 96 in aztec_macros/src/utils/hir_utils.rs

GitHub Actions / Code

Unknown word (typenames)
unresolved_traits_impls
.iter()
.filter(|trait_impl| {
}),
);
struct_typenames

Check warning on line 117 in aztec_macros/src/utils/hir_utils.rs

GitHub Actions / Code

Unknown word (typenames)
}
assert!(
left.bit_size == right.bit_size,
"Not equal bitsize: lhs {}, rhs {}",

Check warning on line 837 in compiler/noirc_evaluator/src/brillig/brillig_ir.rs

GitHub Actions / Code

Unknown word (bitsize)
left.bit_size,
right.bit_size
);
}
for (i, bit_size) in arguments.iter().flat_map(flat_bit_sizes).enumerate() {
// Calldatacopy tags everything with field type, so when downcast when necessary

Check warning on line 131 in compiler/noirc_evaluator/src/brillig/brillig_ir/entry_point.rs

GitHub Actions / Code

Unknown word (Calldatacopy)
if bit_size < FieldElement::max_num_bits() {
self.push_opcode(BrilligOpcode::Cast {
destination: MemoryAddress(MAX_STACK_SIZE + i),
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 1525 in compiler/noirc_frontend/src/hir_def/types.rs

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()));