Skip to content

Commit

Permalink
Fix invalid return removal
Browse files Browse the repository at this point in the history
  • Loading branch information
nicklockwood committed Sep 1, 2024
1 parent fd5f91c commit 8bdfe22
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
15 changes: 13 additions & 2 deletions Sources/Rules/RedundantReturn.swift
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,25 @@ public extension FormatRule {
}

// Make sure this is a type of scope that supports implicit returns
let lastKeyword = isClosure ? "" : formatter.lastSignificantKeyword(at: startOfScopeIndex, excluding: ["throws"])
if !isClosure, formatter.isConditionalStatement(at: startOfScopeIndex, excluding: ["where"]) ||
["do", "else", "catch"].contains(formatter.lastSignificantKeyword(at: startOfScopeIndex, excluding: ["throws"]))
["do", "else", "catch"].contains(lastKeyword)
{
return
}

// Only strip return from conditional block if conditionalAssignment rule is enabled
let stripConditionalReturn = formatter.options.enabledRules.contains("conditionalAssignment")
var stripConditionalReturn = formatter.options.enabledRules.contains("conditionalAssignment")

// Don't strip return if type is opaque
// (https://github.com/nicklockwood/SwiftFormat/issues/1819)
if stripConditionalReturn,
lastKeyword == "func",
let arrowIndex = formatter.index(of: .operator("->", .infix), before: startOfScopeIndex),
formatter.tokens[arrowIndex ..< startOfScopeIndex].contains(.identifier("some"))
{
stripConditionalReturn = false
}

// Make sure the body only has a single statement
guard formatter.blockBodyHasSingleStatement(
Expand Down
27 changes: 27 additions & 0 deletions Tests/Rules/RedundantReturnTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1261,4 +1261,31 @@ class RedundantReturnTests: XCTestCase {
rules: [.redundantReturn, .conditionalAssignment],
options: options)
}

func testReturnNotRemovedFromSwitchBodyWithOpaqueReturnType() {
// https://github.com/nicklockwood/SwiftFormat/issues/1819
let input = """
extension View {
func foo() -> some View {
if #available(iOS 16.0, *) {
return self.scrollIndicators(.hidden)
} else {
return self
}
}
func bar() -> (some View) {
if #available(iOS 16.0, *) {
return self.scrollIndicators(.hidden)
} else {
return self
}
}
}
"""
let options = FormatOptions(swiftVersion: "5.9")
testFormatting(for: input,
rules: [.redundantReturn, .conditionalAssignment],
options: options)
}
}

0 comments on commit 8bdfe22

Please sign in to comment.