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
I'll start by exploring the repository to understand its structure and locate the relevant code for the RemoveUnusedImports recipe. Let's first check what we're working with.
- Assistant
Let me explore the repository structure more broadly.
- Assistant
The issue is about
RemoveUnusedImportsin the Java module. Let me find the relevant source files. - Assistant
Let me look at the RemoveUnusedImports.java file first to understand the implementation.
- Assistant
Let me continue viewing the file to understand the logic.
- Assistant
Let me continue reading the file to understand the full logic.
- Assistant
Let me continue reading the file to understand how
collectUnqualifiedTypeNamesworks and to see the full logic. - Assistant
Let me look at the key methods -
collectUnqualifiedTypeNamesandcollectSourceIdentifierNames- to understand how imports are matched to their usage. - Assistant
Let me continue reading to see the
isPartOfQualifiedReferenceandcollectSourceIdentifierNamesmethods. - Assistant
Now let me look at the test file to understand existing test cases:
- Assistant
Now I understand the structure. The issue is that
BloomFilteris used in generics (BloomFilter<T>) but the import is being removed. Let me search for any existing tests related to generics: - Assistant
No results. Let me search for "extends" in the test file to find tests related to class inheritance with generics.
- Assistant
Let me check the type hierarchy of JavaType to understand how generics are represented:
- Assistant
Let me look at the JavaType class to understand the type hierarchy.
- Assistant
JavaType.Parameterized extends FullyQualified. Now let me look at howTypeUtils.asFullyQualifiedworks: - Assistant
Now I need to understand how types are detected in
typesInUse. Let me look at howgetTypesInUse()is populated: - Assistant
Let me look at how
typesInUseis populated. Let me look for a method that buildstypesInUse. - Assistant
Let me look at the
TypesInUseclass and its implementations. - Assistant
Let me look at the
TypesInUseclass to understand how it collects types. - Assistant
Let me look at the
FindTypesInUseclass to understand how types are collected. - Assistant
Let me look at FindTypesInUse to see how types are collected from the tree:
- Assistant
Let me look at FindTypesInUse class to understand how types are collected:
- Assistant
Now let me understand the issue better. I need to see how
typesInUsecollects types from generic type parameters. Let me write a small test to reproduce the issue first: - Assistant
Let me search for existing tests that cover generics usage in the extends clause:
- Assistant
Let me search for tests involving generic types in the test file:
- Assistant
Let me look at recent changes to RemoveUnusedImports to understand what might have changed:
- Assistant
Let me look at the most recent commit that might have introduced this issue:
- Assistant
The commit
330504939is likely the culprit. It added a check forsourceIdentifierNames. Let me look at what it changed. - Assistant
Now I understand the commit history. The key commit
330504939added thecollectSourceIdentifierNamescheck to handle imports only referenced in type attribution. Let me now check the other recent commit: - Assistant
Let me understand the type hierarchy better:
- Assistant
Let me look at the Parameterized.getFullyQualifiedName():
- Assistant
Let me first try to reproduce the issue. I'll run a simple test to understand how the types are collected:
- Assistant
Let me look at the
NoMissingTypesclass and understand the flow better: - Assistant
Let me look at the test file more carefully, searching for generic type tests:
- Assistant
Let me search for existing tests that show how the recipe handles type parameters:
- Assistant
Let me now look at the recent test added for the "type attribution" fix to understand the expected behavior:
- Assistant
Let me now look at the issue more carefully. I need to trace through the logic for the case where a type is used ONLY in generic type parameters in the extends clause. Let me write a test to reproduce the issue:
- Assistant
Let me try building and running the test to reproduce the issue:
- Assistant
Good, tests pass. Now let me write a test to reproduce the issue. Let me first look at how the test framework works:
- Assistant
Let me look at the
NoMissingTypesclass to understand the precondition: - Assistant
Let me try to reproduce the issue with a test. First, let me understand the structure of the tests better:
- Assistant
Let me now search for existing tests that involve generics in extends clauses to understand the patterns better:
- Assistant
Let me try to write a reproduction test to understand the issue better:
- Assistant
Let me try to understand the issue by examining how the AST represents the extends clause with generics. Let me look at the
J.ParameterizedTypeclass: - Assistant
Let me look at the
ParameterizedTypeclass to understand its structure: - Assistant
Let me look at how
visitParameterizedTypeworks in the JavaVisitor: - Assistant
Let me try running the existing tests to understand the behavior, and then create a targeted test:
- Assistant
Let me look at how
FindMissingTypesworks to understand the precondition: - Assistant
Let me look at
FindMissingTypesto understand how it works. - Assistant
Let me look at
FindMissingTypesVisitorto understand the precondition better: - Assistant
Let me look at the
isAllowedToHaveNullTypemethod: - Assistant
Let me look at the
isParameterizedTypeandisTypeParametermethods: - Assistant
Now I understand the issue. Let me trace through the code for the specific case where
BloomFilteris used only as a generic type parameter:-
In
FindMissingTypes.isAllowedToHaveNullType,isParameterizedType(ident)returnstruefor theBloomFilteridentifier inBloomFilter<T>, soNoMissingTypespasses even whenBloomFilter's type is null. -
When
BloomFilter's type is null:FindTypesInUse.visitTypeskips it → not intypesInUsetypesByPackagedoesn't haveBloomFilter→combinedTypesis emptycollectUnqualifiedTypeNamesdoesn't add it (type is null, notFullyQualified)
-
The first condition removes the import:
combinedTypes.isEmpty() && !unqualifiedTypeNames.contains(...)=true && true -
The
sourceIdentifierNamescheck (which WOULD catch this) is never reached because the first condition already triggered.
The fix: add
sourceIdentifierNamescheck to both the first condition and the lastnoneMatchcondition. -
- Assistant
Now I understand the root cause. The issue is:
-
For
BloomFilterinextends AtomicReference<BloomFilter<T>>, theBloomFilteridentifier (asclazzof aParameterizedType) is allowed to have a null type byFindMissingTypes.isAllowedToHaveNullType→isParameterizedType(ident)returns true. -
When the type is null:
typesInUsedoesn't containBloomFilter→typesByPackageis empty →combinedTypes.isEmpty()is truecollectUnqualifiedTypeNamesdoesn't add it (type is null) →!unqualifiedTypeNames.contains(...)is true- First condition evaluates to
true && true= true → import removed
-
The
sourceIdentifierNamescheck (which DOES contain "BloomFilter") is at line 264 but is never reached because the first condition already removed the import.
The fix: Add
sourceIdentifierNamescheck to the first condition (line 227) and the last condition (line 269-274). -
- Assistant
Now I'll apply the fix. I need to add
sourceIdentifierNameschecks to both the first condition (line 227) and the last condition (lines 269-274): - Assistant
Let me use the special edit command:
- Assistant
Now let me update the last condition (lines 269-274):
- Assistant
Good, now let me verify the changes are correct by looking at both modified lines:
- Assistant
Now let me run the existing tests to make sure my changes don't break anything:
- Assistant
One test failed. Let me look at the failing test:
- Assistant
I see the issue. The
removeImportIfFullyQualifiedInJavaDoctest expectsDateto be removed, butDateappears insourceIdentifierNamesvia Javadoc. I need a more targeted fix - instead ofsourceIdentifierNames, I should track identifiers that appear as unqualified type references even when their type is null. - Assistant
Let me revert and take a better approach. I need to modify
collectUnqualifiedTypeNamesto also track simple names for identifiers with null types that are still used as type references: - Assistant
Let me take a cleaner approach. I'll modify
collectUnqualifiedTypeNamesto also return simple names of identifiers that have null type but are not part of qualified references: - Assistant
I need to modify the approach. Let me change
collectUnqualifiedTypeNamesto also track identifiers with null type that are used as unqualified type references: - Assistant
Good. Now let me update the first condition to use
unqualifiedIdentifierSimpleNames: - Assistant
The file seems corrupted. Let me check the current state:
- Assistant
The file got corrupted. Let me reset and start over:
- Assistant
Let me verify the file is clean and then make changes carefully:
- Assistant
Good, file is clean. Let me now implement the fix properly. The key insight is that
collectUnqualifiedTypeNamesneeds to also track identifiers with null type that are used as type references (like theclazzof aParameterizedType). I'll modify the method to also collect simple names for these cases: - Assistant
Let me take a cleaner approach. I'll modify
collectUnqualifiedTypeNamesto also track identifiers with null types that are used as unqualified type references. I'll use a wrapper class: - Assistant
Let me use sed to make the changes:
- Assistant
Now let me make the changes step by step using sed:
- Assistant
Good, now let me update the first condition (the line after
JavaType.FullyQualified qualidType = ...): - Assistant
The insertion was in the wrong place. Let me fix this by restoring and doing it correctly:
- Assistant
Let me open the file and make changes carefully with proper line numbers:
- Assistant
Let me escape the
!character. - Assistant
Now I know the exact line numbers. Let me make the changes step by step:
- Assistant
Now let me add the new set declaration after line 78:
- Assistant
I need to add a blank line after the new code. Let me fix that:
- Assistant
Good. Now let me update the first condition. Let me find the exact line number:
- Assistant
Good, line 232. Let me update it.
- Assistant
Now let me update the last condition (line 279):
- Assistant
Good. Now I need to add the new
collectUnqualifiedIdentifierSimpleNamesmethod. Let me find the right place: - Assistant
Let me add the new method before the closing brace of the inner class:
- Assistant
I need to add the new method between line 544 (
}) and line 545 (}). Let me insert it there. - Assistant
Good. Now let me verify all the changes look correct by checking the diff:
- Assistant
Good, the diff looks correct. Now let me run the tests:
- Assistant
All 74 tests pass! Let me also run the OrderImports tests since the issue mentions it in the configuration:
- Assistant
All tests pass. Let me clean up the backup file:
- Assistant
Let me also run the broader Java tests to make sure nothing is broken:
- Assistant
All tests pass. Let me also clean up the backup file:
- Assistant
Let me do a final review of the changes:
- Assistant
There's an unexpected change to settings.gradle.kts. Let me check what that is:
- Assistant
Let me revert the unrelated change to settings.gradle.kts:
- Assistant
Now let me verify only my intended changes remain:
- Assistant
Good, only the intended file is changed. Let me run the tests one final time to confirm everything passes:
- Assistant
All tests pass. Let me clean up temporary files:
- Assistant
Now let me do a final review of the complete diff to make sure everything is correct:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.