Commit 15c7c6ab97

Isaac Freund <ifreund@ifreund.xyz>
2021-02-24 12:29:17
zig fmt: handle comments in switch case value list
1 parent 1b8eca0
Changed files (2)
lib/std/zig/parser_test.zig
@@ -4202,6 +4202,37 @@ test "zig fmt: respect extra newline between switch items" {
     );
 }
 
+test "zig fmt: insert trailing comma if there are comments between switch values" {
+    try testTransform(
+        \\const a = switch (b) {
+        \\    .c => {},
+        \\
+        \\    .d, // foobar
+        \\    .e
+        \\    => f,
+        \\
+        \\    .g, .h
+        \\    // comment
+        \\    => i,
+        \\};
+        \\
+    ,
+        \\const a = switch (b) {
+        \\    .c => {},
+        \\
+        \\    .d, // foobar
+        \\    .e,
+        \\    => f,
+        \\
+        \\    .g,
+        \\    .h,
+        \\    // comment
+        \\    => i,
+        \\};
+        \\
+    );
+}
+
 test "zig fmt: error for invalid bit range" {
     try testError(
         \\var x: []align(0:0:0)u8 = bar;
lib/std/zig/render.zig
@@ -1533,7 +1533,9 @@ fn renderSwitchCase(
     } else if (switch_case.ast.values.len == 1) {
         // render on one line and drop the trailing comma if any
         try renderExpression(gpa, ais, tree, switch_case.ast.values[0], .space);
-    } else if (trailing_comma) {
+    } else if (trailing_comma or
+        hasComment(tree, tree.firstToken(switch_case.ast.values[0]), switch_case.ast.arrow_token))
+    {
         // Render each value on a new line
         try renderExpressions(gpa, ais, tree, switch_case.ast.values, .comma);
     } else {