diff --git a/Sources/Rules/SortTypealiases.swift b/Sources/Rules/SortTypealiases.swift index ea7a0c6f..ea19f362 100644 --- a/Sources/Rules/SortTypealiases.swift +++ b/Sources/Rules/SortTypealiases.swift @@ -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: { """ diff --git a/Tests/Rules/SortTypealiasesTests.swift b/Tests/Rules/SortTypealiasesTests.swift index 0762dd19..0bdaf816 100644 --- a/Tests/Rules/SortTypealiasesTests.swift +++ b/Tests/Rules/SortTypealiasesTests.swift @@ -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() {