Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Sources/SwiftFormat/Rules/OmitExplicitReturns.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public final class OmitExplicitReturns: SyntaxFormatRule {
guard let accessorBlock = binding.accessorBlock,
let transformed = transformAccessorBlock(accessorBlock)
else {
return node
return super.visit(node)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the condition was not met, the node was returned immediately, preventing the additional visit logic from executing.
By calling super.visit, the visit process continues, allowing the formatting logic in visit(_ node: ClosureExprSyntax) to be applied.

}

binding.accessorBlock = transformed
Expand Down Expand Up @@ -145,7 +145,7 @@ public final class OmitExplicitReturns: SyntaxFormatRule {
CodeBlockItemListSyntax([
CodeBlockItemSyntax(
leadingTrivia: returnStmt.leadingTrivia,
item: .expr(returnStmt.expression!),
item: .expr(returnStmt.expression!.detached.with(\.trailingTrivia, [])),
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since returnStmt.expression and returnStmt had the same trailingTrivia, formatting caused trailingTrivia to appear twice when present.
To fix this, I detached the trailingTrivia of returnStmt.expression when rewrapping with CodeBlockItemSyntax, ensuring it does not get duplicated.

semicolon: nil,
trailingTrivia: returnStmt.trailingTrivia
)
Expand Down
42 changes: 42 additions & 0 deletions Tests/SwiftFormatTests/Rules/OmitReturnsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -119,4 +119,46 @@ final class OmitReturnsTests: LintOrFormatRuleTestCase {
]
)
}

func testInVariableBindings() {
assertFormatting(
OmitExplicitReturns.self,
input: """
var f = l.filter { 1️⃣return $0.a != o }
var bar = l.filter {
2️⃣return $0.a != o
}
""",
expected: """
var f = l.filter { $0.a != o }
var bar = l.filter {
$0.a != o
}
""",
findings: [
FindingSpec("1️⃣", message: "'return' can be omitted because body consists of a single expression"),
FindingSpec("2️⃣", message: "'return' can be omitted because body consists of a single expression"),
]
)
}

func testInVariableBindingWithTrailingTrivia() {
assertFormatting(
OmitExplicitReturns.self,
input: """
var f = l.filter {
1️⃣return $0.a != o // comment
}
""",
expected: """
var f = l.filter {
$0.a != o // comment
}
""",
findings: [
FindingSpec("1️⃣", message: "'return' can be omitted because body consists of a single expression")
]
)
}

}