Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import static org.openrewrite.rpc.RpcObjectData.State.*;
import static org.openrewrite.rpc.RpcObjectData.State.DELETE;
import static org.openrewrite.rpc.RpcObjectData.State.END_OF_OBJECT;

@Value
public class GetObject implements RpcRequest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@
import org.openrewrite.internal.ListUtils;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.tree.*;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaSourceFile;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.marker.Markup;
import org.openrewrite.maven.MavenDownloadingException;
import org.openrewrite.maven.MavenDownloadingExceptions;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@
import org.openrewrite.internal.StringUtils;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.tree.*;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaSourceFile;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.kotlin.tree.K;
import org.openrewrite.marker.Markup;
import org.openrewrite.maven.MavenDownloadingException;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertEquals;

class DependencyTest {
@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2120,4 +2120,104 @@ public class WithoutMap {
)
);
}

@Issue("https://github.com/openrewrite/rewrite/issues/5703")
@Test
void wildcardImportsWithConflictingNames() {
rewriteRun(
spec -> spec.expectedCyclesThatMakeChanges(2),
java(
"""
import java.sql.*;
import java.sql.Date;
import java.util.*;

class Main {
final Date date = new Date(123);
final java.util.Date date2 = new java.util.Date(123);
}
""",
"""
import java.sql.Date;

class Main {
final Date date = new Date(123);
final java.util.Date date2 = new java.util.Date(123);
}
"""
)
);
}

@Issue("https://github.com/openrewrite/rewrite/issues/5703")
@Test
void wildcardImportsWithSamePackageConflict() {
rewriteRun(
java(
"""
package com.helloworld;

public class Date {}
"""
),
java(
"""
package com.helloworld;

import java.util.*;

class Main {
final Date date = new Date();
final java.util.Date date2 = new java.util.Date(123);
}
""",
"""
package com.helloworld;

class Main {
final Date date = new Date();
final java.util.Date date2 = new java.util.Date(123);
}
"""
)
);
}

@Issue("https://github.com/openrewrite/rewrite/issues/5703")
@Test
void onlyFullyQualifiedUsageShouldRemoveWildcard() {
rewriteRun(
java(
"""
import java.util.*;

class Main {
final java.util.Date date2 = new java.util.Date(123);
}
""",
"""
class Main {
final java.util.Date date2 = new java.util.Date(123);
}
"""
)
);
}

@Issue("https://github.com/openrewrite/rewrite/issues/5703")
@Test
void keepImportWhenBothQualifiedAndUnqualifiedUsageExists() {
rewriteRun(
java(
"""
import java.util.Date;

class Test {
Date date1 = new Date(); // unqualified usage
java.util.Date date2 = new java.util.Date(); // qualified usage
}
"""
)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@

import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.*;
import org.openrewrite.java.style.ImportLayoutStyle;
import org.openrewrite.java.style.IntelliJ;
import org.openrewrite.java.tree.*;
Expand Down Expand Up @@ -84,6 +81,9 @@ public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionCon
Map<String, TreeSet<String>> methodsAndFieldsByTypeName = new HashMap<>();
Map<String, Set<JavaType.FullyQualified>> typesByPackage = new HashMap<>();

// Collect all unqualified type references upfront for efficiency
Set<String> unqualifiedTypeNames = collectUnqualifiedTypeNames(cu);

for (JavaType.Method method : cu.getTypesInUse().getUsedMethods()) {
if (method.hasFlags(Flag.Static)) {
methodsAndFieldsByTypeName.computeIfAbsent(method.getDeclaringType().getFullyQualifiedName(), t -> new TreeSet<>())
Expand Down Expand Up @@ -178,7 +178,7 @@ public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionCon
anImport.used = true;
usedStaticWildcardImports.add(elem.getTypeName());
} else if (((methodsAndFields == null ? 0 : methodsAndFields.size()) +
(staticClasses == null ? 0 : staticClasses.size())) < layoutStyle.getNameCountToUseStarImport()) {
(staticClasses == null ? 0 : staticClasses.size())) < layoutStyle.getNameCountToUseStarImport()) {
// replacing the star with a series of unfolded imports
anImport.imports.clear();

Expand Down Expand Up @@ -208,8 +208,8 @@ public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionCon
usedStaticWildcardImports.add(elem.getTypeName());
}
} else if (staticClasses != null && staticClasses.stream().anyMatch(c -> elem.getTypeName().equals(c.getFullyQualifiedName())) ||
(methodsAndFields != null && methodsAndFields.contains(qualid.getSimpleName())) ||
(targetMethodsAndFields != null && targetMethodsAndFields.contains(qualid.getSimpleName()))) {
(methodsAndFields != null && methodsAndFields.contains(qualid.getSimpleName())) ||
(targetMethodsAndFields != null && targetMethodsAndFields.contains(qualid.getSimpleName()))) {
anImport.used = true;
} else {
anImport.used = false;
Expand Down Expand Up @@ -238,18 +238,27 @@ public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionCon
// replacing the star with a series of unfolded imports
anImport.imports.clear();

// add each unfolded import
combinedTypes.stream().map(JavaType.FullyQualified::getClassName).sorted().distinct().forEach(type ->
anImport.imports.add(new JRightPadded<>(elem
// add each unfolded import, but only for types that are used unqualified
combinedTypes.stream()
.filter(fqType -> unqualifiedTypeNames.contains(fqType.getFullyQualifiedName()))
.map(JavaType.FullyQualified::getClassName)
.sorted()
.distinct()
.forEach(type -> anImport.imports.add(new JRightPadded<>(elem
.withQualid(qualid.withName(name.withSimpleName(type.substring(type.lastIndexOf('.') + 1))))
.withPrefix(Space.format("\n")), Space.EMPTY, Markers.EMPTY))
);
);

// move whatever the original prefix of the star import was to the first unfolded import
anImport.imports.set(0, anImport.imports.get(0).withElement(anImport.imports.get(0)
.getElement().withPrefix(elem.getPrefix())));

changed = true;
if (!anImport.imports.isEmpty()) {
anImport.imports.set(0, anImport.imports.get(0).withElement(anImport.imports.get(0)
.getElement().withPrefix(elem.getPrefix())));
changed = true;
} else {
// No types are used unqualified, so remove the wildcard import entirely
anImport.used = false;
changed = true;
}
} else {
usedWildcardImports.add(target);
}
Expand All @@ -269,11 +278,14 @@ public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionCon
// Do not use direct imports that are imported by a wildcard import
Set<String> ambiguousStaticImportNames = getAmbiguousStaticImportNames(cu);
for (ImportUsage anImport : importUsage) {
if (anImport.imports.isEmpty()) {
continue; // Skip import usages that have been completely removed
}
J.Import elem = anImport.imports.get(0).getElement();
if (!"*".equals(elem.getQualid().getSimpleName())) {
if (elem.isStatic()) {
if (usedStaticWildcardImports.contains(elem.getTypeName()) &&
!ambiguousStaticImportNames.contains(elem.getQualid().getSimpleName())) {
!ambiguousStaticImportNames.contains(elem.getQualid().getSimpleName())) {
anImport.used = false;
changed = true;
}
Expand All @@ -295,13 +307,13 @@ public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionCon
for (int i = 0; i < importGroup.size(); i++) {
JRightPadded<J.Import> anImport = importGroup.get(i);
if (i == 0 && lastUnusedImportSpace != null && anImport.getElement().getPrefix().getLastWhitespace()
.chars().filter(c -> c == '\n').count() <= 1) {
.chars().filter(c -> c == '\n').count() <= 1) {
anImport = anImport.withElement(anImport.getElement().withPrefix(lastUnusedImportSpace));
}
imports.add(anImport);
}
lastUnusedImportSpace = null;
} else if (lastUnusedImportSpace == null) {
} else if (lastUnusedImportSpace == null && !anImportGroup.imports.isEmpty()) {
lastUnusedImportSpace = anImportGroup.imports.get(0).getElement().getPrefix();
}
}
Expand Down Expand Up @@ -454,6 +466,54 @@ private static Set<String> getAmbiguousStaticImportNames(J.CompilationUnit cu) {
private static boolean conflictsWithJavaLang(J.Import elem) {
return JAVA_LANG_CLASS_NAMES.contains(elem.getClassName());
}

/**
* Collect all fully qualified names of types that are used in unqualified form.
* This is more efficient than checking each type individually during wildcard unfolding.
*
* @return a set of fully qualified type names that have unqualified references.
*/
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;
}

@Override
public J.Import visitImport(J.Import import_, Set<String> unqualifiedTypeNames) {
// Don't traverse into import statements
return import_;
}

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;
}
}.reduce(cu, new HashSet<>());
}
}

