parser: check assign expr with undefined variable (#13653)

pull/13658/head
yuyi 2022-03-04 16:33:14 +08:00 committed by GitHub
parent 63b41e67fa
commit f70e5bd69b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 53 additions and 0 deletions

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/assign_expr_undefined_err_m.vv:5:14: error: undefined variable: `x`
3 | n := 2
4 | x := match a {
5 | 'add'{ n + x }
| ^
6 | else{0}
7 | }

View File

@ -0,0 +1,9 @@
fn main(){
a := 'add'
n := 2
x := match a {
'add'{ n + x }
else{0}
}
println(x)
}

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/assign_expr_undefined_err_n.vv:4:27: error: undefined variable: `x`
2 | a := 'add'
3 | n := 2
4 | x := if a == 'add' { n + x } else { 0 }
| ^
5 | println(x)
6 | }

View File

@ -0,0 +1,6 @@
fn main(){
a := 'add'
n := 2
x := if a == 'add' { n + x } else { 0 }
println(x)
}

View File

@ -63,6 +63,17 @@ fn (mut p Parser) check_undefined_variables(exprs []ast.Expr, val ast.Expr) ? {
p.check_undefined_variables(exprs, val.left) ?
p.check_undefined_variables(exprs, val.right) ?
}
ast.IfExpr {
p.check_undefined_variables(exprs, val.left) ?
for branch in val.branches {
p.check_undefined_variables(exprs, branch.cond) ?
for stmt in branch.stmts {
if stmt is ast.ExprStmt {
p.check_undefined_variables(exprs, stmt.expr) ?
}
}
}
}
ast.MapInit {
for key in val.keys {
p.check_undefined_variables(exprs, key) ?
@ -71,6 +82,19 @@ fn (mut p Parser) check_undefined_variables(exprs []ast.Expr, val ast.Expr) ? {
p.check_undefined_variables(exprs, value) ?
}
}
ast.MatchExpr {
p.check_undefined_variables(exprs, val.cond) ?
for branch in val.branches {
for expr in branch.exprs {
p.check_undefined_variables(exprs, expr) ?
}
for stmt in branch.stmts {
if stmt is ast.ExprStmt {
p.check_undefined_variables(exprs, stmt.expr) ?
}
}
}
}
ast.ParExpr {
p.check_undefined_variables(exprs, val.expr) ?
}