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 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
Now let's run this test to reproduce the issue.
Assistant
There's already a guava jar bundled for tests. Let's update the test to use real guava classpath.
Assistant
Let's rewrite the test to use real Guava classpath, closer to the original issue.
Assistant
Now let's check import for JavaParser in the test file.
Assistant
Same package, JavaParser class is directly accessible since it's in org.openrewrite.java package. Good, no import needed. Let's run the test.
Assistant
parse returns a Stream already; fix that.
Assistant
Now let's check if OrderImports is importable directly.
Assistant
Good, restoring settings.gradle.kts is fine since it wasn't needed for this build. Now let's finalize the RemoveUnusedImportsTest.java by cleaning up debug tests and keeping only meaningful regression tests.
Assistant
Let's remove the debug test and rename the last one to avoid duplicate meaning (it's field-based, redundant with the field test). I'll clean this up into a concise, meaningful set of regression tests.
Assistant
Let's remove the extra
@DocumentExamplefrom my new test since one already exists in the class.Assistant
Now let's view the rest of the file and remove the stray comment line reference, then run full test suite.
Assistant
Good, this looks clean. Let's remove the awkward comment line and run the full test class.
Assistant
Now let's now also apply the defensive robustness fix in
RemoveUnusedImports.javato make the manual Parameterized-type-parameter collection recursive (handling arbitrarily nested generics), rather than relying solely onTypesInUseincidentally flattening nested parameterized types. Let's view the relevant code section again.Assistant
There's an extra closing brace at line 107. Let me fix that.
Assistant
Now let's add the helper method
addParameterizedTypesToPackageMapand required imports (newSetFromMap,IdentityHashMap).Assistant
Now let's add the helper static method. Let's find a good place, e.g., right after
getAmbiguousStaticImportNamesor before it.Assistant
Need a blank line before
getAmbiguousStaticImportNames.Assistant
Now let's compile and run the full RemoveUnusedImportsTest suite.
Assistant
All tests in the whole test class pass. Let's verify test count matches expectations and none were skipped.
Assistant
80 tests, 0 failures. Now let's run the broader rewrite-java-test suite to check for regressions in other tests that might exercise RemoveUnusedImports or related logic (OrderImports, ChangeType, etc.).
Assistant
All tests in
rewrite-java-testpass. Let's also run rewrite-java module's own tests (if any) to be thorough.Assistant
All good. Let's view the final diff for the source and test files.
Assistant
This is a clean, self-contained robustness fix. Now let's review the test diff.
Assistant
Let's also double check
git diff --statoverall, and confirm no other stray files were left behind.Assistant
Clean. Let's do a final full test run of both modules once more to be fully sure, and also test the OrderImports test suite since we touched shared infra.
Assistant
All pass. Let's view the final full diff once more for review.
Assistant
This looks good. Now let's go through the checklist.
Assistant
Everything passes. Let's do a final check to see git status once more, and then submit.
Assistant
Now let me review the checklist as requested:
Checklist review:
- If an error was reported in the issue description, I have successfully reproduced it.
I attempted extensive reproduction of the exact scenario from the issue (a class using
extends AtomicReference<BloomFilter<T>>whereBloomFilteris only referenced via a generic type argument), using both a hand-rolled stub class and the real GuavaBloomFilterclass from the bundled test classpath jar. In every variation I tried (superclass generic argument, field, method parameter, bounded type parameter, wildcard bound, deeply nested generics, combined withOrderImports), the import was correctly retained by the currentRemoveUnusedImportsimplementation — I could not reproduce actual removal. Tracing through the code, I found that the historic fix inRemoveUnusedImports(populatingtypesByPackagefromJavaType.Parameterized#getTypeParameters()) combined withTypesInUsealready flattening nested parameterized types as independent entries meant the described symptom did not manifest in this codebase state. That said, I identified that the manual type-parameter walk inRemoveUnusedImportsonly recursed one level deep and relied incidentally onTypesInUsedoing deeper flattening — a fragile, implicit dependency that matches the spirit of the reported bug (imports "used in Generics only" being at risk of removal). I hardened this exact code path.
- If an error was reported in the issue description, I have successfully reproduced it.
I attempted extensive reproduction of the exact scenario from the issue (a class using
Assistant
-
If an error was reported in the issue description, I have confirmed that my fix resolves the error. Since I could not reproduce a failing case with the current codebase, I instead made the relevant code (
typesByPackagepopulation fromJavaType.Parameterized) explicitly recursive and self-contained (no longer implicitly relying onTypesInUseto have already flattened nested generics), which directly targets the exact mechanism the issue describes. I added 6 regression tests exercising the reported scenario and several related variants (field, method parameter, bounded type parameter, wildcard bound, deeply/doubly-nested generics usingMap<String, Map<Integer, BloomFilter<T>>>) — all pass with the fix in place, confirming imports used only via generics (at any nesting depth) are retained. -
I have thought about edge cases and made sure my fix handles them as well. I covered: superclass type arguments, field types, method parameter types, bounded type parameters (
T extends BloomFilter<T>), wildcard bounds (? extends BloomFilter<?>), and multi-level nested generics (Map<String, Map<Integer, BloomFilter<T>>>). I also added an identity-basedseenguard against infinite recursion for potential self-referential generic structures (e.g., recursive generic bounds) to keep the new recursive helper safe. -
I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I ran the full
RemoveUnusedImportsTestsuite (80 tests, 0 failures), theOrderImportsTestsuite, the entirerewrite-java-testmodule test suite, and therewrite-javamodule test suite — all passed with no regressions.
-
Assistant
Everything is in order. Let's submit the final solution.
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
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →