Commit 7e4177a4b1

yunsh1 <yunsangho@kakao.com>
2023-10-08 19:03:20
fmt: Skip extra newline if doc_comment exists
1 parent 6a12fd6
Changed files (2)
lib/std/zig/parser_test.zig
@@ -4270,6 +4270,69 @@ test "zig fmt: remove newlines surrounding doc comment" {
     );
 }
 
+test "zig fmt: remove newlines surrounding doc comment between members" {
+    try testTransform(
+        \\f1: i32,
+        \\
+        \\
+        \\/// doc comment
+        \\
+        \\f2: i32,
+        \\
+    ,
+        \\f1: i32,
+        \\
+        \\/// doc comment
+        \\f2: i32,
+        \\
+    );
+}
+
+test "zig fmt: remove newlines surrounding doc comment between members within container decl (1)" {
+    try testTransform(
+        \\const Foo = struct {
+        \\    fn foo() void {}
+        \\
+        \\
+        \\    /// doc comment
+        \\
+        \\
+        \\    fn bar() void {}
+        \\};
+        \\
+    ,
+        \\const Foo = struct {
+        \\    fn foo() void {}
+        \\
+        \\    /// doc comment
+        \\    fn bar() void {}
+        \\};
+        \\
+    );
+}
+
+test "zig fmt: remove newlines surrounding doc comment between members within container decl (2)" {
+    try testTransform(
+        \\const Foo = struct {
+        \\    fn foo() void {}
+        \\    /// doc comment 1
+        \\
+        \\    /// doc comment 2
+        \\
+        \\    fn bar() void {}
+        \\};
+        \\
+    ,
+        \\const Foo = struct {
+        \\    fn foo() void {}
+        \\    /// doc comment 1
+        \\    /// doc comment 2
+        \\    fn bar() void {}
+        \\};
+        \\
+    );
+}
+
 test "zig fmt: remove newlines surrounding doc comment within container decl" {
     try testTransform(
         \\const Foo = struct {
lib/std/zig/render.zig
@@ -3188,8 +3188,10 @@ fn renderExtraNewlineToken(r: *Render, token_index: Ast.TokenIndex) Error!void {
     else
         token_starts[token_index - 1] + tokenSliceForRender(tree, token_index - 1).len;
 
-    // If there is a comment present, it will handle the empty line
+    // If there is a immediately preceding comment or doc_comment,
+    // skip it because required extra newline has already been rendered.
     if (mem.indexOf(u8, tree.source[prev_token_end..token_start], "//") != null) return;
+    if (token_index > 0 and tree.tokens.items(.tag)[token_index - 1] == .doc_comment) return;
 
     // Iterate backwards to the end of the previous token, stopping if a
     // non-whitespace character is encountered or two newlines have been found.