Skip to content

Commit c05d1b8

Browse files
authored
Merge pull request #503 from stackotter/issue-298
Avoid removing certain disambiguating parens from conditions (fixes #298)
2 parents c4d5e68 + 32e369e commit c05d1b8

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

Sources/SwiftFormatRules/NoParensAroundConditions.swift

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,16 @@ public final class NoParensAroundConditions: SyntaxFormatRule {
3030
assert(tuple.elementList.count == 1)
3131
let expr = tuple.elementList.first!.expression
3232

33-
// If the condition is a function with a trailing closure, removing the
34-
// outer set of parentheses introduces a parse ambiguity.
35-
if let fnCall = expr.as(FunctionCallExprSyntax.self), fnCall.trailingClosure != nil {
36-
return ExprSyntax(tuple)
33+
// If the condition is a function with a trailing closure or if it's an immediately called
34+
// closure, removing the outer set of parentheses introduces a parse ambiguity.
35+
if let fnCall = expr.as(FunctionCallExprSyntax.self) {
36+
if fnCall.trailingClosure != nil {
37+
// Leave parentheses around call with trailing closure.
38+
return ExprSyntax(tuple)
39+
} else if fnCall.calledExpression.as(ClosureExprSyntax.self) != nil {
40+
// Leave parentheses around immediately called closure.
41+
return ExprSyntax(tuple)
42+
}
3743
}
3844

3945
diagnose(.removeParensAroundExpression, on: expr)

Tests/SwiftFormatRulesTests/NoParensAroundConditionsTests.swift

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,4 +160,17 @@ final class NoParensAroundConditionsTests: LintOrFormatRuleTestCase {
160160
}
161161
""")
162162
}
163+
164+
func testParensAroundAmbiguousConditions() {
165+
XCTAssertFormatting(
166+
NoParensAroundConditions.self,
167+
input: """
168+
if ({ true }()) {}
169+
if (functionWithTrailingClosure { 5 }) {}
170+
""",
171+
expected: """
172+
if ({ true }()) {}
173+
if (functionWithTrailingClosure { 5 }) {}
174+
""")
175+
}
163176
}

0 commit comments

Comments
 (0)