From 315b2deda9aa5e2698b214ac0e5dc5face286a9b Mon Sep 17 00:00:00 2001 From: yuyi Date: Sun, 16 Jan 2022 19:12:27 +0800 Subject: [PATCH] cgen: fix match sumtype var returning sumtype value (#13184) --- vlib/v/gen/c/cgen.v | 10 +++++-- .../match_sumtype_var_return_sumtype_test.v | 30 +++++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 vlib/v/tests/match_sumtype_var_return_sumtype_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 73a6f99d4d..61014c2e1f 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -2421,9 +2421,9 @@ fn (mut g Gen) expr_with_cast(expr ast.Expr, got_type_raw ast.Type, expected_typ got_styp := g.typ(got_type) if expected_type != ast.void_type { unwrapped_expected_type := g.unwrap_generic(expected_type) - unwrapped_got_type := g.unwrap_generic(got_type) unwrapped_exp_sym := g.table.sym(unwrapped_expected_type) - unwrapped_got_sym := g.table.sym(unwrapped_got_type) + mut unwrapped_got_type := g.unwrap_generic(got_type) + mut unwrapped_got_sym := g.table.sym(unwrapped_got_type) expected_deref_type := if expected_is_ptr { unwrapped_expected_type.deref() @@ -2445,11 +2445,15 @@ fn (mut g Gen) expr_with_cast(expr ast.Expr, got_type_raw ast.Type, expected_typ is_already_sum_type = true } } - if is_already_sum_type { + if is_already_sum_type && !g.inside_return { // Don't create a new sum type wrapper if there is already one g.prevent_sum_type_unwrapping_once = true g.expr(expr) } else { + if mut unwrapped_got_sym.info is ast.Aggregate { + unwrapped_got_type = unwrapped_got_sym.info.types[g.aggregate_type_idx] + unwrapped_got_sym = g.table.sym(unwrapped_got_type) + } g.get_sumtype_casting_fn(unwrapped_got_type, unwrapped_expected_type) fname := '${unwrapped_got_sym.cname}_to_sumtype_$unwrapped_exp_sym.cname' g.call_cfn_for_casting_expr(fname, expr, expected_is_ptr, unwrapped_exp_sym.cname, diff --git a/vlib/v/tests/match_sumtype_var_return_sumtype_test.v b/vlib/v/tests/match_sumtype_var_return_sumtype_test.v new file mode 100644 index 0000000000..e2fff78c1f --- /dev/null +++ b/vlib/v/tests/match_sumtype_var_return_sumtype_test.v @@ -0,0 +1,30 @@ +module main + +type Sum = Struct | int + +struct Struct { +mut: + value int +} + +fn sum(mut s Sum) Sum { + match mut s { + Struct { + return s + } + else { + return s + } + } +} + +fn test_match_sumtype_var_return_sumtype() { + mut s := Sum(Struct{ + value: 42 + }) + s = sum(mut s) + dump(s) + ret := '$s' + assert ret.contains('Sum(Struct{') + assert ret.contains('value: 42') +}