private static class ImportUsage {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.Duration;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import org.openrewrite.internal.ManagedThreadLocal;
import org.openrewrite.java.JavaPrinter;
import org.openrewrite.java.JavaTypeVisitor;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.internal.TypesInUse;
import org.openrewrite.java.tree.*;
import org.openrewrite.javascript.JavaScriptVisitor;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import org.openrewrite.xml.AddOrUpdateChild;
import org.openrewrite.xml.AddToTagVisitor;
import org.openrewrite.xml.ChangeTagValueVisitor;
import org.openrewrite.xml.TagNameComparator;
import org.openrewrite.xml.tree.Xml;

import java.util.*;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@

import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.test.SourceSpecs.*;
import static org.openrewrite.test.SourceSpecs.other;
import static org.openrewrite.test.SourceSpecs.text;

class FindSourceFilesTest implements RewriteTest {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.openrewrite.internal.ListUtils;
import org.openrewrite.style.GeneralFormatStyle;
import org.openrewrite.style.Style;
import org.openrewrite.yaml.MergeYaml.InsertMode;
import org.openrewrite.yaml.tree.Yaml;

import java.util.ArrayList;
Expand All @@ -35,7 +36,6 @@
import static org.openrewrite.Tree.randomId;
import static org.openrewrite.internal.ListUtils.*;
import static org.openrewrite.internal.StringUtils.*;
import static org.openrewrite.yaml.MergeYaml.InsertMode;
import static org.openrewrite.yaml.MergeYaml.InsertMode.*;
import static org.openrewrite.yaml.MergeYaml.REMOVE_PREFIX;

Expand Down
1 change: 1 addition & 0 deletions rewrite.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ recipeList:
- org.openrewrite.recipes.RecipeNullabilityBestPracticesSubset
# - org.openrewrite.java.recipes.ExamplesExtractor
# - org.openrewrite.java.OrderImports
- org.openrewrite.java.RemoveUnusedImports
- org.openrewrite.java.SimplifySingleElementAnnotation
- org.openrewrite.java.format.EmptyNewlineAtEndOfFile
- org.openrewrite.java.format.RemoveTrailingWhitespace
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,6 @@
*/
package org.openrewrite.toml;

import org.intellij.lang.annotations.Language;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.test.SourceSpec;
import org.openrewrite.test.SourceSpecs;
import org.openrewrite.toml.tree.Toml;

import java.util.function.Consumer;

public class Assertions {
private Assertions() {
}
Expand Down
Loading