Skip to content

Commit

Permalink
cgen: allow unwrapping of foo.bar as string, where foo.bar is `?s…
Browse files Browse the repository at this point in the history
…tring` (fix #22960) (#22973)
  • Loading branch information
Delta456 authored Nov 26, 2024
1 parent 0e0408f commit f2387ab
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
10 changes: 9 additions & 1 deletion vlib/v/gen/c/cgen.v
Original file line number Diff line number Diff line change
Expand Up @@ -7797,10 +7797,18 @@ fn (mut g Gen) as_cast(node ast.AsCast) {
} else {
mut is_optional_ident_var := false
if node.expr is ast.Ident {
if node.expr.info is ast.IdentVar && node.expr.info.is_option {
if node.expr.info is ast.IdentVar && node.expr.info.is_option
&& !unwrapped_node_typ.has_flag(.option) {
g.unwrap_option_type(unwrapped_node_typ, node.expr.name, node.expr.is_auto_heap())
is_optional_ident_var = true
}
} else if node.expr is ast.SelectorExpr {
if node.expr.expr is ast.Ident && node.expr.typ.has_flag(.option)
&& !unwrapped_node_typ.has_flag(.option) {
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
}
}
if !is_optional_ident_var {
g.expr(node.expr)
Expand Down
File renamed without changes.
20 changes: 20 additions & 0 deletions vlib/v/tests/options/option_unwrap_selector_expr_as_cast_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
struct Foo {
foo string
bar ?string
}

fn (f Foo) str() string {
mut ret := f.foo
bar_value := f.bar as string
if bar_value == '' {
return ret
}
return ret + '%' + bar_value
}

fn test_selector_expr_as_cast() {
ff := Foo{
foo: 'Fooooo'
}
assert '${ff}' == 'Fooooo'
}

0 comments on commit f2387ab

Please sign in to comment.