Skip to content

Commit 1d6b9b9

Browse files
committed
checker: fix int values incorrectly promoted to f32 (fixes #7692)
(cherry picked from commit dd594699e23de07e08318828d7d7ff1347d6560a)
1 parent c1c86ed commit 1d6b9b9

3 files changed

Lines changed: 25 additions & 0 deletions

File tree

vlib/v/checker/assign.v

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,14 @@ fn (mut c Checker) update_option_assignment_smartcast(mut expr ast.Expr, left_ty
120120
}
121121
}
122122

123+
@[inline]
124+
fn (c &Checker) disallow_implicit_int_to_f32_assign(got ast.Type, expected ast.Type) bool {
125+
got_type := c.table.unalias_num_type(got).clear_flags()
126+
expected_type := c.table.unalias_num_type(expected).clear_flags()
127+
return expected_type == ast.f32_type
128+
&& got_type in [ast.i32_type, ast.int_type, ast.i64_type, ast.isize_type, ast.u32_type, ast.u64_type, ast.usize_type]
129+
}
130+
123131
// TODO: 980 line function
124132
fn (mut c Checker) assign_stmt(mut node ast.AssignStmt) {
125133
prev_inside_assign := c.inside_assign
@@ -1132,6 +1140,11 @@ or use an explicit `unsafe{ a[..] }`, if you do not want a copy of the slice.',
11321140
} else {
11331141
right_type_unwrapped
11341142
}
1143+
if original_op == .assign
1144+
&& c.disallow_implicit_int_to_f32_assign(assign_right_type, left_type_unwrapped) {
1145+
c.error('cannot assign to `${left}`: ${c.expected_msg(assign_right_type,
1146+
left_type_unwrapped)}', right_pos)
1147+
}
11351148
c.check_expected(assign_right_type, left_type_unwrapped) or {
11361149
if left.is_auto_deref_arg() && left_type.is_ptr() {
11371150
left_deref := left_type.deref()
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
vlib/v/checker/tests/assign_int_to_f32_err.vv:5:16: error: cannot assign to `my_float_32`: expected `f32`, not `int`
2+
3 | _ = my_float_32
3+
4 | my_int := int(2147483583)
4+
5 | my_float_32 = my_int
5+
| ~~~~~~
6+
6 | }
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
fn main() {
2+
mut my_float_32 := f32(3.2)
3+
_ = my_float_32
4+
my_int := int(2147483583)
5+
my_float_32 = my_int
6+
}

0 commit comments

Comments
 (0)