From fd13a757855e185b4250c65fe89bbd72c9479a52 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 28 May 2018 16:59:42 -0400 Subject: [PATCH] zig fmt: allow same line struct literal with no trailing comma See #1003 --- std/zig/parser_test.zig | 15 +++++++++++++++ std/zig/render.zig | 31 +++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 550d8fa111..72818bc074 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -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{ diff --git a/std/zig/render.zig b/std/zig/render.zig index 1528ae31aa..86e972c173 100644 --- a/std/zig/render.zig +++ b/std/zig/render.zig @@ -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);