From 11bcd40b4a53650d947d5987cc2574b4354be031 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Wed, 11 Jun 2025 02:19:34 -0300 Subject: [PATCH] checker: add error for `if mut x != none {`, when `x` is an immutable option (fix #24692) (#24694) --- vlib/v/checker/if.v | 4 ++++ vlib/v/checker/tests/option_mut_non_mut_err.out | 7 +++++++ vlib/v/checker/tests/option_mut_non_mut_err.vv | 7 +++++++ 3 files changed, 18 insertions(+) create mode 100644 vlib/v/checker/tests/option_mut_non_mut_err.out create mode 100644 vlib/v/checker/tests/option_mut_non_mut_err.vv diff --git a/vlib/v/checker/if.v b/vlib/v/checker/if.v index faf305c6f0..6d16d9e07c 100644 --- a/vlib/v/checker/if.v +++ b/vlib/v/checker/if.v @@ -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 diff --git a/vlib/v/checker/tests/option_mut_non_mut_err.out b/vlib/v/checker/tests/option_mut_non_mut_err.out new file mode 100644 index 0000000000..e3ea838652 --- /dev/null +++ b/vlib/v/checker/tests/option_mut_non_mut_err.out @@ -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 | } diff --git a/vlib/v/checker/tests/option_mut_non_mut_err.vv b/vlib/v/checker/tests/option_mut_non_mut_err.vv new file mode 100644 index 0000000000..98e3c14164 --- /dev/null +++ b/vlib/v/checker/tests/option_mut_non_mut_err.vv @@ -0,0 +1,7 @@ +fn main() { + option_1 := ?int(10) + if mut option_1 != none { + option_1 = 11 + } + println('Options: ${option_1}') +}