Skip to content

Commit

Permalink
Fix redundantReturn with consecutive if statements
Browse files Browse the repository at this point in the history
  • Loading branch information
nicklockwood committed Oct 1, 2023
1 parent ab80f3a commit 1b3d72a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
10 changes: 5 additions & 5 deletions Sources/FormattingHelpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1199,15 +1199,14 @@ extension Formatter {
/// Finds all of the branch bodies in an if statement.
/// Returns the index of the `startOfScope` and `endOfScope` of each branch.
func ifStatementBranches(at ifIndex: Int) -> [ConditionalBranch] {
assert(tokens[ifIndex] == .keyword("if"))
var branches = [(startOfBranch: Int, endOfBranch: Int)]()
var nextConditionalBranchIndex: Int? = ifIndex

while let conditionalBranchIndex = nextConditionalBranchIndex,
["if", "else"].contains(tokens[conditionalBranchIndex].string),
let startOfBody = index(of: .startOfScope, after: conditionalBranchIndex),
tokens[startOfBody] == .startOfScope("{"),
let endOfBody = endOfScope(at: startOfBody),
tokens[endOfBody] == .endOfScope("}")
conditionalBranchIndex == ifIndex || tokens[conditionalBranchIndex] == .keyword("else"),
let startOfBody = index(of: .startOfScope("{"), after: conditionalBranchIndex),
let endOfBody = endOfScope(at: startOfBody)
{
branches.append((startOfBranch: startOfBody, endOfBranch: endOfBody))
nextConditionalBranchIndex = index(of: .nonSpaceOrCommentOrLinebreak, after: endOfBody)
Expand All @@ -1219,6 +1218,7 @@ extension Formatter {
/// Finds all of the branch bodies in a switch statement.
/// Returns the index of the `startOfScope` and `endOfScope` of each branch.
func switchStatementBranches(at switchIndex: Int) -> [ConditionalBranch] {
assert(tokens[switchIndex] == .keyword("switch"))
guard let startOfSwitchScope = index(of: .startOfScope("{"), after: switchIndex),
let firstCaseIndex = index(of: .nonSpaceOrCommentOrLinebreak, after: startOfSwitchScope),
tokens[firstCaseIndex].isSwitchCaseOrDefault
Expand Down
17 changes: 17 additions & 0 deletions Tests/RulesTests+Redundancy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2659,6 +2659,23 @@ class RedundancyTests: RulesTests {
testFormatting(for: input, output, rule: FormatRules.redundantReturn, options: options)
}

func testNoRemoveReturnInConsecutiveIfStatements() {
let input = """
func foo() -> String? {
if bar {
return nil
}
if baz {
return "baz"
} else {
return "quux"
}
}
"""
let options = FormatOptions(swiftVersion: "5.9")
testFormatting(for: input, rule: FormatRules.redundantReturn, options: options)
}

func testRedundantIfStatementReturnInRedundantClosure() {
let input = """
let value = {
Expand Down

0 comments on commit 1b3d72a

Please sign in to comment.