commit e51a44b3422a1fad0ec75078f3576f0fa447d986 (tree)
parent 225910f9341fbc725ff5e0d2c653e29bc2f21cb8
Author: John Schmidt <john.schmidt.h@gmail.com>
Date: Fri, 28 Jan 2022 23:10:14 +0100
fmt: handle doc comments on struct members
Closes https://github.com/ziglang/zig/issues/10443.
Diffstat:
2 files changed, 31 insertions(+), 3 deletions(-)
diff --git a/lib/std/zig/parser_test.zig b/lib/std/zig/parser_test.zig
@@ -396,6 +396,25 @@ test "zig fmt: container declaration, multiline string, add trailing comma" {
);
}
+test "zig fmt: container declaration, doc comment on member, add trailing comma" {
+ try testTransform(
+ \\pub const Pos = struct {
+ \\ /// X-axis.
+ \\ x: u32,
+ \\ /// Y-axis.
+ \\ y: u32
+ \\};
+ ,
+ \\pub const Pos = struct {
+ \\ /// X-axis.
+ \\ x: u32,
+ \\ /// Y-axis.
+ \\ y: u32,
+ \\};
+ \\
+ );
+}
+
test "zig fmt: remove empty lines at start/end of container decl" {
try testTransform(
\\const X = struct {
diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig
@@ -1930,15 +1930,24 @@ fn renderContainerDecl(
const src_has_trailing_comma = token_tags[rbrace - 1] == .comma;
if (!src_has_trailing_comma) one_line: {
- // We can only print all the members in-line if there are no comments or multiline strings,
- // and all the members are fields.
+ // We print all the members in-line unless one of the following conditions are true:
+
+ // 1. The container has comments or multiline strings.
if (hasComment(tree, lbrace, rbrace) or hasMultilineString(tree, lbrace, rbrace)) {
break :one_line;
}
+
+ // 2. A member of the container has a doc comment.
+ for (token_tags[lbrace + 1 .. rbrace - 1]) |tag| {
+ if (tag == .doc_comment) break :one_line;
+ }
+
+ // 3. The container has non-field members.
for (container_decl.ast.members) |member| {
if (!node_tags[member].isContainerField()) break :one_line;
}
- // All the declarations on the same line.
+
+ // Print all the declarations on the same line.
try renderToken(ais, tree, lbrace, .space); // lbrace
for (container_decl.ast.members) |member| {
try renderMember(gpa, ais, tree, member, .space);