Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions Sources/SwiftFormatRules/NoParensAroundConditions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
13 changes: 13 additions & 0 deletions Tests/SwiftFormatRulesTests/NoParensAroundConditionsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) {}
""")
}
}