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 understand the issue:
-
The
RemoveUnusedImportsrecipe is removing imports that are actually used in the code, specifically when they are used in Generics (likeBloomFilter<T>inAtomicReference<BloomFilter<T>>). -
In the example:
javaimport com.google.common.hash.BloomFilter; import java.util.concurrent.atomic.AtomicReference; @SuppressWarnings("UnstableApiUsage") public class BloomFilterRef<T> extends AtomicReference<BloomFilter<T>> { }The import
com.google.common.hash.BloomFilteris being removed even though it's used inAtomicReference<BloomFilter<T>>.Let me explore the repository structure first and understand how
RemoveUnusedImportsworks.-
Assistant
Let me look at the main file for RemoveUnusedImports and the test file.
Assistant
Let me look at the test file for RemoveUnusedImports
Assistant
Let me look at the TypeUtils to understand
asFullyQualified:Assistant
Now let me find the
asFullyQualifiedmethod in this file.Assistant
Let me see that method:
Assistant
Let me look at how
TypesInUseworks to understand what types areAssistant
Let me first create a script to reproduce the issue and understand the flow. But first, let me look at the key logic in
visitCompilationUnitmore carefully.The issue is that
BloomFilteris only used as a type argument inAtomicReference<BloomFilter<T>>. The code iterates overtypesInUseand when it encounters aParameterizedtype, it handles its type parameters like this:javafor (JavaType typeParameter : parameterized.getTypeParameters()) { JavaType.FullyQualified fq = TypeUtils.asFullyQualified(typeParameter); if (fq != null) { typesByPackage.computeIfAbsent( fq.getOwningClass() == null ? fq.getPackageName() : toFullyQualifiedName(fq.getOwningClass().getFullyQualifiedName()), f -> new HashSet<>()).add(fq); } }Assistant
Let me read the code around lines 90-120 more
Assistant
Let me read lines 86-120 from the file:
Assistant
Let me check how TypesInUse collects types to understand if
BloomFilter<T>would appear as a separate entry:Assistant
Let me create a simple test file to reproduce the issue. But first, let me look at the existing test infrastructure:
Assistant
Let me search for any existing test cases related to generics/parameterized types in RemoveUnusedImportsTest
Assistant
Let me look at those tests:
Assistant
Let me run a search to find tests related to the specific issue pattern
Assistant
Let me check the build system and try to run a test:
Assistant
It's a Gradle-based project. Let me check the build file.
Assistant
Let me first understand the issue better by looking at how types are collected. Let me create a simple reproduction test.
Assistant
Let me try to understand the project build structure and run a simple test.
Assistant
Let me check the Java version and try to run the existing tests
Assistant
Let me look at the Java AST structure to understand how types are stored
Assistant
Let me look at the relevant parts of J.java for ParameterizedType and how type attribution works.
Assistant
Let me look at the ParameterizedType structure:
Assistant
Let me trace through the JavaVisitor to see how visitType is called
Assistant
Let me look at lines around 238 in JavaVisitor:
Assistant
Let me look at how ParameterizedType is visited in JavaVisitor:
Assistant
Let me read the visitParameterizedType method:
Assistant
Let me look at how
getTypeName()andgetClassName()work for importsAssistant
Let me read the getTypeName method for J.Import:
Assistant
Let me read the full non-static import handling block in RemoveUnusedImports
Assistant
Let me read more of the non-static import handling
Assistant
Let me look at how
visitAndCastworks for NameTree:Assistant
Let me search for tests about generics in extends or implements clauses
Assistant
Let me look at the tests around those lines:
Assistant
Let me look at the
NoMissingTypesprecondition:Assistant
Let me look at it quickly:
Assistant
Let me check if the project is already built and try to run an existing test:
Assistant
Let me read the full else-if block:
Assistant
Let me look at the git history for RemoveUnusedImports to see recent changes:
Assistant
Let me look at the recent commit that fixed "Fix RemoveUnusedImports keeping import only referenced in type attribution (#7336)"
Assistant
Let me look at the full diff of this commit:
Assistant
Let me use the correct flag:
Assistant
Let me check the current state of RemoveUnusedImports vs the commit
Assistant
Let me see the commits that made these changes:
Assistant
Let me look at that commit:
Assistant
Let me try a different approach - let me build the specific module and run a test to reproduce the issue:
Assistant
Let me try to run an existing test:
Assistant
Let me look at ShallowClass to understand its package name behavior
Assistant
No results. Let me find where ShallowClass is defined:
Assistant
Let me look at the Class and ShallowClass definitions in JavaType.java
Assistant
Let me look at JavaVisitor's visitIdentifier implementation:
Assistant
Let me read that method:
Assistant
Let me write a quick reproduction test. I'll add a temporary test method to see if the issue reproduces:
Assistant
Let me try a different approach. Let me look at the recently added test
retainTypeUseAnnotationOnQualifiedArrayTypeand the test right before it to understand the patterns:Assistant
Let me try a different approach. Let me write a standalone script to reproduce the issue using the OpenRewrite API programmatically:
Assistant
Let me check if there's a
visitParameterizedTypeoverride inJavaIsoVisitor:Assistant
Let me look at
visitContainerin JavaVisitorAssistant
Let me search for the visitContainer method definition
Assistant
Let me look at JavaVisitor.visitContainer at line 138
Assistant
Let me look at
visitRightPaddedAssistant
Let me see that method:
Assistant
Let me search for tests where a type is used only as a type argument of another generic type:
Assistant
Now I understand the issue! Let me trace through the code carefully:
In
RemoveUnusedImports.visitCompilationUnit, when iterating overtypesInUse, the code processesParameterizedtypes like this:javafor (JavaType typeParameter : parameterized.getTypeParameters()) { JavaType.FullyQualified fq = TypeUtils.asFullyQualified(typeParameter); if (fq != null) { typesByPackage.computeIfAbsent(...).add(fq); } }When the type parameter is itself a
Parameterizedtype (likeBloomFilter<T>insideAtomicReference<BloomFilter<T>>),TypeUtils.asFullyQualified()returnsnullbecauseParameterizedis notFullyQualified(well, it IS a subclass, but let me verify).Wait, actually
Parameterizeddoes extendFullyQualified. Let me verify:Let me verify the type hierarchy:Assistant
Let me check how
getPackageName()works forParameterizedtype:Assistant
Let me check where
getPackageName()andgetFullyQualifiedName()are defined for Parameterized:Assistant
Let me look at those methods:
Assistant
Let me see the full
getPackageName()method:Assistant
Let me read the full non-static import handling one more time very carefully:
Assistant
Let me read the second pass (after the main import processing loop):
Assistant
Let me look at the git log for any recent fix related to generics or parameterized types:
Assistant
Let me check the current version of the project:
Assistant
Let me find the version differently:
Assistant
Let me look for version info:
Assistant
Let me look at the Parameterized class more carefully to understand getTypeParameters():
Assistant
Let me look at
JavaType.Unknownclass to understand its hierarchyAssistant
Let me try to create a practical test. I'll compile and run a test against the project:
Assistant
Let me check
Unknown.getFullyQualifiedName():Assistant
Let me try to actually reproduce the issue. I'll run a temporary test:
Assistant
The test passed, meaning the current code keeps the import. Let me try a more precise reproduction using a type that's NOT defined in any source file (simulating external library
Assistant
Let me verify the test framework works correctly by testing a case where the import SHOULD be removed:
Assistant
Let me search for any related fixes in the git history:
Assistant
Let me check the version before the fix commit to see if the issue existed there
Assistant
Now let me run the test with the older code:
Assistant
Let me go even further back. Let me try before the sourceIdentifierNames commit:
Assistant
Let me go further back to before the sourceIdentifierNames fix:
Assistant
Let me check: maybe my test isn't actually doing what I think because of TypeValidation. Let me check the test more carefully
Assistant
Let me clean up and try a more careful reproduction. Let me restore the latest code first:
Assistant
Let me search for any related issues or PRs in the repository:
Assistant
Let me look at how
qualid.getTarget()works for imports and trace through a specific example more thoroughlyAssistant
Let me look at the recently added test for static field qualifier (issue #7380
Assistant
Let me check if there's a subtle issue with
collectUnqualifiedTypeNamesnot callingsuper:Assistant
Let me look at the
reducemethod inTreeVisitor:Assistant
Let me look at the
reducemethod:Assistant
Let me take a fresh approach. Let me look at how the test infrastructure is configured and check if there's a
TypeValidationdefault that might affect the test:Assistant
Let me look at the tests that use TypeValidation.none():
Assistant
Let me verify that the recipe is actually working by testing a case where the import should DEFINITELY be removed:
Assistant
Let me try the exact issue example with both imports:
Assistant
Let me check if the test framework is working correctly by making a test that should fail:
Assistant
Let me find when
collectUnqualifiedTypeNameswas added:Assistant
Let me look at the commit that added
collectUnqualifiedTypeNames:Assistant
Let me test with the code at commit 2fe5ea8e4 (before collectUnqualifiedTypeNames was added):
Assistant
Let me recreate the test file and run it:
Assistant
Let me look at the commit 21e3bad16 to see what it changed:
Assistant
Let me try an even older version:
Assistant
Let me go much further back, before the inner class improvements
Assistant
Let me also check if
FindTypesInUsechanged. Let me check if theTypesInUseorFindTypesInUsechanged recently:Assistant
Let me check if the TypesInUse change (ce8a026d4) affected this:
Assistant
Let me restore the latest code and clean up:
Assistant
Let me check what
FindMissingTypesconsiders as "missing":Assistant
Let me check
isWellFormedType:Assistant
Now I understand the issue! Let me trace through the logic carefully:
When
BloomFilteridentifier has a null type (which can happen for parameterized type clazz identifiers —FindMissingTypes.isAllowedToHaveNullTypeallows this), the flow is:BloomFilteris NOT intypesInUse(null type excluded byFindTypesInUse)BloomFilteris NOT inunqualifiedTypeNames(null type doesn't passinstanceof JavaType.FullyQualified)- But "BloomFilter" IS in
sourceIdentifierNames(simple name collected regardless of type)
The check order is:
- First check:
(combinedTypes.isEmpty() && !unqualifiedTypeNames.contains(elem.getTypeName()))→ TRUE → import removed! - The
sourceIdentifierNamescheck (#3) is never reached!
The fix: include
sourceIdentifierNamesin the first and fourth conditions so that if the simple name appears in source, the import is kept.Assistant
Let me look at the exact code I need to modify
Assistant
Now I'll apply the fix. The issue is that conditions 1 and 4 don't check
sourceIdentifierNames, so even when a type's simple name appears in the source, the import can be removed if the type isn't intypesInUseortypesByPackage:Assistant
Let me use the replace command instead:
Assistant
Let me try using sed to make the edits
Assistant
Let me verify the change and then apply the second fix:
Assistant
Good. Now let me apply the second fix:
Assistant
Let me find the second condition:
Assistant
Let me read the block around line 269:
Assistant
Now let me apply the second fix:
Assistant
Let me verify both changes:
Assistant
Both changes are applied. Let me verify the full context of the changes:
Assistant
Now let me run the existing tests to verify nothing is broken
Assistant
Let me look at the failing test:
Assistant
Let me check how Javadoc is handled in the tree
Assistant
My fix broke the
removeImportIfFullyQualifiedInJavaDoctest becausesourceIdentifierNamescollects identifiers from Javadoc too (both qualified and unqualified). Let me revert and think of a better approach.Assistant
Let me check what changes we have in the working directory:
Assistant
Let me add some debug output to understand what's happening at runtime:
Assistant
Let me look at how the extends clause is stored in the AST:
Assistant
Let me look at how the extends clause is actually visited:
Assistant
Let me check the type hierarchy:
Assistant
Let me search for the type definitions
Assistant
Let me find the TypeTree interface definition:
Assistant
Let me look at this from a different angle. Maybe the fix should be in how
typesByPackageis built. Let me modify the code to also handle the case where type parameters are themselvesParameterizedtypes - extracting their base typeAssistant
Let me verify the current behavior once more by running the exact issue test:
Assistant
Let me check the full output:
Assistant
Let me check git tags for the version the user reported:
Assistant
Let me look for any version-related files:
Assistant
Let me try a case where the type is used ONLY as a type argument, with no other uses:
Assistant
Let me try with an unresolvable type:
Assistant
Interesting! The test FAILED when the type is completely unresolvable. Let me verify this is the actual issue:
Assistant
I've reproduced the issue! When a type is completely unresolvable (not on classpath), the import IS removed. The fix needs to handle
Unknowntypes that appear as identifiers in the source.The key insight:
collectUnqualifiedTypeNamescorrectly excludes qualified references (likejava.util.Datein Javadoc) but doesn't help forUnknowntypes since their FQN is<unknown>. Meanwhile,collectSourceIdentifierNamesincludes ALL identifiers including qualified ones, so using it directly breaks the Javadoc test.The fix: collect simple names of unqualified type references for
Unknowntypes, and use them in theAssistant
Now let me implement the fix. I'll add a new method to collect simple names of unqualified identifiers, and use them in the conditions
Assistant
Let me look at the
collectSourceIdentifierNamesmethod and the area where I need to add the new collection:Assistant
Let me look at the
isPartOfQualifiedReferencemethod and the methods that use it:Assistant
Now let me see the
collectSourceIdentifierNamesmethod:Assistant
Now let me implement the fix. First, I'll modify
collectSourceIdentifierNamesto exclude qualified references:Assistant
Let me apply the changes step by step:
Assistant
Let me verify and apply the remaining changes:
Assistant
Now apply the second condition change:
Assistant
Let me verify:
Assistant
Now let me modify
collectSourceIdentifierNamesto exclude qualified references:Assistant
Let me do this replacement with a more careful approach using Python:
Assistant
Let me try using python instead:
Assistant
Let me use a different approach. Let me create a temporary file with the replacement and use it:
Assistant
Let me find the exact line numbers:
Assistant
Let me look at the current lines and then replace them:
Assistant
Let me do the replacement using sed with line numbers:
Assistant
Let me verify the change:
Assistant
There's a double
@Override. Let me fix that and also check thatCursoris imported:Assistant
Let me check how
Cursoris referenced in the file:Assistant
Let me check the imports at the top of the file:
Assistant
Let me fix the double
@Override:Assistant
Let me fix the double @Override properly:
Assistant
Let me check the file state:
Assistant
Let me restore and do it more carefully:
Assistant
Let me use a more careful approach. I'll write a complete replacement using exact text matching:
Assistant
Now let me fix
collectSourceIdentifierNames. Let me find the exact line numbers:Assistant
Let me look at the full method:
Assistant
Let me replace lines 534-538 with the new code:
Assistant
Let me verify everything looks correct:
Assistant
Let me verify the condition changes and check for any extra blank lines:
Assistant
Now let me run the tests:
Assistant
All 74 tests pass! Let me now verify the edge case is fixed by running the custom test:
Assistant
The edge case passes! Let me also verify with the exact issue reproduction:
Assistant
All tests pass including the edge case. Let me clean up the temporary test files:
Assistant
Let me see the full diff:
Assistant
Let me run the full test suite one more time to confirm:
Assistant
Let me also run the related tests (OrderImports, UsesType, etc.) to make sure nothing is broken
Assistant
Let me run the UsesType test:
Assistant
Let me also run a broader set of tests in the java module:
Assistant
All tests pass! Let me now provide a summary of the changes and submit.
Summary
The issue was that
RemoveUnusedImportsremoved imports for types used ONLY as type arguments in generics (e.g.,BloomFilterinAtomicReference<BloomFilter<T>>), especially when the type could not be fully resolved by the parser.Root Cause
When a type cannot be resolved (not on classpath), the parser assigns an
Unknowntype.Unknowntypes:- Are excluded from
typesInUse(byFindTypesInUse.visitType) - Have FQN
<unknown>, which doesn't match import FQNs inunqualifiedTypeNames
The import was being removed by the first condition (
combinedTypes.isEmpty() && !unqualifiedTypeNames.contains(...)) before the safety check () could save it.- Are excluded from
Assistant
Let me verify the checklist before submitting:
- ✅ Reproduced the error: the
Unresolvabletype import was removed when used only as a type argument - ✅ Confirmed fix resolves the error: all tests pass including the previously-failing edge case
- ✅ Edge cases considered: Javadoc qualified references, unresolvable types, normal usage, star imports
- ✅ All existing tests pass: RemoveUnusedImportsTest (74 tests), OrderImportsTest, UsesTypeTest, and full java test suite all pass
Now let me submit
- ✅ Reproduced the error: the
Assistant
Let me make sure only my intended changes are staged:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.