From fd144b30f268bbca57e543b2ac746782b67b37f8 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sat, 18 May 2024 08:35:55 -0300 Subject: [PATCH] cgen: fix C struct init when it has default expr (#21510) --- vlib/v/gen/c/cgen.v | 7 ++++-- vlib/v/tests/c_structs/cstruct.h | 3 ++- .../c_structs/cstruct_default_value_test.v | 25 +++++++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) create mode 100644 vlib/v/tests/c_structs/cstruct_default_value_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index b5f20e86b6..41f4bf0abf 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -7126,15 +7126,18 @@ fn (mut g Gen) type_default(typ_ ast.Type) string { } else { '{' } - if sym.language == .v { + if sym.language in [.c, .v] { for field in info.fields { field_sym := g.table.sym(field.typ) if field.has_default_expr || field_sym.kind in [.array, .map, .string, .bool, .alias, .i8, .i16, .int, .i64, .u8, .u16, .u32, .u64, .f32, .f64, .char, .voidptr, .byteptr, .charptr, .struct_, .chan] { + if sym.language == .c && !field.has_default_expr { + continue + } field_name := c_name(field.name) if field.has_default_expr { mut expr_str := '' - if g.table.sym(field.typ).kind in [.sum_type, .interface_] { + if field_sym.kind in [.sum_type, .interface_] { expr_str = g.expr_string_with_cast(field.default_expr, field.default_expr_typ, field.typ) } else { diff --git a/vlib/v/tests/c_structs/cstruct.h b/vlib/v/tests/c_structs/cstruct.h index 26302f6599..94156494f1 100644 --- a/vlib/v/tests/c_structs/cstruct.h +++ b/vlib/v/tests/c_structs/cstruct.h @@ -25,10 +25,11 @@ typedef struct Foo { typedef struct Bar { int a; + float b; } Bar; /// typedef struct TestAlias { int a; -}; \ No newline at end of file +}; diff --git a/vlib/v/tests/c_structs/cstruct_default_value_test.v b/vlib/v/tests/c_structs/cstruct_default_value_test.v new file mode 100644 index 0000000000..c67875e992 --- /dev/null +++ b/vlib/v/tests/c_structs/cstruct_default_value_test.v @@ -0,0 +1,25 @@ +#include "@VMODROOT/cstruct.h" + +struct Foo { + a int = 3 +} + +struct C.Bar { + a int = 3 + b f64 +} + +struct FooBar { + foo Foo + bar C.Bar +} + +fn test_main() { + a := dump(Foo{}) + b := dump(C.Bar{}) + c := dump(FooBar{}) + + assert a.a == b.a + assert b.a == c.bar.a + assert b.b == c.bar.b +}