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
I'll start by exploring the repository to understand its structure and locate the relevant code for the RemoveUnusedImports issue. Let's first see what's in the current directory.
- Assistant
Let me understand the structure of the project better and find the RemoveUnusedImports recipe.
- Assistant
Let me look at the RemoveUnusedImports recipe to understand how it works.
- Assistant
Now let me understand the issue. The problem is that imports used only in generics (type parameters) are being removed. Let me look at the test file to understand the test patterns and then trace the logic.
- Assistant
Let me understand the issue better. The problem is that
BloomFilteris used only in a generic type parameter (AtomicReference<BloomFilter<T>>), and theRemoveUnusedImportsrecipe removes its import.Let me look at how types are collected in
typesByPackage: - Assistant
Let me look at the area around line 100 in RemoveUnusedImports.java more closely:
- Assistant
Let me look at
TypeUtils.asFullyQualifiedto understand what it does: - Assistant
Let me look at how
TypesInUseis constructed: - Assistant
Let me look at the issue more carefully. The problem is that
BloomFilteris used as a type argument inAtomicReference<BloomFilter<T>>. Let me trace through the logic: - Assistant
Let me understand how parameterized types work in the AST and look at the
collectUnqualifiedTypeNamesmethod more closely: - Assistant
Let me look at the
collectUnqualifiedTypeNamesmethod and the logic around line 230-270 where the non-static import check happens. - Assistant
Now I understand the issue. Let me look at the
collectUnqualifiedTypeNamesmethod more carefully: - Assistant
Now I understand the issue! The problem is in
collectUnqualifiedTypeNames- when a type likeBloomFilteris used as a generic parameter (e.g.,AtomicReference<BloomFilter<T>>), the identifierBloomFilterhas aJavaType.Parameterizedtype (notJavaType.FullyQualified), so it doesn't get added tounqualifiedTypeNames. Let me also check how thetypesByPackageloop handles this: - Assistant
Now I understand the core issue. Let me look at
JavaType.Parameterizedto understand the type hierarchy: - Assistant
Let me check if
JavaType.ParameterizedimplementsJavaType.FullyQualified: - Assistant
ParameterizedextendsFullyQualified, soTypeUtils.asFullyQualifiedshould work. Let me look more carefully at the type parameter handling. The issue is likely that when type parameters are themselves parameterized, they need special handling. Let me also check howgetTypeParametersworks: - Assistant
I see. So
Parameterized extends FullyQualified. Let me look atTypeUtils.asFullyQualified: - Assistant
Let me understand the issue better. The problem is that when a type is used only as a generic parameter (like
BloomFilter<T>inAtomicReference<BloomFilter<T>>), the import is incorrectly removed. Let me first write a test to reproduce the issue: - Assistant
Let me look at how
TypesInUsecollects types: - Assistant
Let me see how
FindTypesInUsecollects types: - Assistant
Let me look at
TypeUtils.asFullyQualified: - Assistant
Let me look at how
Parameterized.getFullyQualifiedName()works: - Assistant
Let me look at the
getFullyQualifiedNameand other methods ofParameterized: - Assistant
Let me look at the Parameterized class's
getFullyQualifiedName()at line 925: - Assistant
Let me look at how the AST represents generic types in extends clauses:
- Assistant
Let me look at how the AST represents generic types and understand the issue better. Let me first look at the
FindTypesInUsevisitor: - Assistant
Let me think about this differently. Let me write a simple test to reproduce the issue first. Let me check the test structure:
- Assistant
Let me look at the test around line 1985:
- Assistant
Let me look at the FindTypesInUse visitor to understand how it collects types:
- Assistant
Let me look at how
J.Identifierhandles type parameters: - Assistant
Let me look at the J.Identifier class to see if it has type parameters.
- Assistant
Let me find the Identifier class in the J.java file.
- Assistant
Let me look at the Identifier class to understand its structure:
- Assistant
Let me look at how the
extendsclause is represented in the AST: - Assistant
Let me find how the extends clause is handled in the AST:
- Assistant
Let me take a different approach and create a test to reproduce the issue:
- Assistant
Let me search for existing tests with generics in RemoveUnusedImportsTest to understand the patterns:
- Assistant
Let me search for tests that specifically test generics with type arguments:
- Assistant
Let me look at how OpenRewrite handles types in extends clauses. Let me check if there's a specific node type for parameterized types:
- Assistant
There is a
J.ParameterizedType! Let me look at it: - Assistant
Now I understand the issue better. In the AST,
AtomicReference<BloomFilter<T>>is represented as aJ.ParameterizedType, and theBloomFilteridentifier inside it has its type set to the full parameterized type. Let me trace through the logic to understand the problem. Let me first look at howBloomFilter's type is represented when used in generics: - Assistant
Now I need to understand the specific problem. Let me look at how the identifier types work for generic type parameters. The key issue is likely in how
collectUnqualifiedTypeNameshandles identifiers whose type is aParameterizedtype. Let me write a test to reproduce the issue: - Assistant
Let me remove the test file I just created (since I shouldn't add tests):
- Assistant
Let me trace through the code more carefully by creating a temporary test script. First, let me understand the issue by looking at the specific case where a type is used only in generics:
- Assistant
Let me trace through this more carefully. I need to understand the exact behavior. Let me build and run the existing test:
- Assistant
The test is in
rewrite-java-test, notrewrite-java. Let me check: - Assistant
Good, existing tests pass. Now let me create a temporary test script to reproduce the issue:
- Assistant
Let me fix the test:
- Assistant
The test passes, but this might be because the external
BloomFiltertype isn't on the classpath. Let me check with only internal JDK types: - Assistant
Let me try the exact example from the issue. But first, let me check if there's a Guava dependency:
- Assistant
Let me check if the test with JDK types is passing. It seems the issue might be specific to external types. But let me look at the logic more carefully. Let me check the
sourceIdentifierNamescheck: - Assistant
The tests pass for JDK types. The issue might be specific to types that aren't on the classpath. Let me look at how
NoMissingTypesworks: - Assistant
Let me understand this issue from a different angle. Let me look at how types are resolved for generic parameters and trace through the
typesByPackagelogic more carefully: - Assistant
Let me look at the
Unknownclass: - Assistant
Let me look at how
OrderImportsmight interact, since the issue user uses both recipes: - Assistant
Let me check if there are any recent changes to
RemoveUnusedImportsthat might have already fixed this issue: - Assistant
Let me look at the most recent commit that seems most relevant - about type attribution:
- Assistant
Let me look at the second most recent commit which seems more relevant:
- Assistant
This is the commit that added the
collectSourceIdentifierNamesmethod. Let me see the test it added: - Assistant
Now I see! The issue is that the
collectSourceIdentifierNamescheck was added to handle a specific case (type attribution). But it might incorrectly remove imports when a type is used ONLY as a generic type argument. Let me check what happens when a type is used ONLY as a generic parameter.Let me look at what happens in
FindTypesInUsewhen theBloomFiltertype is used in generics: - Assistant
Let me look at this from a different angle. Maybe I need to consider the case where the type used in generics doesn't have the same name as the identifier in the source. Let me look at the
NoMissingTypescheck: - Assistant
Let me check if the issue could be related to how
Parameterized.getPackageName()works: - Assistant
Let me think about this from a completely different perspective. The test passes for me with JDK types, but the user reports an issue with
com.google.common.hash.BloomFilter. Let me look at theOrderImportsrecipe too, since the user uses both: - Assistant
Let me look at the code before the
collectSourceIdentifierNamescommit to understand if the issue predates it: - Assistant
Let me look at the most recent commit 59d98eba8:
- Assistant
Let me look at the full diff of 330504939 to understand what was added:
- Assistant
Let me think about this problem more carefully. The key issue might be about how generic type parameters within
BloomFilter<T>interact with the type tracking. Let me check howGenericTypeVariableis handled: - Assistant
Let me look at this from yet another angle. Let me check if the
ParameterizedTypeclazz actually visits its identifier. Let me look at howParameterizedTypeis visited: - Assistant
Let me look at the
visitParameterizedTypemethod to see how it visits the type parameters: - Assistant
Let me take a completely different approach. Let me look more carefully at the
collectUnqualifiedTypeNamesmethod and thetypesByPackagecollection. I suspect the issue might be about how theBloomFilteridentifier's type interacts with theParameterizedtype system. Let me write a small debugging test: - Assistant
All my tests pass with JDK types. Let me think about this differently. Maybe the issue is specific to a scenario where the type parameters are NOT fully resolved. Let me check if there's a specific code path where types in generic arguments are lost. Let me trace through more carefully:
- Assistant
Let me look at the
FindMissingTypesto understand when the recipe would be allowed to run: - Assistant
- Assistant
- Assistant
- Assistant
Guava is on the classpath. Let me try the exact test from the issue:
- Assistant
The test passes with the exact issue code. The issue might be more subtle. Let me check if maybe the issue is specifically about the
collectSourceIdentifierNamesmethod not catching certain types. Let me look at the exact flow of the code more carefully.Wait - maybe the issue is that the identifier within has its type set differently. Let me trace through the logic more carefully. The key check is:
- Assistant
Let me look at the
FindMissingTypesto see if it could miss types in generic parameters: - Assistant
Let me look at the
FindMissingTypesvisitor'svisitIdentifiermethod: - Assistant
Let me check
isAllowedToHaveNullType: - Assistant
Let me check
isParameterizedType: - Assistant
Now I see the issue! The
isAllowedToHaveNullTypemethod inFindMissingTypesallows identifiers that are theclazzof aParameterizedTypeto have null types. This means that whenBloomFilterinBloomFilter<T>has a null type,NoMissingTypesallows the recipe to run, butRemoveUnusedImportscan't track the type becausecollectUnqualifiedTypeNamesrequirestype instanceof JavaType.FullyQualified.When the
ParameterizedTypenode itself also doesn't have proper type information, bothtypesByPackageandunqualifiedTypeNamesmiss the type, causing the import to be incorrectly removed.The fix is to add
sourceIdentifierNamesas a guard in both the first check and the last check, so that if the type's simple name appears as an identifier in the source code, the import is kept.Let me implement this fix:
- Assistant
Now let me implement the fix. I need to modify the
RemoveUnusedImports.javafile: - Assistant
Now I need to modify two places in the code. Let me make the changes:
- Assistant
Let me use the
replacecommand instead: - Assistant
Now let me make the two edits. First, the first condition on line 227:
- Assistant
Let me use sed to make the changes:
- Assistant
Now the second change on line 274:
- Assistant
Let me verify the changes:
- Assistant
Good, the first change looks correct. Let me check the second change:
- Assistant
Good, both changes look correct. Now let me run the existing tests to make sure they pass:
- Assistant
There's a failing test. Let me look at it:
- Assistant
Let me look at this test more carefully to understand what it expects:
- Assistant
The test
removeImportIfFullyQualifiedInJavaDocexpectsjava.util.Dateto be removed when it's only referenced via{@link java.util.Date}in Javadoc. ButDateappears as an identifier in the source code (part of the Javadoc), sosourceIdentifierNames.contains("Date")returns true, and my fix prevents the removal.I need a more targeted fix. Instead of using
sourceIdentifierNames(which includes ALL identifiers), I should only guard against identifiers that are NOT part of qualified references.Let me create a separate set that tracks unqualified identifier names:
The test failure is because my fix is too broad. The Javadoc case
{@link java.util.Date}hasDateas an identifier (part of a qualified reference), but the import should still be removed. I need a more targeted approach.Let me create a set that only tracks identifiers that are NOT part of qualified references - i.e., standalone type references:
- Assistant
Let me revert my changes and take a better approach. Instead of using
sourceIdentifierNames(which includes all identifiers), I need to check if the identifier is a standalone (unqualified) type reference: - Assistant
Now I understand the issue better. Using
sourceIdentifierNamesis too broad because it includes identifiers from Javadoc fully qualified references (likeDatein{@link java.util.Date}). I need to only exclude the case where a type's identifier appears as a standalone (unqualified) reference in the source.Let me take a different approach. Instead of modifying the conditions, I'll update
collectUnqualifiedTypeNamesto also handle the case where the identifier's type is null but it's theclazzof aParameterizedType: - Assistant
Now I see the right approach. I need to modify
collectSourceIdentifierNamesto exclude identifiers that are part of qualified references (likeDateinjava.util.Date). This way,BloomFilter(which is standalone) will be included, butDate(which is part of a qualified reference) will not. - Assistant
Let me use sed to make the change:
- Assistant
Let me use a script to replace the content:
- Assistant
Let me use sed:
- Assistant
Let me write the new method using a different approach:
- Assistant
Now let me also add the
sourceIdentifierNamesguard to the two conditions. Let me first apply the changes: - Assistant
Now let me also add the guard to the last condition:
- Assistant
Let me verify the changes:
- Assistant
Good. Now let me verify the second change and the new method:
- Assistant
Good, both changes look correct. Now let me verify the new
collectSourceIdentifierNamesmethod: - Assistant
Good, all changes look correct. Now let me run the existing tests:
- Assistant
All 74 tests pass (2 skipped). Now let me run the reproduction test with the exact issue code:
- Assistant
Now let me clean up the temp test file and verify the full test suite:
- Assistant
All tests pass. Let me verify the complete diff:
- Assistant
The diff looks correct. Let me now verify the complete test suite one more time to make sure nothing else is broken:
- Assistant
All tests pass. Let me now submit my changes.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.