Skip to content

Commit f2387ab

Browse files
authored
cgen: allow unwrapping of foo.bar as string, where foo.bar is ?string (fix #22960) (#22973)
1 parent 0e0408f commit f2387ab

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

vlib/v/gen/c/cgen.v

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7797,10 +7797,18 @@ fn (mut g Gen) as_cast(node ast.AsCast) {
77977797
} else {
77987798
mut is_optional_ident_var := false
77997799
if node.expr is ast.Ident {
7800-
if node.expr.info is ast.IdentVar && node.expr.info.is_option {
7800+
if node.expr.info is ast.IdentVar && node.expr.info.is_option
7801+
&& !unwrapped_node_typ.has_flag(.option) {
78017802
g.unwrap_option_type(unwrapped_node_typ, node.expr.name, node.expr.is_auto_heap())
78027803
is_optional_ident_var = true
78037804
}
7805+
} else if node.expr is ast.SelectorExpr {
7806+
if node.expr.expr is ast.Ident && node.expr.typ.has_flag(.option)
7807+
&& !unwrapped_node_typ.has_flag(.option) {
7808+
g.unwrap_option_type(node.expr.typ, '${node.expr.expr.name}.${node.expr.field_name}',
7809+
node.expr.expr.is_auto_heap())
7810+
is_optional_ident_var = true
7811+
}
78047812
}
78057813
if !is_optional_ident_var {
78067814
g.expr(node.expr)
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
struct Foo {
2+
foo string
3+
bar ?string
4+
}
5+
6+
fn (f Foo) str() string {
7+
mut ret := f.foo
8+
bar_value := f.bar as string
9+
if bar_value == '' {
10+
return ret
11+
}
12+
return ret + '%' + bar_value
13+
}
14+
15+
fn test_selector_expr_as_cast() {
16+
ff := Foo{
17+
foo: 'Fooooo'
18+
}
19+
assert '${ff}' == 'Fooooo'
20+
}

0 commit comments

Comments
 (0)