Commit 8b5e4af78e

John Schmidt <john.schmidt.h@gmail.com>
2022-01-28 23:10:14
fmt: handle doc comments on struct members
Closes https://github.com/ziglang/zig/issues/10443.
1 parent aad6ef1
Changed files (2)
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 {
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);