Skip to content

Commit

Permalink
Fix issue where closure with if expression in method call would be un…
Browse files Browse the repository at this point in the history
…expectedly removed
  • Loading branch information
calda authored and nicklockwood committed Oct 27, 2023
1 parent 0116632 commit e1b3873
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
1 change: 1 addition & 0 deletions Sources/Rules.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6271,6 +6271,7 @@ public struct _FormatRules {
case (nil, nil):
potentialStartOfExpressionContainingClosure = nil
case (.some(let startOfScope), nil):
guard formatter.tokens[startOfScope] == .startOfScope("{") else { return }
potentialStartOfExpressionContainingClosure = startOfScope
case (nil, let .some(assignmentBeforeClosure)):
potentialStartOfExpressionContainingClosure = assignmentBeforeClosure
Expand Down
64 changes: 64 additions & 0 deletions Tests/RulesTests+Redundancy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8485,6 +8485,70 @@ class RedundancyTests: RulesTests {
testFormatting(for: input, rule: FormatRules.redundantClosure, options: options)
}

func testClosureNotRemovedInMethodCall() {
let input = """
XCTAssert({
if foo {
bar
} else {
baaz
}
}())
"""

let options = FormatOptions(swiftVersion: "5.9")
testFormatting(for: input, rule: FormatRules.redundantClosure, options: options)
}

func testClosureNotRemovedInMethodCall2() {
let input = """
method("foo", {
if foo {
bar
} else {
baaz
}
}())
"""

let options = FormatOptions(swiftVersion: "5.9")
testFormatting(for: input, rule: FormatRules.redundantClosure, options: options)
}

func testClosureNotRemovedInMethodCall3() {
let input = """
XCTAssert({
if foo {
bar
} else {
baaz
}
}(), "message")
"""

let options = FormatOptions(swiftVersion: "5.9")
testFormatting(for: input, rule: FormatRules.redundantClosure, options: options)
}

func testClosureNotRemovedInMethodCall4() {
let input = """
method(
"foo",
{
if foo {
bar
} else {
baaz
}
}(),
"bar"
)
"""

let options = FormatOptions(swiftVersion: "5.9")
testFormatting(for: input, rule: FormatRules.redundantClosure, options: options)
}

// MARK: Redundant optional binding

func testRemovesRedundantOptionalBindingsInSwift5_7() {
Expand Down

0 comments on commit e1b3873

Please sign in to comment.