Skip to content

Commit

Permalink
zig fmt: allow same line struct literal with no trailing comma
Browse files Browse the repository at this point in the history
See #1003
  • Loading branch information
andrewrk committed May 28, 2018
1 parent 122a747 commit fd13a75
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
15 changes: 15 additions & 0 deletions std/zig/parser_test.zig
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
test "zig fmt: struct literal no trailing comma" {
try testTransform(
\\const a = foo{ .x = 1, .y = 2 };
\\const a = foo{ .x = 1,
\\ .y = 2 };
,
\\const a = foo{ .x = 1, .y = 2 };
\\const a = foo{
\\ .x = 1,
\\ .y = 2,
\\};
\\
);
}

test "zig fmt: array literal with hint" {
try testTransform(
\\const a = []u8{
Expand Down
31 changes: 31 additions & 0 deletions std/zig/render.zig
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,37 @@ fn renderExpression(allocator: &mem.Allocator, stream: var, tree: &ast.Tree, ind
return;
}

const src_has_trailing_comma = blk: {
const maybe_comma = tree.prevToken(suffix_op.rtoken);
break :blk tree.tokens.at(maybe_comma).id == Token.Id.Comma;
};

const src_same_line = blk: {
const loc = tree.tokenLocation(tree.tokens.at(lbrace).end, suffix_op.rtoken);
break :blk loc.line == 0;
};

if (!src_has_trailing_comma and src_same_line) {
// render all on one line, no trailing comma
try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None);
try renderToken(tree, stream, lbrace, indent, Space.Space);

var it = field_inits.iterator(0);
while (it.next()) |field_init| {
if (it.peek() != null) {
try renderExpression(allocator, stream, tree, indent, field_init.*, Space.None);

const comma = tree.nextToken(field_init.*.lastToken());
try renderToken(tree, stream, comma, indent, Space.Space);
} else {
try renderExpression(allocator, stream, tree, indent, field_init.*, Space.Space);
}
}

try renderToken(tree, stream, suffix_op.rtoken, indent, space);
return;
}

try renderExpression(allocator, stream, tree, indent, suffix_op.lhs, Space.None);
try renderToken(tree, stream, lbrace, indent, Space.Newline);

Expand Down

0 comments on commit fd13a75

Please sign in to comment.