From d7a27bf803fd29c499090c7bd0460fae9f0cf0f7 Mon Sep 17 00:00:00 2001 From: danielsan901998 Date: Tue, 30 Jan 2024 16:24:41 +0100 Subject: [PATCH] Use mem.zeroes for empty union initializer list --- src/translate_c.zig | 5 +++++ .../empty union initializer list.c | 20 +++++++++++++++++++ test/cases/translate_c/static empty struct.c | 2 +- 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 test/cases/translate_c/empty union initializer list.c diff --git a/src/translate_c.zig b/src/translate_c.zig index 6a762468906a..fc2d56ba05da 100644 --- a/src/translate_c.zig +++ b/src/translate_c.zig @@ -2505,6 +2505,11 @@ fn transInitListExprRecord( var field_inits = std.ArrayList(ast.Payload.ContainerInit.Initializer).init(c.gpa); defer field_inits.deinit(); + if (init_count == 0) { + const source_loc = @as(*const clang.Expr, @ptrCast(expr)).getBeginLoc(); + return transZeroInitExpr(c, scope, source_loc, ty); + } + var init_i: c_uint = 0; var it = record_def.field_begin(); const end_it = record_def.field_end(); diff --git a/test/cases/translate_c/empty union initializer list.c b/test/cases/translate_c/empty union initializer list.c new file mode 100644 index 000000000000..33238d2ed8d2 --- /dev/null +++ b/test/cases/translate_c/empty union initializer list.c @@ -0,0 +1,20 @@ +union U { + int x; + long y; +}; + +void foo(void) { + union U u = {}; +} +// translate-c +// target=x86_64-linux +// c_frontend=clang +// +// pub const union_U = extern union { +// x: c_int, +// y: c_long, +// }; +// pub export fn foo() void { +// var u: union_U = @import("std").mem.zeroes(union_U); +// _ = &u; +// } diff --git a/test/cases/translate_c/static empty struct.c b/test/cases/translate_c/static empty struct.c index 080d7977fdaa..8300b7c673ca 100644 --- a/test/cases/translate_c/static empty struct.c +++ b/test/cases/translate_c/static empty struct.c @@ -11,7 +11,7 @@ static inline void foo() { // pub const struct_empty_struct = extern struct {}; // pub fn foo() callconv(.C) void { // const bar = struct { -// var static: struct_empty_struct = struct_empty_struct{}; +// var static: struct_empty_struct = @import("std").mem.zeroes(struct_empty_struct); // }; // _ = &bar; // }