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 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 locate the Java recipe and its tests, inspect how type usages are collected (especially parameterized types), then reproduce with the narrowest existing test task before changing source. After the fix I’ll rerun targeted tests and review the diff for related edge cases.
- Assistant
rgis unavailable, so I’ll usefind/grepto identify the implementation and test locations. - Assistant
I found the implementation but no obvious same-module test by class-name search. I’ll inspect the visitor and locate recipe tests across the repository, including Kotlin test sources.
- Assistant
The implementation already special-cases one level of
JavaType.Parameterized, but it only callsasFullyQualifiedon each direct type argument. That likely fails for a nested parameterized argument (and perhaps generic arrays/wildcards). I’ll inspect the collectors and recent tests to understand intended source-vs-attribution safeguards before reproducing. - Assistant
The reported case is a direct generic argument and should appear supported at first glance, so I’ll check repository history/status and test fixtures. The key question is whether
BloomFilter<T>appears inTypesInUseas a parameterized type itself or only nested inside the parameterizedAtomicReference; the current one-level loop may depend on parser attribution details. - Assistant
There are pre-existing changes to
settings.gradle.kts; I’ll leave them untouched. The latest recipe commits added source-reference filtering, so I’ll inspect those diffs and use the existing Guava test classpath to run an exact temporary reproduction without modifying tests. - Assistant
The exact logic now should retain
BloomFilter: its identifier is present and the raw type ofBloomFilter<T>should be collected. ExistingleaveImportIfRemovedTypeIsStillReferredToalready verifiesList<Integer>, but that type is a field declaration rather than a generic superclass argument. I’ll run that baseline test, then create a temporary Gradle init script/task or external test source so the exact Guava case can be exercised without altering repository tests. - Assistant
The baseline passes. The likely structural distinction is nested parameterization:
AtomicReference<BloomFilter<T>>may contribute only the outerParameterized, andTypeUtils.asFullyQualified(BloomFilter<T>)may not unwrap it. I’ll inspectTypeUtilsandTypesInUse, then build a tiny external Java main against Gradle’s compiled test runtime to print actual types and recipe output. - Assistant
I need the exact
asFullyQualifiedimplementation and type-collection traversal around parameterized nodes. - Assistant
asFullyQualifiedconfirms it does not unwrapParameterized. I’ll inspect howFindTypesInUserecords identifiers; this can confirm the nested type is omitted without needing a custom runner. - Assistant
JavaType.ParameterizedextendsFullyQualified, so unwrapping is not the defect. The exact AST behavior remains important. I’ll inject an external/tmpJUnit source directory through a temporary Gradle init script (no repository test files changed) and run the reported Guava case verbatim. - Assistant
The exact reported case already passes on this repository’s current parser/recipe, indicating intervening code changes incidentally fixed it. However, the collection remains shallow: each
TypesInUseentry only records its raw type and direct type parameters. Hidden variants such asOuter<List<BloomFilter<T>>>, generic arrays, or wildcard bounds can still lose imports depending on which attributed nodes are independently visited. I’ll search history for the original issue/fix and inspect JavaType shapes to implement a general recursive collector rather than a case-specific patch. - Assistant
History confirms commit
7b99b434a4was the original fix for this exact issue (#1128/#1139), and its code is already present. Still, its implementation only handles direct parameters and duplicates package-key logic. I’ll inspect that commit’s test to ensure my external reproduction matches it, then strengthen the collector recursively in source code. This preserves current behavior while correctly covering nested parameterized arguments and bounds. - Assistant
I’ll replace the shallow conditional with a recursive helper. It will:
- add raw fully-qualified types for every parameterized level,
- recurse through all generic arguments,
- recurse through generic-variable/wildcard bounds and array element types,
- use identity-based cycle detection because attributed generic bounds may be self-referential,
- preserve the owning-class package-key behavior used for inner types.
This is narrowly scoped to constructing
typesByPackage; source-identifier checks still prevent attribution-only imports from being retained. - Assistant
python3is not installed, so no source change occurred. I’ll use the repository editor commands instead, replacing the existing type loop and inserting the helpers directly. - Assistant
The loop replacement is correct. I’ll insert the recursive and package-key helpers immediately before the next existing helper.
- Assistant
The helper compiles conceptually and uses existing wildcard imports for
IdentityHashMap/Collections. I’ll extend only the external/tmpreproduction with nested parameterized, wildcard-bound, and generic-array uses, then run it along with the full existingRemoveUnusedImportsTestsuite. - Assistant
The full suite exposed an important compatibility detail in wildcard folding: sets intentionally retain distinct parameterized instances, and replacing them with raw types changed the count across recipe cycles. I’ll preserve the original top-level/direct-argument insertion semantics exactly, and recurse only beyond each direct argument. Cycle detection will be per traversal path rather than global, so a type independently present in
TypesInUseis still processed in its original role. Then I’ll rerun the failed test plus external reproductions before the full suite. - Assistant
The second line-range edit used stale positions after the first edit shifted the file, leaving remnants of the old helper. I’ve identified the entire corrupted block (
322:351) and will replace it atomically with the two correct helpers before compiling. - Assistant
Compilation passes. I’ll now rerun the previously failing wildcard/inner-class test and both external generic reproductions as a fast regression check.
- Assistant
The remaining difference is now clear: top-level parameterized inner types historically use their package (
java.util), while direct argument inner types use their owning class (java.util.Map). Routing both through one helper movedEntry<K,V>out of the wildcard package count. I’ll restore that exact top-level package behavior and rerun the focused tests. - Assistant
Focused tests now pass, including the exact issue, nested wildcard/array case, and the prior wildcard-count regression. I’ll run the complete existing
RemoveUnusedImportsTestclass without the temporary source injection, then inspect repository status/diff and ensure only the intended source file (plus the pre-existing settings change) is present. - Assistant
All 76 existing recipe tests pass (2 skipped), and
git diff --checkis clean. The only unrelated worktree change is the pre-existingsettings.gradle.ktsmodification observed before my edits; I have not touched it. I’ll run the module’s style/static checks if available, then perform a final status review and submit. - Assistant
The style task does not exist in this project, so that check was not applicable; compilation, targeted tests, the complete recipe test class, and whitespace validation already passed.
Checklist:
- If an error was reported, successfully reproduced it: The current repository already contained the historical one-level fix, so the exact Guava snippet did not fail before my change. I verified the report with an external
/tmptest and confirmed from repository history that this is issue #1128; inspection exposed the remaining shallow traversal for nested generic forms. - Confirmed the fix resolves the error: The exact
AtomicReference<BloomFilter<T>>reproduction passes after the change, as does an external nested wildcard/array variant. - Thought about edge cases: The traversal now handles nested parameterized types, generic bounds, arrays, and self-referential type graphs via identity cycle detection. I also preserved existing package/count behavior for parameterized inner classes after detecting it with .
- If an error was reported, successfully reproduced it: The current repository already contained the historical one-level fix, so the exact Guava snippet did not fail before my change. I verified the report with an external
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.