Skip to content

Commit 7faf1bf

Browse files
authored
cgen: fix casting primitive type to alias, where option alias is expected (fix #23859) (#23860)
1 parent a74f317 commit 7faf1bf

File tree

2 files changed

+46
-3
lines changed

2 files changed

+46
-3
lines changed

vlib/v/gen/c/assign.v

+11-3
Original file line numberDiff line numberDiff line change
@@ -66,18 +66,26 @@ fn (mut g Gen) expr_opt_with_alias(expr ast.Expr, expr_typ ast.Type, ret_typ ast
6666
g.writeln('${ret_styp} ${ret_var} = {.state=2, .err=_const_none__, .data={EMPTY_STRUCT_INITIALIZATION}};')
6767

6868
if expr !is ast.None {
69-
g.write('_option_clone((${option_name}*)')
70-
has_addr := expr !in [ast.Ident, ast.SelectorExpr]
69+
is_option_expr := expr_typ.has_flag(.option)
70+
if is_option_expr {
71+
g.write('_option_clone((${option_name}*)')
72+
} else {
73+
g.write('_option_ok(&(${styp}[]){ ')
74+
}
75+
has_addr := is_option_expr && expr !in [ast.Ident, ast.SelectorExpr]
7176
if has_addr {
7277
expr_styp := g.styp(expr_typ).replace('*', '_ptr')
7378
g.write('ADDR(${expr_styp}, ')
74-
} else {
79+
} else if is_option_expr {
7580
g.write('&')
7681
}
7782
g.expr(expr)
7883
if has_addr {
7984
g.write(')')
8085
}
86+
if !is_option_expr {
87+
g.write(' }')
88+
}
8189
g.writeln(', (${option_name}*)&${ret_var}, sizeof(${styp}));')
8290
}
8391
g.write(line)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
module main
2+
3+
type Float = f32
4+
5+
struct Note {
6+
mut:
7+
seen string
8+
}
9+
10+
fn (mut n Note) bad_call(value ?Float) {
11+
if val := value {
12+
n.seen += ', ${val}'
13+
}
14+
}
15+
16+
fn (mut n Note) good_call(value ?f32) {
17+
if val := value {
18+
n.seen += ', ${val}'
19+
}
20+
}
21+
22+
fn test_main() {
23+
mut good := Note{}
24+
mut bad := Note{}
25+
mut c := 0
26+
for {
27+
good.good_call(f32(c))
28+
bad.bad_call(Float(c))
29+
c += 1
30+
if c >= 5 {
31+
break
32+
}
33+
}
34+
assert '${good.seen}' == '${bad.seen}'
35+
}

0 commit comments

Comments
 (0)