Commit 92568a0097

martinhath <martinhath@users.noreply.github.com>
2022-08-12 10:45:11
Sema: add error for signed integer division
stage1 error reads error: division with 'i32' and 'comptime_int': signed integers must use @divTrunc, @divFloor, or @divExact Fixes: #12339
1 parent fa50e17
Changed files (3)
src/Sema.zig
@@ -11261,7 +11261,12 @@ fn zirDiv(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
         try sema.addDivByZeroSafety(block, resolved_type, maybe_rhs_val, casted_rhs, is_int);
     }
 
-    const air_tag = if (is_int) Air.Inst.Tag.div_trunc else switch (block.float_mode) {
+    const air_tag = if (is_int) blk: {
+        if (lhs_ty.isSignedInt() or rhs_ty.isSignedInt()) {
+            return sema.fail(block, src, "division with '{s}' and '{s}': signed integers must use @divTrunc, @divFloor, or @divExact", .{ @tagName(lhs_ty.tag()), @tagName(rhs_ty.tag()) });
+        }
+        break :blk Air.Inst.Tag.div_trunc;
+    } else switch (block.float_mode) {
         .Optimized => Air.Inst.Tag.div_float_optimized,
         .Strict => Air.Inst.Tag.div_float,
     };
test/cases/compile_errors/stage1/obj/signed_integer_division.zig
@@ -1,9 +0,0 @@
-export fn foo(a: i32, b: i32) i32 {
-    return a / b;
-}
-
-// error
-// backend=stage1
-// target=native
-//
-// tmp.zig:2:14: error: division with 'i32' and 'i32': signed integers must use @divTrunc, @divFloor, or @divExact
test/cases/compile_errors/signed_integer_division.zig
@@ -0,0 +1,9 @@
+export fn foo(a: i32, b: i32) i32 {
+    return a / b;
+}
+
+// error
+// backend=stage2
+// target=native
+//
+// :2:14: error: division with 'i32' and 'i32': signed integers must use @divTrunc, @divFloor, or @divExact