Skip to content

Conversation

@amanthatdoescares
Copy link

@amanthatdoescares amanthatdoescares commented Dec 20, 2025

Problem

The RemoveUnusedImports feature only considered imports at the top level of files, missing imports inside #if conditional compilation blocks. This led to:

  • False negatives: Unused imports inside #if blocks weren't detected
  • Incomplete cleanup: Projects with platform-specific or feature-flagged imports wouldn't get fully cleaned up

Solution

Implement recursive syntax tree traversal to find ALL imports throughout the entire file structure, including those inside conditional compilation blocks.
Fixes: #2335

Now properly handles all imports including those inside #if blocks while keeping platform-specific imports safe.

Copy link
Member

@ahoppen ahoppen left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for opening the PR. It seems to me like it contains quite a few unrelated changes with possible regressions though. A couple things that jump out to me are (but there seem to be quite a few others). Could you ensure that your PR only focuses on the issue it aims to resolve?

  • The removal of the comment on RemoveUnusedImportsCommand
  • The removal of the filepath check for #if os(Windows)
  • The removal of temporaryDocumentHasErrorDiagnostic

One of the particular challenges here is that we must not remove import statements in inactive #if clauses. For example, consider the following, which we have quite a few times in SourceKit-LSP. All of these import statements are necessary but on macOS, you can remove all but import Darwin without causing a compilation error. We should have a test for this that ensures only import statements from active #if clauses are removed?

#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(CRT)
import CRT
#elseif canImport(Bionic)
import Bionic
#endif

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Remove unused imports should be able to remove unused import declarations in active #if clauses

2 participants