cgen: fix multi-return in if/match exprs (#12139)

pull/11131/merge
05st 2021-10-10 18:45:01 -05:00 committed by GitHub
parent 0f7dfb984a
commit e69df54a36
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 3 deletions

View File

@ -4879,7 +4879,10 @@ fn (mut g Gen) cast_expr(node ast.CastExpr) {
}
fn (mut g Gen) concat_expr(node ast.ConcatExpr) {
styp := g.typ(node.return_type)
mut styp := g.typ(node.return_type)
if g.inside_return {
styp = g.typ(g.fn_decl.return_type)
}
sym := g.table.get_type_symbol(node.return_type)
is_multi := sym.kind == .multi_return
if !is_multi {
@ -5163,8 +5166,8 @@ fn (mut g Gen) return_stmt(node ast.Return) {
}
// regular cases
if fn_return_is_multi && node.exprs.len > 0 && !g.expr_is_multi_return_call(node.exprs[0]) {
if node.exprs.len == 1 && node.exprs[0] is ast.IfExpr {
// use a temporary for `return if cond { x,y } else { a,b }`
if node.exprs.len == 1 && (node.exprs[0] is ast.IfExpr || node.exprs[0] is ast.MatchExpr) {
// use a temporary for `return if cond { x,y } else { a,b }` or `return match expr { abc { x, y } else { z, w } }`
g.write('$ret_typ $tmpvar = ')
g.expr(node.exprs[0])
g.writeln(';')

View File

@ -82,3 +82,29 @@ fn test_multi_values() {
assert x == 'abc'
assert y == 'def'
}
fn match_expr(x bool) (int, int) {
return match x {
true { 1, 1 }
else { 0, 0 }
}
}
fn if_expr(x bool) (int, int) {
return if x { 3, 3 } else { 2, 2 }
}
fn test_multi_return_if_match_expr() {
a, b := match_expr(true)
c, d := match_expr(false)
x, y := if_expr(true)
z, w := if_expr(false)
assert a == 1
assert b == 1
assert c == 0
assert d == 0
assert x == 3
assert y == 3
assert z == 2
assert w == 2
}