From 621ad241d6dfbde60ee8a5b1d0dcd7d9cf29f8f3 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 21 Feb 2021 20:25:31 -0700 Subject: [PATCH] zig fmt: if nested --- lib/std/zig/parser_test.zig | 40 ++++++++++++++++++------------------- lib/std/zig/render.zig | 10 +++++++++- 2 files changed, 29 insertions(+), 21 deletions(-) diff --git a/lib/std/zig/parser_test.zig b/lib/std/zig/parser_test.zig index 2ba85dca3c..375f12a3f5 100644 --- a/lib/std/zig/parser_test.zig +++ b/lib/std/zig/parser_test.zig @@ -1449,26 +1449,26 @@ test "zig fmt: if-else with comment before else" { ); } -//test "zig fmt: if nested" { -// try testCanonical( -// \\pub fn foo() void { -// \\ return if ((aInt & bInt) >= 0) -// \\ if (aInt < bInt) -// \\ GE_LESS -// \\ else if (aInt == bInt) -// \\ GE_EQUAL -// \\ else -// \\ GE_GREATER -// \\ else if (aInt > bInt) -// \\ GE_LESS -// \\ else if (aInt == bInt) -// \\ GE_EQUAL -// \\ else -// \\ GE_GREATER; -// \\} -// \\ -// ); -//} +test "zig fmt: if nested" { + try testCanonical( + \\pub fn foo() void { + \\ return if ((aInt & bInt) >= 0) + \\ if (aInt < bInt) + \\ GE_LESS + \\ else if (aInt == bInt) + \\ GE_EQUAL + \\ else + \\ GE_GREATER + \\ else if (aInt > bInt) + \\ GE_LESS + \\ else if (aInt == bInt) + \\ GE_EQUAL + \\ else + \\ GE_GREATER; + \\} + \\ + ); +} test "zig fmt: respect line breaks in if-else" { try testCanonical( diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig index 37587fe5d3..b9edbbf515 100644 --- a/lib/std/zig/render.zig +++ b/lib/std/zig/render.zig @@ -984,7 +984,8 @@ fn renderWhile(ais: *Ais, tree: ast.Tree, while_node: ast.full.While, space: Spa try renderToken(ais, tree, while_node.ast.while_token + 1, .none); // ( try renderExpression(ais, tree, while_node.ast.cond_expr, .none); // condition - if (nodeIsBlock(node_tags[while_node.ast.then_expr])) { + const then_tag = node_tags[while_node.ast.then_expr]; + if (nodeIsBlock(then_tag) and !nodeIsIf(then_tag)) { if (while_node.payload_token) |payload_token| { try renderToken(ais, tree, payload_token - 2, .space); // ) try renderToken(ais, tree, payload_token - 1, .none); // | @@ -2128,6 +2129,13 @@ fn nodeIsBlock(tag: ast.Node.Tag) bool { }; } +fn nodeIsIf(tag: ast.Node.Tag) bool { + return switch (tag) { + .@"if", .if_simple => true, + else => false, + }; +} + fn nodeCausesSliceOpSpace(tag: ast.Node.Tag) bool { return switch (tag) { .@"catch",