1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

parser: check for_in mut key (#8235)

This commit is contained in:
yuyi 2021-01-21 19:46:15 +08:00 committed by GitHub
parent 62c2168b0b
commit f399c17e3d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 30 additions and 0 deletions

View File

@ -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 {`

View File

@ -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 | }

View File

@ -0,0 +1,6 @@
fn main() {
mut m := [1, 2, 3]
for mut i, _ in m {
println(i)
}
}

View File

@ -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 | }

View File

@ -0,0 +1,6 @@
fn main() {
mut m := {'foo': 1, 'bar': 2}
for mut k, _ in m {
println(k)
}
}