Skip to content

Commit fb63404

Browse files
authored
Merge pull request #935 from TTOzzi/fix-OmitExplicitReturns
Improve the formatting logic of OmitExplicitReturns rule
2 parents 5412cab + 6f0b35a commit fb63404

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

Sources/SwiftFormat/Rules/OmitExplicitReturns.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ public final class OmitExplicitReturns: SyntaxFormatRule {
6060
guard let accessorBlock = binding.accessorBlock,
6161
let transformed = transformAccessorBlock(accessorBlock)
6262
else {
63-
return node
63+
return super.visit(node)
6464
}
6565

6666
binding.accessorBlock = transformed
@@ -145,7 +145,7 @@ public final class OmitExplicitReturns: SyntaxFormatRule {
145145
CodeBlockItemListSyntax([
146146
CodeBlockItemSyntax(
147147
leadingTrivia: returnStmt.leadingTrivia,
148-
item: .expr(returnStmt.expression!),
148+
item: .expr(returnStmt.expression!.detached.with(\.trailingTrivia, [])),
149149
semicolon: nil,
150150
trailingTrivia: returnStmt.trailingTrivia
151151
)

Tests/SwiftFormatTests/Rules/OmitReturnsTests.swift

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,4 +119,46 @@ final class OmitReturnsTests: LintOrFormatRuleTestCase {
119119
]
120120
)
121121
}
122+
123+
func testInVariableBindings() {
124+
assertFormatting(
125+
OmitExplicitReturns.self,
126+
input: """
127+
var f = l.filter { 1️⃣return $0.a != o }
128+
var bar = l.filter {
129+
2️⃣return $0.a != o
130+
}
131+
""",
132+
expected: """
133+
var f = l.filter { $0.a != o }
134+
var bar = l.filter {
135+
$0.a != o
136+
}
137+
""",
138+
findings: [
139+
FindingSpec("1️⃣", message: "'return' can be omitted because body consists of a single expression"),
140+
FindingSpec("2️⃣", message: "'return' can be omitted because body consists of a single expression"),
141+
]
142+
)
143+
}
144+
145+
func testInVariableBindingWithTrailingTrivia() {
146+
assertFormatting(
147+
OmitExplicitReturns.self,
148+
input: """
149+
var f = l.filter {
150+
1️⃣return $0.a != o // comment
151+
}
152+
""",
153+
expected: """
154+
var f = l.filter {
155+
$0.a != o // comment
156+
}
157+
""",
158+
findings: [
159+
FindingSpec("1️⃣", message: "'return' can be omitted because body consists of a single expression")
160+
]
161+
)
162+
}
163+
122164
}

0 commit comments

Comments
 (0)