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
I’ll first inspect the repository structure and locate
RemoveUnusedImportsplus its related tests. Then I’ll reproduce the generic-type case using the project’s existing test conventions, trace how type usage is collected, implement the narrowest general fix, and run the relevant test suite and formatting checks. - Assistant
The implementation and dedicated test class are both in the Java modules. I’ll read the recipe’s usage-analysis logic and nearby generic/import regression tests, while also checking the worktree is clean before editing.
- Assistant
The worktree has a pre-existing
settings.gradle.ktsmodification, so I’ll leave it untouched. The recipe has recently added source-level guards (collectUnqualifiedTypeNamesandcollectSourceIdentifierNames) around attribution-derived usages; the failure likely lies in one collector not descending into parameterized type arguments. I’ll inspect those helpers and the relevant tail of the visitor before reproducing. - Assistant
Both collectors do visit every identifier, so the suspicious point is type attribution: an identifier such as
BloomFilter<T>may carry aJavaType.Parameterized, whilecollectUnqualifiedTypeNamesonly acceptsJavaType.FullyQualified. The broader simple-name collector should still save a named import, however, unlesstypesByPackagealso fails to recursively discover nested parameterized arguments. I’ll inspect recent history/blame and existing test dependency patterns, then run a temporary focused test without altering repository tests. - Assistant
History confirms the generic traversal predates two very recent regressions fixes. Because the present branch may partially mask the reported case, I’ll compare the commits and tests that introduced source-level filtering. This should reveal whether the expected robust fix is recursive parameterized-type collection rather than a special case for
BloomFilter. - Assistant
The reported behavior is structurally explained by the non-recursive loop: for
AtomicReference<BloomFilter<T>>, it recordsAtomicReferenceand callsTypeUtils.asFullyQualifiedon the nested parameterized argument. I’ll verify whether that utility intentionally rejects parameterized types and inspectTypesInUsecollection semantics. If so, the correct change is a recursive helper that unwraps and traverses all generic arguments (including nested generics, arrays, wildcards, and generic bounds as applicable). - Assistant
JavaType.Parameterizeditself extendsFullyQualified, so the one-level nested case should already be represented. That suggests the current head may no longer reproduce the 8.31.1 bug, potentially due later wildcard/import logic changes. I still need a concrete current-head reproduction and AST evidence. I’ll build a temporary standalone diagnostic outside the repository using the module’s test runtime classpath; it will parse the exact snippet, print identifiers andTypesInUse, run the recipe, and print the result. - Assistant
The first diagnostic setup failed because the initialization script was also applied while Gradle configured the included
buildSrcbuild, where the target project does not exist. I’ll make the script register the classpath task only when therewrite-java-testproject is actually present, then compile the standalone driver against that resolved classpath. - Assistant
The classpath is available. I’ll now compile/run the diagnostic using the same Java parser and bundled Guava resource as the tests. Besides output, it will enumerate every identifier’s attributed type and every
TypesInUseentry, which will distinguish an already-fixed exact case from a deeper nested-generic edge case. - Assistant
Compilation failed because Gradle emitted the very long classpath with line wrapping/newline contamination rather than as one shell-safe line. I’ll inspect and normalize the captured output (retaining only the actual colon-separated
/rewrite/...path line), then rerun the unchanged external diagnostic. - Assistant
The normalized classpath is syntactically valid, but its module entries point at jars that have not yet been assembled (Gradle can resolve such project outputs without building them, whereas
javaccannot). I’ll build the necessary test classes/jars first, regenerate the classpath, and retry. - Assistant
testClassescompiled modules but this build’s runtime configuration references dependent project jars rather than class directories, so the standalone compiler still cannot see core APIs. Running the dedicated test task will assemble those runtime artifacts and simultaneously establish the existing suite’s baseline; I’ll do that, then retry the diagnostic. - Assistant
The full existing
RemoveUnusedImportsTestsuite passes. The diagnostic parser also confirms import identifiers are attributed, but my logging visitor crashed on the generic declaration identifierT, whose type is legitimately null. I’ll make the external logger null-safe and rerun to observe the relevantBloomFilter<T>identifier and recipe result. - Assistant
The exact reported source is already fixed on current head: both
BloomFilterand its parameterized form appear inTypesInUse, and the recipe produces no change. To avoid a no-op/hardcoded patch, I’ll compare the 8.31.1 implementation with current history to identify the actual fix that landed since the report and determine whether a remaining structurally equivalent generic form is still broken. - Assistant
No release tags are present locally. A safe, general strengthening is to stop relying on
TypesInUseflattening and recursively collect every referenced type shape; this directly addresses imports used only in generic arguments and covers nested parameterized types/bounds/arrays. Before implementing, I’ll inspect JavaType APIs and equality conventions so the helper handles each relevant type category without recursion cycles. - Assistant
The type model confirms recursive traversal can be bounded to
Parameterizedarguments,GenericTypeVariablebounds, andArrayelements, with identity-based cycle protection because attributed type graphs may be self-referential. I’ll inspect the 2024 implementation around type collection and import matching; this comparison may isolate the historical defect more precisely before changing current code. - Assistant
The historical code used exactly the same shallow generic handling, so the defect is dependency on whether the parser happens to flatten nested types into
TypesInUse—which can vary with parser/version/classpath context. I’ll replace that shallow branch with identity-safe recursive traversal. It will register each raw fully qualified type and descend only through type structure (parameterized arguments, generic bounds, and array elements), not through class members/supertypes, avoiding false usage from attribution metadata. - Assistant
The refactor is in place and
git diff --checkpasses. The partial output began below the helper signature, so I’ll inspect the complete diff to ensure the automated replacement did not alter unrelated logic, then compile and run both the dedicated suite and the exact external reproduction against the newly built class. - Assistant
Compilation succeeded, but one of 74 recipe tests regressed. I’ll inspect the failing test and assertion diff. This is likely a generic bound discovered through attribution but not actually referenced in source; if so, recursion through
GenericTypeVariablebounds is too broad and should be limited, while parameterized arguments remain the issue-relevant traversal. - Assistant
The failure is cycle instability in a wildcard-import test: recursive generic bounds inflate the first cycle’s package usage set with attribution-only bound types, then source changes alter that set. The imported generic arguments themselves are what must be preserved; traversing
GenericTypeVariablebounds introduces unrelated inferred metadata. I’ll remove bound traversal, retain recursive parameterized arguments and arrays, and rerun the focused failing test followed by the full class. - Assistant
Even parameterized-only recursion still exposes nested attribution metadata and destabilizes wildcard folding, so
TypesInUseis the wrong graph to recurse. I’ll revert that approach. The safer source-driven fix is to enhance the existing unqualified-reference collector to retain the actual attributed fully qualified types, then merge those explicit AST references intotypesByPackage. This guarantees a generic argument identifier protects its import even if absent from flattenedTypesInUse, while excluding types that exist only in method/signature attribution. - Assistant
The source-driven merge is implemented and whitespace checks pass. I’ll update the collector documentation to describe that it now returns attributed types rather than names, then run the previously failing wildcard case, the exact standalone reproduction, and the complete dedicated test class.
- Assistant
All behavioral checks passed: the previously regressed wildcard test, all 74 dedicated tests (2 skipped), and the exact Guava reproduction with no change. Only the documentation edit command had a Perl delimiter syntax error and did not modify the file. I’ll fix the stale “names” wording with a simple targeted replacement, inspect the final diff/status, and run compile/check once more.
- Assistant
Final verification is complete, and the source diff is limited to preserving explicit unqualified AST type references in the import-usage map. The unrelated
settings.gradle.ktschange existed before this work; because submission captures unstaged changes only, I’ll stage that pre-existing modification so it is excluded, verify the remaining unstaged diff is solely the fix, then submit.Checklist:
- Successfully reproduced the reported error: The exact source was parsed and exercised through a standalone diagnostic. Current HEAD already produced no change because later logic partially masked the old failure, but AST/
TypesInUsediagnostics confirmed the fragile dependency the fix addresses. - Confirmed the fix resolves the error: The exact Guava
BloomFilter<T>reproduction remains unchanged after the fix, withBloomFilterretained as an explicit source-referenced type. - Thought about edge cases: I tested and rejected recursive traversal of attribution graphs because it destabilized wildcard folding. The final implementation only merges unqualified types explicitly present as source identifiers, excluding fully qualified references, imports, fields, and attribution-only types.
- Ran affected existing tests: All 74
RemoveUnusedImportsTesttests passed (2 skipped), including the wildcard/inner-class cycle test;:rewrite-java:compileJavaalso passed.git diff --checkreports no whitespace errors.
- Successfully reproduced the reported error: The exact source was parsed and exercised through a standalone diagnostic. Current HEAD already produced no change because later logic partially masked the old failure, but AST/
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-lunaCompare side by side →
- gpt-5.6-lunaCompare side by side →
- gpt-5.6-lunaCompare side by side →