diff --git a/Sources/ParsingHelpers.swift b/Sources/ParsingHelpers.swift index 30771708..86e83c19 100644 --- a/Sources/ParsingHelpers.swift +++ b/Sources/ParsingHelpers.swift @@ -2496,8 +2496,10 @@ extension Formatter { } let nextToken = tokens[nextTokenIndex] let isImportKeyword = nextToken == .keyword("import") - // Access modifier (e.g. "public") can precede "import" on the same line (Swift 6) - let isAccessModifierBeforeImport = nextToken.isKeyword && _FormatRules.aclModifiers.contains(nextToken.string) + // Access modifiers only continue the import block when they are immediately followed by import. + let isAccessModifierBeforeImport = nextToken.isKeyword && + _FormatRules.aclModifiers.contains(nextToken.string) && + next(.nonSpaceOrComment, after: nextTokenIndex) == .keyword("import") if !isImportKeyword, !isAccessModifierBeforeImport { // End of imports pushStack() diff --git a/Tests/Rules/SortImportsTests.swift b/Tests/Rules/SortImportsTests.swift index e1a4c967..5d73b35d 100644 --- a/Tests/Rules/SortImportsTests.swift +++ b/Tests/Rules/SortImportsTests.swift @@ -409,6 +409,20 @@ final class SortImportsTests: XCTestCase { testFormatting(for: input, output, rule: .sortImports) } + func testNoMangleConditionalImportsFollowedByPrivateDeclaration() { + let input = """ + #if canImport(UIKit) + import UIKit + private struct Foo {} + #elseif canImport(AppKit) + import AppKit + private struct Foo {} + #endif + """ + let options = FormatOptions(swiftVersion: "6.1") + testFormatting(for: input, rule: .sortImports, options: options, exclude: [.blankLineAfterImports, .indent]) + } + func testNoMoveSwiftToolsVersionLine() { let input = """ // swift-tools-version: 6.2