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.
<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?
import 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?
import 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?
import java.util.concurrent.atomic.AtomicReference; @SuppressWarnings("UnstableApiUsage") public class BloomFilterRef<T> extends AtomicReference<BloomFilter<T>> { }What is the full stack trace of any errors you encountered?
stacktrace output hereAre you interested in contributing a fix to OpenRewrite?
Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you call ) using or commands. However you don't need to use or before submitting your changes. In fact, only submits currently unstaged changes because it uses to get the changes that need to be submitted. Assistant
Let me start by exploring the repository structure to understand what we're working with.
Assistant
This is the OpenRewrite repository. The issue is about
RemoveUnusedImportsremoving imports that are used in generics. Let me find the relevant recipe.Assistant
Let me see the full file, especially the truncated part:
Assistant
Now let me understand the issue. The key part is how
typesByPackageis built. Let me look at theTypeUtils.asFullyQualifiedmethod:Assistant
Let me check the relationship between
JavaType.ParameterizedandJavaType.FullyQualified:Assistant
Interesting! So
JavaType.Parameterized extends FullyQualified. That meansasFullyQualifiedwould return the Parameterized type itself if it's notJavaType.Unknown. Let me verify by checking the Parameterized class.Assistant
Let me check what
toFullyQualifiedNamedoes:Assistant
Let me check the
FullyQualifiedabstract class and howParameterizeddelegates methods likegetFullyQualifiedName()andgetOwningClass():Assistant
Let me look at the existing tests for
RemoveUnusedImports:Assistant
Now let me reproduce the issue. Let me create a temporary test using JDK types that match the pattern (a generic type used only as a parameterized type argument of another generic type):
Assistant
Let me create a temporary test to reproduce the issue:
Assistant
The test passed, meaning the import was NOT removed with JDK types. Let me check the git history to understand recent changes to this file:
Assistant
Let me look at the recent commit that added the
collectSourceIdentifierNamesand related methods:Assistant
Let me check the current version of the repo:
Assistant
Let me look at the test added for #7336 to understand the scenario:
Assistant
So that test removes an import (
org.example.a.Something) when it's only referenced as a parameter type of a statically imported method. TheSomethingsimple name doesn't appear in source code.Now, the new issue (#7380 was the static field qualifier issue). Let me look at the #7383 fix.
Assistant
Let me look at how
TypesInUsecollects types:Assistant
Let me reproduce with locally-defined types that closely match the Guava scenario (a generic type used as a parameterized type argument):
Assistant
The test passed (import kept). Let me dig deeper. Let me write a debug test that prints the types in use to understand the type structure:
Assistant
Wait, I'm not sure
RewriteTest.noop()exists. Let me look at how to do a debug print. Let me look at how other tests print things or useafterRecipe.Actually, let me simplify. Let me just use a no-op recipe and inspect. But I need a way to access the compilation unit. Let me check the RewriteTest API.
Assistant
Let me fix the debug test using the proper API:
Assistant
Let me use a different debug approach. Let me write a standalone test that parses and inspects types directly:
Assistant
Let me write a standalone debug test that parses and inspects the types in use:
Assistant
Let me find the test output:
Assistant
Now I can see the types in use. The
BloomFilterappears as both a rawClassand aParameterizedtype. With the current code, the import is kept. Let me check whether the issue might require the actual Guava JAR (where type attribution may differ). Let me check if Guava is available:Assistant
There's a Guava JAR available. Let me see how tests use it:
Assistant
Let me write a reproduction using the actual Guava JAR's
BloomFilter:Assistant
Let me check how the guava classpath is configured for tests:
Assistant
Guava is on the test runtime classpath. Let me use the right name:
Assistant
Still passes. Let me debug the actual types in use with the Guava JAR:
Assistant
The issue seems already handled in the current code. Let me re-verify the current state of the key check in the file by reading it directly:
Assistant
The fix appears present. Let me check if perhaps the issue is about a regression introduced by the recent
sourceIdentifierNamescheck. Let me test by reverting that check temporarily to see the original behavior:Assistant
There's a small diff in settings.gradle.kts (removing rewrite-android). This was probably done to make the build work. Let me restore it... actually, let me not worry about that.
Let me reconsider. Maybe the issue is NOT reproducible because the fix is in place. But the task expects me to fix the issue. So maybe the repo is actually at a state BEFORE the fix and I'm confusing myself.
Wait, let me re-read: the git log showed commits #7336 and #7383. But maybe those commits are AFTER the current HEAD? No, git log shows commits reachable from HEAD.
Let me verify: is HEAD at 2d625133c, and are #7336/#7383 ancestors?
Assistant
Let me run the full existing test suite for RemoveUnusedImports to check the current state:
Assistant
The issue isn't reproducing with the current code. Let me try many variations to find a case that triggers the bug, especially ones involving the
sourceIdentifierNamescheck:Assistant
All pass. Let me check when
collectUnqualifiedTypeNameswas added:Assistant
Let me check the
NoMissingTypesprecondition:Assistant
Let me try more unusual generic usage patterns - type witnesses, generic method invocations, and array generics:
Assistant
Let me verify the working tree matches HEAD for RemoveUnusedImports.java:
Assistant
The fix is present in HEAD. Let me check the version this repo corresponds to and look at recent overall commits:
Assistant
Let me re-verify the exact HEAD and the position of the fix commits:
Assistant
Let me check out the parent of the #7336 fix to understand the original bug behavior:
Assistant
At the parent of #7336, the check was:
if (combinedTypes.isEmpty() || sourcePackage.equals(elem.getPackageName()) && ...) { anImport.used = false; changed = true; }Note:
combinedTypes.isEmpty()WITHOUT the&& !unqualifiedTypeNames.contains(elem.getTypeName()). So at this version, if combinedTypes was empty, the import was removed.But wait, #7383 added the
unqualifiedTypeNamespart. #7336 was the sourceIdentifierNames. Let me check the order:- #5714 (2e5fe355a) added
collectUnqualifiedTypeNamesandunqualifiedTypeNames. - #7336 (330504939) added
sourceIdentifierNames. - #7383 (59d98eba8) added
&& !unqualifiedTypeNames.contains(elem.getTypeName())to the first if and the last elif.
Wait, but the parent of #7336 already had
unqualifiedTypeNames(from #5714) and thecombinedTypes.stream().noneMatch(...)check. Let me look at the full check at the parent of #7336.- #5714 (2e5fe355a) added
Assistant
Let me check the actual Guava version being used and examine the BloomFilter signature:
Assistant
Let me verify the recipe actually runs in my test by adding a genuinely unused import that should be removed:
Assistant
The recipe runs (removes unused
List) and keepsBloomFilter. The issue appears fixed at HEAD. Let me very carefully re-read the exact current import-removal logic character by character:Assistant
Let me test a star/wildcard import scenario with generics-only usage:
Assistant
The first test "failed" because the star import was correctly unfolded (expected behavior, my test was just missing the
after). Let me re-examine thecollectUnqualifiedTypeNamesandisPartOfQualifiedReferencemethods carefully, since the fix relies on them:Assistant
Let me look at what the #5714 commit (first
unqualifiedTypeNamesfix) changed, to understand the bug progression:Assistant
Let me do a precise diff between the working tree file and HEAD, and also compare with the pre-#7383 version:
Assistant
The fix is fully present (working tree == #7383 commit state). Let me write a comprehensive debug test to triple-confirm the internal state for the exact scenario:
Assistant
Let me find how to get results from a RecipeRun. Let me check RecipeRun fields.
Assistant
The
runmethod takes aLargeSourceSet. Let me check what implements LargeSourceSet or how to create one from a List. Let me look at how RewriteTest creates it.Assistant
Confirmed: NO CHANGES (imports kept). The issue is fixed at HEAD. Let me check the history of the type-iteration loop to understand when the bug was originallypresent:
Assistant
Let me check if there are RemoveUnusedImports tests in the TCK or other modules:
Assistant
Let me find the actual version number of the repo at HEAD:
Assistant
Let me do an experiment: temporarily disable the type-parameter extraction loop to see if that's what keeps the BloomFilter import:
Assistant
Let me search the entire repo for any reference to this issue or "BloomFilter":
Assistant
Let me test more "remove bug" edge cases - casts, array generics, and qualified-within-generic scenarios:
Assistant
All pass. The issue is comprehensively fixed at HEAD. Let me do a definitive experiment: temporarily replace the file with the pre-#7383 version (330504939) to confirm whether the bug reproduces there:
Assistant
Even at the pre-#7383 version, the BloomFilter import is kept. So the bug doesn't reproduce there either with the current type attribution. Let me restore the fixed version:
Assistant
Let me run the specific #7383 test to verify that fix is active in the working tree:
Assistant
Both #7383 and #7336 fixes are active. Let me check the CLAUDE.md and .claude directory for any hints about this issue:
Assistant
Let me test the exact issue scenario WITHOUT Guava on the classpath (BloomFilter unresolved), to see if NoMissingTypes skips or if the import gets removed:
Assistant
I found the bug! When
BloomFilteris unresolved (its type attribution is Unknown), the recipe removes the import becausecombinedTypesis empty andunqualifiedTypeNamesdoesn't contain it (sincecollectUnqualifiedTypeNamesonly tracks FullyQualified-typed identifiers). Let me investigate whyNoMissingTypesdidn't skip:Assistant
Let me debug the identifier type and FindMissingTypes result for the unresolved case:
Assistant
Now I understand - the
BloomFilteridentifier has typeUnknownbutFindMissingTypesreturns 0 missing! SoNoMissingTypesdoesn't skip. Let me look atisAllowedToHaveNullType:Assistant
Let me look at
isAllowedToHaveNullType:Assistant
Found the root cause!
FindMissingTypes.isAllowedToHaveNullTypereturnstrueforisParameterizedType(ident)— so an unresolved type used as the clazz of aParameterizedType(likeBloomFilterinBloomFilter<T>) is NOT flagged as missing. ThusNoMissingTypesdoesn't skip the recipe, andRemoveUnusedImportsremoves the import becausecombinedTypesis empty andunqualifiedTypeNamesdoesn't contain the unresolved type.Let me check if there are existing tests where an unused import's simple name coincidentally matches a class/variable name (to avoid a regression):
Assistant
Let me check the current behavior for the potential regression case (a class named the same as an unused import):
Assistant
The fix should keep the import when the type is used unqualified in the source even if its type attribution is
Unknown. Let me first check what type unresolved method-call names and field accesses get, to design a targeted fix:Assistant
The unresolved
BloomFilteridentifiers all havetype=UnknownandfieldType=null, and they're all type references (field type, static method qualifier, return type). Now let me implement the fix. First, let me view the exact code around the call site and thecollectUnqualifiedTypeNamesmethod:Assistant
Now let me implement the fix. First, modify the call site to get both FQN and simple-name sets:
Assistant
Now let me implement the fix. First, modify the call site:
Assistant
No Python. Let me use the
replacecommand. Let me open the file first:Assistant
Now let me modify condition 1 (the first
if). Let me view the exact lines:Assistant
Now let me modify condition 4 (the last
else if):Assistant
Now let me modify the
collectUnqualifiedTypeNamesmethod to return the holder and populate both sets. Let me view it:Assistant
The replace command requires the displayed lines. Let me navigate to line 479 first.
Assistant
Now let me edit the
collectUnqualifiedTypeNamesmethod (lines 479-525):Assistant
Now let me add the
UnqualifiedTypesholder class nearImportUsage:Assistant
Now let me compile and run my reproduction test to verify the fix:
Assistant
The import is still being removed! My fix didn't take effect. Let me debug why the
unqualifiedTypeSimpleNamesisn't being populated. Let me replicate the collection logic in a test:Assistant
The
BloomFilteridentifier's type is aJavaType.FullyQualifiedwith FQN<unknown>(notJavaType.Unknown)! Let me check the class hierarchy ofJavaType.Unknown:Assistant
JavaType.Unknown extends FullyQualifiedwith FQN<unknown>! Sotype instanceof JavaType.FullyQualifiedcatches Unknown first. I need to checkJavaType.UnknownBEFOREJavaType.FullyQualified. Let me fix the order:Assistant
Now let me re-run the reproduction test:
Assistant
That was the debug test (old logic copy). Let me re-run the actual recipe reproduction test:
Assistant
The fix works. The generics-only import is now KEPT, and a genuinely unused import is still REMOVED. Now let me run the full existing test suite to check for regressions:
Assistant
All existing tests pass. Let me now verify several edge cases to ensure no regressions and that the fix is robust:
Assistant
The key tests pass (including
unresolvedTypeInGenericsKept— the exact issue scenario). TheunresolvedTypeFieldKeptfailed only due to test type-validation of unresolved types. Let me fix the test setup:Assistant
Let me rewrite the test file cleanly:
Assistant
All edge cases pass. Let me also test the method-named-same-as-type edge case to be thorough:
Assistant
Let me check whether
NoMissingTypesskips for the unresolved method invocation case (which would mean my change doesn't affect it in practice):Assistant
This confirms the fix is exactly right:
- Method call case (
Bar()):FindMissingTypesflags it as missing (1 missing) →NoMissingTypesskips → import kept (existing correct behavior; my change doesn't affect it). - Generics case (
BloomFilter<T>):FindMissingTypesreturns 0 missing (becauseisAllowedToHaveNullTypeallowsParameterizedTypeclazz to be Unknown) →NoMissingTypesdoes NOT skip → recipe runs → before fix: removes import (bug); after fix: keeps import (correct).
Let me clean up the temp test files and run the full existing suite once more:
- Method call case (
Assistant
Let me force a clean re-run to be 100% sure the tests pass against my new code:
Assistant
All tests pass with the forced re-run. Let me also run related import tests (OrderImports, since the issue runs both recipes) and check for other tests referencing RemoveUnusedImports:
Assistant
Let me review the final diff of my changes:
Assistant
The diff is clean and complete. Let me do a final compile check of the main module and verify the resolved (exact issue with Guava) case one more time:
Assistant
Let me run a final verification with the exact issue scenario (both resolved with Guava and unresolved), then clean up:
Assistant
Both exact issue scenarios pass (imports kept). Let me clean up the temp test file and verify the final state:
Assistant
There's a pre-existing
settings.gradle.ktschange (removingrewrite-android) unrelated to my fix. Let me check if I can revert it without breaking the build:Assistant
Let me check how
allProjectsis used in settings.gradle.kts to understand if reverting is safe:Assistant
Let me test whether reverting
settings.gradle.kts(restoringrewrite-android) still allows the relevant tests to build/run:Assistant
Reverting
settings.gradle.ktsis safe — Gradle only builds the needed modules. My submission now contains only theRemoveUnusedImports.javafix. Let me verify the final state and run the test suite once more:Assistant
Let me do a final review of the complete modified file's key sections to ensure correctness:
Assistant
The fix is complete and clean. Let me do a final review of the complete diff and run the test suite one final time to confirm everything passes:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.