From 3e52d54586f44799335cfb76cfa9add5b0dfb7f8 Mon Sep 17 00:00:00 2001 From: 05st <60903484+05st@users.noreply.github.com> Date: Wed, 20 Oct 2021 03:52:11 -0500 Subject: [PATCH] cgen: fix match expr when evaluating to sumtype (#12237) --- vlib/v/gen/c/cgen.v | 12 ++++++++++++ vlib/v/tests/match_expr_returning_sumtype_test.v | 13 +++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 vlib/v/tests/match_expr_returning_sumtype_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 76efc36afb..9ada6badb3 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -4264,6 +4264,9 @@ fn (mut g Gen) need_tmp_var_in_match(node ast.MatchExpr) bool { if node.is_expr && node.return_type != ast.void_type && node.return_type != 0 { cond_sym := g.table.get_final_type_symbol(node.cond_type) sym := g.table.get_type_symbol(node.return_type) + if g.table.type_kind(node.return_type) == .sum_type { + return true + } if sym.kind == .multi_return { return false } @@ -4298,6 +4301,7 @@ fn (mut g Gen) match_expr(node ast.MatchExpr) { } need_tmp_var := g.need_tmp_var_in_match(node) is_expr := (node.is_expr && node.return_type != ast.void_type) || g.inside_ternary > 0 + mut cond_var := '' mut tmp_var := '' mut cur_line := '' @@ -4496,7 +4500,11 @@ fn (mut g Gen) match_expr_switch(node ast.MatchExpr, is_expr bool, cond_var stri } g.indent++ g.writeln('{') + if is_expr && tmp_var.len > 0 && g.table.get_type_symbol(node.return_type).kind == .sum_type { + g.expected_cast_type = node.return_type + } g.stmts_with_tmp_var(branch.stmts, tmp_var) + g.expected_cast_type = 0 g.writeln('} break;') g.indent-- } @@ -4644,7 +4652,11 @@ fn (mut g Gen) match_expr_classic(node ast.MatchExpr, is_expr bool, cond_var str g.writeln(') {') } } + if is_expr && tmp_var.len > 0 && g.table.get_type_symbol(node.return_type).kind == .sum_type { + g.expected_cast_type = node.return_type + } g.stmts_with_tmp_var(branch.stmts, tmp_var) + g.expected_cast_type = 0 if g.inside_ternary == 0 && node.branches.len >= 1 { g.write('}') } diff --git a/vlib/v/tests/match_expr_returning_sumtype_test.v b/vlib/v/tests/match_expr_returning_sumtype_test.v new file mode 100644 index 0000000000..7c97064293 --- /dev/null +++ b/vlib/v/tests/match_expr_returning_sumtype_test.v @@ -0,0 +1,13 @@ +type Ty = bool | int + +fn test(a bool) Ty { + return match a { + true { 123 } + else { false } + } +} + +fn test_match_expr_sumtype_eval() { + assert test(true) == Ty(123) + assert test(false) == Ty(false) +}