checker: fix match expr with if expr (fix #10177 #10178) (#10179)

pull/10182/head
yuyi 2021-05-23 22:59:57 +08:00 committed by GitHub
parent 7f12bfa563
commit eb5ac23988
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 54 additions and 0 deletions

View File

@ -5326,6 +5326,9 @@ pub fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type {
mut stmt := branch.stmts[branch.stmts.len - 1] mut stmt := branch.stmts[branch.stmts.len - 1]
match mut stmt { match mut stmt {
ast.ExprStmt { ast.ExprStmt {
if node.is_expr {
c.expected_type = node.expected_type
}
expr_type := c.expr(stmt.expr) expr_type := c.expr(stmt.expr)
if ret_type == ast.void_type { if ret_type == ast.void_type {
ret_type = expr_type ret_type = expr_type

View File

@ -40,3 +40,10 @@ vlib/v/checker/tests/if_match_expr.vv:23:3: error: `match` expression branch has
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
24 | _ = match true {true {1} else {-1}} // OK 24 | _ = match true {true {1} else {-1}} // OK
25 | match true {true {1} else {-1}} // result 25 | match true {true {1} else {-1}} // result
vlib/v/checker/tests/if_match_expr.vv:25:3: error: return type mismatch, it should be `int`
23 | match true {true {} else {}} // statement not expression
24 | _ = match true {true {1} else {-1}} // OK
25 | match true {true {1} else {-1}} // result
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
26 | }
27 | }

View File

@ -1018,6 +1018,7 @@ fn (mut g Gen) stmts_with_tmp_var(stmts []ast.Stmt, tmp_var string) {
g.skip_stmt_pos = true g.skip_stmt_pos = true
g.write('$tmp_var = ') g.write('$tmp_var = ')
g.stmt(stmt) g.stmt(stmt)
g.writeln(';')
} }
} else { } else {
g.stmt(stmt) g.stmt(stmt)

View File

@ -0,0 +1,43 @@
fn foo1() int {
return match 1 {
1 {
if true {
1
} else {
2
}
}
else {
if true {
3
} else {
4
}
}
}
}
fn foo2() int {
return match 1 {
1 {
match true {
true { 1 }
false { 2 }
}
}
else {
match false {
true { 3 }
false { 4 }
}
}
}
}
fn test_match_expr_with_if_or_match_expr() {
println(foo1())
assert foo1() == 1
println(foo2())
assert foo2() == 1
}