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: Overflowing assignment will result in an error #2321

Merged
merged 7 commits into from
Aug 15, 2023
Merged
Show file tree
Hide file tree
Changes from 5 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "overflowing_assignment"
type = "bin"
authors = [""]
compiler_version = "0.9.0"

[dependencies]
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
fn main() {
let x:u8 = -1;
let y:u8 = 300;
assert(x!=y);
}
6 changes: 5 additions & 1 deletion crates/noirc_frontend/src/hir/type_check/errors.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use acvm::FieldElement;
use noirc_errors::CustomDiagnostic as Diagnostic;
use noirc_errors::Span;
use thiserror::Error;
Expand Down Expand Up @@ -29,6 +30,8 @@ pub enum Source {
pub enum TypeCheckError {
#[error("Operator {op:?} cannot be used in a {place:?}")]
OpCannotBeUsed { op: HirBinaryOp, place: &'static str, span: Span },
#[error("The literal `{expr:?}` cannot fit into `{ty}` which has range `{range}`")]
OverflowingAssignment { expr: FieldElement, ty: Type, range: String, span: Span },
#[error("Type {typ:?} cannot be used in a {place:?}")]
TypeCannotBeUsed { typ: Type, place: &'static str, span: Span },
#[error("Expected type {expected_typ:?} is not the same as {expr_typ:?}")]
Expand Down Expand Up @@ -170,7 +173,8 @@ impl From<TypeCheckError> for Diagnostic {
| TypeCheckError::IntegerTypeMismatch { span, .. }
| TypeCheckError::FieldComparison { span, .. }
| TypeCheckError::AmbiguousBitWidth { span, .. }
| TypeCheckError::IntegerAndFieldBinaryOperation { span } => {
| TypeCheckError::IntegerAndFieldBinaryOperation { span }
| TypeCheckError::OverflowingAssignment { span, .. } => {
Diagnostic::simple_error(error.to_string(), String::new(), span)
}
TypeCheckError::PublicReturnType { typ, span } => Diagnostic::simple_error(
Expand Down
32 changes: 31 additions & 1 deletion crates/noirc_frontend/src/hir/type_check/stmt.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use noirc_errors::{Location, Span};

use crate::hir_def::expr::HirIdent;
use crate::hir_def::expr::{HirExpression, HirIdent, HirLiteral};
use crate::hir_def::stmt::{
HirAssignStatement, HirConstrainStatement, HirLValue, HirLetStatement, HirPattern, HirStatement,
};
Expand Down Expand Up @@ -259,9 +259,39 @@ impl<'interner> TypeChecker<'interner> {
expr_span,
}
});
if annotated_type.is_unsigned() {
self.lint_overflowing_uint(&rhs_expr, &annotated_type);
}
annotated_type
} else {
expr_type
}
}

jfecher marked this conversation as resolved.
Show resolved Hide resolved
/// Check if an assignment is overflowing with respect to `annotated_type`
/// in a declaration statement where `annotated_type` is an unsigned integer
fn lint_overflowing_uint(&mut self, rhs_expr: &ExprId, annotated_type: &Type) {
let expr = self.interner.expression(rhs_expr);
let span = self.interner.expr_span(rhs_expr);
match expr {
HirExpression::Literal(HirLiteral::Integer(value)) => {
let v: u128 = value.to_u128();
Ethan-000 marked this conversation as resolved.
Show resolved Hide resolved
if let Type::Integer(_, bit) = annotated_type {
let max = 1 << bit;
Ethan-000 marked this conversation as resolved.
Show resolved Hide resolved
if v >= max {
self.errors.push(TypeCheckError::OverflowingAssignment {
expr: value,
ty: annotated_type.clone(),
range: format!("0..={}", max - 1),
span,
});
};
};
}
HirExpression::Prefix(_) => self
.errors
.push(TypeCheckError::InvalidUnaryOp { kind: annotated_type.to_string(), span }),
_ => {}
}
}
}
4 changes: 4 additions & 0 deletions crates/noirc_frontend/src/hir_def/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,10 @@
matches!(self.follow_bindings(), Type::Integer(Signedness::Signed, _))
}

pub fn is_unsigned(&self) -> bool {
matches!(self.follow_bindings(), Type::Integer(Signedness::Unsigned, _))
}

fn contains_numeric_typevar(&self, target_id: TypeVariableId) -> bool {
// True if the given type is a NamedGeneric with the target_id
let named_generic_id_matches_target = |typ: &Type| {
Expand Down Expand Up @@ -556,7 +560,7 @@
Type::Bool => write!(f, "bool"),
Type::String(len) => write!(f, "str<{len}>"),
Type::FmtString(len, elements) => {
write!(f, "fmtstr<{len}, {elements}>")

Check warning on line 563 in crates/noirc_frontend/src/hir_def/types.rs

View workflow job for this annotation

GitHub Actions / Spellcheck / Spellcheck

Unknown word (fmtstr)
}
Type::Unit => write!(f, "()"),
Type::Error => write!(f, "error"),
Expand Down
Loading