From aa340472e63bafe223ac56151d618f8e95213837 Mon Sep 17 00:00:00 2001 From: yuyi Date: Mon, 15 Jul 2024 20:18:49 +0800 Subject: [PATCH] cgen: fix fn mut argument of sumtype reference (#21874) --- vlib/v/gen/c/fn.v | 10 +++++-- vlib/v/tests/fn_mut_arg_of_sumtype_ref_test.v | 29 +++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/fn_mut_arg_of_sumtype_ref_test.v diff --git a/vlib/v/gen/c/fn.v b/vlib/v/gen/c/fn.v index d42cf6295cdd93..0e14ef1daacdb2 100644 --- a/vlib/v/gen/c/fn.v +++ b/vlib/v/gen/c/fn.v @@ -2608,8 +2608,14 @@ fn (mut g Gen) ref_or_deref_arg(arg ast.CallArg, expected_type ast.Type, lang as g.write('&/*mut*/') } else if arg.is_mut && arg_typ.is_ptr() && expected_type.is_ptr() && g.table.sym(arg_typ).kind == .struct_ && expected_type == arg_typ.ref() { - g.write('&/*mut*/') - g.expr(arg.expr) + if arg.expr is ast.PrefixExpr && arg.expr.op == .amp { + g.arg_no_auto_deref = true + g.expr(arg.expr) + g.arg_no_auto_deref = false + } else { + g.write('&/*mut*/') + g.expr(arg.expr) + } return } else if exp_is_ptr && !arg_is_ptr && !(arg_sym.kind == .alias && g.table.unaliased_type(arg_typ).is_pointer() && expected_type.is_pointer()) { diff --git a/vlib/v/tests/fn_mut_arg_of_sumtype_ref_test.v b/vlib/v/tests/fn_mut_arg_of_sumtype_ref_test.v new file mode 100644 index 00000000000000..07980ebc5eb69f --- /dev/null +++ b/vlib/v/tests/fn_mut_arg_of_sumtype_ref_test.v @@ -0,0 +1,29 @@ +module main + +pub struct Expr1 {} + +pub struct Expr2 {} + +pub type Expr = Expr1 | Expr2 + +pub struct Gen { +} + +fn (mut g Gen) foo(mut expr &Expr1) string { + return '${expr}' +} + +pub fn (mut g Gen) bar(mut expr Expr) string { + return match mut expr { + Expr1 { g.foo(mut &expr) } + Expr2 { '' } + } +} + +fn test_fn_mut_arg_of_sumtype_ref() { + mut expr := &Expr1{} + mut g := Gen{} + ret := g.bar(mut expr) + println(ret) + assert ret == 'Expr1{}' +}