From d714dcef753ee3309164b13697319f09122a8368 Mon Sep 17 00:00:00 2001 From: Tim Basel Date: Wed, 19 Jan 2022 13:37:40 +0100 Subject: [PATCH] cgen: fix return of mut symtype (#13214) --- vlib/v/gen/c/cgen.v | 2 ++ vlib/v/tests/fn_return_mut_sumtype_test.v | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 vlib/v/tests/fn_return_mut_sumtype_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index e75b5e38d9..df0d246ae3 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -5004,6 +5004,8 @@ fn (mut g Gen) return_stmt(node ast.Return) { if g.fn_decl.return_type.is_ptr() { var_str := g.expr_string(expr0) g.write(var_str.trim('&')) + } else if g.table.sym(g.fn_decl.return_type).kind in [.sum_type, .interface_] { + g.expr_with_cast(expr0, node.types[0], g.fn_decl.return_type) } else { g.write('*') g.expr(expr0) diff --git a/vlib/v/tests/fn_return_mut_sumtype_test.v b/vlib/v/tests/fn_return_mut_sumtype_test.v new file mode 100644 index 0000000000..a529611e5a --- /dev/null +++ b/vlib/v/tests/fn_return_mut_sumtype_test.v @@ -0,0 +1,23 @@ +type Sum = Struct | int + +struct Struct { +mut: + value int +} + +fn update(mut s Struct) Sum { + s.value += 1 + return s +} + +fn test_fn_return_mut_sumtype() { + mut s := Sum(Struct{ + value: 1 + }) + if mut s is Struct { + s = update(mut s) + assert s.value == 2 + } else { + assert false + } +}