From 791cbbfb62cffafa4a26ffdc93859f884665c349 Mon Sep 17 00:00:00 2001 From: Christoffer Lerno Date: Mon, 3 Nov 2025 16:47:57 +0100 Subject: [PATCH] Fix division-by-zero checks on `a /= 0` and `b /= 0f` #2558. --- releasenotes.md | 1 + src/compiler/sema_expr.c | 3 +-- test/test_suite/expressions/assign_div_by.c3 | 14 ++++++++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 test/test_suite/expressions/assign_div_by.c3 diff --git a/releasenotes.md b/releasenotes.md index c76166af0..0d7bfccdb 100644 --- a/releasenotes.md +++ b/releasenotes.md @@ -11,6 +11,7 @@ ### Fixes - `Foo.is_eq` would return false if the type was a `typedef` and had an overload, but the underlying type was not comparable. - Remove division-by-zero checks for floating point in safe mode #2556. +- Fix division-by-zero checks on `a /= 0` and `b /= 0f` #2558. ### Stdlib changes diff --git a/src/compiler/sema_expr.c b/src/compiler/sema_expr.c index 8f7373a13..d78a4d997 100644 --- a/src/compiler/sema_expr.c +++ b/src/compiler/sema_expr.c @@ -7326,10 +7326,9 @@ BITSTRUCT_OK: switch (right->const_expr.const_kind) { case CONST_INTEGER: - if (int_is_zero(right->const_expr.ixx)) RETURN_SEMA_ERROR(right, operator == BINARYOP_MOD_ASSIGN ? "% by zero not allowed." : "Division by zero not allowed."); + if (int_is_zero(right->const_expr.ixx)) RETURN_SEMA_ERROR(right, operator == BINARYOP_MOD_ASSIGN ? "%% by zero not allowed." : "Division by zero not allowed."); break; case CONST_FLOAT: - if (right->const_expr.fxx.f == 0) RETURN_SEMA_ERROR(right, operator == BINARYOP_MOD_ASSIGN ? "% by zero not allowed." : "% by zero not allowed."); break; default: break; diff --git a/test/test_suite/expressions/assign_div_by.c3 b/test/test_suite/expressions/assign_div_by.c3 new file mode 100644 index 000000000..543bb1a10 --- /dev/null +++ b/test/test_suite/expressions/assign_div_by.c3 @@ -0,0 +1,14 @@ +module test; +struct Foo +{ + float val; + int ival; +} + +fn int main() +{ + Foo bar; + bar.val /= 0f; + bar.ival /= 0; // #error: Division by zero not allowed + return 0; +}