Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve handling of inner classes #4483

Merged
merged 7 commits into from
Sep 16, 2024
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 @@ -22,14 +22,12 @@
import org.openrewrite.style.NamedStyles;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;
import org.openrewrite.test.SourceSpec;

import static java.util.Collections.emptySet;
import static java.util.Collections.singletonList;
import static org.openrewrite.Tree.randomId;
import static org.openrewrite.java.Assertions.addTypesToSourceSet;
import static org.openrewrite.java.Assertions.java;
import static org.openrewrite.java.Assertions.srcMainJava;
import static org.openrewrite.java.Assertions.version;
import static org.openrewrite.java.Assertions.*;

class OrderImportsTest implements RewriteTest {

Expand All @@ -53,7 +51,7 @@ void multipleClassesWithTheSameNameButDifferentPackages() {
"""
import java.awt.List;
import java.util.List;

class Test {}
"""
)
Expand Down Expand Up @@ -87,9 +85,9 @@ void blankLinesNotFollowedByBlockArentAdded() {
java(
"""
import java.util.List;

import static java.util.Collections.*;

class A {}
"""
)
Expand Down Expand Up @@ -133,15 +131,15 @@ void unfoldStar() {
java(
"""
import java.util.*;

class A {
List<Integer> list;
List<Integer> list2;
}
""",
"""
import java.util.List;

class A {
List<Integer> list;
List<Integer> list2;
Expand All @@ -158,7 +156,7 @@ void unfoldStarMultiple() {
java(
"""
import java.util.*;

class A {
List<Integer> list;
Map<Integer, Integer> map;
Expand All @@ -167,7 +165,7 @@ class A {
"""
import java.util.List;
import java.util.Map;

class A {
List<Integer> list;
Map<Integer, Integer> map;
Expand Down Expand Up @@ -196,18 +194,18 @@ void unfoldStaticStar() {
java(
"""
import java.util.List;

import static java.util.Collections.*;

class A {
List<Integer> list = emptyList();
}
""",
"""
import java.util.List;

import static java.util.Collections.emptyList;

class A {
List<Integer> list = emptyList();
}
Expand Down Expand Up @@ -270,25 +268,25 @@ void springCloudFormat() {
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import reactor.core.publisher.Mono;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.server.ServerWebExchange;

import static java.util.Arrays.stream;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.toAsyncPredicate;

class A {}
"""
)
Expand Down Expand Up @@ -340,7 +338,7 @@ void preservesStaticStarImportWhenRemovingUnused() {
java(
"""
import static java.util.Collections.*;

class Test {
Object[] o = new Object[] { emptyList(), emptyMap(), emptySet() };
}
Expand All @@ -362,7 +360,7 @@ public class MyCollections extends java.util.Collections {}
java(
"""
import static my.MyCollections.*;

class Test {
Object[] o = new Object[] { emptyList(), emptyMap(), emptySet() };
}
Expand All @@ -378,7 +376,7 @@ void preservesStaticMethodArguments() {
java(
"""
import static java.util.Collections.*;

class Test {
Object[] o = new Object[] { emptyList(), emptyMap(), emptySet() };
}
Expand Down Expand Up @@ -470,9 +468,9 @@ class Test {
""",
"""
import static java.util.Collections.singletonList;

import java.util.List;

class Test {
}
"""
Expand Down Expand Up @@ -510,10 +508,10 @@ void detectBlockPattern() {
// org.slf4j should be detected as a block pattern, and not be moved to all other imports.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;

public class C {
}
"""
Expand Down Expand Up @@ -554,14 +552,14 @@ void doNotFoldImports() {
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

public class C {
}
"""
Expand Down Expand Up @@ -668,12 +666,12 @@ void foldPackageWithExistingImports() {
singletonList(
new NamedStyles(
randomId(), "test", "test", "test", emptySet(), singletonList(
ImportLayoutStyle.builder()
.packageToFold("java.util.*", false)
.importAllOthers()
.importStaticAllOthers()
.build()
)
ImportLayoutStyle.builder()
.packageToFold("java.util.*", false)
.importAllOthers()
.importStaticAllOthers()
.build()
)
)
))),
java(
Expand All @@ -686,4 +684,44 @@ void foldPackageWithExistingImports() {
)
);
}

@Test
void nestedInnerClass() {
// language=java
rewriteRun(
spec -> spec.recipe(new OrderImports(true)),
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
java(
"""
import org.openrewrite.java.tree.JContainer;
import org.openrewrite.java.tree.JLeftPadded;
import org.openrewrite.java.tree.JRightPadded;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.JavaType.Variable;
import org.openrewrite.java.tree.Space;

public class Foo {
Variable myVariable = null;
JLeftPadded<JavaType> myLeftPadded = null;
JRightPadded<JavaType> myRightPadded = null;
JContainer<JavaType> myContainer = null;
Space mySpace = null;
JavaType.Variable myVariable = null;
}
""",
"""
import org.openrewrite.java.tree.*;
import org.openrewrite.java.tree.JavaType.Variable;

public class Foo {
Variable myVariable = null;
JLeftPadded<JavaType> myLeftPadded = null;
JRightPadded<JavaType> myRightPadded = null;
JContainer<JavaType> myContainer = null;
Space mySpace = null;
JavaType.Variable myVariable = null;
}
"""
)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2035,4 +2035,37 @@ class CImpl {
)
);
}

@Test
void staticNestedInnerClass() {
// language=java
rewriteRun(
java(
"""
package a;

public class A {
public final class B {}
public static class C {}
}
""",
SourceSpec::skip),
java(
"""
import a.*;

public class Foo {
A method(A.B ab, A.C ac) {}
}
""",
"""
import a.A;

public class Foo {
A method(A.B ab, A.C ac) {}
}
"""
)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,20 @@ public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionCon
for (JavaType typeParameter : parameterized.getTypeParameters()) {
JavaType.FullyQualified fq = TypeUtils.asFullyQualified(typeParameter);
if (fq != null) {
typesByPackage.computeIfAbsent(fq.getPackageName(), f -> new HashSet<>()).add(fq);
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.getPackageName(), f -> new HashSet<>()).add(fq);
typesByPackage.computeIfAbsent(
fq.getOwningClass() == null ?
fq.getPackageName() :
toFullyQualifiedName(fq.getOwningClass().getFullyQualifiedName()),
f -> new HashSet<>()).add(fq);
}
}

Expand Down Expand Up @@ -152,7 +160,7 @@ public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionCon
SortedSet<String> targetMethodsAndFields = methodsAndFieldsByTypeName.get(modifiedTarget);

Set<JavaType.FullyQualified> staticClasses = null;
for (JavaType.FullyQualified maybeStatic : typesByPackage.getOrDefault(elem.getPackageName(), emptySet())) {
for (JavaType.FullyQualified maybeStatic : typesByPackage.getOrDefault(target, emptySet())) {
if (maybeStatic.getOwningClass() != null && outerType.startsWith(maybeStatic.getOwningClass().getFullyQualifiedName())) {
if (staticClasses == null) {
staticClasses = new HashSet<>();
Expand Down Expand Up @@ -207,8 +215,9 @@ public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionCon
changed = true;
}
} else {
Set<JavaType.FullyQualified> types = typesByPackage.getOrDefault(elem.getPackageName(), new HashSet<>());
Set<JavaType.FullyQualified> typesByFullyQualifiedClassPath = typesByPackage.getOrDefault(toFullyQualifiedName(elem.getPackageName()), new HashSet<>());
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<JavaType.FullyQualified> combinedTypes = Stream.concat(types.stream(), typesByFullyQualifiedClassPath.stream())
.collect(Collectors.toSet());
JavaType.FullyQualified qualidType = TypeUtils.asFullyQualified(elem.getQualid().getType());
Expand Down Expand Up @@ -236,7 +245,7 @@ public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionCon

changed = true;
} else {
usedWildcardImports.add(elem.getQualid().getTarget().toString());
usedWildcardImports.add(target);
}
} else if (combinedTypes.stream().noneMatch(c -> {
if ("*".equals(elem.getQualid().getSimpleName())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -788,11 +788,8 @@ private static String packageOrOuterClassName(JRightPadded<J.Import> anImport) {
if (anImport.getElement().isStatic()) {
return typeName;
} else {
String className = anImport.getElement().getClassName();
if (className.contains("$")) {
return anImport.getElement().getPackageName() + "." +
className.substring(0, className.lastIndexOf('$'))
.replace('$', '.');
if (typeName.contains("$")) {
return typeName.substring(0, typeName.lastIndexOf('$')).replace('$', '.');
}
return anImport.getElement().getPackageName();
}
Expand Down
Loading