Skip to content

Commit ed1c8a6

Browse files
committed
[Lint/Format] Extend return omission rule to include closures
1 parent a6041ff commit ed1c8a6

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

Sources/SwiftFormat/Core/Pipelines+Generated.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,11 @@ class LintPipeline: SyntaxVisitor {
6060
return .visitChildren
6161
}
6262

63+
override func visit(_ node: ClosureExprSyntax) -> SyntaxVisitorContinueKind {
64+
visitIfEnabled(OmitReturns.visit, for: node)
65+
return .visitChildren
66+
}
67+
6368
override func visit(_ node: ClosureParameterSyntax) -> SyntaxVisitorContinueKind {
6469
visitIfEnabled(NoLeadingUnderscores.visit, for: node)
6570
return .visitChildren

Sources/SwiftFormat/Rules/OmitReturns.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,20 @@ public final class OmitReturns: SyntaxFormatRule {
3737
return decl
3838
}
3939

40+
public override func visit(_ node: ClosureExprSyntax) -> ExprSyntax {
41+
let expr = super.visit(node)
42+
43+
// test { return ... }
44+
if var closure = expr.as(ClosureExprSyntax.self),
45+
let `return` = containsSingleReturn(closure.statements) {
46+
closure.statements = unwrapReturnStmt(`return`)
47+
diagnose(.omitReturnStatement, on: `return`, severity: .refactoring)
48+
return ExprSyntax(closure)
49+
}
50+
51+
return expr
52+
}
53+
4054
private func containsSingleReturn(_ body: CodeBlockItemListSyntax) -> ReturnStmtSyntax? {
4155
if let element = body.firstAndOnly?.as(CodeBlockItemSyntax.self),
4256
let ret = element.item.as(ReturnStmtSyntax.self),

Tests/SwiftFormatTests/Rules/OmitReturnsTests.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,19 @@ final class OmitReturnsTests: LintOrFormatRuleTestCase {
1515
}
1616
""")
1717
}
18+
19+
func testOmitReturnInClosure() {
20+
XCTAssertFormatting(
21+
OmitReturns.self,
22+
input: """
23+
vals.filter {
24+
return $0.count == 1
25+
}
26+
""",
27+
expected: """
28+
vals.filter {
29+
$0.count == 1
30+
}
31+
""")
32+
}
1833
}

0 commit comments

Comments
 (0)