1
0
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:
Felipe Pena 2023-07-19 20:29:59 -03:00 committed by GitHub
parent 0073283f53
commit bd3501affa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 41 additions and 2 deletions

View File

@ -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}[]) { ')
}

View File

@ -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,9 +310,14 @@ 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 {
sym := g.table.sym(field.typ)

View 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
}