Skip to content

Commit

Permalink
Merge pull request swiftlang#503 from stackotter/issue-298
Browse files Browse the repository at this point in the history
Avoid removing certain disambiguating parens from conditions (fixes swiftlang#298)
  • Loading branch information
allevato committed Jun 29, 2023
1 parent fe958d1 commit c0a9fa2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
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 }) {}
""")
}
}

0 comments on commit c0a9fa2

Please sign in to comment.