checker: fail if else isn't the last branch of match

pull/4413/head
Enzo Baldisserri 2020-04-14 20:31:51 +02:00 committed by GitHub
parent 0c63f5c80d
commit 86402204a7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 80 additions and 55 deletions

View File

@ -1355,7 +1355,17 @@ pub fn (c mut Checker) match_expr(node mut ast.MatchExpr) table.Type {
}
else {}
}
if !node.branches[node.branches.len - 1].is_else {
mut has_else := node.branches[node.branches.len - 1].is_else
if !has_else {
for i, branch in node.branches {
if branch.is_else && i != node.branches.len - 1 {
c.error('`else` must be the last branch of `match`', branch.pos)
has_else = true
break
}
}
if !has_else {
mut used_values_count := 0
for bi, branch in node.branches {
used_values_count += branch.exprs.len
@ -1419,6 +1429,7 @@ pub fn (c mut Checker) match_expr(node mut ast.MatchExpr) table.Type {
c.error(err_details, node.pos)
}
}
}
c.expected_type = cond_type
mut ret_type := table.void_type
for branch in node.branches {

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/inout/match_else_last_expr.v:4:3: error: `else` must be the last branch of `match`
2| match 1 {
3| 1 { println('1') }
4| else { println('else') }
~~~~~~
5| 4 { println('4') }
6| }

View File

@ -0,0 +1,7 @@
fn main() {
match 1 {
1 { println('1') }
else { println('else') }
4 { println('4') }
}
}

View File

@ -1919,8 +1919,8 @@ fn (p mut Parser) match_expr() ast.MatchExpr {
// p.warn('match block')
stmts := p.parse_block()
pos := token.Position{
line_nr: match_first_pos.line_nr
pos: match_first_pos.pos
line_nr: branch_first_pos.line_nr
pos: branch_first_pos.pos
len: branch_last_pos.pos - branch_first_pos.pos + branch_last_pos.len
}
branches << ast.MatchBranch{