From 242d6fa1ff55357c3abc639a372dad24a9b6e8c4 Mon Sep 17 00:00:00 2001 From: yuyi Date: Mon, 6 Feb 2023 17:58:03 +0800 Subject: [PATCH] checker: disallow `for mut letter in 'abc' {` (#17234) --- vlib/v/checker/for.v | 5 +++-- vlib/v/checker/tests/for_in_mut_string.out | 12 ++++++------ vlib/v/checker/tests/for_in_mut_string.vv | 5 +++++ 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/vlib/v/checker/for.v b/vlib/v/checker/for.v index b5c9bf47ce..20a3e6749d 100644 --- a/vlib/v/checker/for.v +++ b/vlib/v/checker/for.v @@ -113,6 +113,9 @@ fn (mut c Checker) for_in_stmt(mut node ast.ForInStmt) { } else {} } + } else if node.val_is_mut { + c.error('string type is immutable, it cannot be changed', node.pos) + return } if sym.kind == .struct_ { // iterators @@ -139,8 +142,6 @@ fn (mut c Checker) for_in_stmt(mut node ast.ForInStmt) { node.kind = sym.kind node.val_type = val_type node.scope.update_var_type(node.val_var, val_type) - } else if sym.kind == .string && node.val_is_mut { - c.error('string type is immutable, it cannot be changed', node.pos) } else if sym.kind == .any { node.cond_type = typ node.kind = sym.kind diff --git a/vlib/v/checker/tests/for_in_mut_string.out b/vlib/v/checker/tests/for_in_mut_string.out index 989006ae91..e46da21c6b 100644 --- a/vlib/v/checker/tests/for_in_mut_string.out +++ b/vlib/v/checker/tests/for_in_mut_string.out @@ -5,10 +5,10 @@ vlib/v/checker/tests/for_in_mut_string.vv:19:6: error: string type is immutable, | ~~~ 20 | println(ch) 21 | } -vlib/v/checker/tests/for_in_mut_string.vv:20:3: error: `println` can not print void expressions - 18 | fn wrap_text(mut gv Grid) { - 19 | for mut ch in gv.header { - 20 | println(ch) - | ~~~~~~~~~~~ +vlib/v/checker/tests/for_in_mut_string.vv:23:6: error: string type is immutable, it cannot be changed 21 | } - 22 | } + 22 | + 23 | for mut letter in 'abc' { + | ~~~ + 24 | bit := letter - 1 + 25 | println(bit) diff --git a/vlib/v/checker/tests/for_in_mut_string.vv b/vlib/v/checker/tests/for_in_mut_string.vv index d9779394cd..2a36f7f608 100644 --- a/vlib/v/checker/tests/for_in_mut_string.vv +++ b/vlib/v/checker/tests/for_in_mut_string.vv @@ -19,4 +19,9 @@ fn wrap_text(mut gv Grid) { for mut ch in gv.header { println(ch) } + + for mut letter in 'abc' { + bit := letter - 1 + println(bit) + } }