From 0390a7a988664cd0b8e88d859dda0ec0c6903820 Mon Sep 17 00:00:00 2001 From: yuyi Date: Mon, 31 Oct 2022 02:26:33 +0800 Subject: [PATCH] cgen: fix return match expr of sumtype result (#16264) --- vlib/v/gen/c/cgen.v | 8 ++++-- ...return_match_expr_of_sumtype_result_test.v | 25 +++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/return_match_expr_of_sumtype_result_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 8b94fdb91b..762b3623b9 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -1666,8 +1666,10 @@ fn (mut g Gen) stmts_with_tmp_var(stmts []ast.Stmt, tmp_var string) bool { g.expr(stmt.expr) g.writeln(';') } else { + ret_typ := g.fn_decl.return_type.clear_flag(.optional) + styp = g.base_type(ret_typ) g.write('_option_ok(&($styp[]) { ') - g.expr(stmt.expr) + g.expr_with_cast(stmt.expr, stmt.typ, ret_typ) g.writeln(' }, ($c.option_name*)(&$tmp_var), sizeof($styp));') } } @@ -1696,8 +1698,10 @@ fn (mut g Gen) stmts_with_tmp_var(stmts []ast.Stmt, tmp_var string) bool { g.expr(stmt.expr) g.writeln(';') } else { + ret_typ := g.fn_decl.return_type.clear_flag(.result) + styp = g.base_type(ret_typ) g.write('_result_ok(&($styp[]) { ') - g.expr(stmt.expr) + g.expr_with_cast(stmt.expr, stmt.typ, ret_typ) g.writeln(' }, ($c.result_name*)(&$tmp_var), sizeof($styp));') } } diff --git a/vlib/v/tests/return_match_expr_of_sumtype_result_test.v b/vlib/v/tests/return_match_expr_of_sumtype_result_test.v new file mode 100644 index 0000000000..dfa33e98c3 --- /dev/null +++ b/vlib/v/tests/return_match_expr_of_sumtype_result_test.v @@ -0,0 +1,25 @@ +type Foo = int | string + +fn foo1() !Foo { + return match true { + true { 1 } + else { '' } + } +} + +fn foo2() ?Foo { + return match true { + true { 1 } + else { '' } + } +} + +fn test_return_match_expr_of_sumtype_opt_res() { + ret1 := foo1() or { return } + println(ret1) + assert '$ret1' == 'Foo(1)' + + ret2 := foo2() or { return } + println(ret2) + assert '$ret2' == 'Foo(1)' +}