From 32e369e8082f1a9f008f54b5f4365e0386d1ad05 Mon Sep 17 00:00:00 2001 From: stackotter Date: Tue, 4 Apr 2023 21:23:40 +1000 Subject: [PATCH] Avoid disambiguating parentheses being removed from called closures in conditions (#298) A bit of a mouthfull to fit into a reasonably sized commit message. The NoParensAroundConditions rule removed parens around immediately called closures and in doing so introduced ambiguities into code that was correct to begin with. --- .../NoParensAroundConditions.swift | 14 ++++++++++---- .../NoParensAroundConditionsTests.swift | 13 +++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/Sources/SwiftFormatRules/NoParensAroundConditions.swift b/Sources/SwiftFormatRules/NoParensAroundConditions.swift index 162715254..1ee8678a7 100644 --- a/Sources/SwiftFormatRules/NoParensAroundConditions.swift +++ b/Sources/SwiftFormatRules/NoParensAroundConditions.swift @@ -30,10 +30,16 @@ public final class NoParensAroundConditions: SyntaxFormatRule { assert(tuple.elementList.count == 1) let expr = tuple.elementList.first!.expression - // If the condition is a function with a trailing closure, removing the - // outer set of parentheses introduces a parse ambiguity. - if let fnCall = expr.as(FunctionCallExprSyntax.self), fnCall.trailingClosure != nil { - return ExprSyntax(tuple) + // If the condition is a function with a trailing closure or if it's an immediately called + // closure, removing the outer set of parentheses introduces a parse ambiguity. + if let fnCall = expr.as(FunctionCallExprSyntax.self) { + if fnCall.trailingClosure != nil { + // Leave parentheses around call with trailing closure. + return ExprSyntax(tuple) + } else if fnCall.calledExpression.as(ClosureExprSyntax.self) != nil { + // Leave parentheses around immediately called closure. + return ExprSyntax(tuple) + } } diagnose(.removeParensAroundExpression, on: expr) diff --git a/Tests/SwiftFormatRulesTests/NoParensAroundConditionsTests.swift b/Tests/SwiftFormatRulesTests/NoParensAroundConditionsTests.swift index 865082ed3..9dbe9d244 100644 --- a/Tests/SwiftFormatRulesTests/NoParensAroundConditionsTests.swift +++ b/Tests/SwiftFormatRulesTests/NoParensAroundConditionsTests.swift @@ -160,4 +160,17 @@ final class NoParensAroundConditionsTests: LintOrFormatRuleTestCase { } """) } + + func testParensAroundAmbiguousConditions() { + XCTAssertFormatting( + NoParensAroundConditions.self, + input: """ + if ({ true }()) {} + if (functionWithTrailingClosure { 5 }) {} + """, + expected: """ + if ({ true }()) {} + if (functionWithTrailingClosure { 5 }) {} + """) + } }