From e69df54a362dccf4a6e03de2bfbc36f9fe3f6cb4 Mon Sep 17 00:00:00 2001 From: 05st <60903484+05st@users.noreply.github.com> Date: Sun, 10 Oct 2021 18:45:01 -0500 Subject: [PATCH] cgen: fix multi-return in if/match exprs (#12139) --- vlib/v/gen/c/cgen.v | 9 ++++++--- vlib/v/tests/fn_multiple_returns_test.v | 26 +++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index c7210c74dd..759497dc3e 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -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(';') diff --git a/vlib/v/tests/fn_multiple_returns_test.v b/vlib/v/tests/fn_multiple_returns_test.v index a89c4551c9..bae15dc1c4 100644 --- a/vlib/v/tests/fn_multiple_returns_test.v +++ b/vlib/v/tests/fn_multiple_returns_test.v @@ -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 +}