authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-05-28 16:59:42-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-05-28 17:00:04-04:00
logfd13a757855e185b4250c65fe89bbd72c9479a52
tree2a167a76359e806a3971464052aeaac040b447d1
parent122a74724cb527ae6e1997c2c77118047fb50a2c

zig fmt: allow same line struct literal with no trailing comma

See #1003

2 files changed, 46 insertions(+), 0 deletions(-)

std/zig/parser_test.zig+15
......@@ -1,3 +1,18 @@
1test "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
116test "zig fmt: array literal with hint" {
217 try testTransform(
318 \\const a = []u8{
std/zig/render.zig+31
......@@ -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