From 1ef718c1e1ee52cbda13522062cdd8032ca92825 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Tue, 13 Apr 2021 11:31:40 +0300 Subject: [PATCH] cgen: fix `return if cond { x,y } else { a,b }` generation --- vlib/v/gen/c/cgen.v | 10 ++++++++++ vlib/v/tests/fn_multiple_returns_test.v | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index ce648d3bd2..51006b418a 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -4687,6 +4687,16 @@ 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]) { // not_optional_none { //&& !fn_return_is_optional { + if node.exprs.len == 1 && node.exprs[0] is ast.IfExpr { + // use a temporary for `return if cond { x,y } else { a,b }` + tmpvar := g.new_tmp_var() + tmptyp := g.typ(g.fn_decl.return_type) + g.write('$tmptyp $tmpvar = ') + g.expr(node.exprs[0]) + g.writeln(';') + g.writeln('return $tmpvar;') + return + } // typ_sym := g.table.get_type_symbol(g.fn_decl.return_type) // mr_info := typ_sym.info as ast.MultiReturn mut styp := '' diff --git a/vlib/v/tests/fn_multiple_returns_test.v b/vlib/v/tests/fn_multiple_returns_test.v index eaac1338e1..a89c4551c9 100644 --- a/vlib/v/tests/fn_multiple_returns_test.v +++ b/vlib/v/tests/fn_multiple_returns_test.v @@ -72,3 +72,13 @@ fn test_multiple_ret() { assert res3_1 == 'replaced' assert res3_2 == 'val' } + +fn multi_values() (string, string) { + return if 1 > 0 { 'abc', 'def' } else { 'jkl', 'mno' } +} + +fn test_multi_values() { + x, y := multi_values() + assert x == 'abc' + assert y == 'def' +}