checker: add error for if mut x != none {, when x is an immutable option (fix #24692) (#24694)

This commit is contained in:
Felipe Pena 2025-06-11 02:19:34 -03:00 committed by GitHub
parent c5c2c804b8
commit 11bcd40b4a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 18 additions and 0 deletions

View File

@ -606,6 +606,10 @@ fn (mut c Checker) smartcast_if_conds(mut node ast.Expr, mut scope ast.Scope, co
c.smartcast_if_conds(mut node.right, mut scope, control_expr)
} else if node.left in [ast.Ident, ast.SelectorExpr] && node.op == .ne
&& node.right is ast.None {
if (node.left is ast.Ident && node.left.is_mut)
|| (node.left is ast.SelectorExpr && node.left.is_mut) {
c.fail_if_immutable(mut node.left)
}
if node.left is ast.Ident && c.comptime.get_ct_type_var(node.left) == .smartcast {
node.left_type = c.type_resolver.get_type(node.left)
c.smartcast(mut node.left, node.left_type, node.left_type.clear_flag(.option), mut

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/option_mut_non_mut_err.vv:3:9: error: `option_1` is immutable, declare it with `mut` to make it mutable
1 | fn main() {
2 | option_1 := ?int(10)
3 | if mut option_1 != none {
| ~~~~~~~~
4 | option_1 = 11
5 | }

View File

@ -0,0 +1,7 @@
fn main() {
option_1 := ?int(10)
if mut option_1 != none {
option_1 = 11
}
println('Options: ${option_1}')
}