Skip to content

Commit bd3501a

Browse files
authored
cgen: fix option ptr initialization (#18893)
1 parent 0073283 commit bd3501a

3 files changed

Lines changed: 41 additions & 2 deletions

File tree

vlib/v/gen/c/cgen.v

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1917,6 +1917,9 @@ fn (mut g Gen) expr_with_tmp_var(expr ast.Expr, expr_typ ast.Type, ret_typ ast.T
19171917
// option ptr assignment simplification
19181918
if is_ptr_to_ptr_assign {
19191919
g.write('${tmp_var} = ')
1920+
} else if expr is ast.PrefixExpr && expr.right is ast.StructInit
1921+
&& (expr.right as ast.StructInit).init_fields.len == 0 {
1922+
g.write('_option_none(&(${styp}[]) { ')
19201923
} else {
19211924
g.write('_option_ok(&(${styp}[]) { ')
19221925
}

vlib/v/gen/c/struct.v

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,12 @@ fn (mut g Gen) struct_init(node ast.StructInit) {
5959
shared_styp = g.typ(shared_typ)
6060
g.writeln('(${shared_styp}*)__dup${shared_styp}(&(${shared_styp}){.mtx = {0}, .val =(${styp}){')
6161
} else if is_amp || g.inside_cast_in_heap > 0 {
62-
g.write('(${styp}*)memdup(&(${styp}){')
62+
if node.typ.has_flag(.option) {
63+
basetyp := g.base_type(node.typ)
64+
g.write('(${basetyp}*)memdup(&(${basetyp}){')
65+
} else {
66+
g.write('(${styp}*)memdup(&(${styp}){')
67+
}
6368
} else if node.typ.is_ptr() {
6469
basetyp := g.typ(node.typ.set_nr_muls(0))
6570
if is_multiline {
@@ -305,7 +310,12 @@ fn (mut g Gen) struct_init(node ast.StructInit) {
305310
if g.is_shared && !g.inside_opt_data && !g.is_arraymap_set {
306311
g.write('}, sizeof(${shared_styp}))')
307312
} else if is_amp || g.inside_cast_in_heap > 0 {
308-
g.write(', sizeof(${styp}))')
313+
if node.typ.has_flag(.option) {
314+
basetyp := g.base_type(node.typ)
315+
g.write(', sizeof(${basetyp}))')
316+
} else {
317+
g.write(', sizeof(${styp}))')
318+
}
309319
}
310320
}
311321

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
struct Abc {
2+
a int
3+
}
4+
5+
fn test_option_init() {
6+
a := ?Abc{
7+
a: 1
8+
}
9+
dump(a)
10+
b := &?Abc{
11+
a: 1
12+
}
13+
dump(b)
14+
15+
assert *b? == a?
16+
}
17+
18+
fn test_option_empty() {
19+
a := ?Abc{}
20+
dump(a)
21+
b := &?Abc{}
22+
dump(b)
23+
24+
assert a == none
25+
assert b == none
26+
}

0 commit comments

Comments
 (0)