Fix range crash

This commit is contained in:
Nick Lockwood
2025-11-28 22:09:19 +00:00
parent bc2cca2d60
commit c037026ffb
3 changed files with 38 additions and 2 deletions
+2 -2
View File
@@ -741,7 +741,7 @@ public extension Formatter {
for i in range.reversed() {
let token = tokens[i]
switch token {
case .startOfScope(":") where scopeStack.last == .endOfScope("#endif"):
case .startOfScope(":") where [.endOfScope("#endif"), .endOfScope("}")].contains(scopeStack.last):
break
case .startOfScope where scopeStack.last?.isEndOfScope(token) == true:
scopeStack.removeLast()
@@ -758,7 +758,7 @@ public extension Formatter {
case .linebreak:
linebreakEncountered = true
case .endOfScope("case"), .endOfScope("default"):
if scopeStack.last != .endOfScope("#endif") {
if ![.endOfScope("#endif"), .endOfScope("}")].contains(scopeStack.last) {
fallthrough
}
case .endOfScope:
+2
View File
@@ -173,12 +173,14 @@ public extension Formatter {
$0.isEndOfScope(startToken) || $0 == .endOfScope("#endif")
})
}
assert(endIndex ?? index >= index)
return endIndex
}
while let endIndex = self.index(after: startIndex, where: {
$0.isEndOfScope(startToken)
}), let token = token(at: endIndex) {
if token == .endOfScope("}") {
assert(endIndex >= index)
return endIndex
}
startIndex = endIndex
+34
View File
@@ -1524,4 +1524,38 @@ final class UnusedArgumentsTests: XCTestCase {
testFormatting(for: input, rule: .unusedArguments)
}
func testIfdefCrash() {
let input = """
func test(unused: Int) {
foo {
if true {
#if FOO
switch 1 {
default: ()
}
#endif
} else if true {
()
}
}
}
"""
let output = """
func test(unused _: Int) {
foo {
if true {
#if FOO
switch 1 {
default: ()
}
#endif
} else if true {
()
}
}
}
"""
testFormatting(for: input, output, rule: .unusedArguments)
}
}