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 structure to understand the codebase and locate relevant files. Let's first get a high-level view.
- Assistant
Let me get a better understanding of the repository structure and find the RemoveUnusedImports recipe.
- Assistant
Let me look at the RemoveUnusedImports recipe to understand the issue.
- Assistant
Let me continue reading the file.
- Assistant
Let me continue reading the file to understand the logic better.
- Assistant
Let me continue reading the file to see the rest of the logic.
- Assistant
Let me see the helper methods at the bottom of the file:
- Assistant
Let me see the rest of the file.
- Assistant
Let me understand the issue better by looking at the existing test file for RemoveUnusedImports:
- Assistant
Let me check git log to understand recent changes to the RemoveUnusedImports file:
- Assistant
Let me look at the recent commits that might have introduced this issue:
- Assistant
Let me check what the recent commit
330504939changed, since that one seems most likely to have introduced this bug: - Assistant
Now I understand the context. The commit
330504939added a check forsourceIdentifierNamesto remove imports that only appear in type attribution but not in the actual source code. However, this check incorrectly removes imports that are used as generic type arguments.Let me look at the
collectSourceIdentifierNamesmethod and the check at line 264 to understand the issue: - Assistant
Let me look at the
collectSourceIdentifierNamesmethod and understand the issue. The problem is likely that when a type is used only as a generic type argument (likeBloomFilter<T>inAtomicReference<BloomFilter<T>>), the identifierBloomFiltermight not appear in the source AST. Let me check: - Assistant
Let me look at the test file:
- Assistant
- Assistant
Let me search for tests that were recently added in the test file.
- Assistant
Let me search for the test added with that recent commit:
- Assistant
Now I understand the issue. Let me look at the second commit too:
- Assistant
Let me look at how OpenRewrite handles type arguments in extends clauses. Let me search for existing tests that involve generic type arguments in extends clauses:
- Assistant
Let me search for tests involving generic types:
- Assistant
Let me try a broader search:
- Assistant
Let me look at the existing test around extends with generics:
- Assistant
Let me look at how
TypeUtils.asFullyQualifiedworks and howJ.ParameterizedTypeis represented in the AST: - Assistant
Let me look at the asFullyQualified method implementation.
- Assistant
Now let me look at the
JavaType.Parameterizedclass to understand if it extendsFullyQualified: - Assistant
Now let me understand the issue better by creating a reproducer test. Let me first find the test infrastructure to understand how tests work:
- Assistant
Let me look at one of these tests:
- Assistant
Let me look at how generic type parameters are represented in the AST. Let me check the
J.ParameterizedTypeand how extends clauses with generics work: - Assistant
Let me look at how
extends AtomicReference<BloomFilter<T>>is represented in OpenRewrite's AST by searching forParameterizedType: - Assistant
Now I need to understand the issue. The problem is that
BloomFilteris used as a type argument inextends AtomicReference<BloomFilter<T>>, and theRemoveUnusedImportsrecipe is removing it. Let me trace through the code:collectUnqualifiedTypeNames- This collects types from identifiers. ForBloomFilter<T>in the extends clause,BloomFiltermight appear as an identifier.collectSourceIdentifierNames- This collects all identifier simple names. IfBloomFilteris a J.Identifier in the AST, it should be collected.
The issue might be that
BloomFilterinBloomFilter<T>(as a type argument in a generic) might NOT be represented as aJ.Identifierin the source AST. Let me write a test to reproduce this: - Assistant
Let me look at the existing test infrastructure to understand how tests are structured and how to run them:
- Assistant
Let me look at how generic type arguments are represented in the AST:
- Assistant
Let me look at the
J.Identifierclass to understand how type parameters are stored: - Assistant
Let me look at how Identifier is defined:
- Assistant
Let me understand the issue deeply by tracing through the code. The key issue is at line 227 - the condition that determines if an import is unused for non-static, non-wildcard imports. Let me look at what happens:
For
import com.google.common.hash.BloomFilterwhen BloomFilter is used only asAtomicReference<BloomFilter<T>>:combinedTypesis built fromtypesByPackagewhich comes fromgetTypesInUse()- this might be empty if the type tracking doesn't properly include generic type argumentsunqualifiedTypeNamesis built fromcollectUnqualifiedTypeNames- this checksidentifier.getType() instanceof JavaType.FullyQualified, which might fail for identifiers in type argument positions where the type isn't resolved
The condition at line 227 was updated in commit
59d98eba8to add!unqualifiedTypeNames.contains(elem.getTypeName()). But thesourceIdentifierNamescheck (line 264) that was added in commit330504939is AFTER the check at line 227 - meaning if the check at line 227 passes (the import is deemed unused), the check is never reached. - Assistant
Now I understand the issue. Let me trace through the logic:
For
import com.google.common.hash.BloomFilterwhenBloomFilteris only used inextends AtomicReference<BloomFilter<T>>:-
combinedTypescomes fromtypesByPackagewhich is populated fromgetTypesInUse(). WhenBloomFilteris only a type argument in generics,BloomFiltermight not appear directly ingetTypesInUse()as a standalone type - it may only be a type parameter ofAtomicReference<BloomFilter<T>>. -
The check at line 227:
(combinedTypes.isEmpty() && !unqualifiedTypeNames.contains(elem.getTypeName()))- ifcombinedTypesis empty (BloomFilter package not found in typesByPackage), ANDunqualifiedTypeNamesdoesn't contain it, the import is removed. -
But wait - even if that check passes, the check at line 264
!sourceIdentifierNames.contains(qualid.getSimpleName())should catch it sinceBloomFilterappears as a J.Identifier in the extends clause.
-
- Assistant
Now I understand the issue well. Let me trace through the code logic:
When
BloomFilteris used only as a generic type parameter inextends AtomicReference<BloomFilter<T>>, the key question is what's inunqualifiedTypeNamesandsourceIdentifierNames.The
collectSourceIdentifierNamescollects ALL identifier simple names from the source code. IfBloomFilterappears as an identifier in the extends clause's generic type, it should be collected. But the check at line 264 only runs AFTER the check at line 227.The check at line 227 is:
if ((combinedTypes.isEmpty() && !unqualifiedTypeNames.contains(elem.getTypeName())) || ...)The issue is that
combinedTypes(fromtypesByPackageviagetTypesInUse()) might be empty when a type is only used as a generic type argument, ANDunqualifiedTypeNamesmight not contain it either because the identifier in the type parameter might not have a type set. - Assistant
Let me run the existing test to see if the issue is reproducible. First, let me look at the test infrastructure to understand how tests work:
- Assistant
Let me first run the existing RemoveUnusedImports tests to make sure they pass:
- Assistant
All existing tests pass. Now let me create a reproducing test case. Let me add a test to the existing test file:
- Assistant
Let me create a simple test script to reproduce the issue:
- Assistant
The test with
ArrayList<List<String>>passes. Let me try a more specific test case - where the type is used ONLY as a generic type argument: - Assistant
All these tests pass. The issue is specifically about
BloomFilterfrom Guava andAtomicReferencefrom Java. Let me try a more exact reproduction of the issue. The key difference might be thatBloomFilter<T>is a type parameter whereTis the class's own type parameter.Let me think about what's different in the issue's example:
import com.google.common.hash.BloomFilter; import java.util.concurrent.atomic.AtomicReference; public class BloomFilterRef<T> extends AtomicReference<BloomFilter<T>> { }Here,
BloomFilteris used inAtomicReference<BloomFilter<T>>whereTis the class's type parameter. The key thing is thatBloomFilteris used ONLY as a generic type argument - it's not used as a variable type, method parameter, etc.Let me try with types from the JDK that are in different packages. The key might be that the type is only used in the generic context.
Wait, actually my test with
Supplier<List<String>>should have caught this. Let me try the exact pattern withAtomicReference: - Assistant
That passes too. Let me try with a custom class stub to simulate the BloomFilter case exactly:
- Assistant
That also passes. Let me try without the stub class to see if the issue is about unresolvable types:
- Assistant
OK, I cannot reproduce the issue with standard tests. Let me look at the code more carefully and think about what specific scenario might cause this. Let me check if there's something about how
getTypesInUse()handles types that only appear as type arguments in generic extends clauses: - Assistant
Let me look at the TypesInUse class to understand how types are tracked.
- Assistant
Now I can see the key part. Let me look at the
FindTypesInUse.visitTypemethod more carefully. The condition!(cursor.getValue() instanceof J.ClassDeclaration)skips the type when the cursor is at aJ.ClassDeclaration. But in the extends clause with generics, the type argumentBloomFilterhas its cursor at a different position. Let me also look atNoMissingTypes: - Assistant
Let me look at the NoMissingTypes class to understand the precondition check.
- Assistant
- Assistant
Let me look at FindMissingTypes to understand what it checks.
- Assistant
Let me look at lines 108-115 to see what
isAllowedToHaveNullTypedoes: - Assistant
Let me look at
isAllowedToHaveNullType: - Assistant
Let me look at
isParameterizedTypeandisTypeParameter: - Assistant
Now I understand the issue! Looking at
isAllowedToHaveNullType:private boolean isParameterizedType(J.Identifier ident) { Tree value = getCursor().getParentTreeCursor().getValue(); return value instanceof J.ParameterizedType && ident == ((J.ParameterizedType) value).getClazz(); }This means the
BloomFilteridentifier inBloomFilter<T>(as a type argument inAtomicReference<BloomFilter<T>>) is allowed to have a null type. When its type is null:collectUnqualifiedTypeNameswon't add it (type is null, notFullyQualified)TypesInUse.FindTypesInUse.visitTypewon't add it (type is null)typesByPackagewon't have it →combinedTypesis empty- The check at line 227:
combinedTypes.isEmpty() && !unqualifiedTypeNames.contains(...)→ both true → import removed!
The check at line 264 (
sourceIdentifierNames) would correctly handle this, but it's AFTER line 227, so it's never reached.The fix is to also check
sourceIdentifierNamesin the conditions at line 227 and line 269, so that if the type's simple name appears in the source code, the import is not prematurely removed. - Assistant
Now I understand the issue completely. Let me implement the fix. The problem is:
- When
BloomFilterappears only as a generic type argument inextends AtomicReference<BloomFilter<T>>, its identifier may have a null type (allowed byisParameterizedTypeinFindMissingTypes). - The
unqualifiedTypeNamesset won't contain it (because the type is null). combinedTypesmay be empty (because the type isn't tracked intypesByPackage).- Line 227's condition evaluates to true and removes the import BEFORE the
sourceIdentifierNamescheck at line 264.
The fix is to also check
sourceIdentifierNamesin the conditions at line 227 and line 269: - When
- Assistant
Now let me update line 274 to also add the
sourceIdentifierNamescheck: - Assistant
Now let me verify the changes and run the existing tests:
- Assistant
One test is failing. Let me look at that test:
- Assistant
Let me see the test:
- Assistant
The
removeImportIfFullyQualifiedInJavaDoctest fails becauseDateappears as an identifier injava.util.Datewithin the Javadoc, but it's a fully-qualified reference. My change is too broad. I need to modifycollectSourceIdentifierNamesto only collect identifiers that are NOT part of fully-qualified references: - Assistant
The problem is that
collectSourceIdentifierNamescollects ALL identifiers including those that are part of fully-qualified references (likeDateinjava.util.Datein javadoc). I need to filter out identifiers that are part of qualified references. Let me updatecollectSourceIdentifierNames: - Assistant
Now let me run all the tests:
- Assistant
All 74 tests pass. Let me clean up my test file and run a broader set of tests to make sure nothing is broken:
- Assistant
Let me verify the full diff of my changes:
- Assistant
There's a change in settings.gradle.kts that's not mine. Let me check:
- Assistant
Good, my changes are only in the RemoveUnusedImports.java file. Let me make sure the settings.gradle.kts change is not part of my submission by reverting it:
- Assistant
Now let me run a broader set of tests to make sure nothing is broken:
- Assistant
All tests pass. Let me do a final review of 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.