Skip to content

Commit 48c733e

Browse files
dabelknapallevato
authored andcommitted
Correctly identify functions with trailing closures. (swiftlang#97)
1 parent 0eb4fac commit 48c733e

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

Sources/Rules/NoEmptyTrailingClosureParentheses.swift

+7-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,13 @@ public final class NoEmptyTrailingClosureParentheses: SyntaxFormatRule {
1515
public override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
1616
guard node.argumentList.count == 0 else { return node }
1717

18-
guard let name = node.calledExpression.firstToken?.withoutTrivia() else { return node }
18+
guard node.trailingClosure != nil && node.argumentList.isEmpty && node.leftParen != nil else {
19+
return node
20+
}
21+
guard let name = node.calledExpression.lastToken?.withoutTrivia() else {
22+
return node
23+
}
24+
1925
diagnose(.removeEmptyTrailingParentheses(name: "\(name)"), on: node)
2026

2127
let formattedExp = replaceTrivia(on: node.calledExpression,

Tests/SwiftFormatTests/NoEmptyTrailingClosureParenthesesTests.swift

+14
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ public class NoEmptyTrailingClosureParenthesesTests: DiagnosingTestCase {
1717
}
1818
greetEnthusiastically() { "John" }
1919
greetApathetically { "not John" }
20+
func myfunc(cls: MyClass) {
21+
cls.myClosure { $0 }
22+
}
23+
func myfunc(cls: MyClass) {
24+
cls.myBadClosure() { $0 }
25+
}
2026
""",
2127
expected: """
2228
func greetEnthusiastically(_ nameProvider: () -> String) {
@@ -27,8 +33,16 @@ public class NoEmptyTrailingClosureParenthesesTests: DiagnosingTestCase {
2733
}
2834
greetEnthusiastically { "John" }
2935
greetApathetically { "not John" }
36+
func myfunc(cls: MyClass) {
37+
cls.myClosure { $0 }
38+
}
39+
func myfunc(cls: MyClass) {
40+
cls.myBadClosure { $0 }
41+
}
3042
""")
3143
XCTAssertDiagnosed(.removeEmptyTrailingParentheses(name: "greetEnthusiastically"))
44+
XCTAssertDiagnosed(.removeEmptyTrailingParentheses(name: "myBadClosure"))
45+
XCTAssertNotDiagnosed(.removeEmptyTrailingParentheses(name: "myClosure"))
3246
}
3347

3448
#if !os(macOS)

0 commit comments

Comments
 (0)