parser: improve error messages of 'for val in array' (#14459)

yuyi 2022-05-19 16:53:27 +08:00 committed by Jef Roosens
parent c5933aa3c5
commit 7c7d59acee
Signed by: Jef Roosens
GPG Key ID: B75D4F293C7052DB
3 changed files with 18 additions and 1 deletions

View File

@ -125,7 +125,8 @@ fn (mut p Parser) for_stmt() ast.Stmt {
is_stack_obj: true is_stack_obj: true
}) })
} else if p.scope.known_var(val_var_name) { } else if p.scope.known_var(val_var_name) {
return p.error('redefinition of value iteration variable `$val_var_name`') return p.error_with_pos('redefinition of value iteration variable `$val_var_name`, use `for ($val_var_name in array) {` if you want to check for a condition instead',
val_var_pos)
} }
p.check(.key_in) p.check(.key_in)
if p.tok.kind == .name && p.tok.lit in [key_var_name, val_var_name] { if p.tok.kind == .name && p.tok.lit in [key_var_name, val_var_name] {

View File

@ -0,0 +1,7 @@
vlib/v/parser/tests/for_val_in_array_err.vv:5:6: error: redefinition of value iteration variable `val`, use `for (val in array) {` if you want to check for a condition instead
3 | fn main() {
4 | val := `+`
5 | for val in [TokenValue(`+`), TokenValue(`-`)] {
| ~~~
6 | println("ok")
7 | break

View File

@ -0,0 +1,9 @@
type TokenValue = rune | u64
fn main() {
val := `+`
for val in [TokenValue(`+`), TokenValue(`-`)] {
println("ok")
break
}
}