cgen: fix alloc empty struct array error (#14007)

pull/14010/head
牧心 2022-04-11 19:16:09 +08:00 committed by GitHub
parent 843ce43077
commit 25d8faabf6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 32 additions and 3 deletions

View File

@ -300,3 +300,15 @@ fn test_alias_string_contains() {
names := [Str('')]
assert (Str('') in names) == true
}
struct XYZ {}
fn test_array_append_empty_struct() {
mut names := []XYZ{cap: 2}
names << XYZ{}
assert (XYZ{} in names) == true
// test fixed array
array := [XYZ{}]
assert (XYZ{} in names) == true
}

View File

@ -151,7 +151,7 @@ fn (mut g Gen) array_init(node ast.ArrayInit) {
} else {
g.write('0, ')
}
if elem_type.unaliased_sym.kind == .function {
if elem_type.unaliased_sym.kind == .function || g.is_empty_struct(elem_type) {
g.write('sizeof(voidptr), ')
} else {
g.write('sizeof($elem_styp), ')
@ -217,7 +217,7 @@ fn (mut g Gen) array_init(node ast.ArrayInit) {
} else {
g.write('0, ')
}
if elem_type.unaliased_sym.kind == .function {
if elem_type.unaliased_sym.kind == .function || g.is_empty_struct(elem_type) {
g.write('sizeof(voidptr), ')
} else {
g.write('sizeof($elem_styp), ')
@ -251,6 +251,8 @@ fn (mut g Gen) array_init(node ast.ArrayInit) {
len := node.exprs.len
if elem_type.unaliased_sym.kind == .function {
g.write('new_array_from_c_array($len, $len, sizeof(voidptr), _MOV((voidptr[$len]){')
} else if g.is_empty_struct(elem_type) {
g.write('new_array_from_c_array${noscan}($len, $len, sizeof(voidptr), _MOV(($elem_styp[$len]){')
} else {
g.write('new_array_from_c_array${noscan}($len, $len, sizeof($elem_styp), _MOV(($elem_styp[$len]){')
}

View File

@ -633,7 +633,7 @@ typedef uint8_t byte;
typedef uint32_t rune;
typedef size_t usize;
typedef ptrdiff_t isize;
#ifndef VNOFLOAT
#ifndef VNOFLOAT
typedef float f32;
typedef double f64;
#else

View File

@ -305,3 +305,18 @@ fn (mut g Gen) zero_struct_field(field ast.StructField) bool {
}
return true
}
fn (mut g Gen) is_empty_struct(t Type) bool {
sym := t.unaliased_sym
match sym.info {
ast.Struct {
if sym.info.fields.len > 0 || sym.info.embeds.len > 0 {
return false
}
return true
}
else {
return false
}
}
}