From 25d8faabf6afa80ce86abb23f9c5f4ad6f98159d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=89=A7=E5=BF=83?= Date: Mon, 11 Apr 2022 19:16:09 +0800 Subject: [PATCH] cgen: fix alloc empty struct array error (#14007) --- vlib/arrays/arrays_test.v | 12 ++++++++++++ vlib/v/gen/c/array.v | 6 ++++-- vlib/v/gen/c/cheaders.v | 2 +- vlib/v/gen/c/struct.v | 15 +++++++++++++++ 4 files changed, 32 insertions(+), 3 deletions(-) diff --git a/vlib/arrays/arrays_test.v b/vlib/arrays/arrays_test.v index 74eb69b7d3..ee05cfac1f 100644 --- a/vlib/arrays/arrays_test.v +++ b/vlib/arrays/arrays_test.v @@ -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 +} diff --git a/vlib/v/gen/c/array.v b/vlib/v/gen/c/array.v index ef32a7e9c4..2941a21943 100644 --- a/vlib/v/gen/c/array.v +++ b/vlib/v/gen/c/array.v @@ -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]){') } diff --git a/vlib/v/gen/c/cheaders.v b/vlib/v/gen/c/cheaders.v index c7117e1c1e..f179ce908f 100644 --- a/vlib/v/gen/c/cheaders.v +++ b/vlib/v/gen/c/cheaders.v @@ -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 diff --git a/vlib/v/gen/c/struct.v b/vlib/v/gen/c/struct.v index fa3600c33d..29fb490bbd 100644 --- a/vlib/v/gen/c/struct.v +++ b/vlib/v/gen/c/struct.v @@ -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 + } + } +}