Fix handling of any keyword in sortTypealiases rule (#2348)

This commit is contained in:
Cal Stephens
2026-01-29 13:10:36 -08:00
parent c402af2674
commit 371139897b
2 changed files with 22 additions and 25 deletions
+14
View File
@@ -149,6 +149,20 @@ public extension FormatRule {
)
}
}
// If sorting moved an `any` keyword to a position other than the start of the
// composition, move it back to the start. In `any Foo & Bar`, the `any` applies
// to the entire composition and must remain at the beginning.
if let newEqualsIndex = formatter.index(of: .operator("=", .infix), after: typealiasIndex),
let startOfType = formatter.index(of: .nonSpaceOrCommentOrLinebreak, after: newEqualsIndex),
let (_, _, endOfComposition) = formatter.parseProtocolCompositionTypealias(at: typealiasIndex),
let firstAnd = formatter.index(of: .operator("&", .infix), after: newEqualsIndex),
let anyIndex = formatter.index(of: .identifier("any"), in: firstAnd ... endOfComposition)
{
let removeEnd = formatter.token(at: anyIndex + 1)?.isSpace == true ? anyIndex + 1 : anyIndex
formatter.removeTokens(in: anyIndex ... removeEnd)
formatter.insert([.identifier("any"), .space(" ")], at: startOfType)
}
}
} examples: {
"""
+8 -25
View File
@@ -93,31 +93,11 @@ final class SortTypealiasesTests: XCTestCase {
}
func testSortWrappedMultilineTypealiasWithAny() {
let input = """
typealias Dependencies
= any FooProviding
& any BarProviding
& any BaazProviding
& any QuuxProviding
"""
let output = """
typealias Dependencies
= any BaazProviding
& any BarProviding
& any FooProviding
& any QuuxProviding
"""
testFormatting(for: input, output, rule: .sortTypealiases)
}
func testSortWrappedMultilineTypealiasWithMixedAny() {
let input = """
typealias Dependencies
= any FooProviding
& BarProviding
& any BaazProviding
& BaazProviding
& QuuxProviding
"""
@@ -125,7 +105,7 @@ final class SortTypealiasesTests: XCTestCase {
typealias Dependencies
= any BaazProviding
& BarProviding
& any FooProviding
& FooProviding
& QuuxProviding
"""
@@ -216,11 +196,14 @@ final class SortTypealiasesTests: XCTestCase {
testFormatting(for: input, output, rule: .sortTypealiases)
}
func testSortSingleLineTypealiasBeginningWithAny() {
func testSortSingleLineTypealiasWithLeadingAny() {
let input = """
typealias Placeholders = any Bar & Foo
typealias Wrapped = any UIView & UIContentView
"""
testFormatting(for: input, rule: .sortTypealiases)
let output = """
typealias Wrapped = any UIContentView & UIView
"""
testFormatting(for: input, output, rule: .sortTypealiases)
}
func testCollectionTypealiasWithArrayOfExistentialTypes() {