Skip to content

Commit

Permalink
fix: do not discard negative sign from field literals in comptime int…
Browse files Browse the repository at this point in the history
…erpreter (#7439)
  • Loading branch information
TomAFrench authored Feb 19, 2025
1 parent b26d7f7 commit 1d04f8b
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 1 deletion.
1 change: 1 addition & 0 deletions compiler/noirc_frontend/src/hir/comptime/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -715,6 +715,7 @@ impl<'local, 'interner> Interpreter<'local, 'interner> {
let location = self.elaborator.interner.expr_location(&id);

if let Type::FieldElement = &typ {
let value = if is_negative { -value } else { value };
Ok(Value::Field(value))
} else if let Type::Integer(sign, bit_size) = &typ {
match (sign, bit_size) {
Expand Down
28 changes: 27 additions & 1 deletion compiler/noirc_frontend/src/parser/parser/global.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,12 @@ fn ident_to_pattern(ident: Ident, mutable: bool) -> Pattern {

#[cfg(test)]
mod tests {
use acvm::FieldElement;

use crate::{
ast::{
IntegerBitSize, ItemVisibility, LetStatement, Pattern, Signedness, UnresolvedTypeData,
ExpressionKind, IntegerBitSize, ItemVisibility, LetStatement, Literal, Pattern,
Signedness, UnresolvedTypeData,
},
parser::{
parser::{
Expand Down Expand Up @@ -171,4 +174,27 @@ mod tests {
let error = get_single_error(&errors, span);
assert_eq!(error.to_string(), "Expected a ';' but found end of input");
}

#[test]
fn parse_negative_field_global() {
let src = "
global foo: Field = -17;
";
let (let_statement, _visibility) = parse_global_no_errors(src);
let Pattern::Identifier(name) = &let_statement.pattern else {
panic!("Expected identifier pattern");
};
assert_eq!("foo", name.to_string());
assert_eq!(let_statement.pattern.span().start(), 16);
assert_eq!(let_statement.pattern.span().end(), 19);

let ExpressionKind::Literal(Literal::Integer(abs_value, is_negative)) =
let_statement.expression.kind
else {
panic!("Expected integer literal expression, got {:?}", let_statement.expression.kind);
};

assert!(is_negative);
assert_eq!(abs_value, FieldElement::from(17u128));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[package]
name = "regression_7433"
type = "bin"
authors = [""]

[dependencies]
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// These two globals should cancel out.
global positive_global: Field = 17;
global negative_global: Field = -17; // Previously the negative sign here would be dropped so this became 17.

fn main() {
assert_eq(positive_global + negative_global, 0);
}

0 comments on commit 1d04f8b

Please sign in to comment.