Skip to content

Commit af8df87

Browse files
authored
cgen: fix option ptr assignment (#18394)
1 parent c4a20f0 commit af8df87

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

vlib/v/gen/c/cgen.v

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1883,19 +1883,32 @@ fn (mut g Gen) expr_with_tmp_var(expr ast.Expr, expr_typ ast.Type, ret_typ ast.T
18831883
g.gen_option_error(ret_typ, expr)
18841884
g.writeln(';')
18851885
} else {
1886+
mut is_ptr_to_ptr_assign := false
18861887
g.writeln('${g.typ(ret_typ)} ${tmp_var};')
18871888
if ret_typ.has_flag(.option) {
18881889
if expr_typ.has_flag(.option) && expr in [ast.StructInit, ast.ArrayInit, ast.MapInit] {
18891890
g.write('_option_none(&(${styp}[]) { ')
18901891
} else {
1891-
g.write('_option_ok(&(${styp}[]) { ')
1892+
is_ptr_to_ptr_assign = (expr is ast.SelectorExpr
1893+
|| (expr is ast.Ident && !(expr as ast.Ident).is_auto_heap()))
1894+
&& ret_typ.is_ptr() && expr_typ.is_ptr() && expr_typ.has_flag(.option)
1895+
// option ptr assignment simplification
1896+
if is_ptr_to_ptr_assign {
1897+
g.write('${tmp_var} = ')
1898+
} else {
1899+
g.write('_option_ok(&(${styp}[]) { ')
1900+
}
18921901
}
18931902
} else {
18941903
g.write('_result_ok(&(${styp}[]) { ')
18951904
}
18961905
g.expr_with_cast(expr, expr_typ, ret_typ)
18971906
if ret_typ.has_flag(.option) {
1898-
g.writeln(' }, (${c.option_name}*)(&${tmp_var}), sizeof(${styp}));')
1907+
if is_ptr_to_ptr_assign {
1908+
g.writeln(';')
1909+
} else {
1910+
g.writeln(' }, (${c.option_name}*)(&${tmp_var}), sizeof(${styp}));')
1911+
}
18991912
} else {
19001913
g.writeln(' }, (${c.result_name}*)(&${tmp_var}), sizeof(${styp}));')
19011914
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
[heap]
2+
struct Node[T] {
3+
mut:
4+
value T
5+
next ?&Node[T]
6+
}
7+
8+
fn print_t(node ?&Node[int]) ?&Node[int] {
9+
println(node)
10+
assert node == none
11+
return node
12+
}
13+
14+
fn test_main() {
15+
n := Node[int]{
16+
value: 5
17+
}
18+
t := print_t(n.next)
19+
assert t == none
20+
}

0 commit comments

Comments
 (0)