From 6438512529a6ba784decd62ae9ae92703c2d0bfa Mon Sep 17 00:00:00 2001 From: yuyi Date: Fri, 31 Dec 2021 15:54:06 +0800 Subject: [PATCH] checker: add error for `for mut var in string {` (fix #12998) (#13000) --- vlib/v/checker/checker.v | 2 ++ vlib/v/checker/tests/for_in_mut_string.out | 14 ++++++++++++++ vlib/v/checker/tests/for_in_mut_string.vv | 22 ++++++++++++++++++++++ 3 files changed, 38 insertions(+) create mode 100644 vlib/v/checker/tests/for_in_mut_string.out create mode 100644 vlib/v/checker/tests/for_in_mut_string.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 2ad90a7977..43fd827491 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -2590,6 +2590,8 @@ 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 == .map && !(node.key_var.len > 0 && node.val_var.len > 0) { c.error( diff --git a/vlib/v/checker/tests/for_in_mut_string.out b/vlib/v/checker/tests/for_in_mut_string.out new file mode 100644 index 0000000000..989006ae91 --- /dev/null +++ b/vlib/v/checker/tests/for_in_mut_string.out @@ -0,0 +1,14 @@ +vlib/v/checker/tests/for_in_mut_string.vv:19:6: error: string type is immutable, it cannot be changed + 17 | + 18 | fn wrap_text(mut gv Grid) { + 19 | for mut ch in gv.header { + | ~~~ + 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) + | ~~~~~~~~~~~ + 21 | } + 22 | } diff --git a/vlib/v/checker/tests/for_in_mut_string.vv b/vlib/v/checker/tests/for_in_mut_string.vv new file mode 100644 index 0000000000..d9779394cd --- /dev/null +++ b/vlib/v/checker/tests/for_in_mut_string.vv @@ -0,0 +1,22 @@ +module main + +[heap] +pub struct Grid { +pub mut: + header string +} + +fn main() { + h := 'yo' + + mut grid := Grid{ + header: h + } + wrap_text(mut grid) +} + +fn wrap_text(mut gv Grid) { + for mut ch in gv.header { + println(ch) + } +}