From e384e74142699d388ef72b2c6ddd9392ad695f9b Mon Sep 17 00:00:00 2001 From: Isaiah <16439221+pisaiah@users.noreply.github.com> Date: Thu, 21 Nov 2024 05:44:56 -0500 Subject: [PATCH] cgen: fix option unwrap for fields of interface type (fixes #22930) (#22931) --- vlib/v/gen/c/cgen.v | 3 ++- .../options/option_selector_unwrap_types_test.v | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index e7224f46bba43b..f8c1055d3a3392 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -4059,7 +4059,8 @@ fn (mut g Gen) selector_expr(node ast.SelectorExpr) { g.write('*') } cast_sym := g.table.sym(g.unwrap_generic(typ)) - if field_sym.kind == .interface && cast_sym.kind == .interface { + if field_sym.kind == .interface && cast_sym.kind == .interface + && !is_option_unwrap { ptr := '*'.repeat(field.typ.nr_muls()) dot := if node.expr_type.is_ptr() { '->' } else { '.' } g.write('I_${field_sym.cname}_as_I_${cast_sym.cname}(${ptr}${node.expr}${dot}${node.field_name}))') diff --git a/vlib/v/tests/options/option_selector_unwrap_types_test.v b/vlib/v/tests/options/option_selector_unwrap_types_test.v index f7a8f71c6b62bf..cc5a29120685c1 100644 --- a/vlib/v/tests/options/option_selector_unwrap_types_test.v +++ b/vlib/v/tests/options/option_selector_unwrap_types_test.v @@ -1,5 +1,9 @@ type SumType = int | string +interface Interface { + a int +} + struct Struct { a int } @@ -9,6 +13,7 @@ struct Foo { b ?string c ?SumType d ?Struct + e ?Interface } fn test_main() { @@ -19,6 +24,9 @@ fn test_main() { d: Struct{ a: 123 } + e: Struct{ + a: 456 + } } if w.a != none { dump(w.a) @@ -44,4 +52,10 @@ fn test_main() { } else { assert false } + if w.e != none { + dump(w.e) + assert w.e.a == 456 + } else { + assert false + } }