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 first inspect the repository structure and locate
RemoveUnusedImportsand its tests. Then I’ll reproduce the generic-type import removal with the project’s existing test infrastructure, trace the type-usage logic, implement the narrowest general fix, and run the relevant test suite. - Assistant
The implementation and test class are in the expected Java modules. There is a pre-existing modification to
settings.gradle.kts; I’ll leave it untouched and inspect both the recipe’s usage accounting and nearby regression tests before deciding how to reproduce without modifying tests. - Assistant
The code already attempts to preserve parameterized type arguments in
typesByPackage, so the likely regression is in one of the newer source-reference filters (unqualifiedTypeNamesorsourceIdentifierNames) rather than the broad type table itself. I’ll inspect the rest of the implementation, its recent history, and the relevant portions of the test class to identify the exact mismatch. - Assistant
The regression aligns with commit
#7383or#7336, which added the source identifier safeguards. I’ll compare those changes against their parent revisions and inspect the test fixtures they introduced. This should reveal whether generic arguments represented asJavaType.Parameterizedare omitted by the collector (which currently accepts onlyFullyQualifiedidentifier types). - Assistant
Although the simple-name collector should theoretically see
BloomFilter, the report needs an attributed Guava type to reproduce accurately. I’ll check available test classpaths/dependencies and the test harness conventions. If Guava is unavailable, I’ll use an equivalent two-source fixture in a temporary standalone JUnit test copied outside tracked test paths, preserving the sameAtomicReference<GenericType<T>>AST shape. - Assistant
Guava is available at test runtime, so I can reproduce the exact report without touching repository tests. I’ll first build the relevant test classes, then compile and run a temporary
/tmpJava program against the resolved test runtime classpath. The program will parse the reported source with Guava attribution, run the recipe, print the result, and inspect identifier/type shapes if needed. - Assistant
The modules compile successfully. I’ll now obtain Gradle’s exact
testRuntimeClasspathvia a temporary init script and use OpenRewrite’s public parser/recipe APIs in/tmp/Repro.java. This avoids any tracked test changes while still providing a precise before/after reproduction. - Assistant
I’ll use
InMemoryLargeSourceSetand inspect all generated recipe results. The program will also visit non-import identifiers and print their attributed Java type classes, which will distinguish an AST traversal failure from a type normalization failure. - Assistant
The classpath file contains project output paths that Gradle emitted relative to the subproject directory, so
javapcould not resolve them from the repository root. I’ll inspect and normalize those entries (or prepend the subproject directory) before compiling the reproduction. - Assistant
Gradle resolves project dependencies to jars, but
testClassesdid not package those jars. I’ll prepend every module’s compiled main classes/resources to the classpath, then compile the temporary reproducer using the current Java 21 parser implementation and Guava jar. - Assistant
The corrected classpath resolves the APIs. I’ll run the exact source now. The diagnostic visitor will identify every
BloomFilteroccurrence, its node type attribution, and its immediate parent, followed by the recipe’s resulting source. - Assistant
The parser implementation jar listed by Gradle was not packaged, and its module classes were not built by
testClassesbecause it is a runtime-only project dependency. I’ll explicitly build therewrite-java-21jar (and the other project jars needed on runtime classpath), then rerun the same reproducer. - Assistant
The exact reported case no longer reproduces on the current parser/recipe: both imports are retained, and the generic raw-type identifier is a
JavaType.Class. That means the repository has partially fixed the original report, likely through later changes, but a related edge case remains for generic type arguments whose identifier attribution is itselfJavaType.Parameterized(nested generic/member types). I’ll search all branches/history and inspectTypesInUsecollection plus parameterized-type utilities to find the intended general gap rather than hardcoding the Guava case. - Assistant
A concrete weakness is visible in the type table: it adds only direct parameters of each
TypesInUseparameterized entry, while nested generic arguments can require recursive traversal. Before changing that, I’ll verifyTypeUtils.asFullyQualified(Parameterized)behavior and howTypesInUsepopulates nested generic types. Then I’ll construct attributed nested-generic variations to see which imports are actually dropped. - Assistant
Parameterizedis aFullyQualified, so direct generic parameters are normalized correctly, but nested parameters are not recursively added by this recipe. I’ll broaden the/tmpreproducer into a matrix using custom source types (including nested parameterized arguments, wildcard bounds, arrays, and generic bounds), then report which imports disappear. This directly tests edge cases while preserving attribution. - Assistant
All attributed generic-shape variants are retained on current HEAD because the newer source-level identifier/unqualified checks compensate for incomplete type-table recursion. To determine the actual historical defect and ensure a meaningful fix, I’ll inspect
RemoveUnusedImportsat tag/version8.31.1and search subsequent commits for the first change that made the exact Guava case pass. This will show whether the intended fix was already folded into a broader refactor or whether current behavior is accidental. - Assistant
The parameterized-type handling dates to 2021, predating the report, so the defect is likely not a missing feature wholesale but a package-key mismatch for certain generic type representations. I’ll print the exact
TypesInUseentries and resultingtypesByPackagesemantics for the Guava fixture, then inspect the historical 8.31.1-era source commit around August 2024 to identify what changed immediately afterward. - Assistant
The report’s version predates two September 2024 fixes. I’ll inspect those commits’ tests and implementation diffs; one may be the canonical resolution of this issue under a broader “nested classes” title. I’ll also use
awk(Python is unavailable) to add theTypesInUsediagnostics to the temporary reproducer. - Assistant
The historical Guava type is explicitly present both as a parameterized entry and a raw class in current
TypesInUse, confirming the original defect was parser/version-sensitive and is now masked by multiple later safeguards. A robust fix should not depend on whether the parser emits both representations. I’ll refactor type collection to recursively register every fully qualified type reachable through parameterized arguments (including arrays, wildcard/generic bounds), rather than only one level. Before editing, I’ll inspect project style for identity-based cycle guards and Java version constraints, then make a source-only change. - Assistant
I’ll replace the ad hoc one-level loop with two focused helpers: one recursively unwraps type containers with an identity cycle guard; the other consistently indexes a fully qualified type by its import target (package or owning class). This preserves existing inner-class behavior while making generic-only usage independent of redundant raw entries in
TypesInUse. - Assistant
The second insertion landed inside the anonymous visitor because line numbers shifted after the first edit. I caught this in the diff before compiling. I’ll remove that misplaced block and reinsert it at class scope immediately before the collector Javadoc, restoring the visitor’s
@Overrideannotation. - Assistant
The helper is now correctly scoped and
git diff --checkis clean. I’ll compile the recipe, rerun both the exact Guava reproduction and the generic-shape matrix against the rebuilt classes, and then run the completeRemoveUnusedImportsTestclass to detect regressions in wildcard, inner-class, static-import, and attribution-only behavior. - Assistant
Compilation and both reproductions pass, but one existing test in the full recipe class failed. I’ll inspect the XML failure details and compare the unexpected output. Given the recursive bound handling, the likely regression is retention of a type that appears only in method attribution; if so, I’ll narrow recursion to syntactic parameterized type arguments rather than all generic bounds, preserving the intended fix without broadening implicit usage.
- Assistant
The failure is a wildcard-threshold regression, not an attribution-only type: historically the raw type of a
Parameterizedentry is indexed by its package even when it is an inner type (Map.Entry), which contributes to retainingjava.util.*. My helper accidentally applied the owning-class key to that raw type. I’ll preserve that established distinction—parameterized raw types by package, type arguments by their import owner—while retaining recursive traversal of arguments. Then I’ll rerun the failed test first and the full class afterward. - Assistant
The targeted regression and all 74 recipe tests now pass (2 existing skips), and established wildcard behavior is preserved. To verify that the new recursion—not the current parser’s redundant raw-type entry—is what protects generic-only imports, I’ll create a temporary synthetic check that filters
TypesInUsedown to an outer parameterized type representation if the API permits cache manipulation. Otherwise, I’ll at least rerun exact and nested fixtures after a clean rebuild, then inspect the final diff and static checks. - Assistant
The API can synthesize a filtered
TypesInUse, but current source-reference safeguards would still mask the historical failure. While reviewing edge cases, I found an important compatibility detail: a parameterized inner class used as a type argument must be indexed both by its owning class (as the old one-level loop did) and recursively by its raw package. I’ll adjust argument handling to preserve the old direct-argument indexing before recursion, preventing a subtle inner-generic regression. - Assistant
The full recipe test class still passes after the compatibility adjustment, as do the exact Guava and nested/wildcard/array/bound generic fixtures; formatting checks are clean. I’ll now review the complete source diff for unnecessary changes, run the module’s main style/static checks, and isolate the pre-existing
settings.gradle.ktsmodification so it is not included in submission. - Assistant
The project does not define
checkstyleMain, so that specific check is not applicable;compileJava,git diff --check, and the complete focused test class are the available validations and have passed. The source diff is limited to recursive type-container collection and extraction of the existing package-key logic. I’ll stage only the pre-existing settings change (to exclude it from the special unstaged-only submission), confirm the final unstaged patch contains exactly one source file, and rerun compilation once more.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.