Let me understand the issue better. The problem is that when BloomFilter<T> is used in a generic type parameter in the extends clause (extends AtomicReference<BloomFilter<T>>), the import for BloomFilter is being incorrectly removed.
Let me trace through the code to understand how the import usage is determined for non-static imports.
Looking at the visitor code:
- First, types are collected from
cu.getTypesInUse().getTypesInUse() into typesByPackage map.
- Then for each import, it checks if the import is used by looking up in
typesByPackage.
For non-static imports:
String target = qualid.getTarget().toString();
Set<JavaType.FullyQualified> types = typesByPackage.getOrDefault(target, new HashSet<>());
Set<JavaType.FullyQualified> typesByFullyQualifiedClassPath = typesByPackage.getOrDefault(toFullyQualifiedName(target), new HashSet<>());
The target for an import like import com.google.common.hash.BloomFilter; would be the fully qualified name. Let me check what qualid.getTarget().toString() returns.
Looking at the Java AST, for import com.google.common.hash.BloomFilter;:
- The
qualid is the identifier BloomFilter
- The
target is the package path com.google.common.hash
- So
qualid.getTarget().toString() returns "com.google.common.hash" not the full FQN
Wait, let me re-read the code more carefully. For an import statement, qualid is the full path from package to class name. So qualid.getTarget() would be com.google.common.hash (the package) and qualid.getName() would be BloomFilter.
Actually, looking at the code:
J.Import elem = anImport.imports.get(0).getElement();
J.FieldAccess qualid = elem.getQualid();
J.Identifier name = qualid.getName();
For import com.google.common.hash.BloomFilter;:
qualid represents the full qualified name
qualid.getName() returns BloomFilter (the simple name)
qualid.getTarget() returns com.google.common.hash (the target/package)
So qualid.getTarget().toString() would be "com.google.common.hash".
Then:
String target = qualid.getTarget().toString();
Set<JavaType.FullyQualified> types = typesByPackage.getOrDefault(target, new HashSet<>());
This would look up typesByPackage with key "com.google.common.hash".
Now, in the type collection phase:
for (JavaType javaType : cu.getTypesInUse().getTypesInUse()) {
if (javaType instanceof JavaType.Parameterized) {
JavaType.Parameterized parameterized = (JavaType.Parameterized) javaType;
typesByPackage.computeIfAbsent(parameterized.getType().getPackageName(), f -> new HashSet<>())
.add(parameterized.getType());
When BloomFilter<T> is used in AtomicReference<BloomFilter<T>>, it would be added as a JavaType.Parameterized type. The parameterized.getType() would be the BloomFilter type, and parameterized.getType().getPackageName() would be "com.google.common.hash".
So the key should be "com.google.common.hash" and the value should include the BloomFilter type.
But wait, there's also this code:
String target = qualid.getTarget().toString();
Set<JavaType.FullyQualified> types = typesByPackage.getOrDefault(target, new HashSet<>());
Set<JavaType.FullyQualified> typesByFullyQualifiedClassPath = typesByPackage.getOrDefault(toFullyQualifiedName(target), new HashSet<>());
Where toFullyQualifiedName(target) is called on "com.google.common.hash", which would give... just "com.google.common.hash" since it's already a fully qualified name.
So both lookups would return the same result.
Actually wait, let me think about what toFullyQualifiedName does. Let me check:
static String toFullyQualifiedName(String name)
This is likely trying to convert a simple name or partial path to a fully qualified name. If the input is already a full FQN like "com.google.common.hash", it might just return it as is.
Actually, looking at the code more carefully, the check is:
Set<String> topLevelTypeNames = Stream.concat(types.stream(), typesByFullyQualifiedClassPath.stream())
.filter(fq -> fq.getOwningClass() == null)
.map(JavaType.FullyQualified::getFullyQualifiedName)
.collect(toSet());
Set<JavaType.FullyQualified> combinedTypes = Stream.concat(types.stream(), typesByFullyQualifiedClassPath.stream())
.filter(fq -> fq.getOwningClass() == null || !topLevelTypeNames.contains(fq.getOwningClass().getFullyQualifiedName()))
.collect(toSet());
JavaType.FullyQualified qualidType = TypeUtils.asFullyQualified(elem.getQualid().getType());
if ((combinedTypes.isEmpty() && !unqualifiedTypeNames.contains(elem.getTypeName())) || sourcePackage.equals(elem.getPackageName()) && qualidType != null && !qualidType.getFullyQualifiedName().contains("$")) {
anImport.used = false;
changed = true;
So the issue might be:
combinedTypes is empty (the BloomFilter type is not being found in typesByPackage)
unqualifiedTypeNames doesn't contain com.google.common.hash.BloomFilter
- So
anImport.used = false is set
The question is: why isn't BloomFilter being added to typesByPackage?
Let me think about this more carefully. When the code processes AtomicReference<BloomFilter<T>>, it will:
- First see
AtomicReference as a type
- See the type parameter
BloomFilter<T>
But the way types are collected:
for (JavaType javaType : cu.getTypesInUse().getTypesInUse()) {
if (javaType instanceof JavaType.Parameterized) {
JavaType.Parameterized parameterized = (JavaType.Parameterized) javaType;
typesByPackage.computeIfAbsent(parameterized.getType().getPackageName(), f -> new HashSet<>())
.add(parameterized.getType());
The key here is parameterized.getType().getPackageName(). For BloomFilter<T>, parameterized.getType() would be the BloomFilter type, and getPackageName() would return "com.google.common.hash".
So typesByPackage should have "com.google.common.hash" -> {BloomFilter type}.
Then when checking the import:
String target = qualid.getTarget().toString();
Set<JavaType.FullyQualified> types = typesByPackage.getOrDefault(target, new HashSet<>());
For the import com.google.common.hash.BloomFilter, qualid.getTarget().toString() should return "com.google.common.hash".
Wait, I need to verify this. Let me look at the J.Import structure more carefully.
For import com.google.common.hash.BloomFilter;:
elem.getQualid() returns a J.FieldAccess
J.FieldAccess has target (the left side) and name (the rightmost identifier)
- For a single-segment path like
BloomFilter, target might be null or empty
- For a multi-segment path like
com.google.common.hash.BloomFilter, target is com.google.common.hash
Actually, I think for imports, the qualid is structured differently. Let me think...
In Java AST, for import com.google.common.hash.BloomFilter:
- The qualid might be
com.google.common.hash.BloomFilter where:
- The outermost FieldAccess has
target = com.google.common.hash and name = BloomFilter
- The
target itself might be a nested FieldAccess
Actually, I think qualid.getTarget().toString() would be com.google.common.hash, not the full FQN.
But then the check is:
Set<JavaType.FullyQualified> types = typesByPackage.getOrDefault(target, new HashSet<>());
Where target = "com.google.common.hash". And typesByPackage should have this key with BloomFilter type as value.
Let me also check what toFullyQualifiedName(target) does. Looking at the import statement, I see:
import static org.openrewrite.java.tree.TypeUtils.toFullyQualifiedName;
So it's using TypeUtils.toFullyQualifiedName(String). Let me check what this does with "com.google.common.hash".
Actually, I should look at the actual TypeUtils class.
Actually, let me just look at what happens with a simpler case first. The import is for a non-wildcard, non-static import:
} else {
String target = qualid.getTarget().toString();
Set<JavaType.FullyQualified> types = typesByPackage.getOrDefault(target, new HashSet<>());
Set<JavaType.FullyQualified> typesByFullyQualifiedClassPath = typesByPackage.getOrDefault(toFullyQualifiedName(target), new HashSet<>());
...
}
For import java.util.List;:
qualid.getTarget().toString() = "java.util"
typesByPackage.getOrDefault("java.util", ...) should contain List
For import com.google.common.hash.BloomFilter;:
qualid.getTarget().toString() = "com.google.common.hash"
typesByPackage.getOrDefault("com.google.common.hash", ...) should contain BloomFilter
But what if qualid.getTarget().toString() doesn't return what I expect? Let me think about how J.FieldAccess works for a simple import like import BloomFilter;. In that case:
qualid.getTarget() might be null or a different type
qualid.getName() would be the identifier BloomFilter
Actually, I think I need to look at how imports are structured in the AST.
Actually, let me re-read the code more carefully. I see this:
J.FieldAccess qualid = elem.getQualid();
J.Identifier name = qualid.getName();
And later:
if ("*".equals(qualid.getSimpleName())) {
So qualid.getSimpleName() returns the simple name (like BloomFilter).
And then:
String target = qualid.getTarget().toString();
For import com.google.common.hash.BloomFilter;, qualid.getTarget() would be a J.FieldAccess representing com.google.common.hash, and .toString() would return "com.google.common.hash".
OK, I think the issue might be different. Let me check if BloomFilter is actually being collected in typesByPackage.
The code that collects types:
for (JavaType javaType : cu.getTypesInUse().getTypesInUse()) {
if (javaType instanceof JavaType.Parameterized) {
JavaType.Parameterized parameterized = (JavaType.Parameterized) javaType;
typesByPackage.computeIfAbsent(parameterized.getType().getPackageName(), f -> new HashSet<>())
.add(parameterized.getType());
for (JavaType typeParameter : parameterized.getTypeParameters()) {
JavaType.FullyQualified fq = TypeUtils.asFullyQualified(typeParameter);
if (fq != null) {
typesByPackage.computeIfAbsent(
fq.getOwningClass() == null ?
fq.getPackageName() :
toFullyQualifiedName(fq.getOwningClass().getFullyQualifiedName()),
f -> new HashSet<>()).add(fq);
}
}
} else if (javaType instanceof JavaType.FullyQualified) {
JavaType.FullyQualified fq = (JavaType.FullyQualified) javaType;
typesByPackage.computeIfAbsent(
fq.getOwningClass() == null ?
fq.getPackageName() :
toFullyQualifiedName(fq.getOwningClass().getFullyQualifiedName()),
f -> new HashSet<>()).add(fq);
}
}
So when AtomicReference<BloomFilter<T>> is parsed:
AtomicReference is added as a JavaType.FullyQualified (or Parameterized if it has type parameters)
- The type parameter
BloomFilter<T> is also processed as a Parameterized type
- The type parameter
T is also processed
The key question is: is BloomFilter actually in cu.getTypesInUse().getTypesInUse()?
Let me check what TypesInUse collects. It likely collects all types that are referenced in the source code, including in generic type parameters.
Actually, I just realized something. Let me look at the check again:
if ((combinedTypes.isEmpty() && !unqualifiedTypeNames.contains(elem.getTypeName())) || sourcePackage.equals(elem.getPackageName()) && qualidType != null && !qualidType.getFullyQualifiedName().contains("$")) {
anImport.used = false;
changed = true;
For the import com.google.common.hash.BloomFilter:
combinedTypes should contain the BloomFilter type (if it was properly collected)
unqualifiedTypeNames.contains(elem.getTypeName()) - elem.getTypeName() returns "com.google.common.hash.BloomFilter"
The check !unqualifiedTypeNames.contains(elem.getTypeName()) means: "if the import's FQN is NOT in unqualifiedTypeNames". But unqualifiedTypeNames contains FQNs of types that are used unqualified in the code.
So for BloomFilter<T> in the generic, BloomFilter should be added to unqualifiedTypeNames because it's used without a package qualifier.
Wait, let me re-read collectUnqualifiedTypeNames:
private Set<String> collectUnqualifiedTypeNames(J.CompilationUnit cu) {
return new JavaIsoVisitor<Set<String>>() {
@Override
public J.Identifier visitIdentifier(J.Identifier identifier, Set<String> unqualifiedTypeNames) {
JavaType type = identifier.getType();
// Check for unqualified type references (not field references)
if (type instanceof JavaType.FullyQualified && identifier.getFieldType() == null) {
// Check if this identifier is part of a fully qualified reference
// If it's part of a J.FieldAccess chain, it's qualified
if (!isPartOfQualifiedReference(identifier)) {
unqualifiedTypeNames.add(((JavaType.FullyQualified) type).getFullyQualifiedName());
}
}
return identifier;
}
This collects identifiers that have a type (meaning they're type references, not just identifiers), where the fieldType is null (not a field access), and they're not part of a qualified reference.
For BloomFilter<T> in AtomicReference<BloomFilter<T>>:
- The
BloomFilter identifier would be visited
identifier.getType() would be the BloomFilter type
identifier.getFieldType() would be null (it's not a field)
isPartOfQualifiedReference(identifier) - let me check this method
private boolean isPartOfQualifiedReference(J.Identifier identifier) {
// Walk up the cursor to see if this identifier is part of a J.FieldAccess chain
Cursor cursor = getCursor();
while (cursor != null) {
Object value = cursor.getValue();
// This identifier is the name part of a field access
// Check if the target is a package/class reference (not a field)
if (value instanceof J.FieldAccess &&
((J.FieldAccess) value).getName() == identifier &&
((J.FieldAccess) value).getTarget() instanceof J.FieldAccess &&
((J.FieldAccess) value).getTarget().getType() instanceof JavaType.FullyQualified) {
return true; // This is a qualified reference
}
cursor = cursor.getParent();
}
return false;
}
This checks if the identifier is the name part of a FieldAccess where the target is also a FieldAccess with a FullyQualified type. This would be for cases like com.google.common.hash.BloomFilter where:
- The outermost FieldAccess has name
BloomFilter and target com.google.common.hash
- The target is a FieldAccess
For AtomicReference<BloomFilter<T>>:
- The
BloomFilter identifier in the type parameter list is NOT part of a FieldAccess chain
- It's just a simple identifier in the type parameter
- So
isPartOfQualifiedReference should return false
Wait, but the condition in isPartOfQualifiedReference is:
if (value instanceof J.FieldAccess &&
((J.FieldAccess) value).getName() == identifier &&
((J.FieldAccess) value).getTarget() instanceof J.FieldAccess &&
((J.FieldAccess) value).getTarget().getType() instanceof JavaType.FullyQualified)
This is checking if the identifier is the name part of a FieldAccess. For a type parameter in generics, the identifier might be wrapped in a Type tree, not a FieldAccess.
So I think collectUnqualifiedTypeNames should correctly add com.google.common.hash.BloomFilter to the set.
But wait, I need to check the full condition again:
if ((combinedTypes.isEmpty() && !unqualifiedTypeNames.contains(elem.getTypeName())) || sourcePackage.equals(elem.getPackageName()) && qualidType != null && !qualidType.getFullyQualifiedName().contains("$")) {
anImport.used = false;
changed = true;
This says: if combinedTypes is empty AND the FQN is not in unqualifiedTypeNames, then mark as unused.
OR if the import is in the same package and the type is not an inner class.
So the check is:
combinedTypes.isEmpty() && !unqualifiedTypeNames.contains(elem.getTypeName())
For BloomFilter:
combinedTypes - this should be non-empty if BloomFilter is in typesByPackage
unqualifiedTypeNames.contains("com.google.common.hash.BloomFilter") - this should be true if BloomFilter is collected as unqualified
So the first condition should be FALSE (assuming both are populated correctly).
The second condition:
sourcePackage.equals(elem.getPackageName()) && qualidType != null && !qualidType.getFullyQualifiedName().contains("$")
For BloomFilter:
sourcePackage is likely empty (no package declaration)
elem.getPackageName() would be "com.google.common.hash"
- So
sourcePackage.equals(elem.getPackageName()) is false
- The whole condition is false
So the import should NOT be marked as unused. But the issue says it IS being removed...
Let me think about what could go wrong. Maybe the issue is that BloomFilter is not being collected in typesByPackage at all.
When AtomicReference<BloomFilter<T>> is parsed:
AtomicReference is a JavaType.Parameterized
- Its type parameters include
BloomFilter<T>
BloomFilter<T> is also a JavaType.Parameterized
So when iterating through cu.getTypesInUse().getTypesInUse(), the BloomFilter<T> should be included as a Parameterized type.
But wait, let me check if it's the top-level type parameter that's being collected, or if there's some nesting issue.
Actually, looking at the code:
for (JavaType javaType : cu.getTypesInUse().getTypesInUse()) {
if (javaType instanceof JavaType.Parameterized) {
JavaType.Parameterized parameterized = (JavaType.Parameterized) javaType;
typesByPackage.computeIfAbsent(parameterized.getType().getPackageName(), f -> new HashSet<>())
.add(parameterized.getType());
The key is parameterized.getType().getPackageName(). For BloomFilter<T>:
parameterized.getType() returns the BloomFilter type
getPackageName() returns "com.google.common.hash"
So typesByPackage["com.google.common.hash"] should contain the BloomFilter type.
But then when looking up:
String target = qualid.getTarget().toString();
Set<JavaType.FullyQualified> types = typesByPackage.getOrDefault(target, new HashSet<>());
For import com.google.common.hash.BloomFilter;:
qualid.getTarget().toString() - what does this return?
This is the key question. Let me think about the AST structure for imports.
For import com.google.common.hash.BloomFilter;:
elem.getQualid() is a J.FieldAccess
- The structure is like:
J.FieldAccess(target=J.FieldAccess(target=J.FieldAccess(target=J.Identifier("com"), name=J.Identifier("google")), name=J.Identifier("common")), name=J.Identifier("hash")), name=J.Identifier("BloomFilter")
Actually no, I think the import qualid structure might be flatter. Let me check.
Actually, I think for a simple import like import BloomFilter;:
qualid would be just a J.Identifier (not a FieldAccess)
qualid.getTarget() would be null
But for import com.google.common.hash.BloomFilter;:
qualid would be a J.FieldAccess
qualid.getTarget() would be com.google.common.hash
qualid.getName() would be BloomFilter
So qualid.getTarget().toString() should return "com.google.common.hash".
Wait, but what if the qualid for imports is structured differently? Let me check by looking at how imports are parsed.
Actually, I should look at what elem.getTypeName() returns, because that's what's used to look up in methodsAndFieldsByTypeName:
String outerType = elem.getTypeName();
And elem.getTypeName() for com.google.common.hash.BloomFilter would return "com.google.common.hash.BloomFilter".
But for the non-static import check:
String target = qualid.getTarget().toString();
This uses qualid.getTarget(), not elem.getTypeName().
Let me check if there's any special handling for imports. Actually, I should look at how the AST is structured.
Let me just search for how imports work in the codebase:
Actually, I think I need to understand the structure better. Let me look at the J.Import class.
Actually, I think I've been overthinking this. Let me just run a test to see what's happening.
Let me create a simple test case in the test file:
Actually wait, I should first try to build the project and run the existing tests.
Let me check if there are any existing tests that might be related to this issue.
Actually, let me look at the issue more carefully. The user reports that:
Input:
import com.google.common.hash.BloomFilter;
import java.util.concurrent.atomic.AtomicReference;
@SuppressWarnings("UnstableApiUsage")
public class BloomFilterRef<T> extends AtomicReference<BloomFilter<T>> {
}
Output (wrong):
import java.util.concurrent.atomic.AtomicReference;
@SuppressWarnings("UnstableApiUsage")
public class BloomFilterRef<T> extends AtomicReference<BloomFilter<T>> {
}
So BloomFilter import is being removed, but AtomicReference import is kept.
Both types are used in extends AtomicReference<BloomFilter<T>>. The BloomFilter type is used as a type parameter, and AtomicReference is used as the base class.
Both should be in typesByPackage. Let me think about why BloomFilter might not be found.
Actually, I wonder if the issue is with the order of processing. The code first collects all types, then processes imports. But maybe there's an issue with how types are collected from the AST.
Let me look at the collectUnqualifiedTypeNames method more carefully. This method visits all identifiers and checks if they're type references. For BloomFilter<T>:
- The visitor visits the
BloomFilter identifier
identifier.getType() should be the BloomFilter type (not null)
identifier.getFieldType() should be null (it's not a field access)
isPartOfQualifiedReference(identifier) - what does this return?
The isPartOfQualifiedReference method checks if the identifier is part of a FieldAccess chain. For BloomFilter in AtomicReference<BloomFilter<T>>:
- The identifier
BloomFilter is part of a TypeTree.Parameterized (or similar), not a FieldAccess
- So
isPartOfQualifiedReference should return false
But wait, I need to check the isPartOfQualifiedReference method more carefully:
private boolean isPartOfQualifiedReference(J.Identifier identifier) {
Cursor cursor = getCursor();
while (cursor != null) {
Object value = cursor.getValue();
if (value instanceof J.FieldAccess &&
((J.FieldAccess) value).getName() == identifier &&
((J.FieldAccess) value).getTarget() instanceof J.FieldAccess &&
((J.FieldAccess) value).getTarget().getType() instanceof JavaType.FullyQualified) {
return true;
}
cursor = cursor.getParent();
}
return false;
}
This walks up the cursor tree and checks if any parent is a FieldAccess where this identifier is the name. For BloomFilter in AtomicReference<BloomFilter<T>>, the identifier might not be inside a FieldAccess at all, so this would return false.
But what if there's a FieldAccess somewhere in the tree? Let me think...
Actually, the issue might be more subtle. Let me check what identifier.getType() returns for a type parameter.
When parsing AtomicReference<BloomFilter<T>>:
- The
AtomicReference type has type parameters
- One of the type parameters is
BloomFilter<T>
- The
BloomFilter identifier in the type parameter list should have getType() returning the BloomFilter type
But what if getType() returns null? This could happen if the type attribution hasn't been done yet, or if there's some issue with how the type is represented.
Actually, looking at the visitor:
return new JavaIsoVisitor<Set<String>>() {
@Override
public J.Identifier visitIdentifier(J.Identifier identifier, Set<String> unqualifiedTypeNames) {
JavaType type = identifier.getType();
if (type instanceof JavaType.FullyQualified && identifier.getFieldType() == null) {
if (!isPartOfQualifiedReference(identifier)) {
unqualifiedTypeNames.add(((JavaType.FullyQualified) type).getFullyQualifiedName());
}
}
return identifier;
}
So it only adds the type if:
type instanceof JavaType.FullyQualified
identifier.getFieldType() == null
- Not part of a qualified reference
For BloomFilter in AtomicReference<BloomFilter<T>>:
type should be BloomFilter (a JavaType.FullyQualified)
getFileType() should be null
- Not part of a qualified reference
So it should be added. But let me also check what identifier.getFieldType() returns. This is the type of the field if this identifier is a field access. For a type parameter, it should be null.
Hmm, I'm not sure what's going wrong. Let me just try to add a test and run it.
Actually wait, let me look at the code more carefully. I see that collectUnqualifiedTypeNames is using JavaIsoVisitor, which means it visits the entire AST. And it checks if the identifier is part of a qualified reference.
But I wonder if there's an issue with the check in isPartOfQualifiedReference. The check is:
if (value instanceof J.FieldAccess &&
((J.FieldAccess) value).getName() == identifier &&
((J.FieldAccess) value).getTarget() instanceof J.FieldAccess &&
((J.FieldAccess) value).getTarget().getType() instanceof JavaType.FullyQualified)
The condition ((J.FieldAccess) value).getName() == identifier uses reference equality (==). This might not work if the identifier objects are different instances.
But I think this is probably fine, as the visitor would have the same identifier instance.
Actually wait, I just realized something. The check is:
((J.FieldAccess) value).getName() == identifier
This checks if the identifier is the name part of the FieldAccess. For com.google.common.hash.BloomFilter, the outermost FieldAccess would have name = BloomFilter. But for AtomicReference<BloomFilter<T>>, the BloomFilter identifier is not part of a FieldAccess, so this condition would never be true.
Unless... the AST is structured differently than I think.
Actually, let me think about this from a different angle. The issue says that BloomFilter import is removed but AtomicReference import is kept. Both are used in the same expression extends AtomicReference<BloomFilter<T>>.
If BloomFilter is being removed, it means:
combinedTypes is empty for the BloomFilter import, OR
unqualifiedTypeNames doesn't contain BloomFilter's FQN
And AtomicReference is kept, which means:
combinedTypes is NOT empty for the AtomicReference import, OR
unqualifiedTypeNames contains AtomicReference's FQN
Both types should be collected in typesByPackage and unqualifiedTypeNames. So why is there a difference?
Let me look at the type collection code again:
for (JavaType javaType : cu.getTypesInUse().getTypesInUse()) {
if (javaType instanceof JavaType.Parameterized) {
JavaType.Parameterized parameterized = (JavaType.Parameterized) javaType;
typesByPackage.computeIfAbsent(parameterized.getType().getPackageName(), f -> new HashSet<>())
.add(parameterized.getType());
The key is parameterized.getType().getPackageName(). For BloomFilter<T>:
parameterized.getType() returns the BloomFilter type
getPackageName() returns "com.google.common.hash"
But wait, what if parameterized.getType() returns a type with a different structure? Like what if BloomFilter is a generic type itself (which it is, BloomFilter<F>), and the type attribution gives it a different representation?
Actually, BloomFilter from Guava is defined as BloomFilter<F>. So when it appears as BloomFilter<T> (where T is the type parameter of the enclosing class), the type attribution should give it a JavaType.Parameterized with:
type = BloomFilter<F> (the raw type)
typeParameters = [T] (the actual type arguments)
Wait, I think I need to understand the structure better. Let me look at JavaType.Parameterized:
A Parameterized type has:
type: the base type (e.g., BloomFilter)
typeParameters: the actual type arguments
So for BloomFilter<T>:
parameterized.getType() = BloomFilter (the base type, which is a JavaType.FullyQualified)
parameterized.getType().getPackageName() = "com.google.common.hash"
This should work correctly.
But wait, what if the type attribution is not done? The RemoveUnusedImports visitor runs on the AST, and the types are attributed during parsing/type-checking. If the types are not attributed, identifier.getType() might return null.
But the AtomicReference import is kept, so types are being attributed. And AtomicReference is also a parameterized type with a type parameter.
Let me think about this differently. What's the difference between how AtomicReference and BloomFilter appear in the code?
AtomicReference appears as:
- The base class in the extends clause
AtomicReference<BloomFilter<T>> - a parameterized type
BloomFilter appears as:
- A type parameter in
BloomFilter<T>
- This is nested inside
AtomicReference<BloomFilter<T>>
So AtomicReference is at the "top level" of the type, while BloomFilter is a type parameter of AtomicReference.
When iterating through cu.getTypesInUse().getTypesInUse(), both should be included. But maybe there's a difference in how they're represented.
Actually, let me think about this more carefully. cu.getTypesInUse().getTypesInUse() returns a set of types that are used in the compilation unit. This includes:
- Types that are directly referenced (like in new expressions, extends clauses)
- Types that are used in method invocations
- Types that are used as type parameters
So both AtomicReference and BloomFilter should be in this set.
But the way they're added to typesByPackage might be different:
For AtomicReference<BloomFilter<T>>:
AtomicReference is a JavaType.Parameterized
- Its base type is
AtomicReference
- Its type parameters include
BloomFilter<T>
When processing AtomicReference<BloomFilter<T>>:
JavaType.Parameterized parameterized = (JavaType.Parameterized) javaType;
typesByPackage.computeIfAbsent(parameterized.getType().getPackageName(), f -> new HashSet<>())
.add(parameterized.getType());
This adds AtomicReference to typesByPackage["java.util.concurrent.atomic"].
Then, for the type parameters:
for (JavaType typeParameter : parameterized.getTypeParameters()) {
JavaType.FullyQualified fq = TypeUtils.asFullyQualified(typeParameter);
if (fq != null) {
typesByPackage.computeIfAbsent(
fq.getOwningClass() == null ?
fq.getPackageName() :
toFullyQualifiedName(fq.getOwningClass().getFullyQualifiedName()),
f -> new HashSet<>()).add(fq);
}
}
For BloomFilter<T>:
typeParameter is BloomFilter<T>, which is a JavaType.Parameterized
TypeUtils.asFullyQualified(typeParameter) - does this return null for a Parameterized type?
Let me check. asFullyQualified is likely a utility that checks if a type is a FullyQualified type and returns it, or returns null if it's not.
If BloomFilter<T> is a Parameterized type, asFullyQualified might return the base type (i.e., BloomFilter), or it might return null.
Let me check the TypeUtils.asFullyQualified method:
Actually, I don't have access to the source code of TypeUtils. But I can guess that it probably does something like:
static FullyQualified asFullyQualified(JavaType type) {
if (type instanceof FullyQualified) {
return (FullyQualified) type;
}
return null;
}
So if BloomFilter<T> is a Parameterized type, it might NOT be directly a FullyQualified type. The Parameterized type extends FullyQualified? Let me check.
Actually, JavaType.Parameterized probably extends JavaType.FullyQualified. If so, asFullyQualified would return the Parameterized type itself.
But then fq.getPackageName() would be... what? For a Parameterized type, getPackageName() might return the package of the base type (i.e., com.google.common.hash).
Let me assume that asFullyQualified returns the Parameterized type, and getPackageName() returns the package of the base type. Then BloomFilter<T> would be added to typesByPackage["com.google.common.hash"].
OK, so both AtomicReference and BloomFilter should be in typesByPackage. Then why is BloomFilter being removed?
Let me look at the check again:
String target = qualid.getTarget().toString();
Set<JavaType.FullyQualified> types = typesByPackage.getOrDefault(target, new HashSet<>());
Set<JavaType.FullyQualified> typesByFullyQualifiedClassPath = typesByPackage.getOrDefault(toFullyQualifiedName(target), new HashSet<>());
Set<String> topLevelTypeNames = Stream.concat(types.stream(), typesByFullyQualifiedClassPath.stream())
.filter(fq -> fq.getOwningClass() == null)
.map(JavaType.FullyQualified::getFullyQualifiedName)
.collect(toSet());
Set<JavaType.FullyQualified> combinedTypes = Stream.concat(types.stream(), typesByFullyQualifiedClassPath.stream())
.filter(fq -> fq.getOwningClass() == null || !topLevelTypeNames.contains(fq.getOwningClass().getFullyQualifiedName()))
.collect(toSet());
JavaType.FullyQualified qualidType = TypeUtils.asFullyQualified(elem.getQualid().getType());
if ((combinedTypes.isEmpty() && !unqualifiedTypeNames.contains(elem.getTypeName())) || sourcePackage.equals(elem.getPackageName()) && qualidType != null && !qualidType.getFullyQualifiedName().contains("$")) {
anImport.used = false;
changed = true;
For BloomFilter:
target = qualid.getTarget().toString() = "com.google.common.hash"
types = typesByPackage.get("com.google.common.hash") - this should contain BloomFilter
combinedTypes should not be empty
For AtomicReference:
target = qualid.getTarget().toString() = "java.util.concurrent.atomic"
types = typesByPackage.get("java.util.concurrent.atomic") - this should contain AtomicReference
combinedTypes should not be empty
So both should be kept. Unless there's something wrong with how the types are collected.
Actually, let me re-read the type collection code:
for (JavaType javaType : cu.getTypesInUse().getTypesInUse()) {
if (javaType instanceof JavaType.Parameterized) {
JavaType.Parameterized parameterized = (JavaType.Parameterized) javaType;
typesByPackage.computeIfAbsent(parameterized.getType().getPackageName(), f -> new HashSet<>())
.add(parameterized.getType());
for (JavaType typeParameter : parameterized.getTypeParameters()) {
JavaType.FullyQualified fq = TypeUtils.asFullyQualified(typeParameter);
if (fq != null) {
typesByPackage.computeIfAbsent(
fq.getOwningClass() == null ?
fq.getPackageName() :
toFullyQualifiedName(fq.getOwningClass().getFullyQualifiedName()),
f -> new HashSet<>()).add(fq);
}
}
} else if (javaType instanceof JavaType.FullyQualified) {
JavaType.FullyQualified fq = (JavaType.FullyQualified) javaType;
typesByPackage.computeIfAbsent(
fq.getOwningClass() == null ?
fq.getPackageName() :
toFullyQualifiedName(fq.getOwningClass().getFullyQualifiedName()),
f -> new HashSet<>()).add(fq);
}
}
So when processing AtomicReference<BloomFilter<T>>:
javaType = AtomicReference<BloomFilter<T>> (a Parameterized type)
parameterized.getType() = AtomicReference
parameterized.getType().getPackageName() = "java.util.concurrent.atomic"
AtomicReference is added to typesByPackage["java.util.concurrent.atomic"]
Then, for type parameters:
5. typeParameter = BloomFilter<T> (a Parameterized type)
6. fq = TypeUtils.asFullyQualified(typeParameter) - if Parameterized extends FullyQualified, this returns BloomFilter<T>
7. fq.getPackageName() = "com.google.common.hash"
8. BloomFilter<T> is added to typesByPackage["com.google.common.hash"]
So BloomFilter<T> is added to the map. But wait, is it BloomFilter<T> or just BloomFilter?
The fq is the Parameterized type BloomFilter<T>, which is stored as-is. When looking up in typesByPackage, we get back the Parameterized type.
Then, in the check:
Set<String> topLevelTypeNames = Stream.concat(types.stream(), typesByFullyQualifiedClassPath.stream())
.filter(fq -> fq.getOwningClass() == null)
.map(JavaType.FullyQualified::getFullyQualifiedName)
.collect(toSet());
For BloomFilter<T>:
fq.getOwningClass() - for a top-level type, this would be null
fq.getFullyQualifiedName() - this would return... what?
For a Parameterized type, getFullyQualifiedName() might return the FQN of the base type (i.e., com.google.common.hash.BloomFilter).
Actually, I'm not sure. Let me think about this differently.
OK, I think I need to actually run the code and see what's happening. Let me create a test case.
Wait, actually, I just noticed something in the code. Let me look at the qualid.getTarget().toString() again.
For an import like import com.google.common.hash.BloomFilter;:
elem.getQualid() is the qualified name
qualid.getTarget() is the target (the part before the last segment)
But what if the import is structured differently? Let me think about what qualid looks like for a simple import.
For import BloomFilter; (no package):
qualid might be just a J.Identifier with name BloomFilter
qualid.getTarget() might be null
For import com.google.common.hash.BloomFilter;:
qualid is a J.FieldAccess with:
target = com.google.common.hash (a nested FieldAccess or Identifier)
name = BloomFilter
So qualid.getTarget().toString() would return "com.google.common.hash".
But what if the import is stored differently in the AST? Let me check if there's any special handling for imports.
Actually, let me just look at the J.Import class to understand the structure:
Actually, I should just search for the J.Import class:
Let me take a different approach. Let me search for related tests or issues:
Actually, let me just add a test case to the test file and see if it fails:
Let me first compile and run the existing tests to make sure everything works, then add my test case.
Actually, let me re-read the issue description more carefully. The user says:
RemoveUnusedImports removes imports when used in Generics only
So the issue is specifically about imports that are ONLY used in generics (i.e., type parameters). If the import is also used elsewhere (e.g., in a variable declaration), it's kept. But if it's only used in a generic type parameter, it's removed.
This gives me a clue. The issue might be in how types are collected from generic type parameters.
Let me look at collectUnqualifiedTypeNames again. This method collects identifiers that are used as unqualified type references. For BloomFilter<T>:
- The visitor visits the
BloomFilter identifier
identifier.getType() should be the BloomFilter type
- The identifier is added to
unqualifiedTypeNames
But what if identifier.getType() returns null for type parameters? This could happen if the type attribution doesn't properly attribute types in generic type parameter positions.
Actually, I think the issue might be in the isPartOfQualifiedReference method. Let me re-read it:
private boolean isPartOfQualifiedReference(J.Identifier identifier) {
Cursor cursor = getCursor();
while (cursor != null) {
Object value = cursor.getValue();
if (value instanceof J.FieldAccess &&
((J.FieldAccess) value).getName() == identifier &&
((J.FieldAccess) value).getTarget() instanceof J.FieldAccess &&
((J.FieldAccess) value).getTarget().getType() instanceof JavaType.FullyQualified) {
return true;
}
cursor = cursor.getParent();
}
return false;
}
This walks up the cursor and checks if the identifier is part of a qualified reference (i.e., a FieldAccess chain where the target is a package/class).
For BloomFilter in AtomicReference<BloomFilter<T>>:
- The identifier
BloomFilter is in a type parameter position
- Its parent is probably a
TypeTree.Parameterized or similar
- Not a FieldAccess
But what if there's a FieldAccess somewhere in the ancestor chain? Let me think...
Actually, the parent of BloomFilter identifier would be a TypeTree.Parameterized (for BloomFilter<T>), and the parent of that would be... a list of type arguments. The parent of that would be a TypeTree for AtomicReference, and so on.
I don't think there's a FieldAccess in the ancestor chain of BloomFilter in this context. So isPartOfQualifiedReference should return false.
Hmm, but what if the type attribution gives BloomFilter a different structure? Like what if it's wrapped in a J.FieldAccess for some reason?
Actually, I just realized something. Let me check what identifier.getFieldType() returns. This is the field type if this identifier is a field access. For a type parameter, it should be null.
But what if the identifier has a getFieldType() that's not null? This would cause the identifier to NOT be added to unqualifiedTypeNames.
Let me check when getFieldType() is non-null. Looking at the code:
if (type instanceof JavaType.FullyQualified && identifier.getFieldType() == null) {
So the identifier is only added if getFileType() is null. This means the identifier is NOT a field access.
But what if getFileType() is not null for some reason? This could happen if the identifier is part of a field access, even in a type parameter position.
Actually, I think the issue might be that BloomFilter is being visited multiple times, and one of the visits might have a different structure.
OK, I think I need to just run the code and see what's happening. Let me add a test case.
Actually, let me look at the issue from a different angle. Let me search for similar issues or test cases:
Let me search for tests that involve generics:
Actually, let me just try to understand the code flow by tracing through it manually.
For the input:
import com.google.common.hash.BloomFilter;
import java.util.concurrent.atomic.AtomicReference;
@SuppressWarnings("UnstableApiUsage")
public class BloomFilterRef<T> extends AtomicReference<BloomFilter<T>> {
}
-
The visitor collects types from cu.getTypesInUse().getTypesInUse().
-
This includes AtomicReference<BloomFilter<T>>, which is a Parameterized type.
-
For AtomicReference<BloomFilter<T>>:
parameterized.getType() = AtomicReference (FullyQualified)
parameterized.getType().getPackageName() = "java.util.concurrent.atomic"
AtomicReference is added to typesByPackage["java.util.concurrent.atomic"]
- Type parameters:
[BloomFilter<T>]
- For
BloomFilter<T>:
fq = TypeUtils.asFullyQualified(BloomFilter<T>)
- If
BloomFilter<T> is a Parameterized type and Parameterized extends FullyQualified, then fq = BloomFilter<T>
fq.getPackageName() = "com.google.common.hash"
BloomFilter<T> is added to typesByPackage["com.google.common.hash"]
-
Then, the visitor processes each import.
-
For import com.google.common.hash.BloomFilter;:
target = qualid.getTarget().toString() = "com.google.common.hash"
types = typesByPackage.get("com.google.common.hash") = {BloomFilter<T>} (a Parameterized type)
typesByFullyQualifiedClassPath = typesByPackage.get(toFullyQualifiedName("com.google.common.hash")) = same as types
topLevelTypeNames = types with getOwningClass() == null mapped to FQN
- For
BloomFilter<T>: getOwningClass() should be null (top-level type)
getFullyQualifiedName() should be "com.google.common.hash.BloomFilter"
topLevelTypeNames = {"com.google.common.hash.BloomFilter"}
combinedTypes = types where getOwningClass() == null || !topLevelTypeNames.contains(getOwningClass())
BloomFilter<T> has getOwningClass() == null, so it passes the filter
So the check should pass and the import should be kept. But the user says it's being removed...
Let me think about what could go wrong:
BloomFilter<T> is not in typesByPackage (not collected)
BloomFilter<T> is in typesByPackage, but with a different package name
qualid.getTarget().toString() returns something unexpected
unqualifiedTypeNames doesn't contain BloomFilter's FQN
Let me focus on possibility #1. Why would BloomFilter<T> not be in typesByPackage?
One possibility: BloomFilter<T> is not in cu.getTypesInUse().getTypesInUse(). This could happen if the type attribution doesn't include types from generic type parameters.
But that seems unlikely, as the type attribution should include all types that are used in the code.
Another possibility: BloomFilter<T> is in typesInUse, but the code doesn't process it correctly. Let me re-read the type collection code:
for (JavaType javaType : cu.getTypesInUse().getTypesInUse()) {
if (javaType instanceof JavaType.Parameterized) {
JavaType.Parameterized parameterized = (JavaType.Parameterized) javaType;
typesByPackage.computeIfAbsent(parameterized.getType().getPackageName(), f -> new HashSet<>())
.add(parameterized.getType());
For BloomFilter<T>:
javaType = BloomFilter<T> (a Parameterized type)
parameterized.getType() = BloomFilter (the base type)
parameterized.getType().getPackageName() = "com.google.common.hash"
BloomFilter (the base type, not the parameterized type) is added to typesByPackage["com.google.common.hash"]
So BloomFilter (the base type) is added to the map. This should be fine, as the lookup later should still find it.
But wait, let me check the lookup code again:
Set<JavaType.FullyQualified> types = typesByPackage.getOrDefault(target, new HashSet<>());
This gets the set of types from the map. For BloomFilter, the set should contain the BloomFilter type.
Then:
Set<String> topLevelTypeNames = Stream.concat(types.stream(), typesByFullyQualifiedClassPath.stream())
.filter(fq -> fq.getOwningClass() == null)
.map(JavaType.FullyQualified::getFullyQualifiedName)
.collect(toSet());
For the BloomFilter type:
getOwningClass() = null (top-level type)
getFullyQualifiedName() = "com.google.common.hash.BloomFilter"
So topLevelTypeNames = {"com.google.common.hash.BloomFilter"}.
Then:
Set<JavaType.FullyQualified> combinedTypes = Stream.concat(types.stream(), typesByFullyQualifiedClassPath.stream())
.filter(fq -> fq.getOwningClass() == null || !topLevelTypeNames.contains(fq.getOwningClass().getFullyQualifiedName()))
.collect(toSet());
The filter keeps types where:
getOwningClass() == null OR
getOwningClass().getFullyQualifiedName() is NOT in topLevelTypeNames
For BloomFilter:
getOwningClass() = null
- So the first condition is true, and it's kept
So combinedTypes should contain BloomFilter.
Then:
if ((combinedTypes.isEmpty() && !unqualifiedTypeNames.contains(elem.getTypeName())) || sourcePackage.equals(elem.getPackageName()) && qualidType != null && !qualidType.getFullyQualifiedName().contains("$")) {
anImport.used = false;
For BloomFilter:
combinedTypes.isEmpty() = false
- So the first condition is false
sourcePackage.equals(elem.getPackageName()) = false (empty vs "com.google.common.hash")
- So the second condition is false
Therefore, the import should NOT be marked as unused.
But the user says it IS being removed. So there must be something different about the actual behavior.
Let me think about what could be different in the actual code:
- Maybe
BloomFilter is not in typesInUse
- Maybe the type attribution gives a different structure
- Maybe there's a bug in the code that I'm not seeing
Let me look at the issue from another angle. What if the problem is that BloomFilter is NOT added to typesByPackage because it's not in typesInUse?
When would a type not be in typesInUse? Let me think about how TypesInUse works.
TypesInUse collects all types that are referenced in the code. This includes:
- Types in new expressions
- Types in type declarations (extends, implements)
- Types in variable declarations
- Types in method parameters and return types
- Types in generic type arguments
So BloomFilter should be in typesInUse because it's used as a type argument in AtomicReference<BloomFilter<T>>.
But wait, what if there's an issue with how the type arguments are collected? Like what if the type argument BloomFilter<T> is not properly attributed because BloomFilter is not a known type (since we're not actually compiling with the Guava library)?
Actually, that's a good point. When OpenRewrite parses the code, it might not have access to the actual BloomFilter class from Guava. So the type attribution might give BloomFilter a different type, like JavaType.Unknown or something.
Let me check what happens when a type is not found. If BloomFilter is not a known type, the type attribution might give it a JavaType.Unknown type, which would NOT be a FullyQualified type.
In the type collection code:
if (javaType instanceof JavaType.Parameterized) {
...
} else if (javaType instanceof JavaType.FullyQualified) {
...
}
If BloomFilter has a JavaType.Unknown type, it wouldn't match either condition and wouldn't be added to typesByPackage.
But wait, even if the type is unknown, the type argument BloomFilter<T> should still be in typesInUse. And the type argument should be represented as a Parameterized type with the unknown type.
Actually, let me think about this more carefully. When OpenRewrite parses AtomicReference<BloomFilter<T>>:
AtomicReference is a known type (from java.util.concurrent.atomic)
AtomicReference has a type parameter F (or whatever it's defined as)
- The type argument
BloomFilter<T> is provided
- The type attribution tries to match
BloomFilter<T> with the type parameter F
- Since
BloomFilter is not a known type, the type attribution might give it an unknown type
So BloomFilter<T> might be represented as a Parameterized type with:
type = BloomFilter (but with an unknown/invalid type)
typeParameters = [T]
If type is not a FullyQualified type (because it's unknown), then parameterized.getType().getPackageName() might throw a null pointer exception or return null.
Actually, let me check what JavaType.Unknown looks like. If it's not a FullyQualified type, then getPackageName() might throw an exception.
But the code doesn't seem to handle this case, so if BloomFilter is unknown, the code might crash or behave unexpectedly.
But the user says the import is being removed, not that the code crashes. So the code must be handling the unknown type somehow.
Let me think about this differently. Maybe BloomFilter is attributed as a Parameterized type with a FullyQualified base type (even though the class is not actually available). The type attribution might give it a FullyQualified type with a placeholder or synthetic type.
Or maybe the type attribution doesn't even process the type argument if it's unknown. In that case, BloomFilter would not be in typesInUse.
OK, I think I need to just run the code and see what's happening. Let me add a test case.
Actually, wait. Let me re-read the code one more time. I want to make sure I understand the flow correctly.
Actually, I just realized something. The issue says "RemoveUnusedImports removes imports when used in Generics only". This means the import is removed ONLY if the type is used in generics. If the type is also used elsewhere, the import is kept.
So maybe the issue is that BloomFilter is NOT being collected in either typesByPackage or unqualifiedTypeNames. But AtomicReference IS being collected.
Let me check if there's a difference between how AtomicReference and BloomFilter are attributed:
AtomicReference is a standard Java type, so it should be easily attributed
BloomFilter is from Guava, which is not a standard Java type
So AtomicReference is definitely in typesInUse, but BloomFilter might not be.
But wait, AtomicReference<BloomFilter<T>> is a Parameterized type. When the code processes this:
for (JavaType javaType : cu.getTypesInUse().getTypesInUse()) {
if (javaType instanceof JavaType.Parameterized) {
JavaType.Parameterized parameterized = (JavaType.Parameterized) javaType;
typesByPackage.computeIfAbsent(parameterized.getType().getPackageName(), f -> new HashSet<>())
.add(parameterized.getType());
for (JavaType typeParameter : parameterized.getTypeParameters()) {
JavaType.FullyQualified fq = TypeUtils.asFullyQualified(typeParameter);
if (fq != null) {
typesByPackage.computeIfAbsent(
fq.getOwningClass() == null ?
fq.getPackageName() :
toFullyQualifiedName(fq.getOwningClass().getFullyQualifiedName()),
f -> new HashSet<>()).add(fq);
}
}
The code iterates through typesInUse. If BloomFilter is in typesInUse, it should be processed. But if BloomFilter is not in typesInUse, it won't be processed.
So the question is: is BloomFilter in typesInUse?
If BloomFilter is from an unknown package (Guava), the type attribution might not be able to resolve it. In that case, it might be represented as an unknown type, which would NOT be in typesInUse.
But wait, typesInUse should include types that are referenced in the code, regardless of whether they're known or unknown. So even if BloomFilter is not a known type, it should still be in typesInUse.
Actually, let me check what TypesInUse does. It's a visitor that collects all types that are used in the code. It should include:
- Types that are directly referenced (e.g., in extends clauses)
- Types that are used as type arguments
- Types that are used in method signatures
So BloomFilter should be in typesInUse, even if it's from an unknown package.
But the representation might be different. If BloomFilter is unknown, it might be represented as a JavaType.Unknown type. And the check if (javaType instanceof JavaType.Parameterized) might not match.
Actually, wait. The issue is with AtomicReference<BloomFilter<T>>, not just BloomFilter. The entire parameterized type AtomicReference<BloomFilter<T>> should be in typesInUse.
When the code processes AtomicReference<BloomFilter<T>>:
javaType = AtomicReference<BloomFilter<T>> (a Parameterized type)
parameterized.getType() = AtomicReference (FullyQualified)
parameterized.getType().getPackageName() = "java.util.concurrent.atomic"
AtomicReference is added to typesByPackage["java.util.concurrent.atomic"]
Then, for type parameters:
5. typeParameter = BloomFilter<T> (a Parameterized type)
6. fq = TypeUtils.asFullyQualified(BloomFilter<T>)
7. If BloomFilter<T> is a Parameterized type and Parameterized extends FullyQualified, then fq = BloomFilter<T>
8. fq.getPackageName() = "com.google.common.hash" (from the base type)
9. BloomFilter<T> is added to typesByPackage["com.google.common.hash"]
So BloomFilter<T> should be added to the map. Then when looking up the import for BloomFilter, the code should find it.
But wait, the lookup code is:
String target = qualid.getTarget().toString();
Set<JavaType.FullyQualified> types = typesByPackage.getOrDefault(target, new HashSet<>());
For the import com.google.common.hash.BloomFilter:
target = qualid.getTarget().toString() = "com.google.common.hash"
And typesByPackage["com.google.common.hash"] should contain BloomFilter<T>.
So the lookup should succeed. Unless there's something wrong with qualid.getTarget().toString().
Let me think about what qualid.getTarget().toString() returns for an import.
For import com.google.common.hash.BloomFilter;:
elem.getQualid() is the qualified name
- The structure might be:
J.FieldAccess(target=J.Identifier("com"), name=J.Identifier("google")) ... no wait, that's not right.
Actually, I think the structure for com.google.common.hash.BloomFilter would be:
J.FieldAccess(
target = J.FieldAccess(
target = J.FieldAccess(
target = J.Identifier("com"),
name = J.Identifier("google")
),
name = J.Identifier("common")
),
name = J.Identifier("hash")
)
No wait, that's not right either. The structure should be:
J.FieldAccess(
target = J.FieldAccess(
target = J.FieldAccess(
target = J.Identifier("com"),
name = J.Identifier("google")
),
name = J.Identifier("common")
),
name = J.Identifier("hash")
)
Hmm, this doesn't look right. Let me think about this more carefully.
For com.google.common.hash.BloomFilter, the AST structure would be:
J.FieldAccess(
target = J.FieldAccess(
target = J.FieldAccess(
target = J.Identifier("com"),
name = J.Identifier("google")
),
name = J.Identifier("common")
),
name = J.Identifier("hash")
)
No, that's still not right. The structure should be:
J.FieldAccess(
target = J.FieldAccess(
target = J.FieldAccess(
target = J.Identifier("com"),
name = J.Identifier("google")
),
name = J.Identifier("common")
),
name = J.Identifier("hash")
)
Wait, I keep making the same mistake. Let me think about this more carefully.
For com.google.common.hash.BloomFilter, the structure should be:
J.FieldAccess(
target = J.FieldAccess(
target = J.FieldAccess(
target = J.FieldAccess(
target = J.Identifier("com"),
name = J.Identifier("google")
),
name = J.Identifier("common")
),
name = J.Identifier("hash")
),
name = J.Identifier("BloomFilter")
)
So the outermost FieldAccess has:
target = J.FieldAccess(target=J.FieldAccess(target=J.Identifier("com"), name=J.Identifier("google")), name=J.Identifier("common")), name=J.Identifier("hash")
name = J.Identifier("BloomFilter")
And qualid.getTarget().toString() would return "com.google.common.hash".
OK, so the lookup should work. Unless there's something else going on.
Let me check if maybe the issue is with toFullyQualifiedName(target). Let me look at what this does:
String target = qualid.getTarget().toString();
Set<JavaType.FullyQualified> types = typesByPackage.getOrDefault(target, new HashSet<>());
Set<JavaType.FullyQualified> typesByFullyQualifiedClassPath = typesByPackage.getOrDefault(toFullyQualifiedName(target), new HashSet<>());
For target = "com.google.common.hash":
toFullyQualifiedName("com.google.common.hash") - what does this return?
If this function converts a simple name to a FQN, it might not do anything to an already-qualified name. So toFullyQualifiedName("com.google.common.hash") would return "com.google.common.hash".
But if this function does something else, like appending something, it might return a different value.
Actually, I don't know what toFullyQualifiedName does. Let me search for it:
Let me look at the TypeUtils.toFullyQualifiedName method. It's imported at the top of the file:
import static org.openrewrite.java.tree.TypeUtils.toFullyQualifiedName;
So it's from org.openrewrite.java.tree.TypeUtils. Let me search for this method:
Let me search for where this is defined:
OK I think I've been going in circles. Let me just try to create a test and run it to see what's happening. I'll add a test case to the test file and run the tests.
Actually wait, let me look at the code one more time. I want to see if there's something I missed.
Actually, I just thought of something. What if the issue is that BloomFilter is being processed, but it's being added with a different key in typesByPackage?
When BloomFilter<T> is processed:
JavaType.FullyQualified fq = TypeUtils.asFullyQualified(typeParameter);
if (fq != null) {
typesByPackage.computeIfAbsent(
fq.getOwningClass() == null ?
fq.getPackageName() :
toFullyQualifiedName(fq.getOwningClass().getFullyQualifiedName()),
f -> new HashSet<>()).add(fq);
}
The key is:
fq.getOwningClass() == null ? fq.getPackageName() : toFullyQualifiedName(fq.getOwningClass().getFullyQualifiedName())
For BloomFilter<T>:
fq.getOwningClass() - for a top-level type, this should be null
- So the key is
fq.getPackageName() = "com.google.common.hash"
So the key should be correct.
But wait, what if fq.getPackageName() returns something different? Like what if it returns the package of the parameterized type, which might be different from the base type?
For a Parameterized type, getPackageName() probably returns the package of the base type. So for BloomFilter<T>, it should return "com.google.common.hash".
Hmm, but the key in typesByPackage is the package name, and the value is the type. When looking up, we get the set of types from that package. Then we filter based on getOwningClass().
For BloomFilter<T>:
getOwningClass() = null (top-level type)
- So it passes the filter
fq.getOwningClass() == null || ...
So combinedTypes should contain BloomFilter<T>.
Then:
if ((combinedTypes.isEmpty() && !unqualifiedTypeNames.contains(elem.getTypeName())) || ...) {
anImport.used = false;
combinedTypes.isEmpty() = false
- So the first condition is false
Therefore, the import should NOT be marked as unused.
But the user says it IS being removed. So there must be something else going on.
Let me think about this one more time. Maybe the issue is that BloomFilter<T> is NOT in typesInUse at all. This could happen if:
- The type attribution doesn't include types from generic type parameters
- The type attribution can't resolve
BloomFilter because it's an unknown type
If BloomFilter<T> is not in typesInUse, then it won't be processed by the type collection loop. And BloomFilter won't be added to typesByPackage.
But then, why is AtomicReference being kept? Because AtomicReference<BloomFilter<T>> is in typesInUse, and AtomicReference is added to typesByPackage.
So the issue might be that BloomFilter is not being added to typesByPackage because it's not in typesInUse (or it's not being processed correctly).
And unqualifiedTypeNames also might not contain BloomFilter's FQN. Let me check collectUnqualifiedTypeNames:
private Set<String> collectUnqualifiedTypeNames(J.CompilationUnit cu) {
return new JavaIsoVisitor<Set<String>>() {
@Override
public J.Identifier visitIdentifier(J.Identifier identifier, Set<String> unqualifiedTypeNames) {
JavaType type = identifier.getType();
if (type instanceof JavaType.FullyQualified && identifier.getFieldType() == null) {
if (!isPartOfQualifiedReference(identifier)) {
unqualifiedTypeNames.add(((JavaType.FullyQualified) type).getFullyQualifiedName());
}
}
return identifier;
}
For BloomFilter in AtomicReference<BloomFilter<T>>:
- The visitor visits the
BloomFilter identifier
identifier.getType() - what does this return?
If the type attribution couldn't resolve BloomFilter, getType() might return null or an unknown type. In that case:
type instanceof JavaType.FullyQualified would be false
- The identifier would NOT be added to
unqualifiedTypeNames
So if BloomFilter is not a known type, it won't be added to unqualifiedTypeNames.
And if BloomFilter<T> is not in typesInUse (or is in typesInUse but with a non-FullyQualified type), it won't be added to typesByPackage.
So both combinedTypes would be empty AND unqualifiedTypeNames would not contain the FQN. And the import would be marked as unused.
This explains the issue!
So the fix should be to also check for type references in generic type parameters, even if the type attribution can't resolve the type.
But how do we detect this? We need to check if the identifier is a type reference (even if it's not attributed), not just if it has a FullyQualified type.
Actually, wait. The collectUnqualifiedTypeNames method is supposed to collect identifiers that are used as unqualified type references. If the type attribution can't resolve the type, the identifier won't have a type, and it won't be collected.
But the issue is that we're trying to remove unused imports. If an import is for a type that's not in typesInUse (because the type attribution couldn't resolve it), we might incorrectly remove it.
So the fix should be to check if the identifier is used as a type reference, regardless of whether the type attribution could resolve the type.
But how do we know if an identifier is used as a type reference without the type attribution? We'd need to look at the context of the identifier.
Actually, let me re-read the issue description one more time. The user says:
RemoveUnusedImports removes imports when used in Generics only
So the issue is specifically about imports that are ONLY used in generics. If the import is also used elsewhere (e.g., in a variable declaration), it's kept. This suggests that the issue is with how types in generic type parameters are handled.
Let me think about this. If BloomFilter is used in a variable declaration like:
BloomFilter<Object> filter = new BloomFilter<>();
Then:
- The
BloomFilter identifier would be visited
identifier.getType() would return the BloomFilter type (because it's used in a new expression)
- The identifier would be added to
unqualifiedTypeNames
- The import would be kept
But if BloomFilter is only used in a generic type parameter like:
extends AtomicReference<BloomFilter<T>>
Then:
- The
BloomFilter identifier would be visited
identifier.getType() might return null or an unknown type (because the type attribution might not attribute types in generic type parameter positions)
- The identifier would NOT be added to
unqualifiedTypeNames
- The import would be removed
So the issue is that types in generic type parameter positions are not being attributed properly, or the attribution is not being detected by collectUnqualifiedTypeNames.
But wait, AtomicReference is also used in a generic type position (extends AtomicReference<...>), and its import is kept. So the type attribution should be working for AtomicReference.
Let me think about the difference. AtomicReference is used as:
extends AtomicReference<BloomFilter<T>>
Here, AtomicReference is the base class of the extends clause. The type attribution should attribute AtomicReference as a FullyQualified type.
And BloomFilter is used as:
extends AtomicReference<BloomFilter<T>>
Here, BloomFilter is a type argument to AtomicReference. The type attribution should attribute BloomFilter as well, but it might not if BloomFilter is an unknown type.
So the difference is that AtomicReference is a known type (from Java's standard library), while BloomFilter is an unknown type (from Guava). The type attribution can resolve AtomicReference but not BloomFilter.
This makes sense!
So the fix should be to handle the case where a type is not resolved by the type attribution. We need to check if the identifier is used as a type reference, even if the type attribution can't resolve the type.
But how do we detect this? We'd need to look at the context of the identifier.
One approach: check if the identifier is a child of a TypeTree or similar structure that indicates it's being used as a type.
Let me think about the AST structure for AtomicReference<BloomFilter<T>>:
TypeTree.Parameterized(
type = AtomicReference,
typeParameters = [
TypeTree.Parameterized(
type = BloomFilter,
typeParameters = [TypeTree.Identifier(T)]
)
]
)
So BloomFilter is inside a TypeTree.Parameterized. The collectUnqualifiedTypeNames method visits identifiers, and it checks if the identifier has a type. But if the type attribution can't resolve the type, the identifier might not have a type.
So the fix should be to also check the context of the identifier, not just the type. If the identifier is inside a TypeTree, it's likely a type reference.
Actually, let me look at the isPartOfQualifiedReference method again. This method walks up the cursor tree to check if the identifier is part of a FieldAccess chain. We could use a similar approach to check if the identifier is part of a TypeTree.
Let me think about the structure of the AST for type parameters. When visiting BloomFilter in AtomicReference<BloomFilter<T>>:
- The visitor visits the
BloomFilter identifier
- The parent of the identifier might be a
TypeTree.Identifier or similar
Let me check what the parent of the identifier is. In Java, type parameters are represented as TypeTree nodes. So the parent of the BloomFilter identifier might be a TypeTree.Identifier.
Actually, I'm not sure about the exact AST structure. Let me search for how type parameters are represented in the AST:
Actually, let me take a different approach. Let me look at how JavaIsoVisitor visits the AST and what types of nodes it encounters.
Actually, I think I need to just look at the code and trace through it manually. Let me assume the AST structure for AtomicReference<BloomFilter<T>> is something like:
J.ClassDeclaration(
extends = TypeTree.Parameterized(
type = TypeTree.Identifier(AtomicReference),
typeParameters = [
TypeTree.Parameterized(
type = TypeTree.Identifier(BloomFilter),
typeParameters = [
TypeTree.Identifier(T)
]
)
]
)
)
And JavaIsoVisitor visits all nodes, including the identifiers inside TypeTree nodes.
When visiting the BloomFilter identifier:
visitIdentifier is called
identifier.getType() returns the type of the identifier
If the type attribution can't resolve BloomFilter, getType() might return null.
Actually, wait. I just realized something. The TypesInUse visitor collects types from the AST. If BloomFilter is in the AST, it should be collected in TypesInUse, regardless of whether the type attribution can resolve it.
Let me check how TypesInUse works. It visits the AST and collects types. For type parameters, it should collect the type even if it's not a FullyQualified type.
Actually, TypesInUse probably only collects JavaType objects that have a type. If the type attribution can't resolve the type, the JavaType might be null or some kind of unknown type.
Hmm, this is getting complicated. Let me just try to add a test case and see what happens.
Actually, let me look at this from a different angle. The issue title is "RemoveUnusedImports removes imports when used in Generics only". This suggests that the problem is specifically with generic type parameters.
Let me search for existing tests related to generics:
Actually, let me just add a test case that reproduces the issue and see if it fails:
Let me write a test case:
OK let me just start by writing a simple test that reproduces the issue.
<tool_call>
<function=bash_terminal>
<parameter=command>
cd /rewrite && grep -n "Issue" rewrite-java-test/src/test/java/org/openrewrite/java/RemoveUnusedImportsTest.java | tail -20
</tool_call>