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

checker, cgen: fix match expr with branch returning (#16741)

This commit is contained in:
yuyi 2022-12-22 18:55:44 +08:00 committed by GitHub
parent 3c5cfa22d1
commit 82a3551313
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 30 additions and 10 deletions

View File

@ -72,7 +72,7 @@ fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type {
} else if node.is_expr && ret_type.idx() != expr_type.idx() {
c.check_match_branch_last_stmt(stmt, ret_type, expr_type)
}
} else {
} else if stmt !is ast.Return {
if node.is_expr && ret_type != ast.void_type {
c.error('`match` expression requires an expression as the last statement of every branch',
stmt.pos)

View File

@ -1,7 +0,0 @@
vlib/v/checker/tests/match_expr_non_void_stmt_last.vv:9:4: error: `match` expression requires an expression as the last statement of every branch
7 | }
8 | []int {
9 | return arr.str()
| ~~~~~~~~~~~~~~~~
10 | }
11 | }

View File

@ -1737,7 +1737,9 @@ fn (mut g Gen) stmts_with_tmp_var(stmts []ast.Stmt, tmp_var string) bool {
g.set_current_pos_as_last_stmt_pos()
g.skip_stmt_pos = true
mut is_noreturn := false
if stmt is ast.ExprStmt {
if stmt is ast.Return {
is_noreturn = true
} else if stmt is ast.ExprStmt {
is_noreturn = is_noreturn_callexpr(stmt.expr)
}
if !is_noreturn {

View File

@ -23,6 +23,8 @@ fn (mut g Gen) need_tmp_var_in_if(node ast.IfExpr) bool {
if g.need_tmp_var_in_expr(stmt.expr) {
return true
}
} else if branch.stmts[0] is ast.Return {
return true
}
}
}

View File

@ -27,6 +27,8 @@ fn (mut g Gen) need_tmp_var_in_match(node ast.MatchExpr) bool {
if g.need_tmp_var_in_expr(stmt.expr) {
return true
}
} else if branch.stmts[0] is ast.Return {
return true
}
}
}

View File

@ -11,7 +11,9 @@ fn (arr Arr) str() string {
}
}
fn main() {
fn test_match_expr_with_branch_returning() {
println(Arr([0, 0]))
assert '${Arr([0, 0])}' == '[0, 0]'
println(Arr(['0', '0']))
assert '${Arr(['0', '0'])}' == '0 0'
}

View File

@ -0,0 +1,19 @@
fn foo() ! {
a := match true {
true {
2
}
2 == 2 {
return error('hello')
}
else {
0
}
}
println(a)
assert a == 2
}
fn test_match_expr_with_branch_returning() {
foo()!
}