cgen: fix C struct init when it has default expr (#21510)

This commit is contained in:
Felipe Pena 2024-05-18 08:35:55 -03:00 committed by GitHub
parent 755cdca249
commit fd144b30f2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 32 additions and 3 deletions

View File

@ -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 {

View File

@ -25,10 +25,11 @@ typedef struct Foo {
typedef struct Bar {
int a;
float b;
} Bar;
///
typedef struct TestAlias {
int a;
};
};

View File

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