Commit e23bc1f76a

Timon Kruiper <timonkruiper@gmail.com>
2021-01-23 17:33:59
render: fix bug when rendering struct initializer with length 1
This crashed the compiler when running translate-c. See the added test.
1 parent 4ca1f4e
Changed files (2)
lib
std
test
lib/std/zig/render.zig
@@ -965,13 +965,13 @@ fn renderExpression(
             };
 
             if (field_inits.len == 1) blk: {
-                const field_init = field_inits[0].cast(ast.Node.FieldInitializer).?;
-
-                switch (field_init.expr.tag) {
-                    .StructInitializer,
-                    .StructInitializerDot,
-                    => break :blk,
-                    else => {},
+                if (field_inits[0].cast(ast.Node.FieldInitializer)) |field_init| {
+                    switch (field_init.expr.tag) {
+                        .StructInitializer,
+                        .StructInitializerDot,
+                        => break :blk,
+                        else => {},
+                    }
                 }
 
                 // if the expression outputs to multiline, make this struct multiline
@@ -984,7 +984,7 @@ fn renderExpression(
                     .node => |node| try renderExpression(allocator, ais, tree, node, Space.None),
                 }
                 try renderToken(tree, ais, lbrace, Space.Space);
-                try renderExpression(allocator, ais, tree, &field_init.base, Space.Space);
+                try renderExpression(allocator, ais, tree, field_inits[0], Space.Space);
                 return renderToken(tree, ais, rtoken, space);
             }
 
test/translate_c.zig
@@ -102,6 +102,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
         \\} Color;
         \\#define CLITERAL(type)      (type)
         \\#define LIGHTGRAY  CLITERAL(Color){ 200, 200, 200, 255 }   // Light Gray
+        \\typedef struct boom_t
+        \\{
+        \\    int i1;
+        \\} boom_t;
+        \\#define FOO ((boom_t){1})
     , &[_][]const u8{ // TODO properly translate this
         \\pub const struct_Color = extern struct {
         \\    r: u8,
@@ -116,6 +121,13 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
         \\}
         ,
         \\pub const LIGHTGRAY = @import("std").mem.zeroInit(CLITERAL(Color), .{ 200, 200, 200, 255 });
+        ,
+        \\pub const struct_boom_t = extern struct {
+        \\    i1: c_int,
+        \\};
+        \\pub const boom_t = struct_boom_t;
+        ,
+        \\pub const FOO = @import("std").mem.zeroInit(boom_t, .{ 1 });
     });
 
     cases.add("complex switch",