ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
34.13k stars 2.49k forks source link

translate-c: Macros containing struct initialization syntax can generate invalid code. #8949

Closed atoft closed 3 years ago

atoft commented 3 years ago

Importing the following C header causes incorrect Zig code to be generated:

typedef struct
{
    float x;
} MyCStruct; 

#define A(_x)   (MyCStruct) { .x = (_x) }
#define B A(0.f)

Results in:

./zig-cache/o/cc6c60a885134360e93e8ada520ce7a2/cimport.zig:362:28: error: invalid character: ')'
pub const B = A(@as(f32, 0.));
                           ^

A slightly simpler case causes translate-c itself to error:

typedef struct
{
    int x;
} MyCStruct; 

#define A  (MyCStruct) { .x = (0) }

Results in:

./zig-cache/o/ab465fa0d3d09e55c37d8a6119380a06/cimport.zig:17:15: error: unable to translate C expr: unexpected token .Period
pub const A = @compileError("unable to translate C expr: unexpected token .Period");

In general it seems to be the use of struct initialization syntax in a macro giving incorrect results. I encountered this when trying to include the GTK4 header: https://zigforum.org/t/compile-error-in-cimport-code-with-gtk4/499

atoft commented 3 years ago

Thanks for the fix, GTK4 now imports for me without errors :)