render: fix bug when rendering struct initializer with length 1

This crashed the compiler when running translate-c. See the added test.
This commit is contained in:
Timon Kruiper 2021-01-23 17:33:59 +01:00 committed by Andrew Kelley
parent 4ca1f4ec2e
commit e23bc1f76a
2 changed files with 20 additions and 8 deletions

View File

@ -965,13 +965,13 @@ fn renderExpression(
}; };
if (field_inits.len == 1) blk: { if (field_inits.len == 1) blk: {
const field_init = field_inits[0].cast(ast.Node.FieldInitializer).?; if (field_inits[0].cast(ast.Node.FieldInitializer)) |field_init| {
switch (field_init.expr.tag) {
switch (field_init.expr.tag) { .StructInitializer,
.StructInitializer, .StructInitializerDot,
.StructInitializerDot, => break :blk,
=> break :blk, else => {},
else => {}, }
} }
// if the expression outputs to multiline, make this struct multiline // 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), .node => |node| try renderExpression(allocator, ais, tree, node, Space.None),
} }
try renderToken(tree, ais, lbrace, Space.Space); 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); return renderToken(tree, ais, rtoken, space);
} }

View File

@ -102,6 +102,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
\\} Color; \\} Color;
\\#define CLITERAL(type) (type) \\#define CLITERAL(type) (type)
\\#define LIGHTGRAY CLITERAL(Color){ 200, 200, 200, 255 } // Light Gray \\#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 , &[_][]const u8{ // TODO properly translate this
\\pub const struct_Color = extern struct { \\pub const struct_Color = extern struct {
\\ r: u8, \\ 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 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", cases.add("complex switch",