From 59d408f72cfedcd3f9df59b3571544332c62ba0f Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Tue, 29 Jul 2025 07:37:53 +0300 Subject: [PATCH] v: limit -div-by-zero-is-zero influence to just the integer types (for f32 and f64, / produces a +inf or -inf value, and the program continues to run) --- vlib/v/gen/c/infix.v | 4 ++-- vlib/v/gen/c/testdata/div_by_zero_is_zero.c.must_have | 1 + vlib/v/gen/c/testdata/div_by_zero_is_zero.out | 3 +++ vlib/v/gen/c/testdata/div_by_zero_is_zero.vv | 6 ++++++ 4 files changed, 12 insertions(+), 2 deletions(-) diff --git a/vlib/v/gen/c/infix.v b/vlib/v/gen/c/infix.v index 22509fd0e1..c9ccdc9bd4 100644 --- a/vlib/v/gen/c/infix.v +++ b/vlib/v/gen/c/infix.v @@ -1204,8 +1204,6 @@ fn (mut g Gen) gen_plain_infix_expr(node ast.InfixExpr) { needs_cast := node.left_type.is_number() && node.right_type.is_number() && node.op in [.plus, .minus, .mul, .div, .mod] && !(g.pref.translated || g.file.is_translated) - is_safe_div := node.op == .div && g.pref.div_by_zero_is_zero - is_safe_mod := node.op == .mod && g.pref.div_by_zero_is_zero mut typ := node.promoted_type mut typ_str := g.styp(typ) if needs_cast { @@ -1219,6 +1217,8 @@ fn (mut g Gen) gen_plain_infix_expr(node ast.InfixExpr) { typ_str = g.styp(typ) g.write('(${typ_str})(') } + is_safe_div := node.op == .div && g.pref.div_by_zero_is_zero && typ.is_int() + is_safe_mod := node.op == .mod && g.pref.div_by_zero_is_zero && typ.is_int() if node.left_type.is_ptr() && node.left.is_auto_deref_var() && !node.right_type.is_pointer() { g.write('*') } else if !g.inside_interface_deref && node.left is ast.Ident diff --git a/vlib/v/gen/c/testdata/div_by_zero_is_zero.c.must_have b/vlib/v/gen/c/testdata/div_by_zero_is_zero.c.must_have index c5ecb2fa19..18273e593d 100644 --- a/vlib/v/gen/c/testdata/div_by_zero_is_zero.c.must_have +++ b/vlib/v/gen/c/testdata/div_by_zero_is_zero.c.must_have @@ -1,2 +1,3 @@ int c = (int)(VSAFE_DIV_int(a , z)); int d = (int)(VSAFE_MOD_int(a , z)); +f32 fc = (f32)(fa / fz); diff --git a/vlib/v/gen/c/testdata/div_by_zero_is_zero.out b/vlib/v/gen/c/testdata/div_by_zero_is_zero.out index c338e4cdec..546262799d 100644 --- a/vlib/v/gen/c/testdata/div_by_zero_is_zero.out +++ b/vlib/v/gen/c/testdata/div_by_zero_is_zero.out @@ -2,3 +2,6 @@ a == 42 z == 0 c == a / z == 0 d == a % z == 42 +fa == 42.0 +fz == 0.0 +fc == fa / fz == +inf diff --git a/vlib/v/gen/c/testdata/div_by_zero_is_zero.vv b/vlib/v/gen/c/testdata/div_by_zero_is_zero.vv index d1f280b7e8..493cd13356 100644 --- a/vlib/v/gen/c/testdata/div_by_zero_is_zero.vv +++ b/vlib/v/gen/c/testdata/div_by_zero_is_zero.vv @@ -7,3 +7,9 @@ println('a == ${a}') println('z == ${z}') println('c == a / z == ${c}') println('d == a % z == ${d}') +fa := f32(42) +fz := f32(0) +fc := fa / fz +println('fa == ${fa}') +println('fz == ${fz}') +println('fc == fa / fz == ${fc}')