Skip to content

Commit

Permalink
cgen: fix unwrapping option interface field (fix #23540) (#23541)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp authored Jan 21, 2025
1 parent ea5f25e commit 305a272
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
5 changes: 4 additions & 1 deletion vlib/v/gen/c/cgen.v
Original file line number Diff line number Diff line change
Expand Up @@ -4013,6 +4013,9 @@ fn (mut g Gen) selector_expr(node ast.SelectorExpr) {
if i == 0 && (is_option_unwrap || nested_unwrap) {
deref := if g.inside_selector {
'*'.repeat(field.smartcasts.last().nr_muls() + 1)
} else if sym.kind == .interface && !typ.is_ptr()
&& field.orig_type.has_flag(.option) {
''
} else {
'*'
}
Expand Down Expand Up @@ -4196,7 +4199,7 @@ fn (mut g Gen) selector_expr(node ast.SelectorExpr) {
}
g.write(field_name)
if is_option_unwrap {
if field_typ.is_ptr() && g.table.final_sym(node.expr_type).kind in [.sum_type, .interface] {
if g.table.final_sym(node.expr_type).kind in [.sum_type, .interface] {
g.write('->')
} else {
g.write('.')
Expand Down
29 changes: 29 additions & 0 deletions vlib/v/tests/options/option_unwrap_selector_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
interface IBar {
opt ?string
}

struct Bar implements IBar {
opt ?string
}

struct Foo {
field IBar
}

fn (f &Foo) t() {
if f.field.opt != none {
assert f.field.opt == 'foo'
}
}

fn test_main() {
a := Foo{
field: Bar{
opt: 'foo'
}
}
if a.field.opt != none {
assert a.field.opt == 'foo'
}
a.t()
}

0 comments on commit 305a272

Please sign in to comment.