ISSUE DESCRIPTION RemoveUnusedImports removes imports when used in Generics only <!--…
- User
ISSUE DESCRIPTION
RemoveUnusedImports removes imports when used in Generics only
What version of OpenRewrite are you using?
I am using
- OpenRewrite v8.31.1
- Maven/Gradle plugin v6.40.0
How are you running OpenRewrite?
I am using the Maven plugin, and my project is a single module project.
xml<plugin> <groupId>org.openrewrite.maven</groupId> <artifactId>rewrite-maven-plugin</artifactId> <version>6.40.0</version> <executions> <execution> <phase>process-sources</phase> <goals> <goal>run</goal> </goals> <configuration> <activeRecipes combine.children="append"> <recipe>org.openrewrite.java.RemoveUnusedImports</recipe> <recipe>org.openrewrite.java.OrderImports</recipe> </activeRecipes> </configuration> </execution> </executions> </plugin>What is the smallest, simplest way to reproduce the problem?
javaimport com.google.common.hash.BloomFilter; import java.util.concurrent.atomic.AtomicReference; @SuppressWarnings("UnstableApiUsage") public class BloomFilterRef<T> extends AtomicReference<BloomFilter<T>> { }What did you expect to see?
javaimport com.google.common.hash.BloomFilter; import java.util.concurrent.atomic.AtomicReference; @SuppressWarnings("UnstableApiUsage") public class BloomFilterRef<T> extends AtomicReference<BloomFilter<T>> { }What did you see instead?
java Assistant
Let me start by exploring the repository structure to understand the codebase and find the relevant files for the
RemoveUnusedImportsrecipe.Assistant
Let me find the RemoveUnusedImports recipe.
Assistant
Let me look at the test file to understand the testing setup.
Assistant
Let me look at the git history to understand recent changes.
Assistant
Let me look at the recent commits in detail to understand what changed.
Assistant
So the issue described is
RemoveUnusedImports removes imports when used in Generics only. This is likely a regression introduced by commit 330504939, which added thecollectSourceIdentifierNamesand the check!unqualifiedTypeNames.contains(elem.getTypeName()).Wait, let me re-read. The commit 330504939 added
collectSourceIdentifierNamesand a check. Let me look at the actual diff.Assistant
This
ifcheck looks atunqualifiedTypeNames.contains(elem.getTypeName()). Let me look at the current state of the code and theTypeUtils.asFullyQualifiedmethod, since I suspect the issue is with parameterized type parameters.Assistant
Let me check the
JavaType.Parameterizedinterface to understand the class hierarchy.Assistant
Interesting -
Parameterized extends FullyQualified. Let me look at theParameterizedclass more closely.Assistant
Let me reproduce the issue. First, let me check if Guava is available and set up a test reproduction.
Assistant
Guava is available in the test classpath. Let me look at how existing tests use Guava types to understand the test patterns.
Assistant
Let me write a reproduction test. First, let me understand the test framework better by examining how tests specify classpath.
Assistant
Let me look at how tests add dependencies to the parser.
Assistant
Now let me create a reproduction test. Let me write a temporary test file.
Assistant
Let me reproduce with a simpler JDK-only test first to isolate the issue. Let me create a temporary test in the test directory.
Assistant
Interesting - both tests passed (imports kept). Let me check the current version of the repo and verify the recipe is actually running by examining the scenario more carefully.
Assistant
Let me check the actual rewrite version. Let me look at the build.gradle.kts of rewrite-java.
Assistant
Let me look at the test added in commit 330504939 that introduced the
collectSourceIdentifierNameslogic, since that's the most likely culprit for a regression.Assistant
Let me check where
sourceIdentifierNamesis actually used in the current code.Assistant
Let me look at the full context around the import usage decision logic.
Assistant
Let me look at the
TypesInUseclass to understand how it collects types.Assistant
Let me look at how the
typesInUseset is built inTypesInUse.Assistant
Let me look at the
FindTypesInUsevisitor to understand what types it collects, especially how it handles parameterized types.Assistant
My reproduction tests pass. Let me run the full existing test suite to see if there are any currently failing tests that reveal the issue.
Assistant
All existing tests pass. Let me verify whether my Guava test actually resolved the
BloomFiltertype (the test might pass trivially ifNoMissingTypesprevents the recipe from running). Let me checkNoMissingTypes.Assistant
Let me write a more careful test that verifies the recipe actually runs - including a truly unused import that should be removed alongside the BloomFilter import that should be kept.
Assistant
The test passes - the recipe runs (removes
ArrayList) and correctly keepsBloomFilter. So the literal scenario doesn't reproduce with a fully-resolvable type. Let me investigateShallowClasssince the issue may involve types loaded from JARs with incomplete type info.Assistant
Let me search the test file for generic-related test cases and look at the broader context.
Assistant
Let me look at how
visitTypeis invoked in the JavaIsoVisitor and howJ.ParameterizedTypeis handled, to understand if type arguments' types are collected.Assistant
Let me look at the base
JavaVisitorto see howvisitParameterizedTypeandvisitTypeinteract.Assistant
Let me look at the most recent fix (commit 59d98eba8) to understand the pattern of recent fixes.
Assistant
Let me check how
Parameterized.getFullyQualifiedName()works and howJ.Import.getTypeName()works.Assistant
Let me check the actual version of the current repo to understand where we are relative to the reported version.
Assistant
Let me write a comprehensive test with many generic variations to find a failing scenario.
Assistant
All pass. Let me check
J.Import.getTypeName()andgetClassName()to understand how the imported type name is derived, and how it compares to type FQNs.Assistant
Let me write a test that inspects the actual type information for the BloomFilter scenario to understand what type info is available.
Assistant
The output didn't show. The
-iand grep might not capture stdout. Let me check the test report or use a different way to capture stdout. The test framework might redirect stdout. Let me write to a file or check the test output directly.Assistant
Let me check
FindMissingTypesto understand whetherShallowClassis considered a missing type.Assistant
I found a key insight:
FindMissingTypes.isParameterizedTypeallows theclazzof aParameterizedTypeto have a null type. So when a type used as a generic argument is not on the classpath,NoMissingTypesdoesn't block the recipe, but the type isn't collected intounqualifiedTypeNamesortypesByPackage→ import gets removed. Let me reproduce by parsing WITHOUT guava on the classpath.Assistant
The test passed even without guava. Let me inspect the actual type info without guava on the classpath.
Assistant
Without guava,
BloomFilterresolves toUnknownand is NOT intypesInUse. This should cause the import to be removed. But my test passed (no change). Let me verify whether the recipe actually runs by adding an unused import that should be removed.Assistant
The recipe ran (ArrayList removed) but BloomFilter was kept — contradicting my analysis. Let me instrument the recipe temporarily to see what's actually happening.
Assistant
Let me add temporary debug output to understand the actual values.
Assistant
Let me use the edit command instead.
Assistant
The test framework has Guava on the runtime classpath by default, so
BloomFilteractually resolves. Let me reproduce with a genuinely non-existent type to simulate the "not on classpath" scenario.Assistant
I've reproduced the bug. With a non-existent type used as a generic argument (
AtomicReference<NonExistent<T>>), the import is incorrectly removed because:combinedTypesis empty (Unknown type not intypesByPackage)unqualifiedTypeNamesdoesn't contain it (Unknown type not FullyQualified)- The
sourceIdentifierNamescheck exists only in a LATER branch, never reached
Let me first remove the debug line, then apply the fix.
Assistant
Now let me apply the fix to the first branch.
Assistant
Let me apply the fix by adding the
sourceIdentifierNamescheck to the first branch condition.Assistant
Now let me run my reproduction test to verify the fix works.
Assistant
Still failing. Let me check the actual diff output.
Assistant
I see — the 4th branch is the actual remover (the first branch with my fix no longer removes it, but the 4th branch does). I'll use a cleaner, more consistent approach: use
qualidType != null(the import's type must be resolvable) as the guard on both removal branches. When the type is unresolvable, type-attribution-based usage detection is unreliable, so we should rely on the textual check instead. Let me update both branches.Assistant
Now let me add
&& qualidType != nullto the 4th branch.Assistant
Now let me run my reproduction test again.
Assistant
Still failing. Let me check the actual diff to understand which branch is removing it now.
Assistant
My fix works! The recipe now keeps the
NonExistentimport (no change). The test failure is because I provided identicalbefore/afterstrings (framework expects a change in that case). Let me rewrite the test properly: include a truly-unused import to prove the recipe runs, while the generic-argument import is kept.Assistant
The fix works —
ArrayList(unused) is removed whileNonExistent(used as a generic argument with unknown type) is kept. Now let me run the full existing test suite to ensure I haven't broken anything.Assistant
All existing tests pass. Let me test additional edge cases to ensure robustness — different positions where an unresolvable type can appear in generics.
Assistant
Three of four tests pass. The
unresolvedAsRawTypeArgumenttest fails at the test framework'sassertValidTypes(not my recipe) — a raw unknown type argument likeList<NonExistent>is flagged as a malformed/missing type, soNoMissingTypeswould block the recipe in production (import kept). That case is already handled. Let me remove that non-representative test and confirm the rest pass.Assistant
All representative tests pass. Let me also check whether a related wildcard-import scenario has the same problem, to understand the full scope.
Assistant
The wildcard case has the same root cause but is fundamentally harder (can't attribute an unknown simple name to a package). The issue is specifically about named imports, so my fix targets that. Let me verify the exact issue example (BloomFilter) works, and check whether I can simulate a truly-unresolvable Guava type by using an empty classpath.
Assistant
Let me verify the exact issue example with
BloomFilter(resolves via runtime classpath) is kept, AND verify with an empty classpath that an unresolvableBloomFilteris also kept.Assistant
Both pass — the exact issue example is now handled whether
BloomFilterresolves or not. Let me confirm the bug existed before my fix by temporarily reverting and re-running the unresolved case.Assistant
Confirmed — before the fix,
BloomFilterimport is removed (the bug); after the fix, it's kept. I noticesettings.gradle.ktsshows as modified, which I didn't intend. Let me check it.Assistant
The
settings.gradle.ktschange (removingrewrite-android) was not made by me — it's a pre-existing environment modification. I'll restore it so my submission only contains the actual fix. Let me first verify the build still works after restoring.Assistant
Now my diff only contains the
RemoveUnusedImports.javafix. Let me verify the build still works withsettings.gradle.ktsrestored.Assistant
The build works. Let me view my final diff and clean up the temporary test file.
Assistant
My fix is clean and minimal — two changes, both adding
&& qualidType != nullto the two type-attribution-based removal branches. When an import's type is unresolvable (qualidType == null), the recipe now falls back to the textualsourceIdentifierNamescheck (3rd branch) instead of incorrectly removing it. For resolvable imports, behavior is unchanged.Let me clean up the temporary test file and run the full test suite one final time.
Assistant
Clean — only the
RemoveUnusedImports.javachange remains. Let me run the fullRemoveUnusedImportsTestone final time to confirm everything passes.Assistant
All tests pass. Let me also run the
OrderImportstests (the user runs both recipes) and verify no regressions in import-related functionality.Assistant
Let me check which other tests reference
RemoveUnusedImports(as it's often used as a sub-recipe) and run those to ensure no regressions.Assistant
No other test files reference RemoveUnusedImports directly. Let me check if any recipes use it as a sub-recipe (via
Recipecomposition) which might be exercised by other tests.Actually, let me search the main source for usages of RemoveUnusedImports as a sub-recipe.
Assistant
Let me do a final review of the complete modified section to ensure correctness and clean formatting.
Assistant
The fix is clean and correct. Let me verify the final state of the change and confirm the build compiles cleanly before submitting.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.