Commit 550688f427

Isaac Freund <ifreund@ifreund.xyz>
2021-02-22 23:14:01
zig fmt: insert trailing comma in switches
1 parent 4758e0c
Changed files (2)
lib/std/zig/parser_test.zig
@@ -2103,34 +2103,34 @@ test "zig fmt: same line comments in expression" {
     );
 }
 
-//test "zig fmt: add comma on last switch prong" {
-//    try testTransform(
-//        \\test "aoeu" {
-//        \\switch (self.init_arg_expr) {
-//        \\    InitArg.Type => |t| { },
-//        \\    InitArg.None,
-//        \\    InitArg.Enum => { }
-//        \\}
-//        \\ switch (self.init_arg_expr) {
-//        \\     InitArg.Type => |t| { },
-//        \\     InitArg.None,
-//        \\     InitArg.Enum => { }//line comment
-//        \\ }
-//        \\}
-//    ,
-//        \\test "aoeu" {
-//        \\    switch (self.init_arg_expr) {
-//        \\        InitArg.Type => |t| {},
-//        \\        InitArg.None, InitArg.Enum => {},
-//        \\    }
-//        \\    switch (self.init_arg_expr) {
-//        \\        InitArg.Type => |t| {},
-//        \\        InitArg.None, InitArg.Enum => {}, //line comment
-//        \\    }
-//        \\}
-//        \\
-//    );
-//}
+test "zig fmt: add comma on last switch prong" {
+    try testTransform(
+        \\test "aoeu" {
+        \\switch (self.init_arg_expr) {
+        \\    InitArg.Type => |t| { },
+        \\    InitArg.None,
+        \\    InitArg.Enum => { }
+        \\}
+        \\ switch (self.init_arg_expr) {
+        \\     InitArg.Type => |t| { },
+        \\     InitArg.None,
+        \\     InitArg.Enum => { }//line comment
+        \\ }
+        \\}
+    ,
+        \\test "aoeu" {
+        \\    switch (self.init_arg_expr) {
+        \\        InitArg.Type => |t| {},
+        \\        InitArg.None, InitArg.Enum => {},
+        \\    }
+        \\    switch (self.init_arg_expr) {
+        \\        InitArg.Type => |t| {},
+        \\        InitArg.None, InitArg.Enum => {}, //line comment
+        \\    }
+        \\}
+        \\
+    );
+}
 
 test "zig fmt: same-line comment after a statement" {
     try testCanonical(
lib/std/zig/render.zig
@@ -1948,7 +1948,7 @@ const Space = enum {
     space,
     /// Output the token lexeme followed by a newline.
     newline,
-    /// Additionally consume the next token if it is a comma.
+    /// If the next token is a comma, render it as well. If not, insert one.
     /// In either case, a newline will be inserted afterwards.
     comma,
     /// Additionally consume the next token if it is a comma.
@@ -1968,6 +1968,10 @@ fn renderToken(ais: *Ais, tree: ast.Tree, token_index: ast.TokenIndex, space: Sp
 
     try ais.writer().writeAll(lexeme);
 
+    if (space == .comma and token_tags[token_index + 1] != .comma) {
+        try ais.writer().writeByte(',');
+    }
+
     const comment = try renderComments(ais, tree, token_start + lexeme.len, token_starts[token_index + 1]);
     switch (space) {
         .none => {},