diff --git a/vlib/v/parser/for.v b/vlib/v/parser/for.v index b034037391..fb20053a10 100644 --- a/vlib/v/parser/for.v +++ b/vlib/v/parser/for.v @@ -83,6 +83,7 @@ fn (mut p Parser) for_stmt() ast.Stmt { { // `for i in vals`, `for i in start .. end`, `for mut user in users`, `for i, mut user in users` mut val_is_mut := p.tok.kind == .key_mut + mut_pos := p.tok.position() if val_is_mut { p.next() } @@ -91,6 +92,9 @@ fn (mut p Parser) for_stmt() ast.Stmt { mut key_var_name := '' mut val_var_name := p.check_name() if p.tok.kind == .comma { + if val_is_mut { + p.error_with_pos('index of array or key of map cannot be mutated', mut_pos) + } p.next() if p.tok.kind == .key_mut { // `for i, mut user in users {` diff --git a/vlib/v/parser/tests/for_in_mut_index_of_array.out b/vlib/v/parser/tests/for_in_mut_index_of_array.out new file mode 100644 index 0000000000..f8e5a51ab3 --- /dev/null +++ b/vlib/v/parser/tests/for_in_mut_index_of_array.out @@ -0,0 +1,7 @@ +vlib/v/parser/tests/for_in_mut_index_of_array.vv:3:6: error: index of array or key of map cannot be mutated + 1 | fn main() { + 2 | mut m := [1, 2, 3] + 3 | for mut i, _ in m { + | ~~~ + 4 | println(i) + 5 | } diff --git a/vlib/v/parser/tests/for_in_mut_index_of_array.vv b/vlib/v/parser/tests/for_in_mut_index_of_array.vv new file mode 100644 index 0000000000..eb04d9669b --- /dev/null +++ b/vlib/v/parser/tests/for_in_mut_index_of_array.vv @@ -0,0 +1,6 @@ +fn main() { + mut m := [1, 2, 3] + for mut i, _ in m { + println(i) + } +} diff --git a/vlib/v/parser/tests/for_in_mut_key_of_map.out b/vlib/v/parser/tests/for_in_mut_key_of_map.out new file mode 100644 index 0000000000..7c159a0338 --- /dev/null +++ b/vlib/v/parser/tests/for_in_mut_key_of_map.out @@ -0,0 +1,7 @@ +vlib/v/parser/tests/for_in_mut_key_of_map.vv:3:6: error: index of array or key of map cannot be mutated + 1 | fn main() { + 2 | mut m := {'foo': 1, 'bar': 2} + 3 | for mut k, _ in m { + | ~~~ + 4 | println(k) + 5 | } diff --git a/vlib/v/parser/tests/for_in_mut_key_of_map.vv b/vlib/v/parser/tests/for_in_mut_key_of_map.vv new file mode 100644 index 0000000000..22a5acade0 --- /dev/null +++ b/vlib/v/parser/tests/for_in_mut_key_of_map.vv @@ -0,0 +1,6 @@ +fn main() { + mut m := {'foo': 1, 'bar': 2} + for mut k, _ in m { + println(k) + } +}