Skip to content

Commit fd13a75

Browse files
committed
zig fmt: allow same line struct literal with no trailing comma
See #1003
1 parent 122a747 commit fd13a75

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

std/zig/parser_test.zig

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,18 @@
1+
test "zig fmt: struct literal no trailing comma" {
2+
try testTransform(
3+
\\const a = foo{ .x = 1, .y = 2 };
4+
\\const a = foo{ .x = 1,
5+
\\ .y = 2 };
6+
,
7+
\\const a = foo{ .x = 1, .y = 2 };
8+
\\const a = foo{
9+
\\ .x = 1,
10+
\\ .y = 2,
11+
\\};
12+
\\
13+
);
14+
}
15+
116
test "zig fmt: array literal with hint" {
217
try testTransform(
318
\\const a = []u8{

std/zig/render.zig

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -486,6 +486,37 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
486486
return;
487487
}
488488

489+
const src_has_trailing_comma = blk: {
490+
const maybe_comma = tree.prevToken(suffix_op.rtoken);
491+
break :blk tree.tokens.at(maybe_comma).id == Token.Id.Comma;
492+
};
493+
494+
const src_same_line = blk: {
495+
const loc = tree.tokenLocation(tree.tokens.at(lbrace).end, suffix_op.rtoken);
496+
break :blk loc.line == 0;
497+
};
498+
499+
if (!src_has_trailing_comma and src_same_line) {
500+
// render all on one line, no trailing comma
501+
try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None);
502+
try renderToken(tree, stream, lbrace, indent, Space.Space);
503+
504+
var it = field_inits.iterator(0);
505+
while (it.next()) |field_init| {
506+
if (it.peek() != null) {
507+
try renderExpression(allocator, stream, tree, indent, field_init.*, Space.None);
508+
509+
const comma = tree.nextToken(field_init.*.lastToken());
510+
try renderToken(tree, stream, comma, indent, Space.Space);
511+
} else {
512+
try renderExpression(allocator, stream, tree, indent, field_init.*, Space.Space);
513+
}
514+
}
515+
516+
try renderToken(tree, stream, suffix_op.rtoken, indent, space);
517+
return;
518+
}
519+
489520
try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None);
490521
try renderToken(tree, stream, lbrace, indent, Space.Newline);
491522

0 commit comments

Comments
 (0)