From ccb93e677c227e7a4616bcc322d91e2a32a2c7bb Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sun, 30 Mar 2025 10:31:34 -0300 Subject: [PATCH] cgen: fix codegen for selector with embed field option (fix #24084) (#24085) --- vlib/v/gen/c/cgen.v | 6 ++++++ vlib/v/tests/options/option_embed_field_test.v | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 vlib/v/tests/options/option_embed_field_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index c96896aa6c..83181ab0e9 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -7579,6 +7579,12 @@ fn (mut g Gen) as_cast(node ast.AsCast) { g.unwrap_option_type(node.expr.typ, '${node.expr.expr.name}.${node.expr.field_name}', node.expr.expr.is_auto_heap()) is_optional_ident_var = true + } else if node.expr.expr is ast.SelectorExpr && node.expr.typ.has_flag(.option) { + if node.expr.expr.expr is ast.Ident { + g.unwrap_option_type(node.expr.typ, '${node.expr.expr.expr.name}.${node.expr.expr.field_name}.${node.expr.field_name}', + node.expr.expr.expr.is_auto_heap()) + is_optional_ident_var = true + } } } if !is_optional_ident_var { diff --git a/vlib/v/tests/options/option_embed_field_test.v b/vlib/v/tests/options/option_embed_field_test.v new file mode 100644 index 0000000000..63e536d59d --- /dev/null +++ b/vlib/v/tests/options/option_embed_field_test.v @@ -0,0 +1,18 @@ +struct Foo { + optional_one ?string +} + +struct Bar { + foo Foo +} + +fn test_main() { + b := Bar{Foo{ + optional_one: 'hello world' + }} + println(b.foo.optional_one) + x := b.foo.optional_one as string + + assert x == 'hello world' + assert (b.foo.optional_one as string) == 'hello world' +}