From ea163197c74096042e7f7d90f6ffdf561639bac9 Mon Sep 17 00:00:00 2001 From: yuyi Date: Fri, 19 Aug 2022 01:18:03 +0800 Subject: [PATCH] cgen: fix shared optional (#15462) --- vlib/v/gen/c/cgen.v | 4 ++-- vlib/v/tests/shared_optional_test.v | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/shared_optional_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 0e6a12c652..7a005cbfe0 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -2948,7 +2948,7 @@ fn (mut g Gen) expr(node_ ast.Expr) { node.return_type.clear_flag(.optional) } mut shared_styp := '' - if g.is_shared && !ret_type.has_flag(.shared_f) { + if g.is_shared && !ret_type.has_flag(.shared_f) && !g.inside_or_block { ret_sym := g.table.sym(ret_type) shared_typ := ret_type.set_flag(.shared_f) shared_styp = g.typ(shared_typ) @@ -2977,7 +2977,7 @@ fn (mut g Gen) expr(node_ ast.Expr) { g.strs_to_free0 = [] // println('pos=$node.pos.pos') } - if g.is_shared && !ret_type.has_flag(.shared_f) { + if g.is_shared && !ret_type.has_flag(.shared_f) && !g.inside_or_block { g.writeln('}, sizeof($shared_styp))') } // if g.autofree && node.autofree_pregen != '' { // g.strs_to_free0.len != 0 { diff --git a/vlib/v/tests/shared_optional_test.v b/vlib/v/tests/shared_optional_test.v new file mode 100644 index 0000000000..3dd68cab51 --- /dev/null +++ b/vlib/v/tests/shared_optional_test.v @@ -0,0 +1,25 @@ +module main + +struct ABC { +mut: + s string +} + +fn test_shared_optional() { + shared abc := foo() or { panic('scared') } + rlock abc { + println(abc) + assert abc.s == 'hello' + } +} + +fn foo() ?ABC { + mut a := ABC{} + a.bar()? + return a +} + +fn (mut a ABC) bar() ? { + a.s = 'hello' + println(a.s) +}