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 the structure and locate relevant files. Let's first see what's in the current directory.
- Assistant
Let me explore the repository structure first.
- Assistant
Let me examine the main
RemoveUnusedImports.javafile first. - Assistant
Let me look at the test file for RemoveUnusedImports:
- Assistant
Now let me understand the problem better. The issue is that
RemoveUnusedImportsincorrectly removes imports when they're used only as type arguments in generics. Let me look at how the code determines if an import is used: - Assistant
Let me look at the test file to see if there's already a test for generics:
- Assistant
Let me understand the issue better. The problem is that when a type is used only as a type parameter in generics (like
BloomFilterinAtomicReference<BloomFilter<T>>), it's being incorrectly removed. Let me look at howtypesByPackageis built: - Assistant
Let me look at the
collectUnqualifiedTypeNamesmethod more carefully: - Assistant
Let me look at the collectUnqualifiedTypeNames method:
- Assistant
Let me look at the full collectUnqualifiedTypeNames method:
- Assistant
Now let me understand the flow better. The issue is that
BloomFilteris used as a generic type parameter inextends AtomicReference<BloomFilter<T>>. Let me check whatTypeUtils.asFullyQualifieddoes with parameterized types: - Assistant
Let me check how the
collectUnqualifiedTypeNamesmethod handles type references in generic type parameters. The issue might be in how it identifies types in generic contexts likeAtomicReference<BloomFilter<T>>whereBloomFilteris a type parameter. Let me look at the Identifier AST representation: - Assistant
Let me check the asFullyQualified method:
- Assistant
Let me check if
JavaType.ParameterizedextendsJavaType.FullyQualified: - Assistant
Now let me write a test to reproduce the issue:
- Assistant
Let me understand the logic better. The key part is in the non-static import check (around line 227). Let me look at the full condition:
- Assistant
Let me write a test to reproduce the issue first. Let me look at the existing test structure:
- Assistant
Let me search for tests related to generic types being preserved:
- Assistant
Let me look at the full code of
RemoveUnusedImports.javato understand the logic better, particularly the non-static import branch: - Assistant
Now let me write a small test script to reproduce the issue and understand the problem:
- Assistant
Let me look at the existing test to understand how to write a simple test to reproduce the issue:
- Assistant
Let me look at the relevant code more carefully. Let me check how
typesByPackageis built for parameterized types: - Assistant
Let me look at the
collectUnqualifiedTypeNamesmethod more closely. The issue is that when a type appears only as a generic type parameter (likeBloomFilter<T>inextends AtomicReference<BloomFilter<T>>), the identifierBloomFiltermight not be collected. Let me check how the AST looks: - Assistant
Let me first write a small test to reproduce the issue. Let me look at the end of the test file:
- Assistant
Let me look at the end of the test file to add a new test:
- Assistant
Let me first write a small test to reproduce the issue:
- Assistant
Let me first understand the code better by looking at the full
RemoveUnusedImports.javato see the logic flow, especially around thetypesByPackagecollection: - Assistant
Let me check the git history to understand recent changes:
- Assistant
Let me look at the recent fix that might have introduced this issue:
- Assistant
This is the likely culprit! The commit 330504939 added a check for
sourceIdentifierNameswhich might be incorrectly removing imports that are used in generics. Let me look at the changes in detail. - Assistant
Now I see the issue! The commit
330504939added asourceIdentifierNamescheck. Let me look at the full flow of theelsebranch for non-static imports to understand whereBloomFiltermight get incorrectly marked as unused: - Assistant
Let me check the JavaType.Parameterized class more carefully:
- Assistant
Let me now look at how the type checking works in
collectUnqualifiedTypeNames. The key issue might be that when a type likeBloomFilteris only used as a generic type argument inAtomicReference<BloomFilter<T>>, it might not be properly collected. Let me trace through the code: - Assistant
Let me write a small test to reproduce the issue. First, let me check if there are any existing tests that handle this scenario:
- Assistant
Let me run the existing tests first to see the current state:
- Assistant
Let me write a simple test script that we can run to see if the issue reproduces:
- Assistant
Now let me run this test:
- Assistant
The test passed. Let me check if the issue might be related to specific conditions. Let me examine the logic more carefully:
- Assistant
The test passed. Let me now look at the test added in commit 330504939 which introduced the
sourceIdentifierNamescheck, to understand the pattern better: - Assistant
- Assistant
My test passed, which is good. Let me investigate the issue more carefully. The issue is about
BloomFilterbeing used only in generics context. Let me check if maybe the problem is specifically about how theParameterizedTypeidentifiers are collected: - Assistant
Let me look at the
NoMissingTypesprecondition to see if it affects the behavior: - Assistant
Let me look more carefully at the
collectUnqualifiedTypeNamesmethod and trace through the logic for the exact issue scenario. I need to understand how theBloomFilteridentifier is handled inextends AtomicReference<BloomFilter<T>>: - Assistant
Let me look more carefully at the
visitParameterizedTypemethod inJavaVisitor.javato understand how it visits the children: - Assistant
Now let me look at the
NoMissingTypesclass: - Assistant
My test passes. This means the issue might be about a more specific scenario where types are not fully resolved. Let me look more carefully at the case where a type appears ONLY in a generic type parameter. Let me check if
combinedTypescan be empty in this case, which would trigger the first check that removes the import: - Assistant
Now I see the critical path. The issue is that when checking for unused imports, there are two conditions that could incorrectly remove an import used in generics:
-
Line 227:
combinedTypes.isEmpty() && !unqualifiedTypeNames.contains(elem.getTypeName())— If the type is only used as a generic type parameter,combinedTypesmight be empty andunqualifiedTypeNamesmight not have it, causing premature removal before thesourceIdentifierNamescheck. -
Lines 270-273:
combinedTypes.stream().noneMatch(...) && !unqualifiedTypeNames.contains(elem.getTypeName())— Same issue.
The
sourceIdentifierNamescheck on line 263 was designed to catch cases where the import only appears in type attribution, but it's positioned too late in theelse ifchain — it's only reached if the first condition is false. And the finalnoneMatchcheck doesn't considersourceIdentifierNameseither.Let me trace through the exact scenario more carefully. Let me look at the condition on line 227:
-
- Assistant
Let me look at how
TypesInUseis constructed: - Assistant
- Assistant
Now I understand the full picture. Let me look at the critical flow path. The issue is about a specific edge case where the first condition on line 227 can remove the import BEFORE the
sourceIdentifierNamescheck on line 263 is reached. The first condition checks:(combinedTypes.isEmpty() && !unqualifiedTypeNames.contains(elem.getTypeName()))If both
combinedTypesis empty (type not found intypesByPackage) ANDunqualifiedTypeNamesdoesn't have the type name, the import is removed. ThesourceIdentifierNamescheck never gets reached because it's in anelse ifbranch.Also, the last
noneMatchcondition (lines 270-273) similarly doesn't considersourceIdentifierNames:combinedTypes.stream().noneMatch(...) && !unqualifiedTypeNames.contains(elem.getTypeName())The fix is to add
sourceIdentifierNameschecks to BOTH of these conditions so that if the identifier name appears in the actual source code, the import isn't removed. Let me implement this: - Assistant
Now let me implement the fix. I need to add
sourceIdentifierNameschecks to the two conditions that can remove imports before the existingsourceIdentifierNamescheck is reached: - Assistant
Now let me make the fix. I need to modify two conditions:
- Line 227: Add
sourceIdentifierNamescheck to prevent early removal - Line 274: Add
sourceIdentifierNamescheck to prevent removal in the final condition
- Line 227: Add
- Assistant
Let me use the correct syntax:
- Assistant
Now let me also update the last condition. Let me find the line and update it.
- Assistant
Good. Now let me also update the last condition to include the
sourceIdentifierNamescheck: - Assistant
Now let me update the last condition to add
sourceIdentifierNamescheck. - Assistant
Let me verify both changes are correct:
- Assistant
Both changes are in place. Now let me run the existing tests to make sure everything passes:
- Assistant
There's a failing test. Let me look at it:
- Assistant
I see the issue - my change is too broad. The
sourceIdentifierNamesset includes identifiers from fully qualified references like{@link java.util.Date}, whereDateappears as an identifier. I need a more targeted approach. Let me revert my condition changes and instead modifycollectSourceIdentifierNamesto only include identifiers that are NOT part of qualified field access chains: - Assistant
Now let me take a different approach. The root cause is that
collectSourceIdentifierNamescollects ALL identifiers including those in fully qualified references. I need to fix it to exclude identifiers that are part of qualified references (thenamepart of aJ.FieldAccess), while still including identifiers used as unqualified type names in generics: - Assistant
Let me look at the current
collectSourceIdentifierNamesmethod: - Assistant
Now I understand the approach. I need to:
- Modify
collectSourceIdentifierNamesto exclude identifiers that are part of qualified field access chains (likeDateinjava.util.Date) - Add the
sourceIdentifierNamescheck to both the first and last conditions
Let me implement this:
- Modify
- Assistant
Now let me modify the
collectSourceIdentifierNamesmethod to exclude identifiers that are thenameof aFieldAccess(i.e., part of a qualified reference): - Assistant
Let me use sed directly:
- Assistant
Let me use the
replacecommand to make this change. - Assistant
Let me use
editto make both changes. First, let me modifycollectSourceIdentifierNames: - Assistant
Let me use sed instead.
- Assistant
Let me use perl to make the changes.
- Assistant
Let me use the edit command directly:
- Assistant
Let me use
editcommand to make the changes. - Assistant
Good. Now let me add the
sourceIdentifierNamescheck to the first condition and the last condition: - Assistant
Now let me make the two remaining changes. Let me edit line 227 and line 274.
- Assistant
Let me use sed for these changes:
- Assistant
Now let me update the last condition:
- Assistant
Let me verify all changes:
- Assistant
Good. Let me also verify the
collectSourceIdentifierNamesmethod: - Assistant
All three changes are in place. Now let me run the tests:
- Assistant
- Assistant
Let me debug this more carefully. Let me check the AST structure of the Javadoc reference to understand how
Dateappears: - Assistant
Let me find the Javadoc classes:
- Assistant
Let me look at the Javadoc reference handling more carefully:
- Assistant
I see the issue. My change to
collectSourceIdentifierNamesis causing the Javadoc test to fail. The problem is thatDatein{@link java.util.Date}is being excluded from the set (correctly, since it's aFieldAccessname), but this prevents the import from being removed via the first condition.But the first condition already removes it correctly before my change was made. So I need to NOT add
sourceIdentifierNamesto the first and last conditions. Instead, I should only modifycollectSourceIdentifierNamesto properly handle the case.Let me revert the condition changes and only keep the
collectSourceIdentifierNamesfix: - Assistant
Let me verify the file is back to original state and run the full test suite:
- Assistant
Good, the file is back to its original state. Let me run the full test suite to make sure everything passes:
- Assistant
All tests pass with original code. Now let me carefully implement the fix. I need to:
- Modify
collectSourceIdentifierNamesto exclude identifiers that are part of a qualified reference (thenamepart of aJ.FieldAccess) - Add the
sourceIdentifierNamescheck to the first condition (line 227) and last condition (line 274)
This way types used only in generics will have their simple name collected (since they're
ParameterizedType.clazz, notFieldAccess.name), while types only in fully qualified references like Javadoc{@link java.util.Date}will be excluded. - Modify
- Assistant
Now let me make all three changes at once:
- Assistant
Let me use the edit command with
--file: - Assistant
Let me use the replace command:
- Assistant
Let me use the replace command:
- Assistant
Good, the first change is in place. Now let me add the
sourceIdentifierNamescheck to the first and last conditions: - Assistant
Let me try a different approach to make the edit. Let me use
sedagain: - Assistant
Let me use
replacewith the exact text from the file: - Assistant
Good. Now let me update the last condition:
- Assistant
All three changes are in place. Let me run the tests:
- Assistant
The issue is still failing. Let me think about this more carefully. The problem is my changes to the
noneMatchcondition. For the Javadoc case wherecombinedTypesis empty andDateis correctly excluded fromsourceIdentifierNames:- First condition:
combinedTypes.isEmpty() && !unqualifiedTypeNames.contains("java.util.Date") && !sourceIdentifierNames.contains("Date")=true && true && true=true→ import removed ✓
But wait - if
combinedTypesis NOT empty (Date's type IS resolved through the Javadoc identifier), then:- First condition:
false !sourceIdentifierNames.contains("Date")=true→ import removed ✓
And the noneMatch condition I also changed would NOT be reached.
But if
combinedTypesis empty ANDunqualifiedTypeNamesdoesn't have Date:- First condition:
true && true && true=true→ import removed ✓
So in all cases, the import should be removed. Let me check if maybe
DateIS still appearing insourceIdentifierNamesdespite my fix. - First condition:
- Assistant
Let me revert the noneMatch condition change and only keep the other two:
- Assistant
Good. Now let me run the tests with just the two changes:
- Assistant
All tests pass. Let me verify the changes:
- Assistant
The changes look correct. Let me run the full test suite to make sure nothing else is broken:
- Assistant
Let me run the tests differently to see the results:
- Assistant
All tests pass! Let me verify no failures by checking the test report:
- Assistant
74 tests, 2 skipped (the wildcard import tests that were already skipped), 0 failures. All tests pass.
Let me verify the final state of the changes:
- Assistant
Let me check the settings.gradle.kts change:
- Assistant
That's an unrelated change. Let me revert it:
- Assistant
Let me verify the final diff:
- Assistant
Let me run the tests one final time to confirm:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.