mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
cgen: fix option ptr initialization (#18893)
This commit is contained in:
parent
0073283f53
commit
bd3501affa
@ -1917,6 +1917,9 @@ fn (mut g Gen) expr_with_tmp_var(expr ast.Expr, expr_typ ast.Type, ret_typ ast.T
|
||||
// option ptr assignment simplification
|
||||
if is_ptr_to_ptr_assign {
|
||||
g.write('${tmp_var} = ')
|
||||
} else if expr is ast.PrefixExpr && expr.right is ast.StructInit
|
||||
&& (expr.right as ast.StructInit).init_fields.len == 0 {
|
||||
g.write('_option_none(&(${styp}[]) { ')
|
||||
} else {
|
||||
g.write('_option_ok(&(${styp}[]) { ')
|
||||
}
|
||||
|
@ -59,7 +59,12 @@ fn (mut g Gen) struct_init(node ast.StructInit) {
|
||||
shared_styp = g.typ(shared_typ)
|
||||
g.writeln('(${shared_styp}*)__dup${shared_styp}(&(${shared_styp}){.mtx = {0}, .val =(${styp}){')
|
||||
} else if is_amp || g.inside_cast_in_heap > 0 {
|
||||
if node.typ.has_flag(.option) {
|
||||
basetyp := g.base_type(node.typ)
|
||||
g.write('(${basetyp}*)memdup(&(${basetyp}){')
|
||||
} else {
|
||||
g.write('(${styp}*)memdup(&(${styp}){')
|
||||
}
|
||||
} else if node.typ.is_ptr() {
|
||||
basetyp := g.typ(node.typ.set_nr_muls(0))
|
||||
if is_multiline {
|
||||
@ -305,8 +310,13 @@ fn (mut g Gen) struct_init(node ast.StructInit) {
|
||||
if g.is_shared && !g.inside_opt_data && !g.is_arraymap_set {
|
||||
g.write('}, sizeof(${shared_styp}))')
|
||||
} else if is_amp || g.inside_cast_in_heap > 0 {
|
||||
if node.typ.has_flag(.option) {
|
||||
basetyp := g.base_type(node.typ)
|
||||
g.write(', sizeof(${basetyp}))')
|
||||
} else {
|
||||
g.write(', sizeof(${styp}))')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn (mut g Gen) zero_struct_field(field ast.StructField) bool {
|
||||
|
26
vlib/v/tests/option_init_ptr_test.v
Normal file
26
vlib/v/tests/option_init_ptr_test.v
Normal file
@ -0,0 +1,26 @@
|
||||
struct Abc {
|
||||
a int
|
||||
}
|
||||
|
||||
fn test_option_init() {
|
||||
a := ?Abc{
|
||||
a: 1
|
||||
}
|
||||
dump(a)
|
||||
b := &?Abc{
|
||||
a: 1
|
||||
}
|
||||
dump(b)
|
||||
|
||||
assert *b? == a?
|
||||
}
|
||||
|
||||
fn test_option_empty() {
|
||||
a := ?Abc{}
|
||||
dump(a)
|
||||
b := &?Abc{}
|
||||
dump(b)
|
||||
|
||||
assert a == none
|
||||
assert b == none
|
||||
}
|
Loading…
Reference in New Issue
Block a user