commit 6787f163eb6db2b8b89c2ea6cb51d63606487e12 (tree)
parent 5ecf8bddaeebf26ac6cd174f5f79e02ca243e501
Author: Lewis Gaul <Lewis@scphillips.com>
Date: Tue, 16 Mar 2021 08:26:28 +0000
zig fmt: don't add trailing whitespace on switch case
Diffstat:
2 files changed, 58 insertions(+), 3 deletions(-)
diff --git a/lib/std/zig/parser_test.zig b/lib/std/zig/parser_test.zig
@@ -3063,6 +3063,54 @@ test "zig fmt: switch" {
\\}
\\
);
+
+ try testTransform(
+ \\test {
+ \\ switch (x) {
+ \\ foo =>
+ \\ "bar",
+ \\ }
+ \\}
+ \\
+ ,
+ \\test {
+ \\ switch (x) {
+ \\ foo => "bar",
+ \\ }
+ \\}
+ \\
+ );
+}
+
+test "zig fmt: switch multiline string" {
+ try testCanonical(
+ \\test "switch multiline string" {
+ \\ const x: u32 = 0;
+ \\ const str = switch (x) {
+ \\ 1 => "one",
+ \\ 2 =>
+ \\ \\ Comma after the multiline string
+ \\ \\ is needed
+ \\ ,
+ \\ 3 => "three",
+ \\ else => "else",
+ \\ };
+ \\
+ \\ const Union = union(enum) {
+ \\ Int: i64,
+ \\ Float: f64,
+ \\ };
+ \\
+ \\ const str = switch (u) {
+ \\ Union.Int => |int|
+ \\ \\ Comma after the multiline string
+ \\ \\ is needed
+ \\ ,
+ \\ Union.Float => |*float| unreachable,
+ \\ };
+ \\}
+ \\
+ );
}
test "zig fmt: while" {
diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig
@@ -1444,6 +1444,7 @@ fn renderSwitchCase(
switch_case: ast.full.SwitchCase,
space: Space,
) Error!void {
+ const node_tags = tree.nodes.items(.tag);
const token_tags = tree.tokens.items(.tag);
const trailing_comma = token_tags[switch_case.ast.arrow_token - 1] == .comma;
@@ -1466,17 +1467,23 @@ fn renderSwitchCase(
}
// Render the arrow and everything after it
- try renderToken(ais, tree, switch_case.ast.arrow_token, .space);
+ const pre_target_space = if (node_tags[switch_case.ast.target_expr] == .multiline_string_literal)
+ // Newline gets inserted when rendering the target expr.
+ Space.none
+ else
+ Space.space;
+ const after_arrow_space: Space = if (switch_case.payload_token == null) pre_target_space else .space;
+ try renderToken(ais, tree, switch_case.ast.arrow_token, after_arrow_space);
if (switch_case.payload_token) |payload_token| {
try renderToken(ais, tree, payload_token - 1, .none); // pipe
if (token_tags[payload_token] == .asterisk) {
try renderToken(ais, tree, payload_token, .none); // asterisk
try renderToken(ais, tree, payload_token + 1, .none); // identifier
- try renderToken(ais, tree, payload_token + 2, .space); // pipe
+ try renderToken(ais, tree, payload_token + 2, pre_target_space); // pipe
} else {
try renderToken(ais, tree, payload_token, .none); // identifier
- try renderToken(ais, tree, payload_token + 1, .space); // pipe
+ try renderToken(ais, tree, payload_token + 1, pre_target_space); // pipe
}
}