Commit 283d441c19

Lachlan Easton <lachlan@lakebythewoods.xyz>
2020-08-30 02:35:18
zig fmt: fix #3978, fix #2748
1 parent 7d487a4
Changed files (2)
lib/std/zig/parser_test.zig
@@ -3321,6 +3321,59 @@ test "zig fmt: Don't add extra newline after if" {
     );
 }
 
+test "zig fmt: comments in ternary ifs" {
+    try testCanonical(
+        \\const x = if (true) {
+        \\    1;
+        \\} else if (false)
+        \\    // Comment
+        \\    0;
+        \\const y = if (true)
+        \\    // Comment
+        \\    1
+        \\else
+        \\    0;
+        \\
+        \\pub extern "c" fn printf(format: [*:0]const u8, ...) c_int;
+        \\
+    );
+}
+
+test "zig fmt: test comments in field access chain" {
+    try testCanonical(
+        \\pub const str = struct {
+        \\    pub const Thing = more.more //
+        \\        .more() //
+        \\        .more().more() //
+        \\        .more() //
+        \\    // .more() //
+        \\        .more() //
+        \\        .more();
+        \\    data: Data,
+        \\};
+        \\
+        \\pub const str = struct {
+        \\    pub const Thing = more.more //
+        \\        .more() //
+        \\    // .more() //
+        \\    // .more() //
+        \\    // .more() //
+        \\        .more() //
+        \\        .more();
+        \\    data: Data,
+        \\};
+        \\
+        \\pub const str = struct {
+        \\    pub const Thing = more //
+        \\        .more //
+        \\        .more() //
+        \\        .more();
+        \\    data: Data,
+        \\};
+        \\
+    );
+}
+
 const std = @import("std");
 const mem = std.mem;
 const warn = std.debug.warn;
lib/std/zig/render.zig
@@ -522,8 +522,12 @@ fn renderExpression(
                 break :blk if (loc.line == 0) op_space else Space.Newline;
             };
 
-            try renderToken(tree, ais, infix_op_node.op_token, after_op_space);
-            ais.pushIndentOneShot();
+            {
+                try ais.pushIndent();
+                defer ais.popIndent();
+                try renderToken(tree, ais, infix_op_node.op_token, after_op_space);
+            }
+            try ais.pushIndentOneShot();
             return renderExpression(allocator, ais, tree, infix_op_node.rhs, space);
         },
 
@@ -1873,7 +1877,12 @@ fn renderExpression(
 
             if (src_has_newline) {
                 const after_rparen_space = if (if_node.payload == null) Space.Newline else Space.Space;
-                try renderToken(tree, ais, rparen, after_rparen_space); // )
+
+                {
+                    try ais.pushIndent();
+                    defer ais.popIndent();
+                    try renderToken(tree, ais, rparen, after_rparen_space); // )
+                }
 
                 if (if_node.payload) |payload| {
                     try renderExpression(allocator, ais, tree, payload, Space.Newline);