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

parser: disallow match expr at certain places (#6490)

This commit is contained in:
Swastik Baranwal 2020-10-03 19:00:58 +05:30 committed by GitHub
parent a9da4dd437
commit 7e13518cc2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 71 additions and 18 deletions

View File

@ -933,6 +933,8 @@ Note that the ranges use `...` (three dots) rather than `..` (two dots). This is
because the range is *inclusive* of the last element, rather than exclusive
(as `..` ranges are). Using `..` in a match branch will throw an error.
Note: `match` as an expression is not usable in `for` loop and `if` statements.
### Defer
A defer statement defers the execution of a block of statements until the surrounding function returns.

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/for_match_err.vv:3:7: error: cannot use `match` in `for` loop
1 | fn main() {
2 | mut a := 2
3 | for match a {
| ~~~~~
4 | 2 {
5 | println('a == 2')

View File

@ -0,0 +1,15 @@
fn main() {
mut a := 2
for match a {
2 {
println('a == 2')
a = 0
}
0 {
println('a == 0')
}
else {
println('unexpected branch')
}
}
}

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/if_match_expr_err.vv:3:8: error: cannot use `match` with `if` statements
1 | fn main() {
2 | a := 0
3 | if match a {
| ~~~~~
4 | 0 {
5 | println('a is zero')

View File

@ -0,0 +1,13 @@
fn main() {
a := 0
if match a {
0 {
println('a is zero')
}
else {
println('unreachable branch')
}
} 5 < 7 {
println('5 is less than 7')
}
}

View File

@ -11,6 +11,9 @@ fn (mut p Parser) for_stmt() ast.Stmt {
pos := p.tok.position()
p.open_scope()
p.inside_for = true
if p.tok.kind == .key_match {
p.error('cannot use `match` in `for` loop')
}
// defer { p.close_scope() }
// Infinite loop
if p.tok.kind == .lcbr {

View File

@ -34,6 +34,9 @@ fn (mut p Parser) if_expr(is_comptime bool) ast.IfExpr {
comments << p.eat_comments()
p.check(.key_else)
comments << p.eat_comments()
if p.tok.kind == .key_match {
p.error('cannot use `match` with `if` statements')
}
if p.tok.kind == .lcbr {
// else {
has_else = true
@ -72,6 +75,9 @@ fn (mut p Parser) if_expr(is_comptime bool) ast.IfExpr {
}
// `if` or `else if`
p.check(.key_if)
if p.tok.kind == .key_match {
p.error('cannot use `match` with `if` statements')
}
comments << p.eat_comments()
// `if mut name is T`
mut mut_name := false

View File

@ -1,24 +1,24 @@
fn test_for_match() {
mut a := 2
mut b := 0
for match a {
2 {
println('a == 2')
a = 0
true
for {
match a {
2 {
println('a == 2')
a = 0
continue
}
0 {
println('a == 0')
a = 5
b++
break
}
else {
println('unexpected branch')
break
}
}
0 {
println('a == 0')
a = 5
false
}
else {
println('unexpected branch')
false
}
} {
b++
println('${b}. run')
}
assert a == 5
assert b == 1
@ -34,7 +34,7 @@ fn test_for_select() {
x := <-ch1 {
a += x
}
y := <- ch2 {
y := <-ch2 {
a += int(y)
}
} {