From 7cb63d1aae349541aabc165d8c9e5c0943e38511 Mon Sep 17 00:00:00 2001 From: HarmoGlace <23212967+HarmoGlace@users.noreply.github.com> Date: Wed, 26 Apr 2023 11:30:16 +0200 Subject: [PATCH] Fix overflows with operators (#904) --- src/eval/ops.rs | 8 ++++---- tests/typ/compiler/ops.typ | 5 +++++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/eval/ops.rs b/src/eval/ops.rs index 43ee6ceb6..48e74c8ff 100644 --- a/src/eval/ops.rs +++ b/src/eval/ops.rs @@ -53,7 +53,7 @@ pub fn pos(value: Value) -> StrResult { /// Compute the negation of a value. pub fn neg(value: Value) -> StrResult { Ok(match value { - Int(v) => Int(-v), + Int(v) => Int(v.checked_neg().ok_or("value is too large")?), Float(v) => Float(-v), Length(v) => Length(-v), Angle(v) => Angle(-v), @@ -70,7 +70,7 @@ pub fn add(lhs: Value, rhs: Value) -> StrResult { (a, None) => a, (None, b) => b, - (Int(a), Int(b)) => Int(a + b), + (Int(a), Int(b)) => Int(a.checked_add(b).ok_or("value is too large")?), (Int(a), Float(b)) => Float(a as f64 + b), (Float(a), Int(b)) => Float(a + b as f64), (Float(a), Float(b)) => Float(a + b), @@ -137,7 +137,7 @@ pub fn add(lhs: Value, rhs: Value) -> StrResult { /// Compute the difference of two values. pub fn sub(lhs: Value, rhs: Value) -> StrResult { Ok(match (lhs, rhs) { - (Int(a), Int(b)) => Int(a - b), + (Int(a), Int(b)) => Int(a.checked_sub(b).ok_or("value is too large")?), (Int(a), Float(b)) => Float(a as f64 - b), (Float(a), Int(b)) => Float(a - b as f64), (Float(a), Float(b)) => Float(a - b), @@ -165,7 +165,7 @@ pub fn sub(lhs: Value, rhs: Value) -> StrResult { /// Compute the product of two values. pub fn mul(lhs: Value, rhs: Value) -> StrResult { Ok(match (lhs, rhs) { - (Int(a), Int(b)) => Int(a * b), + (Int(a), Int(b)) => Int(a.checked_mul(b).ok_or("value is too large")?), (Int(a), Float(b)) => Float(a as f64 * b), (Float(a), Int(b)) => Float(a * b as f64), (Float(a), Float(b)) => Float(a * b), diff --git a/tests/typ/compiler/ops.typ b/tests/typ/compiler/ops.typ index 2bb06e4d3..937e90244 100644 --- a/tests/typ/compiler/ops.typ +++ b/tests/typ/compiler/ops.typ @@ -33,6 +33,11 @@ #test((1, 2) + (3, 4), (1, 2, 3, 4)) #test((a: 1) + (b: 2, c: 3), (a: 1, b: 2, c: 3)) +--- +// Error: 3-26 value is too large +#(9223372036854775807 + 1) + +--- // Subtraction. #test(1-4, 3*-1) #test(4cm - 2cm, 2cm)