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?
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 callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /rewrite, current file: none) bash-$
Assistant
Let me start by understanding the repository structure and the issue. The issue is about
RemoveUnusedImportsremoving imports when they are used in Generics only. Specifically, in code like:import com.google.common.hash.BloomFilter; import java.util.concurrent.atomic.AtomicReference; @SuppressWarnings("UnstableApiUsage") public class BloomFilterRef<T> extends AtomicReference<BloomFilter<T>> { }The
BloomFilterimport is being removed even though it's used inAtomicReference<BloomFilter<T>>. This is incorrect -BloomFilteris used in the generic type parameter.Let me explore the repository structure first.
Assistant
Let me find the
RemoveUnusedImportsrecipe codeAssistant
Let me look at the RemoveUnusedImports source and related files.
Assistant
Let me also look at the test file for
RemoveUnusedImportsAssistant
Let me look for the
JavaSourceFileor related types to understand how types are collected.Assistant
Let me look at the
TypesInUseclass and how it's constructed.Assistant
Let me look at this file.
Assistant
Let me look at
TypeUtils.asFullyQualified:Assistant
Let me look at this method.
Assistant
Let me first try to reproduce the issue. Let me find the test structure and understand how tests
Assistant
Let me create a reproduction script to better understand the issue
Assistant
Let me look at how the Java LST represents parameterized types and how types are visited
Assistant
Let me look at how
JavaIsoVisitorhandles type visiting, particularly for parameterizedAssistant
Let me look at the
JavaVisitorclass to understand how types are visitedAssistant
Let me look at
visitParameterizedTypeto understand how types are visited for parameterized types.Assistant
Let me look at how class declarations handle the extends clause types
Assistant
Let me create a simple reproduction test and run it to see the issue
Assistant
Let me look at the imports and structure of the test file to understand how tests are
Assistant
Let me try to build the project and run a quick reproduction
Assistant
Let me first check if there's a way to build and run tests quickly
Assistant
Let me trace the code path for how identifiers are visited to understand when types are added
Assistant
Let me look at
visitIdentifierin the JavaVisitor:Assistant
Let me look at some existing similar tests in the RemoveUnusedImportsTest file to find
Assistant
Let me create a reproduction script to test the issue directly
Assistant
Let me check the git history for this repository
Assistant
This looks like a recent version. Let me check the version.
Assistant
Let me check the version in a different way.
Assistant
Let me look at version files
Assistant
Let me look at the search test for
DoesNotUseTypewhich might be relevantAssistant
Let me check if
sourceIdentifierNamesis used inAssistant
Let me look at the context around line 264
Assistant
Let me look at the
J.ParameterizedTypestructure and how the clazz identifierAssistant
Let me look at the ParameterizedType definition
Assistant
Let me write a quick reproduction test as a simple Java program that directly uses the API
Assistant
Let me search for tests with nested parameterized types
Assistant
Let me try to actually build and run the test. Let me first check if I can run a single test.
Assistant
Now let me copy the repro test and run
Assistant
The test passed, meaning the import is being kept correctly. Let me check if this version might already have a fix or if I'm missing something. Let me check the version:
Assistant
Let me check the git log for the RemoveUnusedImports file
Assistant
Let me look at the recent commit that might be related to
Assistant
Let me see the actual diff of that commit:
Assistant
Let me look at
visitExpressionin JavaVisitor to understand how identifiers are traversAssistant
Let me look at
visitExpression:Assistant
Let me verify the test ran correctly by checking the output
Assistant
Let me try running the test with more verbose output
Assistant
Let me force re-run the
Assistant
Let me check the commit that fixed the static field qualifiers issue to see if it's related
Assistant
Let me check if there's a
ShallowClasstypeAssistant
Let me look at the ShallowClass definition and its relationship to FullyQualified
Assistant
Let me create a more comprehensive test to try to reproduce the issue
Assistant
Let me run these tests
Assistant
Let me try with truly external types that aren't on the classpath
Assistant
Let me verify the tests are actually working by adding a test that should remove an import
Assistant
Let me look at the code before the
330504939commit to see if the issue existedAssistant
Let me see the typesByPackage building code in the old version
Assistant
Let me check the version of this codebase
Assistant
Let me search for relevant commits that might have fixed this
Assistant
Let me look at how class declarations handle their extends clause in the Java
Assistant
Let me look at
visitLeftPaddedto understand if it visits theAssistant
Let me find
visitLeftPaddeddefinitionAssistant
Let me look at the visitor hierarchy
Assistant
Let me look at the full diff of changes to RemoveUnusedImports.java since the relevant
Assistant
Let me look at the code state from commit
2fe5ea8e4(before the most recent fixes) to see if the bug existedAssistant
Let me look at how
visitContainerworksAssistant
Let me find
visitContainerdefinitionAssistant
Let me look at
visitContainerAssistant
Let me look at `visitRightPadded
Assistant
Let me look at
visitRightPaddedAssistant
Let me look at how the parser resolves types that are not on the classpath. Let me search for how imports contribute to type
Assistant
Let me look for any related issue references in the git
Assistant
Let me search for any issue references or failing tests related to this
Assistant
Let me check the version of the codebase
Assistant
Let me check for version in settings.gradle.kts or similar files
Assistant
Let me find the project
Assistant
Let me look at the buildSrc directory
Assistant
Let me look at the full diff between the current code and an older version to find what might have fixed this issue
Assistant
Let me search for existing tests with generic type usage in RemoveUnusedImportsTest
Assistant
Let me look at that specific test
Assistant
Let me check if FindTypesInUse overrides visitParameterizedType
Assistant
Let me run the full RemoveUnusedImports test suite to make sure all tests pass
Assistant
Let me look at the JavaType.Parameterized hierarchy
Assistant
Let me look at the Parameterized class in
Assistant
Let me test one more edge case - type used only in generics with fully qualified outer
Assistant
Let me check another edge case - same-package import
Assistant
Let me see the test failure details
Assistant
Let me look at the test output in a different way
Assistant
I found the bug! It occurs when there's a package declaration and external types. Let me create a minimal reproduction
Assistant
Let me run without the grep
Assistant
Let me try with package declaration and external types specifically
Assistant
Let me create a test that shows what happens
Assistant
Let me check how
getPackageName()works for `FullyQualifiedAssistant
Let me look at
getPackageName()forFullyQualifiedAssistant
Let me check what
getSimpleName()returns for `J.FieldAccessAssistant
Let me look at `J.FieldAccess.getSimpleName
Assistant
Let me add debug output to understand the
Assistant
Let me look at the import decision section more
Assistant
Let me add some temporary debug output to trace the issue
Assistant
Let me go to line 73 first
Assistant
Now let me add debug output
Assistant
Let me fix the duplicate comment and add more debug at the import checking
Assistant
Let me fix the duplicate and add debug at import checking
Assistant
Let me clean up the debug code and add it in a cleaner
Assistant
Now let me add debug to the import checking section. Let me go to line 227
Assistant
Let me add debug output right before the import decision
Assistant
Let me try a simpler edit approach
Assistant
Now let me run the test and see the debug output
Assistant
The System.err output might be going to a file. Let me check
Assistant
I found the root cause! The
typesByPackagemap is being printed BEFORE it's populated. AndunqualifiedTypeNamesdoesn't containbar.BloomFilter. Let me move the debug and also check what type the BloomFilter identifier has.Assistant
Let me revert all changes and start
Assistant
Let me add targeted debug to understand why BloomFilter is not in typesByPackage and unqualifiedTypeNames
Assistant
Let me add debug after the typesByPackage population loop
Assistant
Now let me run the test
Assistant
Now I understand the issue! When
BloomFilter<T>can't be resolved by the type resolver (because it's not on the classpath), the type is not added totypesByPackageorunqualifiedTypeNames. But the simple nameBloomFilterIS insourceIdentifierNames.The fix needs to ensure that when
sourceIdentifierNamescontains the import's simple name, we don't remove the import even ifcombinedTypesis empty.Let me make the fix:
Assistant
Now let me apply the fix. The first condition at line 231 should also check
sourceIdentifierNames:Assistant
Now let me also fix the fourth condition at line 273-278
Assistant
Let me remove the debug code and run the tests
Assistant
Let me revert and start fresh
Assistant
Now let me apply the fix cleanly. Open the file and apply both fixes:
Assistant
Now apply the fix for line 227
Assistant
Now apply the second fix for the
Assistant
Now let me run the reproduction test
Assistant
Let me see the detailed failure
Assistant
Let me fix my test to use the single-argument pattern
Assistant
Both tests pass. Let me now run the full RemoveUnusedImports test suite
Assistant
Let me find the failing test
Assistant
Let me look at the failing test
Assistant
My fix is too broad - it breaks the
removeImportIfFullyQualifiedInJavaDoctest. Let me revert the second fix and think more carefully about the right approach.The issue is that
sourceIdentifierNamescontains simple names from Javadoc too. Let me revert the second fix firstAssistant
Let me add debug to
FindTypesInUse.visitType()to see what types are being visitedAssistant
Let me find the
visitTypemethod in `FindTypesInUseAssistant
Let me look at the
visitTypemethodAssistant
Let me add targeted debug to
FindTypesInUse.visitType()to understand what's happening with the BloomFilter typeAssistant
Let me also add debug for skipped
Assistant
Let me run the test with
Assistant
Let me add debug to log ALL types being visited (including skipped ones)
Assistant
Let me run the test again
Assistant
Now I understand the exact issue. The
BloomFilteridentifier has typeJavaType.Unknownbecause it's not on the classpath. It's skipped byFindTypesInUseandcollectUnqualifiedTypeNames, but collected bycollectSourceIdentifierNames.The fix should modify
collectSourceIdentifierNamesto skip identifiers in fully qualified Javadoc references, so we can safely usesourceIdentifierNamesin the import decision conditions without breaking theremoveImportIfFullyQualifiedInJavaDoctest.Let me revert both files and apply the correct fix:Let me revert the debug changes and apply the proper
Assistant
Now let me apply the proper fix. I'll modify
collectSourceIdentifierNamesand add thesourceIdentifierNameschecks:Assistant
Let me apply the fix. First, modify
collectSourceIdentifierNamesto skip fully qualified Javadoc identifiersAssistant
Now let me add the
sourceIdentifierNamescheck to both conditions. First, the first condition at lineAssistant
Let me go to line
Assistant
Now apply the fix at line
Assistant
Now apply the second fix at line 274
Assistant
Now let me run the reproduction test and the full RemoveUnusedImports test
Assistant
Now let me run the full
RemoveUnusedImportsTestAssistant
Let me find the
Assistant
Let me add debug to the `isPartOfFullyQualifiedJavadocReference
Assistant
Let me add debug to check what's happening
Assistant
Let me run the failing test with
Assistant
Now I see the issue. The parent is
JLeftPadded, notJ.FieldAccess. Let me fix the check:Assistant
Now let me run all tests
Assistant
All tests pass! Let me verify by running the test without --info to see the summary
Assistant
All tests pass! Let me now clean up my temporary test file and verify the final state of my
Assistant
Let me check the settings.gradle.kts change
Assistant
That change is not related. Let me revert
Assistant
Let me verify
Assistant
Let me run the full test suite one final time to make sure everything is good
Assistant
Let me also run OrderImports tests and a broader set to ensure nothing else is broken
Assistant
All tests pass. Let me now submit the fix.
Let me review what the fix does:
Summary of Changes
The issue was that
RemoveUnusedImportswas incorrectly removing imports for types that are only used in generic type parameters (e.g.,BloomFilterinAtomicReference<BloomFilter<T>>) when those types couldn't be resolved to a properFullyQualifiedtype (e.g., when they're from external libraries not on the classpath during analysis).Root Cause
When a type like
BloomFilter<T>is used as a type argument andBloomFilteris not on the classpath:- The type system creates
JavaType.Unknownfor the type, which is skipped byFindTypesInUse - As a result,
BloomFilteris not added totypesByPackage - And it's not in
unqualifiedTypeNames(which requiresFullyQualifiedtype) - But it IS in
sourceIdentifierNames(which collects simple names from source)
The first condition in the import-checking logic removes the import when
combinedTypesis empty AND the type is not an unqualified type reference. This incorrectly removed the import for types used in generics but not resolvable.Fix (3 changes)
-
Modified
collectSourceIdentifierNames: Added a check to skip identifiers that are part of fully qualified Javadoc references (like{@link java.util.Date}). This ensures thatsourceIdentifierNamescan be safely used to prevent import removal without breaking the existingremoveImportIfFullyQualifiedInJavaDoctest. -
First condition: Added
&& !sourceIdentifierNames.contains(qualid.getSimpleName())to prevent removal when the type's simple name appears in source code (even if the type can't be resolved). -
Fourth condition: Added the same check for consistency
- The type system creates
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
- gpt-5.6-solCompare side by side →
- gpt-5.6-solCompare side by side →
- gpt-5.6-solCompare side by side →
- gpt-5.6-solCompare side by side →
- gpt-5.6-lunaCompare side by side →
- gpt-5.6-lunaCompare side by side →
- gpt-5.6-lunaCompare side by side →