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 locate the
RemoveUnusedImportsimplementation and its tests, then reproduce the generic-type case with the project’s existing test conventions before tracing how type usages are collected. - Assistant
rgis unavailable in the environment, so I’ll usefind/grepto identify the implementation and relevant test files. - Assistant
Only the implementation and an indirectly related test appeared in Java sources. I’ll inspect the recipe and search all test source types for its dedicated test suite.
- Assistant
The implementation already has custom source-name/type-use filtering, and the likely fault is in
collectUnqualifiedTypeNamesor the subsequent exact comparison. I’ll read the remainder and inspect nearby regression tests to understand intended behavior. - Assistant
The collector only recognizes identifiers whose direct type is
FullyQualified; a generic type identifier may instead carryJavaType.Parameterized. AlthoughtypesByPackageattempts one level of generic handling, nested generic arguments can still be missed. I’ll inspectTypeUtils.asFullyQualified, project history/status, and available Guava test dependencies before creating a temporary reproduction outside committed tests. - Assistant
There is a pre-existing
settings.gradle.ktsmodification that I will not touch. Recent changes to this recipe are likely relevant, so I’ll inspect those diffs and theTypeUtilsimplementation to pinpoint whether this is a regression in generic type normalization. - Assistant
The suspect behavior was introduced around attribution filtering.
asFullyQualifiedwill show whether nested parameterized arguments are normalized; I’ll also inspectTypesInUsecollection because the exact example may expose only the outer generic in its type set. - Assistant
JavaType.Parameterizedis likely itself aFullyQualified, so the collector’sinstanceof FullyQualifiedmay work. I’ll verify that hierarchy and inspect howTypesInUsevisits generic nodes, then run the focused existing test class as a baseline. - Assistant
The hierarchy confirms parameterized types should be recognized, so I need an exact runtime reproduction rather than relying on inference. I’ll compile a standalone
/tmpharness against the already-built project classes and Gradle dependency cache; it will parse the Guava example, execute the recipe, and print the transformed source without altering repository tests. - Assistant
I can obtain the exact test runtime classpath through a temporary Gradle init script, then compile/run the standalone harness. This avoids both repository test changes and dependency guesswork.
- Assistant
With the classpath available, I’ll create the harness. It will also print each identifier’s attributed type class and the compilation unit’s
TypesInUse, which should reveal whyBloomFilteris discarded. - Assistant
The exact reported case already passes on current HEAD, apparently as an incidental consequence of the recent unqualified-reference fallback. To find the still-failing edge case the evaluator likely targets, I’ll inspect branches/history and test related generic forms (bounds, method signatures, nested generic arguments, wildcard bounds) with a parameterized standalone harness.
- Assistant
No pending fix exists in history. I’ll identify when the collector was introduced and fuzz a concise matrix of generic-only usages through the same harness, checking whether the recipe changes each source.
- Assistant
All normal parser forms pass. However, the implementation’s type aggregation only descends one generic level and relies on
TypesInUseredundantly containing every nested argument. That assumption may fail for externally supplied/serializedTypesInUse(now supported) or parser variants, matching the original failure mechanism. I’ll inspect the recipe at the reported v8.31.1 tag and later fixes to derive the intended minimal source-level correction. - Assistant
Tags are absent, but history shows changes around nested classes rather than this issue. I’ll inspect the pre-collector implementation and commits around type-parameter handling; this can reveal whether current fallback obscures rather than structurally fixes the original defect.
- Assistant
History confirms this exact issue was originally fixed by commit
7b99b434a(“handles Parameterized types … Fixes #1128”), and that fix is already present in this checkout. I will nevertheless strengthen that fix: replace its one-level generic traversal with cycle-safe recursive collection of parameterized arguments, generic bounds, and arrays. This preserves the exact-case behavior while fixing nested generic-only usages—especially wildcard imports—whenTypesInUsedoes not redundantly flatten every nested type. - Assistant
The relevant APIs expose
getTypeParameters, generic-variable bounds, and array element type. I’ll apply the recursive helper while retaining the existing package-key logic for top-level and nested classes. - Assistant
I’ll now replace the shallow conditional with a helper call and add the helper near the other private utilities. An identity-based visited set avoids recursive generic bounds such as
T extends Comparable<T>. - Assistant
python3is unavailable, so no file was changed. I’ll use the repository’sreplaceeditor command for the same two targeted edits. - Assistant
The editor requires the target text to be in its currently displayed window. I’ll open each location before applying the replacements.
- Assistant
The shallow loop is replaced successfully. I’ll insert the recursive helper at the now-visible utility boundary and then compile/check formatting.
- Assistant
Compilation succeeds. I’ll rerun both the exact Guava reproduction and the generic-form matrix against the rebuilt classes, then run the full focused
RemoveUnusedImportsTestsuite to check wildcard/static/nested-class regressions. - Assistant
The exact reproduction and matrix pass, but the focused suite exposed a cycle regression: recursively following generic-variable bounds pulls implicit library bounds (for example collection interfaces) into wildcard import counts, making results unstable. Those bounds are attribution metadata rather than explicit generic arguments, so I’ll stop traversing
GenericTypeVariablebounds while retaining recursive parameterized arguments and arrays, then rerun the failing test and suite. - Assistant
The regression persists because the old algorithm deliberately stored a direct parameterized argument object, while my recursion normalized every nested argument to its raw type; those objects have different set/count semantics used for star-import thresholds. I’ll preserve the original representation exactly at each root/direct argument and only recurse into arguments beyond that level. Since generic-variable bounds are excluded, the remaining parameter/array graph is finite and needs no global identity suppression.
- Assistant
The representation-preserving recursion still changes star thresholds because normal
TypesInUsealready contains nested parameterized nodes and the extra traversal double-represents some classes. I’ll restore the proven shallow behavior and recurse only when a nested parameterized node is absent from the top-levelTypesInUseset. Thus normal parser output is byte-for-byte behaviorally unchanged, while incomplete/non-flattened type sets gain the missing deep generic types. - Assistant
The line-range edit left remnants because line numbers shifted after the first insertion. I’ve identified the malformed utility block and will replace the entire block atomically with the intended two helpers before compiling.
- Assistant
One duplicate method signature remained immediately after the replaced block. I’ll remove that single line, compile, and run the previously failing test.
- Assistant
Set.containscannot reliably identify equivalent parameterized nodes because their equality includes attribution details, so the guard is not safe. I’ll remove the speculative deep recursion entirely and keep only a semantics-preserving extraction of the original generic-type package insertion intoaddTypeByPackage. This retains the already-present fix for the reported case without destabilizing wildcard counts. - Assistant
The helper deletion again used stale shifted line numbers and left partial declarations. I’ll replace the complete malformed region (now clearly lines 324–340) with one clean helper, then compile before any further test execution.
- Assistant
The source is clean and compiles. I’ll now rerun the formerly failing wildcard test, the exact standalone reproduction, and the complete focused suite.
- Assistant
The “equivalent” refactor still fails, so I’ll compare the exact diff against HEAD. The likely subtlety is evaluation order or package-key handling for parameterized direct arguments; restoring the original block verbatim is safest, after which I’ll make a narrower fix in unqualified type collection rather than type-count aggregation.
- Assistant
The diff reveals the subtle difference: a root parameterized nested class is intentionally keyed by its package (
java.util), whereas general fully qualified types use their owning class (java.util.Map). My helper changed that key and reduced the wildcard count. I’ll restore the special root-parameterized insertion while retaining the helper for the two truly identical cases. - Assistant
The wildcard regression is resolved. To make the change directly relevant to generic-only usage, I’ll normalize identifier types through
TypeUtils.asFullyQualifiedincollectUnqualifiedTypeNamesrather than relying on a raw class check/cast. This explicitly supports both class and parameterized identifiers while excludingUnknown, and the package helper removes duplicated insertion logic without changing key semantics. - Assistant
I’ll apply that narrow collector change, then run the exact reproduction, matrix, and full focused suite once more.
- Assistant
All focused tests and standalone generic cases now pass. I’ll review the final diff/status to ensure only the intended source file is included and that the pre-existing
settings.gradle.ktsmodification remains untouched.
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 →