From c94003cbc533585e456e044e625a741528399a8d Mon Sep 17 00:00:00 2001 From: patpatpat123 <43899031+patpatpat123@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:03:58 +0800 Subject: [PATCH] Add a replaceStaticImports step for Java Replaces static imports with regular imports and qualified references, so that assertTrue(x) becomes Assertions.assertTrue(x). Available as replaceStaticImports() in Gradle and in Maven, with excludes for the static imports to keep. A static import is only replaced when every use of it can be resolved with certainty, using the project classpath and the JLS scoping rules; otherwise it is left as it is. The JavaParser setup that expandWildcardImports uses moves into a small shared helper. --- CHANGES.md | 1 + README.md | 2 + .../ExpandWildcardsFormatterFunc.java | 27 +- .../ReplaceStaticImportsFormatterFunc.java | 1839 +++++++++++++++++ .../glue/javaparser/SymbolResolution.java | 202 ++ .../java/ReplaceStaticImportsStep.java | 140 ++ plugin-gradle/CHANGES.md | 1 + plugin-gradle/README.md | 68 +- .../gradle/spotless/JavaExtension.java | 25 +- .../spotless/JavaDefaultTargetTest.java | 52 + plugin-maven/CHANGES.md | 1 + plugin-maven/README.md | 73 +- .../spotless/maven/AbstractSpotlessMojo.java | 17 +- .../diffplug/spotless/maven/java/Java.java | 4 + .../maven/java/ReplaceStaticImports.java | 43 + .../java/ReplaceStaticImportsStepTest.java | 68 + .../AmbiguousOnDemandFormatted.test | 11 + .../AmbiguousOnDemandUnformatted.test | 12 + ...cludedMemberUsedThroughOnDemandImport.test | 9 + ...hInvisibleOnDemandCompetitorFormatted.test | 7 + ...nvisibleOnDemandCompetitorUnformatted.test | 9 + .../OnDemandJavaLangFormatted.test | 7 + .../OnDemandJavaLangUnformatted.test | 9 + ...DeclarationThroughTwoImportsFormatted.test | 8 + ...clarationThroughTwoImportsUnformatted.test | 8 + .../SingleAndOnDemandFormatted.test | 9 + .../SingleAndOnDemandUnformatted.test | 10 + ...mportOfAFieldShadowsOnDemandFormatted.test | 8 + ...ortOfAFieldShadowsOnDemandUnformatted.test | 8 + .../UnresolvableOnDemandImport.test | 10 + ...UnresolvableSingleImportOfTheSameName.test | 10 + .../java/ReplaceStaticImportsStepTest.java | 1767 ++++++++++++++++ 32 files changed, 4431 insertions(+), 34 deletions(-) create mode 100644 lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/ReplaceStaticImportsFormatterFunc.java create mode 100644 lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/SymbolResolution.java create mode 100644 lib/src/main/java/com/diffplug/spotless/java/ReplaceStaticImportsStep.java create mode 100644 plugin-maven/src/main/java/com/diffplug/spotless/maven/java/ReplaceStaticImports.java create mode 100644 plugin-maven/src/test/java/com/diffplug/spotless/maven/java/ReplaceStaticImportsStepTest.java create mode 100644 testlib/src/main/resources/java/replacestaticimports/AmbiguousOnDemandFormatted.test create mode 100644 testlib/src/main/resources/java/replacestaticimports/AmbiguousOnDemandUnformatted.test create mode 100644 testlib/src/main/resources/java/replacestaticimports/ExcludedMemberUsedThroughOnDemandImport.test create mode 100644 testlib/src/main/resources/java/replacestaticimports/JavaLangWithInvisibleOnDemandCompetitorFormatted.test create mode 100644 testlib/src/main/resources/java/replacestaticimports/JavaLangWithInvisibleOnDemandCompetitorUnformatted.test create mode 100644 testlib/src/main/resources/java/replacestaticimports/OnDemandJavaLangFormatted.test create mode 100644 testlib/src/main/resources/java/replacestaticimports/OnDemandJavaLangUnformatted.test create mode 100644 testlib/src/main/resources/java/replacestaticimports/SameDeclarationThroughTwoImportsFormatted.test create mode 100644 testlib/src/main/resources/java/replacestaticimports/SameDeclarationThroughTwoImportsUnformatted.test create mode 100644 testlib/src/main/resources/java/replacestaticimports/SingleAndOnDemandFormatted.test create mode 100644 testlib/src/main/resources/java/replacestaticimports/SingleAndOnDemandUnformatted.test create mode 100644 testlib/src/main/resources/java/replacestaticimports/SingleImportOfAFieldShadowsOnDemandFormatted.test create mode 100644 testlib/src/main/resources/java/replacestaticimports/SingleImportOfAFieldShadowsOnDemandUnformatted.test create mode 100644 testlib/src/main/resources/java/replacestaticimports/UnresolvableOnDemandImport.test create mode 100644 testlib/src/main/resources/java/replacestaticimports/UnresolvableSingleImportOfTheSameName.test create mode 100644 testlib/src/test/java/com/diffplug/spotless/java/ReplaceStaticImportsStepTest.java diff --git a/CHANGES.md b/CHANGES.md index 733abfd3d9..78bd099adb 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -12,6 +12,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ## [Unreleased] ### Added - Add a `groupArtifact` option to `PalantirJavaFormatStep`. ([#3179](https://github.com/diffplug/spotless/pull/3179)) +- Add `ReplaceStaticImportsStep`, which replaces static imports with regular imports and qualified references, such as `Assertions.assertTrue(x)`. Static imports to keep can be excluded. ([#1379](https://github.com/diffplug/spotless/issues/1379)) ### Fixed - GrEclipse no longer leaves a `file%3A...` directory in the working directory. ([#2019](https://github.com/diffplug/spotless/issues/2019)) - DBeaver SQL formatter no longer prints an `IndexOutOfBoundsException` when a file starts with a keyword like `SET`. ([#1552](https://github.com/diffplug/spotless/issues/1552)) diff --git a/README.md b/README.md index 1ef8f68f86..9654846cce 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,7 @@ lib('java.ExpandWildcardImportsStep') +'{{yes}} | {{no}} lib('java.ForbidWildcardImportsStep') +'{{yes}} | {{yes}} | {{yes}} | {{no}} |', lib('java.ForbidModuleImportsStep') +'{{yes}} | {{yes}} | {{no}} | {{no}} |', lib('java.ShortenFullyQualifiedTypesStep') +'{{yes}} | {{yes}} | {{no}} | {{no}} |', +lib('java.ReplaceStaticImportsStep') +'{{yes}} | {{yes}} | {{no}} | {{no}} |', extra('java.EclipseJdtFormatterStep') +'{{yes}} | {{yes}} | {{yes}} | {{no}} |', lib('java.FormatAnnotationsStep') +'{{yes}} | {{yes}} | {{no}} | {{no}} |', lib('java.CleanthatJavaStep') +'{{yes}} | {{yes}} | {{no}} | {{no}} |', @@ -151,6 +152,7 @@ lib('yaml.JacksonYamlStep') +'{{yes}} | {{yes}} | [`java.ForbidWildcardImportsStep`](lib/src/main/java/com/diffplug/spotless/java/ForbidWildcardImportsStep.java) | :+1: | :+1: | :+1: | :white_large_square: | | [`java.ForbidModuleImportsStep`](lib/src/main/java/com/diffplug/spotless/java/ForbidModuleImportsStep.java) | :+1: | :+1: | :white_large_square: | :white_large_square: | | [`java.ShortenFullyQualifiedTypesStep`](lib/src/main/java/com/diffplug/spotless/java/ShortenFullyQualifiedTypesStep.java) | :+1: | :+1: | :white_large_square: | :white_large_square: | +| [`java.ReplaceStaticImportsStep`](lib/src/main/java/com/diffplug/spotless/java/ReplaceStaticImportsStep.java) | :+1: | :+1: | :white_large_square: | :white_large_square: | | [`java.EclipseJdtFormatterStep`](lib-extra/src/main/java/com/diffplug/spotless/extra/java/EclipseJdtFormatterStep.java) | :+1: | :+1: | :+1: | :white_large_square: | | [`java.FormatAnnotationsStep`](lib/src/main/java/com/diffplug/spotless/java/FormatAnnotationsStep.java) | :+1: | :+1: | :white_large_square: | :white_large_square: | | [`java.CleanthatJavaStep`](lib/src/main/java/com/diffplug/spotless/java/CleanthatJavaStep.java) | :+1: | :+1: | :white_large_square: | :white_large_square: | diff --git a/lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/ExpandWildcardsFormatterFunc.java b/lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/ExpandWildcardsFormatterFunc.java index 251905cabb..8701ba3693 100644 --- a/lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/ExpandWildcardsFormatterFunc.java +++ b/lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/ExpandWildcardsFormatterFunc.java @@ -30,12 +30,9 @@ import java.util.TreeSet; import java.util.function.Function; import java.util.regex.Pattern; -import javassist.ClassPool; import com.github.javaparser.JavaParser; import com.github.javaparser.ParseResult; -import com.github.javaparser.ParserConfiguration; -import com.github.javaparser.ParserConfiguration.LanguageLevel; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.ImportDeclaration; import com.github.javaparser.ast.Node; @@ -56,10 +53,6 @@ import com.github.javaparser.resolution.declarations.ResolvedValueDeclaration; import com.github.javaparser.resolution.types.ResolvedType; import com.github.javaparser.symbolsolver.JavaSymbolSolver; -import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver; -import com.github.javaparser.symbolsolver.resolution.typesolvers.JarTypeSolver; -import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver; -import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; import com.diffplug.spotless.FormatterFunc; import com.diffplug.spotless.LineEnding; @@ -68,26 +61,10 @@ public class ExpandWildcardsFormatterFunc implements FormatterFunc.NeedsFile { private final JavaParser parser; - static { - // If ClassPool is allowed to cache class files, it does not free the file-lock - ClassPool.cacheOpenedJarFile = false; - } public ExpandWildcardsFormatterFunc(Collection typeSolverClasspath) throws IOException { - // JavaParser defaults to Java 11 and rejects newer syntax such as records; align with JavaParserTypeSolver's default. - this.parser = new JavaParser(new ParserConfiguration().setLanguageLevel(LanguageLevel.BLEEDING_EDGE)); - - CombinedTypeSolver combinedTypeSolver = new CombinedTypeSolver(); - combinedTypeSolver.add(new ReflectionTypeSolver(ReflectionTypeSolver.JCL_ONLY)); - for (File element : typeSolverClasspath) { - if (element.isFile() && element.getName().endsWith(".jar")) { - combinedTypeSolver.add(new JarTypeSolver(element)); - } else if (element.isDirectory()) { - combinedTypeSolver.add(new JavaParserTypeSolver(element)); - } // gracefully ignore non-existing src-directories - } - - SymbolResolver symbolSolver = new JavaSymbolSolver(combinedTypeSolver); + this.parser = SymbolResolution.parser(); + SymbolResolver symbolSolver = new JavaSymbolSolver(SymbolResolution.typeSolver(typeSolverClasspath)); parser.getParserConfiguration().setSymbolResolver(symbolSolver); } diff --git a/lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/ReplaceStaticImportsFormatterFunc.java b/lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/ReplaceStaticImportsFormatterFunc.java new file mode 100644 index 0000000000..619ab0512c --- /dev/null +++ b/lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/ReplaceStaticImportsFormatterFunc.java @@ -0,0 +1,1839 @@ +/* + * Copyright 2026 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.glue.javaparser; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParseResult; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ParserConfiguration.LanguageLevel; +import com.github.javaparser.Position; +import com.github.javaparser.ast.AccessSpecifier; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.ImportDeclaration; +import com.github.javaparser.ast.Node; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.PackageDeclaration; +import com.github.javaparser.ast.body.AnnotationDeclaration; +import com.github.javaparser.ast.body.AnnotationMemberDeclaration; +import com.github.javaparser.ast.body.BodyDeclaration; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.CompactConstructorDeclaration; +import com.github.javaparser.ast.body.ConstructorDeclaration; +import com.github.javaparser.ast.body.EnumConstantDeclaration; +import com.github.javaparser.ast.body.EnumDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.Parameter; +import com.github.javaparser.ast.body.ReceiverParameter; +import com.github.javaparser.ast.body.RecordDeclaration; +import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.comments.Comment; +import com.github.javaparser.ast.expr.AnnotationExpr; +import com.github.javaparser.ast.expr.Expression; +import com.github.javaparser.ast.expr.FieldAccessExpr; +import com.github.javaparser.ast.expr.MemberValuePair; +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.ast.expr.MethodReferenceExpr; +import com.github.javaparser.ast.expr.Name; +import com.github.javaparser.ast.expr.NameExpr; +import com.github.javaparser.ast.expr.ObjectCreationExpr; +import com.github.javaparser.ast.expr.SimpleName; +import com.github.javaparser.ast.expr.SuperExpr; +import com.github.javaparser.ast.expr.ThisExpr; +import com.github.javaparser.ast.expr.TypeExpr; +import com.github.javaparser.ast.expr.TypePatternExpr; +import com.github.javaparser.ast.modules.ModuleDeclaration; +import com.github.javaparser.ast.nodeTypes.SwitchNode; +import com.github.javaparser.ast.stmt.BreakStmt; +import com.github.javaparser.ast.stmt.ContinueStmt; +import com.github.javaparser.ast.stmt.ForEachStmt; +import com.github.javaparser.ast.stmt.ForStmt; +import com.github.javaparser.ast.stmt.LabeledStmt; +import com.github.javaparser.ast.stmt.SwitchEntry; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import com.github.javaparser.ast.type.TypeParameter; +import com.github.javaparser.resolution.Context; +import com.github.javaparser.resolution.TypeSolver; +import com.github.javaparser.resolution.declarations.HasAccessSpecifier; +import com.github.javaparser.resolution.declarations.ResolvedFieldDeclaration; +import com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration; +import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration; +import com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration; +import com.github.javaparser.resolution.declarations.ResolvedValueDeclaration; +import com.github.javaparser.resolution.model.SymbolReference; +import com.github.javaparser.resolution.types.ResolvedReferenceType; +import com.github.javaparser.resolution.types.ResolvedType; +import com.github.javaparser.symbolsolver.JavaSymbolSolver; +import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFactory; + +import com.diffplug.spotless.FormatterFunc; + +/** + * Replaces static imports with regular imports and qualified references: + * {@code import static org.junit.jupiter.api.Assertions.assertTrue;} and {@code assertTrue(x)} become + * {@code import org.junit.jupiter.api.Assertions;} and {@code Assertions.assertTrue(x)}. + * + *

Goal: never introduce a compile error or change behaviour

+ * + *

Each static import is either replaced completely or left exactly as it is. It is replaced only + * when every occurrence of every name it can supply is known to be either + *

+ * Anything else keeps the import: a name the classpath cannot resolve, a supertype it cannot see, a name + * that several imports supply, a use inside a {@code spotless:off} region or a doc comment, and so on. + * + *

How occurrences are classified

+ * + *

JavaParser's resolution of method calls is not reliable enough to decide this (overloads, generics, + * lambdas, the order of imports), so the scoping rules of the JLS are applied directly, and JavaParser is + * mostly asked about types: the members of an imported type, and the members an enclosing class declares + * or inherits. + *

+ * + *

Qualifying a use

+ * + *

A use of {@code member} from type {@code T} becomes {@code T.member}, written with the simple name of + * {@code T} (or {@code Outer.Inner} for a nested type), adding {@code import pkg.Outer;} when needed. If that + * simple name means something else at the use, or the new import could change what another name in the file + * refers to, the fully qualified name is written instead. A static import of a member type becomes a regular + * import of that type, and its uses stay as they are. + * + *

Writing just {@code Math} relies on there being no other type of that name in the file's package, or in a + * package imported on demand. The step checks this against the classpath, and a package that is not on it may + * hold any type, so such names get the fully qualified form. Types missing from a package that is on it, such as + * generated sources, are assumed not to exist. + * + *

Edits are made to the text at the positions JavaParser reports, so formatting is preserved. New + * imports are added after the existing ones, so this step is meant to run before {@code importOrder()}. + */ +public class ReplaceStaticImportsFormatterFunc implements FormatterFunc.Closeable { + private static final Pattern STATIC_IMPORT = Pattern.compile("\\bimport\\s+static\\b"); + private static final Pattern MULTI_RELEASE = Pattern.compile("^META-INF/versions/\\d+/"); + /** A unicode escape of a line terminator, which javac reads as a line break, e.g. hiding code behind a {@code //}. */ + private static final Pattern ESCAPED_LINE_TERMINATOR = Pattern.compile("(? FENCES = List.of( + Pattern.compile("spotless:off[\\s\\S]*?spotless:on"), + Pattern.compile("@formatter:off[\\s\\S]*?@formatter:on")); + /** Unqualified references in doc comments: {@code {@link name}}, {@code @see name}, {@code @throws name}... */ + private static final Pattern DOC_REFERENCE = Pattern.compile("(?:\\{@(?:link|linkplain|value)|@(?:see|throws|exception))\\s+([A-Za-z_$][\\w$]*)(?![\\w$.#])"); + /** Unqualified references in Markdown doc comments: {@code [name]} and {@code [name(int)]}. */ + private static final Pattern MARKDOWN_REFERENCE = Pattern.compile("\\[([A-Za-z_$][\\w$]*)(?:\\([^)\\]]*\\))?\\]"); + /** Methods that every class, enum, record and interface has as members (JLS 4.3.2, 9.2). */ + private static final Set OBJECT_METHODS = Set.of("clone", "equals", "finalize", "getClass", "hashCode", "notify", "notifyAll", "toString", "wait"); + + private final Collection typeSolverClasspath; + private final Set excludes; + /** Reads unicode escapes like javac does, so that a name spelled with them is seen; positions stay those of the text. */ + private final JavaParser parser = new JavaParser(new ParserConfiguration().setLanguageLevel(LanguageLevel.BLEEDING_EDGE).setPreprocessUnicodeEscapes(true)); + /** The packages of each jar on the classpath, read when first needed. */ + private final Map> jarPackages = new HashMap<>(); + private final Map knownPackages = new HashMap<>(); + /** How many classpath entries have a top-level class, by its path such as {@code com/acme/Base}. */ + private final Map copiesOnClasspath = new HashMap<>(); + private static volatile Set jdkPackages; + /** Created when the first file with a static import is formatted, since building it reads every jar. */ + private TypeSolver typeSolver; + private JavaSymbolSolver symbolSolver; + private boolean typeSolverFailed; + + public ReplaceStaticImportsFormatterFunc(Collection typeSolverClasspath, Collection excludes) { + this.typeSolverClasspath = List.copyOf(typeSolverClasspath); + this.excludes = Set.copyOf(excludes); + } + + /** Synchronized because JavaParser's parser and type solver caches are not thread-safe. */ + @Override + public synchronized String apply(String rawUnix) { + if (!STATIC_IMPORT.matcher(rawUnix).find() || ESCAPED_LINE_TERMINATOR.matcher(rawUnix).find()) { + // the edits rely on the lines of the text being the lines that javac sees + return rawUnix; + } + try { + ParseResult parsed = parser.parse(rawUnix); + if (!parsed.isSuccessful() || parsed.getResult().isEmpty()) { + return rawUnix; + } + CompilationUnit cu = parsed.getResult().get(); + if (cu.getImports().stream().noneMatch(ImportDeclaration::isStatic) || cu.getModule().isPresent() || !initializeTypeSolver()) { + return rawUnix; + } + symbolSolver.inject(cu); + String result = new Rewrite(cu, rawUnix).apply(); + if (result.equals(rawUnix) || !parser.parse(result).isSuccessful()) { + return rawUnix; + } + return result; + } catch (RuntimeException | StackOverflowError e) { + // JavaParser can fail in many ways on code it does not fully understand: when in doubt, leave the file alone + return rawUnix; + } + } + + /** Creates the type solver on first use. False if that failed, e.g. for an unreadable jar: then every file stays as it is. */ + private boolean initializeTypeSolver() { + if (symbolSolver == null && !typeSolverFailed) { + try { + // the files of the source directories need symbol resolution too, e.g. to find the type that contains a nested one + ParserConfiguration sourceConfiguration = new ParserConfiguration().setLanguageLevel(LanguageLevel.BLEEDING_EDGE).setPreprocessUnicodeEscapes(true); + TypeSolver solver = SymbolResolution.typeSolver(typeSolverClasspath, sourceConfiguration); + JavaSymbolSolver resolver = new JavaSymbolSolver(solver); + sourceConfiguration.setSymbolResolver(resolver); + typeSolver = solver; + symbolSolver = resolver; + } catch (IOException | RuntimeException e) { + typeSolverFailed = true; + } + } + return symbolSolver != null; + } + + /** Releases the type solver, which JavaParser would otherwise keep in a static cache for as long as its classes are loaded. */ + @Override + public synchronized void close() { + typeSolver = null; + symbolSolver = null; + SymbolResolution.release(); + } + + /** + * Whether the type solver can see the package, so that not finding a type in it means the type does not exist. + * A package it cannot see, e.g. generated code or another module's classes, may hold any type. + */ + private boolean isKnownPackage(String packageName) { + return knownPackages.computeIfAbsent(packageName, this::findPackage); + } + + private boolean findPackage(String packageName) { + if (jdkPackages().contains(packageName)) { + return true; + } + String path = packageName.replace('.', '/'); + for (File entry : typeSolverClasspath) { + if (entry.isDirectory()) { + // only sources count: the type solver cannot read the class files of an output directory + File[] sources = new File(entry, path).listFiles((dir, name) -> name.endsWith(".java")); + if (sources != null && sources.length > 0) { + return true; + } + } else if (entry.isFile() && entry.getName().endsWith(".jar") && jarPackages.computeIfAbsent(entry, ReplaceStaticImportsFormatterFunc::packagesOf).contains(packageName)) { + return true; + } + } + return false; + } + + /** + * Whether more than one jar on the classpath has the top-level class of the type, e.g. two versions of a library. + * A source directory and the classes compiled from it hold the same class, so directories do not count. + */ + private boolean isOnClasspathTwice(ResolvedReferenceTypeDeclaration type) { + String packageName = type.getPackageName(); + if (jdkPackages().contains(packageName)) { + return false; + } + String topLevel = type.getClassName().split("\\.")[0]; + String path = packageName.isEmpty() ? topLevel : packageName.replace('.', '/') + "/" + topLevel; + return copiesOnClasspath.computeIfAbsent(path, this::countCopies) > 1; + } + + private int countCopies(String path) { + int copies = 0; + String packageName = path.contains("/") ? path.substring(0, path.lastIndexOf('/')).replace('/', '.') : ""; + for (File entry : typeSolverClasspath) { + if (entry.isFile() && entry.getName().endsWith(".jar") + && jarPackages.computeIfAbsent(entry, ReplaceStaticImportsFormatterFunc::packagesOf).contains(packageName)) { + try (ZipFile zip = new ZipFile(entry)) { + if (zip.getEntry(path + ".class") != null) { + copies++; + } + } catch (IOException e) { + copies++; // unreadable: assume it may have the class + } + } + } + return copies; + } + + private static Set packagesOf(File jar) { + Set packages = new HashSet<>(); + try (ZipFile zip = new ZipFile(jar)) { + zip.stream().map(ZipEntry::getName).filter(name -> name.endsWith(".class")).forEach(name -> { + String path = MULTI_RELEASE.matcher(name).replaceFirst(""); + int slash = path.lastIndexOf('/'); + packages.add(slash < 0 ? "" : path.substring(0, slash).replace('/', '.')); + }); + } catch (IOException e) { + // an unreadable jar shows no packages, so nothing is assumed about them + } + return packages; + } + + private static Set jdkPackages() { + Set packages = jdkPackages; + if (packages == null) { + packages = new HashSet<>(); + for (Module module : ModuleLayer.boot().modules()) { + packages.addAll(module.getPackages()); + } + jdkPackages = packages; + } + return packages; + } + + /** The kinds of member a static import can supply. */ + private enum Kind { + METHOD, FIELD, TYPE + } + + /** One resolved static import declaration, and what is known about it. */ + private static final class StaticImport { + final ImportDeclaration declaration; + final ResolvedReferenceTypeDeclaration type; + final Map> names = new EnumMap<>(Kind.class); + final Set enumConstants = new HashSet<>(); + /** Canonical names of the member types declared in the imported type itself, by simple name. */ + final Map declaredMemberTypes = new HashMap<>(); + /** The parameter counts of the imported type's instance methods, which compete with its static ones once a call is qualified. */ + final Map> instanceMethods = new HashMap<>(); + /** The types that declare the static methods and fields this import supplies, by name. */ + final Map> declaringTypes = new HashMap<>(); + /** True when this import must stay, because it is excluded or some occurrence could not be classified with certainty. */ + boolean keep; + + StaticImport(ImportDeclaration declaration, ResolvedReferenceTypeDeclaration type) { + this.declaration = declaration; + this.type = type; + for (Kind kind : Kind.values()) { + names.put(kind, new HashSet<>()); + } + } + + boolean supplies(Kind kind, String name) { + return names.get(kind).contains(name); + } + + boolean suppliesAnything(String name) { + return supplies(Kind.METHOD, name) || supplies(Kind.FIELD, name) || supplies(Kind.TYPE, name); + } + + void retainOnly(String member) { + for (Set set : names.values()) { + set.retainAll(Set.of(member)); + } + enumConstants.retainAll(Set.of(member)); + } + } + + /** How many arguments a method takes. */ + private record Arity(int parameters, boolean varargs) { + boolean accepts(int arguments) { + return varargs ? arguments >= parameters - 1 : arguments == parameters; + } + } + + /** An occurrence that uses a static import, and so will be qualified. */ + private record Use(Node node, String name, StaticImport source) {} + + /** What the enclosing classes of an occurrence say about a name. */ + private enum Membership { + /** An enclosing class certainly declares or inherits a member of that name. */ + MEMBER, + /** No enclosing class declares or inherits a member of that name. */ + NOT_MEMBER, + /** It cannot be decided, e.g. because a supertype cannot be resolved. */ + UNKNOWN + } + + /** The member names of one kind that a class has. */ + private static final class Members { + /** Names it certainly has: declared in it, or inherited from a supertype. */ + final Set certain = new HashSet<>(); + /** Names it may have, such as package-private members of a supertype. */ + final Set possible = new HashSet<>(); + /** False when some members cannot be seen, e.g. because a supertype cannot be resolved. */ + boolean complete = true; + + void add(String name, boolean isCertain) { + possible.add(name); + if (isCertain) { + certain.add(name); + } + } + } + + /** A class around an occurrence, and whether the occurrence is in its body, where its members are in scope. */ + private record EnclosingScope(Node node, boolean inBody) {} + + /** What a simple type name refers to at some point of the file. */ + private enum Visible { + /** No type of that name is visible. */ + NOTHING, + /** The expected type. */ + EXPECTED, + /** A top-level type from the same package, an on-demand import or {@code java.lang}, which a single-type import would shadow. */ + SHADOWABLE, + /** Another type, such as a member type in scope, which an import cannot shadow. */ + OTHER, + /** It cannot be determined. */ + UNKNOWN + } + + /** How to qualify a use: the text to write before it, and the import that text needs, or null. */ + private record Qualifier(String text, String importName) {} + + /** The edits that replace one static import's uses, and the imports they need. */ + private static final class Plan { + final List insertions = new ArrayList<>(); + final Set imports = new TreeSet<>(); + } + + private record Edit(int start, int end, String replacement) {} + + /** The work for one file. */ + private final class Rewrite { + private final CompilationUnit cu; + private final String text; + private final int[] lineOffsets; + private final String packageName; + private final List imports = new ArrayList<>(); + /** Members named by single static imports that cannot be resolved: any occurrence of these names may use them. */ + private final Set unresolvedNames = new HashSet<>(); + /** Simple name -> canonical name, for the non-static single-type imports. */ + private final Map typeImports = new HashMap<>(); + private final Set declaredTypeNames = new HashSet<>(); + private final Set declaredTypeQualifiedNames = new HashSet<>(); + private final Set typeParameterNames = new HashSet<>(); + private final Set variableNames = new HashSet<>(); + /** The text ranges that {@code toggleOffOn()} would restore, as start and end offsets. */ + private final List fences = new ArrayList<>(); + private final Map> membersCache = new IdentityHashMap<>(); + private final Map usedUnqualifiedCache = new HashMap<>(); + private final List uses = new ArrayList<>(); + /** Canonical names of the member types to import, for each static import that supplies them. */ + private final Map> memberTypeImports = new IdentityHashMap<>(); + /** Simple name -> canonical name, for the imports planned so far for qualified uses. */ + private final Map plannedSimpleNames = new HashMap<>(); + + Rewrite(CompilationUnit cu, String text) { + this.cu = cu; + this.text = text; + this.lineOffsets = lineOffsets(text); + this.packageName = cu.getPackageDeclaration().map(PackageDeclaration::getNameAsString).orElse(""); + } + + String apply() { + collectFileFacts(); + for (ImportDeclaration declaration : cu.getImports()) { + if (isFenced(declaration)) { + return text; // toggleOffOn() would restore it, whatever this step does + } + } + for (ImportDeclaration declaration : cu.getImports()) { + if (!declaration.isStatic()) { + continue; + } + Optional resolved = resolveImport(declaration); + if (resolved.isPresent()) { + resolved.get().keep |= isExcluded(declaration); + imports.add(resolved.get()); + } else if (declaration.isAsterisk()) { + return text; // it could supply any name, so no name in the file can be attributed with certainty + } else { + unresolvedNames.add(declaration.getName().getIdentifier()); + } + } + if (imports.stream().allMatch(i -> i.keep)) { + return text; + } + classifyOccurrences(); + keepImportsReferencedInComments(); + return edit(); + } + + private void collectFileFacts() { + for (ImportDeclaration declaration : cu.getImports()) { + if (!declaration.isStatic() && !declaration.isAsterisk() && !declaration.isModule()) { + typeImports.put(declaration.getName().getIdentifier(), declaration.getNameAsString()); + } + } + for (TypeDeclaration declaration : cu.findAll(TypeDeclaration.class)) { + declaredTypeNames.add(declaration.getNameAsString()); + declaration.getFullyQualifiedName().ifPresent(declaredTypeQualifiedNames::add); + } + for (TypeParameter parameter : cu.findAll(TypeParameter.class)) { + declaredTypeNames.add(parameter.getNameAsString()); + typeParameterNames.add(parameter.getNameAsString()); + } + for (VariableDeclarator variable : cu.findAll(VariableDeclarator.class)) { + variableNames.add(variable.getNameAsString()); + } + for (Parameter parameter : cu.findAll(Parameter.class)) { + variableNames.add(parameter.getNameAsString()); + } + for (TypePatternExpr pattern : cu.findAll(TypePatternExpr.class)) { + variableNames.add(pattern.getNameAsString()); + } + for (EnumConstantDeclaration constant : cu.findAll(EnumConstantDeclaration.class)) { + variableNames.add(constant.getNameAsString()); + } + for (Pattern fence : FENCES) { + Matcher matcher = fence.matcher(text); + while (matcher.find()) { + fences.add(new int[]{matcher.start(), matcher.end()}); + } + } + } + + /** + * {@code Type.*}, or just {@code Type}, keeps every static import from that type. {@code Type.member} keeps the + * static import of that member, and an on-demand import of the type if the file uses that member through it. + */ + private boolean isExcluded(ImportDeclaration declaration) { + String name = declaration.getNameAsString(); + if (declaration.isAsterisk()) { + return excludes.contains(name + ".*") || excludes.contains(name) || usesExcludedMember(name); + } + String type = declaration.getName().getQualifier().map(Name::asString).orElse(""); + return excludes.contains(name) || excludes.contains(type + ".*") || excludes.contains(type); + } + + private boolean usesExcludedMember(String type) { + for (String exclude : excludes) { + String member = exclude.startsWith(type + ".") ? exclude.substring(type.length() + 1) : ""; + if (!member.isEmpty() && !member.contains(".") && !member.equals("*") + && cu.findAll(SimpleName.class).stream().anyMatch(name -> name.getIdentifier().equals(member))) { + return true; + } + } + return false; + } + + private boolean isFenced(Node node) { + if (fences.isEmpty()) { + return false; + } + int begin = node.getBegin().map(this::offset).orElse(-1); + for (int[] fence : fences) { + if (begin < 0 || (fence[0] <= begin && begin < fence[1])) { + return true; + } + } + return false; + } + + // ---------------------------------------------------------------- the imports + + /** Resolves the imported type and the names it supplies; empty if that cannot be done with certainty. */ + private Optional resolveImport(ImportDeclaration declaration) { + String typeName = declaration.isAsterisk() + ? declaration.getNameAsString() + : declaration.getName().getQualifier().map(Name::asString).orElse(""); + if (typeName.isEmpty()) { + return Optional.empty(); + } + try { + SymbolReference reference = typeSolver.tryToSolveType(typeName); + if (!reference.isSolved()) { + return Optional.empty(); + } + ResolvedReferenceTypeDeclaration type = reference.getCorrespondingDeclaration(); + if (!typeName.equals(type.getQualifiedName())) { + return Optional.empty(); // not the canonical name, so something does not match what the compiler sees + } + requireCompleteAncestry(type, new HashSet<>()); + StaticImport staticImport = new StaticImport(declaration, type); + collectMembers(staticImport); + if (!declaration.isAsterisk()) { + String member = declaration.getName().getIdentifier(); + staticImport.retainOnly(member); + if (!staticImport.suppliesAnything(member)) { + return Optional.empty(); // the type solver does not see this member + } + } + return Optional.of(staticImport); + } catch (RuntimeException e) { + return Optional.empty(); + } + } + + /** Collects the static members that a static import of the type supplies to this file (JLS 6.6, 7.5.3, 7.5.4, 8.4.8). */ + private void collectMembers(StaticImport staticImport) { + ResolvedReferenceTypeDeclaration type = staticImport.type; + Set methods = new LinkedHashSet<>(type.getDeclaredMethods()); + type.getAllMethods().forEach(method -> methods.add(method.getDeclaration())); + for (ResolvedMethodDeclaration method : methods) { + ResolvedReferenceTypeDeclaration declaringType = method.declaringType(); + if (!method.isStatic()) { + if (method.accessSpecifier() != AccessSpecifier.PRIVATE) { + staticImport.instanceMethods.computeIfAbsent(method.getName(), name -> new ArrayList<>()) + .add(new Arity(method.getNumberOfParams(), method.hasVariadicParameter())); + } + } else if (isImportable(method.accessSpecifier(), declaringType) + && !(declaringType.isInterface() && !declaringType.getQualifiedName().equals(type.getQualifiedName()))) { + // static methods of an interface are not inherited + staticImport.names.get(Kind.METHOD).add(method.getName()); + staticImport.declaringTypes.computeIfAbsent(method.getName(), name -> new HashSet<>()).add(declaringType.getQualifiedName()); + } + } + for (ResolvedFieldDeclaration field : type.getAllFields()) { + boolean implicitlyPublicStatic = isInterfaceOrAnnotation(field.declaringType()); + if ((field.isStatic() || implicitlyPublicStatic) + && (implicitlyPublicStatic || isImportable(field.accessSpecifier(), field.declaringType()))) { + staticImport.names.get(Kind.FIELD).add(field.getName()); + staticImport.declaringTypes.computeIfAbsent(field.getName(), name -> new HashSet<>()).add(field.declaringType().getQualifiedName()); + } + } + if (type.isEnum()) { + for (var constant : type.asEnum().getEnumConstants()) { + staticImport.names.get(Kind.FIELD).add(constant.getName()); + staticImport.declaringTypes.computeIfAbsent(constant.getName(), name -> new HashSet<>()).add(type.getQualifiedName()); + staticImport.enumConstants.add(constant.getName()); + } + } + for (ResolvedReferenceTypeDeclaration owner : withAncestors(type)) { + for (ResolvedReferenceTypeDeclaration memberType : owner.internalTypes()) { + if (isInterfaceOrAnnotation(owner) || isImportable(accessOf(memberType), owner)) { + staticImport.names.get(Kind.TYPE).add(memberType.getName()); + if (owner == type) { + staticImport.declaredMemberTypes.put(memberType.getName(), memberType.getQualifiedName()); + } + } + } + } + } + + /** Whether a member with that access, declared in that type, can be imported into this file. */ + private boolean isImportable(AccessSpecifier access, ResolvedTypeDeclaration declaringType) { + if (access == AccessSpecifier.PUBLIC) { + return true; + } + // protected and package-private members are only accessible from the same package here, and private ones never + return access != AccessSpecifier.PRIVATE && packageOf(declaringType).equals(packageName); + } + + /** + * Fails if any ancestor of the type cannot be resolved, or if the type may get members from Lombok: JavaParser would + * silently miss them. Also fails for a type that is on the classpath twice, e.g. in two versions of a library, since + * the compiler may see the other one. + */ + private void requireCompleteAncestry(ResolvedReferenceTypeDeclaration type, Set seen) { + if (!seen.add(type.getQualifiedName())) { + return; + } + if (type.toAst(TypeDeclaration.class).filter(ReplaceStaticImportsFormatterFunc::usesLombok).isPresent()) { + throw new IllegalStateException("Lombok generates members that JavaParser cannot see"); + } + if (isOnClasspathTwice(type)) { + throw new IllegalStateException(type.getQualifiedName() + " is on the classpath twice"); + } + for (ResolvedReferenceType ancestor : type.getAncestors(false)) { + requireCompleteAncestry(ancestor.getTypeDeclaration().orElseThrow(), seen); + } + } + + // ---------------------------------------------------------------- the occurrences + + /** Classifies every occurrence of every name the static imports supply. */ + private void classifyOccurrences() { + Set suppliedNames = new HashSet<>(unresolvedNames); + for (StaticImport staticImport : imports) { + staticImport.names.values().forEach(suppliedNames::addAll); + } + boolean closedWorld = imports.stream().anyMatch(i -> i.declaration.isAsterisk() && !i.keep); + for (SimpleName name : cu.findAll(SimpleName.class)) { + String identifier = name.getIdentifier(); + if (suppliedNames.contains(identifier)) { + if (unresolvedNames.contains(identifier) || isFenced(name)) { + keepSuppliersOf(identifier, Kind.values()); + } else { + classify(name); + } + } else if (closedWorld) { + checkExplained(name); + } + } + for (Name name : cu.findAll(Name.class)) { + if (name.getQualifier().isPresent()) { + continue; + } + String identifier = name.getIdentifier(); + if (suppliedNames.contains(identifier)) { + if (unresolvedNames.contains(identifier) || isFenced(name)) { + keepSuppliersOf(identifier, Kind.values()); + } else { + classifyLeftmostName(name); + } + } else if (closedWorld && name.getParentNode().orElse(null) instanceof AnnotationExpr annotation && !resolves(annotation)) { + keepOnDemandImports(); + } + } + } + + private void classify(SimpleName name) { + Node parent = name.getParentNode().orElse(null); + String identifier = name.getIdentifier(); + if (parent instanceof MethodCallExpr call && call.getName() == name) { + if (call.getScope().isEmpty()) { + classifyMethodCall(call, identifier); + } // else a member access, such as `list.max()` + } else if (parent instanceof NameExpr nameExpr) { + classifyExpressionName(nameExpr, identifier); + } else if (parent instanceof ClassOrInterfaceType type && type.getName() == name) { + if (type.getScope().isPresent()) { + return; // a member type, such as `Map.Entry` + } + if (isMethodReferenceScope(type) && suppliesField(identifier)) { + // `NAMES::add` is parsed as a type, but it may well be a field + classifyFieldUse(type, identifier); + } else { + classifyTypeName(type, identifier); + } + } else if (!isDeclarationOrMemberAccess(parent)) { + // a position this step does not know about: be safe + keepSuppliersOf(identifier, Kind.values()); + } + } + + /** True for the parent of a {@code SimpleName} that declares something, or that names a member of something else. */ + private boolean isDeclarationOrMemberAccess(Node parent) { + return parent instanceof FieldAccessExpr + || parent instanceof MethodCallExpr + || parent instanceof ClassOrInterfaceType + || parent instanceof MethodDeclaration + || parent instanceof ConstructorDeclaration + || parent instanceof CompactConstructorDeclaration + || parent instanceof AnnotationMemberDeclaration + || parent instanceof VariableDeclarator + || parent instanceof Parameter + || parent instanceof ReceiverParameter + || parent instanceof TypeDeclaration + || parent instanceof EnumConstantDeclaration + || parent instanceof TypeParameter + || parent instanceof TypePatternExpr + || parent instanceof MemberValuePair + || parent instanceof LabeledStmt + || parent instanceof BreakStmt + || parent instanceof ContinueStmt; + } + + /** The leftmost segment of a {@link Name}, as used by annotations, imports, packages, modules and {@code Outer.this}. */ + private void classifyLeftmostName(Name name) { + Node root = name; + Node parent = root.getParentNode().orElse(null); + while (parent instanceof Name qualified && qualified.getQualifier().isPresent() && qualified.getQualifier().get() == root) { + root = parent; + parent = root.getParentNode().orElse(null); + } + if (parent instanceof ImportDeclaration || parent instanceof PackageDeclaration || parent instanceof ModuleDeclaration + || (parent != null && parent.findAncestor(ModuleDeclaration.class).isPresent())) { + return; + } + if (parent instanceof AnnotationExpr || parent instanceof SuperExpr || parent instanceof ThisExpr) { + classifyTypeName(name, name.getIdentifier()); // `@Outer.Inner`, `Listener.super.m()`, `Outer.this` + } else { + keepSuppliersOf(name.getIdentifier(), Kind.values()); + } + } + + /** + * The closed-world check for on-demand imports: the type solver may not see every member an on-demand + * import supplies (version skew, Lombok), so they are only removed if every other simple name in the file + * is explained by something else. + */ + private void checkExplained(SimpleName name) { + Node parent = name.getParentNode().orElse(null); + boolean explained = true; + if (parent instanceof MethodCallExpr call && call.getName() == name && call.getScope().isEmpty()) { + explained = membership(call, Kind.METHOD, name.getIdentifier()) == Membership.MEMBER; + } else if (parent instanceof NameExpr nameExpr) { + explained = resolves(nameExpr); + } else if (parent instanceof ClassOrInterfaceType type && type.getName() == name && type.getScope().isEmpty()) { + explained = declaredTypeNames.contains(name.getIdentifier()) || resolves(type); + } + if (!explained) { + keepOnDemandImports(); + } + } + + private boolean resolves(NameExpr nameExpr) { + try { + nameExpr.resolve(); + return true; + } catch (RuntimeException e) { + // not a variable: a type used as a qualifier, or the first segment of a package name + if (isQualifier(nameExpr) && visibleType(context(nameExpr), nameExpr.getNameAsString(), null) != Visible.NOTHING) { + return true; + } + return nameExpr.getParentNode().orElse(null) instanceof FieldAccessExpr && Character.isLowerCase(nameExpr.getNameAsString().charAt(0)); + } + } + + private boolean resolves(ClassOrInterfaceType type) { + try { + type.resolve(); + return true; + } catch (RuntimeException e) { + return false; + } + } + + private boolean resolves(AnnotationExpr annotation) { + try { + annotation.resolve(); + return true; + } catch (RuntimeException e) { + return false; + } + } + + private void keepOnDemandImports() { + for (StaticImport staticImport : imports) { + if (staticImport.declaration.isAsterisk()) { + staticImport.keep = true; + } + } + } + + /** {@code name(...)} without a scope (JLS 15.12.1). */ + private void classifyMethodCall(MethodCallExpr call, String name) { + switch (membership(call, Kind.METHOD, name)) { + case MEMBER: + return; // a method of an enclosing class, not the import + case UNKNOWN: + keepSuppliersOf(name, Kind.METHOD); + return; + case NOT_MEMBER: + break; + } + Optional source = onlySupplier(name, Kind.METHOD); + if (source.isEmpty()) { + return; + } + int arguments = call.getArguments().size(); + boolean instanceOverload = source.get().instanceMethods.getOrDefault(name, List.of()).stream().anyMatch(arity -> arity.accepts(arguments)); + if (instanceOverload) { + // once qualified as `T.name(...)`, an instance method of T could be the one picked, which does not compile + keepSuppliersOf(name, Kind.METHOD); + return; + } + uses.add(new Use(call, name, source.get())); + } + + /** An unqualified name in an expression: a variable, a field, or a type used as a qualifier. */ + private void classifyExpressionName(NameExpr nameExpr, String name) { + if (nameExpr.getParentNode().orElse(null) instanceof SwitchEntry entry && entry.getLabels().contains(nameExpr)) { + switch (switchesOnEnum(entry)) { + case MEMBER: + return; // resolved against the enum type of the switch, not through the import (JLS 14.11.1) + case UNKNOWN: + keepSuppliersOf(name, Kind.values()); + return; + case NOT_MEMBER: + break; // a switch on another type, where the label is an ordinary name (Java 21) + } + } + if (suppliesField(name)) { + classifyFieldUse(nameExpr, name); // a variable obscures a type of the same name (JLS 6.4.2) + } else if (imports.stream().anyMatch(i -> i.supplies(Kind.TYPE, name))) { + if (isQualifier(nameExpr)) { + classifyTypeName(nameExpr, name); + } else { + keepSuppliersOf(name, Kind.TYPE); + } + } + // otherwise the name is only supplied as a method, which a name in an expression cannot refer to + } + + /** {@link Membership#MEMBER} if the switch of this entry is on an enum type, NOT_MEMBER if it is certainly on another type. */ + private Membership switchesOnEnum(SwitchEntry entry) { + try { + Expression selectorExpression = ((SwitchNode) entry.getParentNode().orElseThrow()).getSelector(); + for (NameExpr name : selectorExpression.findAll(NameExpr.class)) { + if (isOutOfScopeLoopVariable(name)) { + return Membership.UNKNOWN; // JavaParser would give the selector the type of a variable that is not in scope + } + } + ResolvedType selector = selectorExpression.calculateResolvedType(); + if (selector.isPrimitive()) { + return Membership.NOT_MEMBER; + } + if (selector.isReferenceType()) { + Optional declaration = selector.asReferenceType().getTypeDeclaration(); + if (declaration.isPresent()) { + return declaration.get().isEnum() ? Membership.MEMBER : Membership.NOT_MEMBER; + } + } + return Membership.UNKNOWN; // e.g. a type variable that JavaParser could not infer + } catch (RuntimeException e) { + return Membership.UNKNOWN; + } + } + + /** JavaParser keeps the variable of a for loop in scope after the loop, which javac does not. */ + private boolean isOutOfScopeLoopVariable(NameExpr nameExpr) { + try { + return isOutOfScopeLoopVariable(nameExpr.resolve(), nameExpr); + } catch (RuntimeException e) { + return false; + } + } + + private boolean isOutOfScopeLoopVariable(ResolvedValueDeclaration value, Node occurrence) { + Node declaration = value.toAst().orElse(null); + if (declaration instanceof VariableDeclarator) { + declaration = declaration.getParentNode().orElse(null); + } + Node variable = declaration; + Node loop = variable == null ? null : variable.getParentNode().orElse(null); + boolean loopVariable = (loop instanceof ForStmt forStmt && forStmt.getInitialization().stream().anyMatch(init -> init == variable)) + || (loop instanceof ForEachStmt forEach && forEach.getVariable() == variable); + return loopVariable && !occurrence.isDescendantOf(loop); + } + + /** A use of a static field: an unqualified name in an expression, or the scope of a method reference. */ + private void classifyFieldUse(Node node, String name) { + switch (localOrField(node, name)) { + case MEMBER: + return; // a local variable, a parameter or a field of an enclosing class + case UNKNOWN: + keepSuppliersOf(name, Kind.FIELD, Kind.TYPE); + return; + case NOT_MEMBER: + onlySupplier(name, Kind.FIELD).ifPresent(source -> uses.add(new Use(node, name, source))); + return; + } + } + + /** For a name in an expression, a local variable or a field of an enclosing class counts as {@link Membership#MEMBER}. */ + private Membership localOrField(Node node, String name) { + try { + Optional value; + if (node instanceof NameExpr nameExpr) { + value = Optional.of(nameExpr.resolve()); + } else { + SymbolReference reference = context(node).solveSymbol(name); + value = reference.isSolved() ? Optional.of(reference.getCorrespondingDeclaration()) : Optional.empty(); + } + if (value.isPresent() && !value.get().isField() && !value.get().isEnumConstant()) { + return isOutOfScopeLoopVariable(value.get(), node) ? Membership.UNKNOWN : Membership.MEMBER; + } + } catch (RuntimeException e) { + // JavaParser could not resolve it, so look for a local of that name ourselves + if (hasLocalNamed(node, name)) { + return Membership.UNKNOWN; + } + } + // JavaParser misses some pattern variables, e.g. `name` in `x instanceof T name ? name : null` + boolean patternVariable = node.findAncestor(BodyDeclaration.class) + .map(body -> body.findAll(TypePatternExpr.class).stream().anyMatch(pattern -> pattern.getNameAsString().equals(name))) + .orElse(false); + return patternVariable ? Membership.UNKNOWN : membership(node, Kind.FIELD, name); + } + + /** True if a variable of that name is declared in the innermost enclosing class, other than as a field. */ + private boolean hasLocalNamed(Node node, String name) { + Node scope = enclosingScopes(node).stream().findFirst().map(EnclosingScope::node).orElse(cu); + for (VariableDeclarator variable : scope.findAll(VariableDeclarator.class)) { + if (variable.getNameAsString().equals(name) && !(variable.getParentNode().orElse(null) instanceof FieldDeclaration)) { + return true; + } + } + for (Parameter parameter : scope.findAll(Parameter.class)) { + if (parameter.getNameAsString().equals(name)) { + return true; + } + } + for (TypePatternExpr pattern : scope.findAll(TypePatternExpr.class)) { + if (pattern.getNameAsString().equals(name)) { + return true; + } + } + return false; + } + + /** An unqualified type name: a class type, the leftmost part of an annotation name, or a qualifier like {@code Entry.comparingByKey()}. */ + private void classifyTypeName(Node node, String name) { + List suppliers = imports.stream().filter(i -> i.supplies(Kind.TYPE, name)).toList(); + if (suppliers.stream().anyMatch(i -> !i.declaration.isAsterisk())) { + // a single-static-import of a type shadows those of static-imports-on-demand (JLS 6.4.1) + suppliers = suppliers.stream().filter(i -> !i.declaration.isAsterisk()).toList(); + } + if (suppliers.isEmpty() || typeImports.containsKey(name)) { + return; // not a member type of an import, or a single-type import of that name shadows them (JLS 6.4.1) + } + if (declaredTypeNames.contains(name)) { + keepSuppliersOf(name, Kind.TYPE); + return; + } + switch (membership(node, Kind.TYPE, name)) { + case MEMBER: + return; + case UNKNOWN: + keepSuppliersOf(name, Kind.TYPE); + return; + case NOT_MEMBER: + break; + } + Set canonicalNames = new HashSet<>(); + for (StaticImport supplier : suppliers) { + // a member type inherited from a supertype can only be imported through the supertype (JLS 7.5.1) + canonicalNames.add(supplier.declaredMemberTypes.getOrDefault(name, "")); + } + if (canonicalNames.size() != 1 || canonicalNames.contains("")) { + keepSuppliersOf(name, Kind.TYPE); + return; + } + if (suppliers.stream().allMatch(i -> i.declaration.isAsterisk())) { + if (isSamePackageType(name)) { + return; // a type of the same package shadows a static-import-on-demand (JLS 6.4.1) + } + // and so may one that the type solver cannot see, such as generated code, so the import stays + keepSuppliersOf(name, Kind.TYPE); + return; + } + String canonicalName = canonicalNames.iterator().next(); + for (StaticImport supplier : suppliers) { + memberTypeImports.computeIfAbsent(supplier, s -> new LinkedHashSet<>()).add(canonicalName); + } + } + + private boolean isSamePackageType(String name) { + try { + return typeSolver.tryToSolveType(packageName.isEmpty() ? name : packageName + "." + name).isSolved(); + } catch (RuntimeException e) { + return true; + } + } + + private boolean suppliesField(String name) { + return imports.stream().anyMatch(i -> i.supplies(Kind.FIELD, name)); + } + + /** + * The one static import that supplies this name, for an occurrence that can only come from a static import. + * If imports of several types supply it, JavaParser cannot be trusted to pick the one the compiler picks, + * unless they all reach the very same declarations, as {@code Mockito.*} and {@code ArgumentMatchers.any} do: + * then the import of the declaring type is the one. + */ + private Optional onlySupplier(String name, Kind kind) { + List suppliers = imports.stream().filter(i -> i.supplies(kind, name)).toList(); + List single = suppliers.stream().filter(i -> !i.declaration.isAsterisk()).toList(); + if (kind == Kind.FIELD && !single.isEmpty()) { + // a single-static-import of a field shadows those of static-imports-on-demand (JLS 6.4.1); for methods, + // it only shadows the override-equivalent ones, so the other overloads still compete + suppliers = single; + } + Set types = new HashSet<>(); + suppliers.forEach(i -> types.add(i.type.getQualifiedName())); + if (types.size() == 1) { + // prefer an excluded import, which keeps its uses as they are, then a single static import + List candidates = suppliers; + return candidates.stream().filter(i -> i.keep).findFirst() + .or(() -> candidates.stream().filter(i -> !i.declaration.isAsterisk()).findFirst()) + .or(() -> Optional.of(candidates.get(0))); + } + Set declaringTypes = new HashSet<>(); + suppliers.forEach(i -> declaringTypes.addAll(i.declaringTypes.getOrDefault(name, Set.of("?")))); + if (declaringTypes.size() == 1) { + String declaringType = declaringTypes.iterator().next(); + for (StaticImport supplier : suppliers) { + if (supplier.type.getQualifiedName().equals(declaringType)) { + return Optional.of(supplier); + } + } + } + keepSuppliersOf(name, kind); + return Optional.empty(); + } + + private void keepSuppliersOf(String name, Kind... kinds) { + for (StaticImport staticImport : imports) { + for (Kind kind : kinds) { + if (staticImport.supplies(kind, name)) { + staticImport.keep = true; + } + } + } + } + + /** Static imports named in doc comments stay, so that {@code javadoc} can still resolve the references. */ + private void keepImportsReferencedInComments() { + for (Comment comment : cu.getAllComments()) { + String content = comment.getContent(); + List patterns = comment.isJavadocComment() || comment.isMarkdownComment() || content.startsWith("/") + ? List.of(DOC_REFERENCE, MARKDOWN_REFERENCE) + : List.of(DOC_REFERENCE); + for (Pattern pattern : patterns) { + Matcher matcher = pattern.matcher(content); + while (matcher.find()) { + keepSuppliersOf(matcher.group(1), Kind.values()); + } + } + } + } + + // ---------------------------------------------------------------- the enclosing classes + + /** Whether an enclosing class of {@code node} declares or inherits a member of that kind and name. */ + private Membership membership(Node node, Kind kind, String name) { + boolean complete = true; + for (EnclosingScope scope : enclosingScopes(node)) { + Members members = members(scope.node()).get(kind); + if (!scope.inBody()) { + // a class's members are not in scope in its header: annotations, type parameters, extends, implements (JLS 6.3) + if (scope.node() instanceof RecordDeclaration && (members.possible.contains(name) || !members.complete)) { + return Membership.UNKNOWN; // a record header declares its components, so be careful there + } + continue; + } + if (members.certain.contains(name)) { + return Membership.MEMBER; + } + if (members.possible.contains(name)) { + return Membership.UNKNOWN; + } + complete &= members.complete; + } + return complete ? Membership.NOT_MEMBER : Membership.UNKNOWN; + } + + /** The classes around a node, innermost first: type declarations, anonymous classes and enum constant bodies. */ + private List enclosingScopes(Node node) { + List scopes = new ArrayList<>(); + Node child = node; + Node parent = node.getParentNode().orElse(null); + while (parent != null) { + if (parent instanceof TypeDeclaration declaration) { + boolean inBody = containsSame(declaration.getMembers(), child) + || (declaration instanceof EnumDeclaration enumDeclaration && containsSame(enumDeclaration.getEntries(), child)); + scopes.add(new EnclosingScope(parent, inBody)); + } else if (parent instanceof ObjectCreationExpr creation && creation.getAnonymousClassBody().isPresent()) { + if (containsSame(creation.getAnonymousClassBody().get(), child)) { + scopes.add(new EnclosingScope(parent, true)); + } + } else if (parent instanceof EnumConstantDeclaration constant && containsSame(constant.getClassBody(), child)) { + scopes.add(new EnclosingScope(parent, true)); + } + child = parent; + parent = parent.getParentNode().orElse(null); + } + return scopes; + } + + private Map members(Node scope) { + return membersCache.computeIfAbsent(scope, this::collectScopeMembers); + } + + private Map collectScopeMembers(Node scope) { + Map members = new EnumMap<>(Kind.class); + for (Kind kind : Kind.values()) { + members.put(kind, new Members()); + } + NodeList> body = new NodeList<>(); + try { + List supertypes = new ArrayList<>(); + if (scope instanceof TypeDeclaration declaration) { + body = declaration.getMembers(); + addImplicitMembers(declaration, members); + if (usesLombok(declaration)) { + throw new IllegalStateException("Lombok generates members that JavaParser cannot see"); + } + supertypes.addAll(directSupertypes(declaration)); + } else if (scope instanceof ObjectCreationExpr creation) { + body = creation.getAnonymousClassBody().orElseGet(NodeList::new); + supertypes.add(creation.getType().resolve().asReferenceType().getTypeDeclaration().orElseThrow()); + OBJECT_METHODS.forEach(method -> members.get(Kind.METHOD).add(method, true)); + } else { + // the members of the enum itself are found through the enclosing EnumDeclaration + body = ((EnumConstantDeclaration) scope).getClassBody(); + } + for (ResolvedReferenceTypeDeclaration supertype : supertypes) { + requireCompleteAncestry(supertype, new HashSet<>()); + addInheritedMembers(supertype, members); + } + } catch (RuntimeException e) { + members.values().forEach(m -> m.complete = false); + } + for (BodyDeclaration declaration : body) { + if (declaration instanceof MethodDeclaration method) { + members.get(Kind.METHOD).add(method.getNameAsString(), true); + } else if (declaration instanceof FieldDeclaration field) { + field.getVariables().forEach(variable -> members.get(Kind.FIELD).add(variable.getNameAsString(), true)); + } else if (declaration instanceof TypeDeclaration type) { + members.get(Kind.TYPE).add(type.getNameAsString(), true); + } else if (declaration instanceof AnnotationMemberDeclaration member) { + members.get(Kind.METHOD).add(member.getNameAsString(), true); + } + } + return members; + } + + /** Members that a type has without declaring them in its body: enum constants, record components, {@code values()}... */ + private void addImplicitMembers(TypeDeclaration declaration, Map members) { + if (declaration instanceof EnumDeclaration enumDeclaration) { + enumDeclaration.getEntries().forEach(entry -> members.get(Kind.FIELD).add(entry.getNameAsString(), true)); + members.get(Kind.METHOD).add("values", true); + members.get(Kind.METHOD).add("valueOf", true); + } else if (declaration instanceof RecordDeclaration record) { + for (Parameter component : record.getParameters()) { + members.get(Kind.FIELD).add(component.getNameAsString(), true); + members.get(Kind.METHOD).add(component.getNameAsString(), true); + } + } + boolean isInterface = declaration instanceof AnnotationDeclaration + || (declaration instanceof ClassOrInterfaceDeclaration classOrInterface && classOrInterface.isInterface()); + for (String method : OBJECT_METHODS) { + // an interface only has the public methods of Object (JLS 9.2), not clone or finalize + if (!isInterface || !(method.equals("clone") || method.equals("finalize"))) { + members.get(Kind.METHOD).add(method, true); + } + } + } + + /** The resolved direct supertypes of a type declaration, including the implicit ones. */ + private List directSupertypes(TypeDeclaration declaration) { + List types = new ArrayList<>(); + List implicit = new ArrayList<>(); + if (declaration instanceof ClassOrInterfaceDeclaration classOrInterface) { + types.addAll(classOrInterface.getExtendedTypes()); + types.addAll(classOrInterface.getImplementedTypes()); + } else if (declaration instanceof EnumDeclaration enumDeclaration) { + types.addAll(enumDeclaration.getImplementedTypes()); + implicit.add("java.lang.Enum"); + } else if (declaration instanceof RecordDeclaration record) { + types.addAll(record.getImplementedTypes()); + implicit.add("java.lang.Record"); + } else if (declaration instanceof AnnotationDeclaration) { + implicit.add("java.lang.annotation.Annotation"); + } + List supertypes = new ArrayList<>(); + for (ClassOrInterfaceType type : types) { + supertypes.add(type.resolve().asReferenceType().getTypeDeclaration().orElseThrow()); + } + for (String name : implicit) { + supertypes.add(typeSolver.solveType(name)); + } + return supertypes; + } + + /** + * Adds the members that a class inherits from a supertype (JLS 8.2, 8.4.8). Private members and static + * interface methods are not inherited; package-private ones only within their package, which depends on + * every class in between, so they are only possible members. + */ + private void addInheritedMembers(ResolvedReferenceTypeDeclaration supertype, Map members) { + for (var method : supertype.getAllMethods()) { + ResolvedMethodDeclaration declaration = method.getDeclaration(); + if (declaration.isStatic() && declaration.declaringType().isInterface()) { + continue; + } + addInherited(members.get(Kind.METHOD), declaration.getName(), declaration.accessSpecifier(), declaration.declaringType()); + } + // a field or member type that two ancestors declare may be hidden on the way, e.g. by a private field of a + // class in between (JLS 8.3, 8.5), so it is only a possible member + List fields = supertype.getAllFields(); + Map fieldCount = new HashMap<>(); + fields.forEach(field -> fieldCount.merge(field.getName(), 1, Integer::sum)); + for (ResolvedFieldDeclaration field : fields) { + AccessSpecifier access = isInterfaceOrAnnotation(field.declaringType()) ? AccessSpecifier.PUBLIC : field.accessSpecifier(); + if (fieldCount.get(field.getName()) > 1) { + members.get(Kind.FIELD).add(field.getName(), false); + } else { + addInherited(members.get(Kind.FIELD), field.getName(), access, field.declaringType()); + } + } + Map typeCount = new HashMap<>(); + List owners = withAncestors(supertype); + owners.forEach(owner -> owner.internalTypes().forEach(memberType -> typeCount.merge(memberType.getName(), 1, Integer::sum))); + for (ResolvedReferenceTypeDeclaration owner : owners) { + for (ResolvedReferenceTypeDeclaration memberType : owner.internalTypes()) { + AccessSpecifier access = isInterfaceOrAnnotation(owner) ? AccessSpecifier.PUBLIC : accessOf(memberType); + if (typeCount.get(memberType.getName()) > 1) { + members.get(Kind.TYPE).add(memberType.getName(), false); + } else { + addInherited(members.get(Kind.TYPE), memberType.getName(), access, owner); + } + } + } + } + + private void addInherited(Members members, String name, AccessSpecifier access, ResolvedTypeDeclaration declaringType) { + String declaringPackage = packageOf(declaringType); + // the JDK that runs the build may not be the one the project compiles against, and their members differ + boolean fromJdk = jdkPackages().contains(declaringPackage) && !"java.lang.Object".equals(declaringType.getQualifiedName()); + if (access == AccessSpecifier.PUBLIC || access == AccessSpecifier.PROTECTED) { + members.add(name, !fromJdk); + } else if (access == AccessSpecifier.NONE && declaringPackage.equals(packageName)) { + members.add(name, false); + } // private members, and package-private ones of another package, are not inherited + } + + // ---------------------------------------------------------------- the edits + + private String edit() { + Map plans = planQualifiers(); + List removed = imports.stream().filter(i -> !i.keep).toList(); + if (removed.isEmpty()) { + return text; + } + List edits = new ArrayList<>(); + Set newImports = new TreeSet<>(); + for (StaticImport staticImport : removed) { + Plan plan = plans.get(staticImport); + if (plan != null) { + edits.addAll(plan.insertions); + newImports.addAll(plan.imports); + } + for (String canonicalName : memberTypeImports.getOrDefault(staticImport, Set.of())) { + if (!canonicalName.equals(typeImports.get(simpleName(canonicalName)))) { + newImports.add(canonicalName); + } + } + } + addImportEdits(removed, newImports, edits); + if (touchesFence(edits)) { + return text; // toggleOffOn() would undo part of the edits, e.g. a new import inside a spotless:off region + } + return applyEdits(edits); + } + + /** Works out how to qualify every use; a static import with a use that cannot be qualified is kept. */ + private Map planQualifiers() { + while (true) { + plannedSimpleNames.clear(); + Map plans = new IdentityHashMap<>(); + Set qualifiedOffsets = new HashSet<>(); + StaticImport failed = null; + for (Use use : uses) { + StaticImport source = use.source(); + if (source.keep) { + continue; + } + int offset = use.node().getBegin().map(this::offset).orElse(-1); + if (!qualifiedOffsets.add(offset)) { + continue; // the same occurrence, seen twice + } + Optional qualifier = offset >= 0 && text.startsWith(use.name(), offset) ? qualifier(use) : Optional.empty(); + if (qualifier.isEmpty()) { + failed = source; + break; + } + Plan plan = plans.computeIfAbsent(source, s -> new Plan()); + plan.insertions.add(new Edit(offset, offset, qualifier.get().text() + ".")); + if (qualifier.get().importName() != null) { + plan.imports.add(qualifier.get().importName()); + } + } + if (failed == null) { + return plans; + } + failed.keep = true; + } + } + + /** Qualifies a use with the simple name of the imported type where that is safe, otherwise with its fully qualified name. */ + private Optional qualifier(Use use) { + ResolvedReferenceTypeDeclaration type = use.source().type; + if (!isReachableThroughContainers(type)) { + return Optional.empty(); + } + Node node = use.node(); + Context context = context(node); + // a nested type of this file may already be visible by its own name, e.g. inside its outer class + if (type.containerType().isPresent() && declaredTypeQualifiedNames.contains(type.getQualifiedName()) + && !typeParameterNames.contains(type.getName()) + && noVariableNamed(node, context, type.getName()) + && isOwnMemberTypeInScope(node, type) + && visibleType(context, type.getName(), type.getQualifiedName()) == Visible.EXPECTED) { + return Optional.of(new Qualifier(type.getName(), null)); + } + String className = type.getClassName(); + String simple = firstSegment(className); + String topLevel = type.getPackageName().isEmpty() ? simple : type.getPackageName() + "." + simple; + // an import of a java.lang type would not last: removeUnusedImports() deletes those as redundant + boolean importable = !"java.lang".equals(type.getPackageName()); + if (noVariableNamed(node, context, simple) && noMemberTypeNamed(node, simple, topLevel)) { + Visible visible = visibleType(context, simple, topLevel); + // a type parameter of an enclosing class shadows the type, and JavaParser does not see that + if (visible == Visible.EXPECTED && !typeParameterNames.contains(simple) && isUnambiguous(simple, topLevel)) { + return Optional.of(new Qualifier(className, null)); + } + if (importable && (visible == Visible.NOTHING || visible == Visible.SHADOWABLE || visible == Visible.EXPECTED)) { + String planned = plannedSimpleNames.get(simple); + if (topLevel.equals(planned)) { + return Optional.of(new Qualifier(className, topLevel)); + } + if (planned == null && canImport(simple)) { + plannedSimpleNames.put(simple, topLevel); + return Optional.of(new Qualifier(className, topLevel)); + } + } + } + String fullyQualified = type.getQualifiedName(); + String first = firstSegment(fullyQualified); + if (type.getPackageName().isEmpty() || !noVariableNamed(node, context, first) || declaredTypeNames.contains(first) + || membership(node, Kind.TYPE, first) != Membership.NOT_MEMBER || visibleType(context, first, null) != Visible.NOTHING) { + return Optional.empty(); // a variable or type of that name would obscure the package (JLS 6.4.2) + } + return Optional.of(new Qualifier(fullyQualified, null)); + } + + /** For a nested type, {@code Outer.Inner} would mean a field of {@code Outer} named {@code Inner} if there is one (JLS 6.5.2). */ + private boolean isReachableThroughContainers(ResolvedReferenceTypeDeclaration type) { + try { + ResolvedReferenceTypeDeclaration inner = type; + Optional container = inner.containerType(); + while (container.isPresent()) { + String innerName = inner.getName(); + if (container.get().getAllFields().stream().anyMatch(field -> field.getName().equals(innerName))) { + return false; + } + inner = container.get(); + container = inner.containerType(); + } + return true; + } catch (RuntimeException e) { + return false; + } + } + + /** True if no variable of that name is in scope, which would obscure a type or package of the same name (JLS 6.4.2). */ + private boolean noVariableNamed(Node node, Context context, String name) { + return !variableNames.contains(name) + && !unresolvedNames.contains(name) + && !suppliesField(name) + && membership(node, Kind.FIELD, name) == Membership.NOT_MEMBER + && !isVisibleAsVariable(context, name); + } + + /** True if no member type of that name is in scope at the node. */ + private boolean noMemberTypeNamed(Node node, String simple, String topLevel) { + return membership(node, Kind.TYPE, simple) == Membership.NOT_MEMBER; + } + + /** + * True if the innermost enclosing class with a member type of that name declares the nested type itself. + * JavaParser does not see member types inherited from superclasses, such as {@code Thread.State}. + */ + private boolean isOwnMemberTypeInScope(Node node, ResolvedReferenceTypeDeclaration type) { + String name = type.getName(); + for (EnclosingScope scope : enclosingScopes(node)) { + Members members = members(scope.node()).get(Kind.TYPE); + if (!scope.inBody() && !(scope.node() instanceof RecordDeclaration)) { + continue; // a class's members are not in scope in its header + } + if (!members.complete) { + return false; + } + if (members.possible.contains(name)) { + return scope.node() instanceof TypeDeclaration declaration + && declaration.getFullyQualifiedName().map(outer -> (outer + "." + name).equals(type.getQualifiedName())).orElse(false); + } + } + return false; + } + + /** + * A type visible through {@code java.lang} or an on-demand import can only be used by its simple name if no + * other on-demand import supplies a type of that name, which would make it ambiguous, and no type of the same + * package has that name, which would shadow it (JLS 6.4.1, 7.5.2). Types the type solver cannot see count too. + */ + private boolean isUnambiguous(String simple, String topLevel) { + if (typeImports.containsKey(simple) && !topLevel.equals(typeImports.get(simple))) { + return false; // an import names another type, even if the type solver cannot resolve it + } + if (topLevel.equals(typeImports.get(simple)) || declaredTypeQualifiedNames.contains(topLevel) + || packageOfQualified(topLevel).equals(packageName)) { + return true; + } + if (!isKnownPackage(packageName)) { + return false; + } + Set providers = new HashSet<>(); + addIfType(providers, "java.lang." + simple); + for (ImportDeclaration declaration : cu.getImports()) { + if (declaration.isModule()) { + return false; + } + if (declaration.isAsterisk() && !declaration.isStatic()) { + String name = declaration.getNameAsString(); + if (!isKnownPackage(name) && !typeSolver.tryToSolveType(name).isSolved()) { + return false; + } + addIfType(providers, name + "." + simple); + } + } + for (StaticImport staticImport : imports) { + if (staticImport.declaration.isAsterisk() && staticImport.keep && staticImport.supplies(Kind.TYPE, simple)) { + providers.add(staticImport.declaredMemberTypes.getOrDefault(simple, "?")); + } + } + return providers.size() == 1 && providers.contains(topLevel); + } + + private void addIfType(Set providers, String name) { + try { + SymbolReference reference = typeSolver.tryToSolveType(name); + if (reference.isSolved()) { + providers.add(reference.getCorrespondingDeclaration().getQualifiedName()); + } + } catch (RuntimeException e) { + providers.add("?" + name); + } + } + + /** Whether {@code import x.simple;} can be added without changing what any other name in the file refers to. */ + private boolean canImport(String simple) { + if (typeImports.containsKey(simple) || declaredTypeNames.contains(simple) || unresolvedNames.contains(simple)) { + return false; + } + for (StaticImport staticImport : imports) { + if (!staticImport.declaration.isAsterisk() && staticImport.declaration.getName().getIdentifier().equals(simple)) { + return false; // a single-static-import of a type with that name would clash (JLS 7.5.3) + } + } + for (Set canonicalNames : memberTypeImports.values()) { + for (String canonicalName : canonicalNames) { + if (simpleName(canonicalName).equals(simple)) { + return false; + } + } + } + return !usedUnqualified(simple); + } + + /** Whether the simple name is used anywhere in the file as a type or an expression name, where a new import could capture it. */ + private boolean usedUnqualified(String simple) { + return usedUnqualifiedCache.computeIfAbsent(simple, s -> { + for (SimpleName name : cu.findAll(SimpleName.class)) { + if (name.getIdentifier().equals(s)) { + Node parent = name.getParentNode().orElse(null); + if (parent instanceof NameExpr || (parent instanceof ClassOrInterfaceType type && type.getScope().isEmpty())) { + return true; + } + } + } + for (Name name : cu.findAll(Name.class)) { + if (name.getQualifier().isEmpty() && name.getIdentifier().equals(s) + && name.findAncestor(ImportDeclaration.class).isEmpty() + && name.findAncestor(PackageDeclaration.class).isEmpty()) { + return true; + } + } + return false; + }); + } + + private Context context(Node node) { + return JavaParserFactory.getContext(node, typeSolver); + } + + private Visible visibleType(Context context, String simple, String expected) { + try { + SymbolReference reference = context.solveType(simple); + if (!reference.isSolved()) { + return Visible.NOTHING; + } + ResolvedTypeDeclaration declaration = reference.getCorrespondingDeclaration(); + if (declaration.getQualifiedName().equals(expected)) { + return Visible.EXPECTED; + } + boolean topLevel = declaration instanceof ResolvedReferenceTypeDeclaration type && type.containerType().isEmpty(); + return topLevel ? Visible.SHADOWABLE : Visible.OTHER; + } catch (RuntimeException e) { + return Visible.UNKNOWN; + } + } + + private boolean isVisibleAsVariable(Context context, String name) { + try { + return context.solveSymbol(name).isSolved(); + } catch (RuntimeException e) { + return true; + } + } + + private void addImportEdits(List removed, Set newImports, List edits) { + Set removedDeclarations = Collections.newSetFromMap(new IdentityHashMap<>()); + removed.forEach(r -> removedDeclarations.add(r.declaration)); + ImportDeclaration lastRemaining = null; + for (ImportDeclaration declaration : cu.getImports()) { + if (!removedDeclarations.contains(declaration)) { + lastRemaining = declaration; + } + } + StringBuilder importLines = new StringBuilder(); + for (String newImport : newImports) { + importLines.append("import ").append(newImport).append(";\n"); + } + List blocks = removalBlocks(removed); + if (!newImports.isEmpty()) { + if (lastRemaining == null) { + // the new imports take the place of the first removed block + int[] first = blocks.remove(0); + edits.add(new Edit(first[0], first[1], importLines.toString())); + } else { + int end = offset(lastRemaining.getEnd().orElseThrow()) + 1; + int newline = text.indexOf('\n', end); + String rest = text.substring(end, newline < 0 ? text.length() : newline).strip(); + if (rest.isEmpty() || rest.startsWith("//")) { + int afterLast = lineEnd(end); + edits.add(new Edit(afterLast, afterLast, importLines.toString())); + } else { + // the line goes on, e.g. with the class or a comment: the new imports go on lines of their own + edits.add(new Edit(end, end, "\n" + importLines.toString().stripTrailing())); + } + } + } + for (int[] block : blocks) { + edits.add(new Edit(block[0], withFollowingBlankLine(block), "")); + } + } + + /** The end of a deleted block, extended over the next line if the block sits between two blank lines, so that only one remains. */ + private int withFollowingBlankLine(int[] block) { + boolean wholeLines = block[0] > 0 && text.charAt(block[0] - 1) == '\n' && text.charAt(block[1] - 1) == '\n'; + boolean blankBefore = block[0] >= 2 && text.charAt(block[0] - 2) == '\n'; + boolean blankAfter = block[1] < text.length() && text.charAt(block[1]) == '\n'; + return wholeLines && blankBefore && blankAfter ? block[1] + 1 : block[1]; + } + + /** The text ranges of the removed imports: whole lines when an import is alone on its line, with adjacent lines merged. */ + private List removalBlocks(List removed) { + List ranges = new ArrayList<>(); + for (StaticImport staticImport : removed) { + int begin = offset(staticImport.declaration.getBegin().orElseThrow()); + int end = offset(staticImport.declaration.getEnd().orElseThrow()) + 1; + int lineStart = text.lastIndexOf('\n', begin - 1) + 1; + int newline = text.indexOf('\n', end); + int contentEnd = newline < 0 ? text.length() : newline; + String rest = text.substring(end, contentEnd).strip(); + // an import alone on its line goes with its line, including a trailing comment about it, such as `// NOPMD` + if (text.substring(lineStart, begin).isBlank() && (rest.isEmpty() || rest.startsWith("//"))) { + ranges.add(new int[]{lineStart, newline < 0 ? text.length() : newline + 1}); + } else { + // shares its line with other code: remove it with the blanks that follow it + int after = end; + while (after < contentEnd && (text.charAt(after) == ' ' || text.charAt(after) == '\t')) { + after++; + } + ranges.add(new int[]{begin, after}); + } + } + ranges.sort(Comparator.comparingInt(range -> range[0])); + List blocks = new ArrayList<>(); + for (int[] range : ranges) { + int[] last = blocks.isEmpty() ? null : blocks.get(blocks.size() - 1); + if (last != null && last[1] == range[0]) { + last[1] = range[1]; + } else { + blocks.add(new int[]{range[0], range[1]}); + } + } + return blocks; + } + + private boolean touchesFence(List edits) { + for (Edit edit : edits) { + for (int[] fence : fences) { + boolean touches = edit.start() == edit.end() + ? fence[0] < edit.start() && edit.start() < fence[1] + : edit.start() < fence[1] && fence[0] < edit.end(); + if (touches) { + return true; + } + } + } + return false; + } + + /** The offset just after the end of the line that contains {@code offset}. */ + private int lineEnd(int offset) { + int newline = text.indexOf('\n', offset); + return newline < 0 ? text.length() : newline + 1; + } + + private String applyEdits(List edits) { + edits.sort(Comparator.comparingInt(Edit::start).thenComparingInt(Edit::end)); + List merged = new ArrayList<>(); + for (Edit edit : edits) { + Edit last = merged.isEmpty() ? null : merged.get(merged.size() - 1); + if (last != null && edit.start() < last.end()) { + throw new IllegalStateException("overlapping edits"); + } + if (last != null && edit.start() == last.start() && last.start() == last.end()) { + // an insertion, then a replacement that starts at the same place + merged.set(merged.size() - 1, new Edit(edit.start(), edit.end(), last.replacement() + edit.replacement())); + } else { + merged.add(edit); + } + } + StringBuilder result = new StringBuilder(text); + for (int i = merged.size() - 1; i >= 0; i--) { + Edit edit = merged.get(i); + result.replace(edit.start(), edit.end(), edit.replacement()); + } + return result.toString(); + } + + private int offset(Position position) { + if (position.line < 1 || position.line >= lineOffsets.length) { + return -1; + } + return lineOffsets[position.line] + position.column - 1; + } + } + + /** True if the type declaration, or one of its members, carries an annotation that may come from Lombok. */ + private static boolean usesLombok(TypeDeclaration declaration) { + CompilationUnit cu = declaration.findCompilationUnit().orElse(null); + Set lombokNames = new HashSet<>(); + boolean lombokOnDemand = false; + if (cu != null) { + for (ImportDeclaration declarationImport : cu.getImports()) { + String name = declarationImport.getNameAsString(); + if (name.equals("lombok") || name.startsWith("lombok.")) { + if (declarationImport.isAsterisk()) { + lombokOnDemand = true; + } else { + lombokNames.add(declarationImport.getName().getIdentifier()); + } + } + } + } + for (AnnotationExpr annotation : declaration.findAll(AnnotationExpr.class)) { + String name = annotation.getNameAsString(); + if (name.startsWith("lombok.") || lombokNames.contains(name) || (lombokOnDemand && !name.contains("."))) { + return true; + } + } + return false; + } + + /** {@code NodeList.contains} compares nodes structurally, which is slow and could match an identical member elsewhere. */ + private static boolean containsSame(List nodes, Node node) { + for (Node element : nodes) { + if (element == node) { + return true; + } + } + return false; + } + + private static List withAncestors(ResolvedReferenceTypeDeclaration type) { + List types = new ArrayList<>(); + types.add(type); + for (ResolvedReferenceType ancestor : type.getAllAncestors()) { + types.add(ancestor.getTypeDeclaration().orElseThrow()); + } + return types; + } + + private static boolean isInterfaceOrAnnotation(ResolvedTypeDeclaration type) { + return type.isInterface() || type.isAnnotation(); + } + + private static AccessSpecifier accessOf(ResolvedReferenceTypeDeclaration type) { + return type instanceof HasAccessSpecifier withAccess ? withAccess.accessSpecifier() : AccessSpecifier.NONE; + } + + private static String packageOf(ResolvedTypeDeclaration type) { + return type instanceof ResolvedReferenceTypeDeclaration reference ? reference.getPackageName() : ""; + } + + private static String packageOfQualified(String qualifiedName) { + int dot = qualifiedName.lastIndexOf('.'); + return dot < 0 ? "" : qualifiedName.substring(0, dot); + } + + private static boolean isQualifier(NameExpr nameExpr) { + Node parent = nameExpr.getParentNode().orElse(null); + if (parent instanceof MethodCallExpr call) { + return call.getScope().filter(scope -> scope == nameExpr).isPresent(); + } + if (parent instanceof FieldAccessExpr access) { + return access.getScope() == nameExpr; + } + return parent instanceof MethodReferenceExpr reference && reference.getScope() == nameExpr; + } + + /** True for the {@code X} of {@code X::method}, which JavaParser parses as a type even when it is a variable. */ + private static boolean isMethodReferenceScope(ClassOrInterfaceType type) { + return type.getParentNode().orElse(null) instanceof TypeExpr typeExpr + && typeExpr.getParentNode().orElse(null) instanceof MethodReferenceExpr reference + && reference.getScope() == typeExpr; + } + + private static String firstSegment(String dottedName) { + int dot = dottedName.indexOf('.'); + return dot < 0 ? dottedName : dottedName.substring(0, dot); + } + + private static String simpleName(String canonicalName) { + return canonicalName.substring(canonicalName.lastIndexOf('.') + 1); + } + + /** {@code lineOffsets[line]} is the offset of the first character of that 1-based line. */ + private static int[] lineOffsets(String text) { + List offsets = new ArrayList<>(); + offsets.add(0); + offsets.add(0); + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) == '\n') { + offsets.add(i + 1); + } + } + return offsets.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/SymbolResolution.java b/lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/SymbolResolution.java new file mode 100644 index 0000000000..ae186c9485 --- /dev/null +++ b/lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/SymbolResolution.java @@ -0,0 +1,202 @@ +/* + * Copyright 2026 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.glue.javaparser; + +import java.io.File; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javassist.ClassPool; + +import com.github.javaparser.JavaParser; +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.ParserConfiguration.LanguageLevel; +import com.github.javaparser.resolution.TypeSolver; +import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration; +import com.github.javaparser.resolution.model.SymbolReference; +import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade; +import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.JarTypeSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver; +import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; + +/** The JavaParser setup shared by the steps that resolve names against the project's classpath. */ +final class SymbolResolution { + static { + // If ClassPool is allowed to cache class files, it does not free the file-lock + ClassPool.cacheOpenedJarFile = false; + } + + private SymbolResolution() {} + + /** A parser that accepts every language level; JavaParser defaults to Java 11 and rejects newer syntax such as records. */ + static JavaParser parser() { + return new JavaParser(new ParserConfiguration().setLanguageLevel(LanguageLevel.BLEEDING_EDGE)); + } + + /** A type solver for the JDK and the given jars and source directories. Entries that do not exist are ignored. */ + static CombinedTypeSolver typeSolver(Collection classpath) throws IOException { + CombinedTypeSolver combinedTypeSolver = new CombinedTypeSolver(); + combinedTypeSolver.add(new ReflectionTypeSolver(ReflectionTypeSolver.JCL_ONLY)); + for (File element : classpath) { + if (element.isFile() && element.getName().endsWith(".jar")) { + combinedTypeSolver.add(new JarTypeSolver(element)); + } else if (element.isDirectory()) { + combinedTypeSolver.add(new JavaParserTypeSolver(element)); + } + } + return combinedTypeSolver; + } + + /** + * Like {@link #typeSolver(Collection)}, but parses the files of the source directories with the given configuration, + * which can have a symbol resolver, and only when a file there mentions the name being looked up. + */ + static CombinedTypeSolver typeSolver(Collection classpath, ParserConfiguration sourceConfiguration) throws IOException { + CombinedTypeSolver combinedTypeSolver = new CombinedTypeSolver(); + combinedTypeSolver.add(new ReflectionTypeSolver(ReflectionTypeSolver.JCL_ONLY)); + for (File element : classpath) { + if (element.isFile() && element.getName().endsWith(".jar")) { + combinedTypeSolver.add(new JarTypeSolver(element)); + } else if (element.isDirectory()) { + combinedTypeSolver.add(new MentionFilter(element, sourceConfiguration)); + } + } + return combinedTypeSolver; + } + + /** + * JavaParser caches a facade for every type solver in a static map, which keeps the type solver, and with it + * every jar it has read, alive for as long as JavaParser's classes are loaded. Clears it. + */ + static void release() { + synchronized (JavaParserFacade.class) { + // JavaParserFacade.get is static synchronized, clearInstances is not + JavaParserFacade.clearInstances(); + } + } + + /** + * A source directory that only asks JavaParser about a type when one of the files that could declare it mentions + * its name. When a package has no file named after the type, JavaParser parses every file of the package to look for + * a non-public top-level type of that name, and most of the names this step looks up are in no package at all. + */ + private static final class MentionFilter implements TypeSolver { + private static final Pattern IDENTIFIER = Pattern.compile("[\\p{javaJavaIdentifierStart}][\\p{javaJavaIdentifierPart}]*"); + private static final String ANY_NAME = "\\u"; + + private final File root; + private final ParserConfiguration configuration; + private final Map> namesByDirectory = new HashMap<>(); + private TypeSolver parent; + private JavaParserTypeSolver delegate; + private RuntimeException failure; + + MentionFilter(File root, ParserConfiguration configuration) { + this.root = root; + this.configuration = configuration; + } + + @Override + public TypeSolver getParent() { + return parent; + } + + @Override + public void setParent(TypeSolver parent) { + this.parent = parent; + } + + @Override + public SymbolReference tryToSolveType(String name) { + return mayDeclare(name) ? delegate().tryToSolveType(name) : SymbolReference.unsolved(); + } + + @Override + public SymbolReference tryToSolveTypeInModule(String qualifiedModuleName, String simpleTypeName) { + return mayDeclare(simpleTypeName) ? delegate().tryToSolveTypeInModule(qualifiedModuleName, simpleTypeName) : SymbolReference.unsolved(); + } + + /** Created on first use, since it walks the whole directory, and remembered when that fails, e.g. for an unreadable folder. */ + private JavaParserTypeSolver delegate() { + if (failure != null) { + throw failure; + } + if (delegate == null) { + try { + JavaParserTypeSolver created = new JavaParserTypeSolver(root, configuration); + created.setParent(parent); + delegate = created; + } catch (RuntimeException e) { + failure = e; + throw e; + } + } + return delegate; + } + + /** A type can only be declared in a file that mentions its name, in a directory of one of the packages the name could have. */ + private boolean mayDeclare(String name) { + String[] segments = name.split("\\."); + String simpleName = segments[segments.length - 1]; + for (int packageLength = 0; packageLength < segments.length; packageLength++) { + File directory = new File(root, String.join("/", Arrays.copyOfRange(segments, 0, packageLength))); + Set names = namesIn(directory); + if (names.contains(simpleName) || names.contains(ANY_NAME)) { + return true; + } + } + return false; + } + + private Set namesIn(File directory) { + return namesByDirectory.computeIfAbsent(directory, dir -> { + Set names = new HashSet<>(); + File[] sources = dir.listFiles((parentDir, fileName) -> fileName.endsWith(".java")); + if (sources == null) { + return names; + } + for (File source : sources) { + String content; + try { + // decoded like JavaParser decodes it, without failing on bytes that are not UTF-8 + content = new String(Files.readAllBytes(source.toPath()), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + if (content.contains(ANY_NAME)) { + // a unicode escape can spell any name, so this file may declare anything + names.add(ANY_NAME); + } + Matcher identifier = IDENTIFIER.matcher(content); + while (identifier.find()) { + names.add(identifier.group()); + } + } + return names; + }); + } + } +} diff --git a/lib/src/main/java/com/diffplug/spotless/java/ReplaceStaticImportsStep.java b/lib/src/main/java/com/diffplug/spotless/java/ReplaceStaticImportsStep.java new file mode 100644 index 0000000000..ef1db42279 --- /dev/null +++ b/lib/src/main/java/com/diffplug/spotless/java/ReplaceStaticImportsStep.java @@ -0,0 +1,140 @@ +/* + * Copyright 2026 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.java; + +import static com.diffplug.spotless.JarState.from; +import static com.diffplug.spotless.JarState.promise; +import static java.util.Objects.requireNonNull; + +import java.io.File; +import java.io.IOException; +import java.io.Serial; +import java.io.Serializable; +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import com.diffplug.spotless.FileSignature; +import com.diffplug.spotless.FormatterFunc; +import com.diffplug.spotless.FormatterStep; +import com.diffplug.spotless.JarState; +import com.diffplug.spotless.Provisioner; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; + +/** + * Replaces static imports with regular imports and qualified references, so that + * {@code assertTrue(x)} becomes {@code Assertions.assertTrue(x)}. + * + *

Uses JavaParser and the project classpath to work out what each name refers to. A static + * import is only replaced when every use of it can be resolved; otherwise it is left as it is. + * + *

Designed to run before {@code importOrder()} and {@code removeUnusedImports()}. + */ +public final class ReplaceStaticImportsStep implements Serializable { + @Serial + private static final long serialVersionUID = 1L; + + private static final String NAME = "replaceStaticImports"; + private static final String INCOMPATIBLE_ERROR_MESSAGE = "There was a problem interacting with JavaParser; maybe you set an incompatible version?"; + private static final String MAVEN_COORDINATES = "com.github.javaparser:javaparser-symbol-solver-core:" + BuildConfig.VERSION_JAVAPARSER; + + private final List typeSolverClasspath; + private final List excludes; + private final JarState.Promised jarState; + + private ReplaceStaticImportsStep(List typeSolverClasspath, List excludes, JarState.Promised jarState) { + this.typeSolverClasspath = typeSolverClasspath; + this.excludes = excludes; + this.jarState = jarState; + } + + /** + * @param typeSolverClasspath source directories and jars used to resolve names, normally the + * source directories and compile classpath of the project + */ + public static FormatterStep create(Set typeSolverClasspath, Provisioner provisioner) { + return create(typeSolverClasspath, List.of(), provisioner); + } + + /** + * @param typeSolverClasspath source directories and jars used to resolve names, normally the + * source directories and compile classpath of the project + * @param excludes static imports to keep: {@code org.assertj.core.api.Assertions.*}, or just the type name, keeps + * every static import from that class; {@code java.util.concurrent.TimeUnit.SECONDS} keeps the static import of + * that member, and an on-demand static import of its class if the file uses the member through it + */ + public static FormatterStep create(Set typeSolverClasspath, Collection excludes, Provisioner provisioner) { + requireNonNull(typeSolverClasspath); + requireNonNull(excludes); + requireNonNull(provisioner); + Set sortedExcludes = new TreeSet<>(); + for (String exclude : excludes) { + sortedExcludes.add(requireNonNull(exclude).trim()); + } + return FormatterStep.create(NAME, + new ReplaceStaticImportsStep(List.copyOf(typeSolverClasspath), List.copyOf(sortedExcludes), promise(() -> from(MAVEN_COORDINATES, provisioner))), + ReplaceStaticImportsStep::equalityState, + State::toFormatter); + } + + private State equalityState() throws IOException { + List jars = typeSolverClasspath.stream().filter(file -> file.isFile() && file.getName().endsWith(".jar")).toList(); + return new State(typeSolverClasspath, FileSignature.signAsList(jars), excludes, jarState.get()); + } + + /** + * Equality depends on the content of the jars, the excludes, the JavaParser version and the JDK version. The + * paths are transient, so that build cache keys do not depend on where the project is. + */ + private static final class State implements Serializable { + @Serial + private static final long serialVersionUID = 1L; + + /** Only used to create the formatter: the equality state is never deserialized, and the paths must not affect equality. */ + @SuppressFBWarnings(value = "SE_TRANSIENT_FIELD_NOT_RESTORED", justification = "paths are kept out of the equality check, like FileSignature does") + private final transient List typeSolverClasspath; + @SuppressWarnings("unused") + private final FileSignature jars; + private final List excludes; + private final JarState jarState; + /** The JDK classes are those of the JDK running the build, which can make a difference. */ + @SuppressWarnings("unused") + private final int jdkVersion = Runtime.version().feature(); + + State(List typeSolverClasspath, FileSignature jars, List excludes, JarState jarState) { + this.typeSolverClasspath = typeSolverClasspath; + this.jars = jars; + this.excludes = excludes; + this.jarState = jarState; + } + + FormatterFunc toFormatter() { + try { + return (FormatterFunc) jarState + .getClassLoader() + .loadClass("com.diffplug.spotless.glue.javaparser.ReplaceStaticImportsFormatterFunc") + .getConstructor(Collection.class, Collection.class) + .newInstance(typeSolverClasspath, excludes); + } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException + | InstantiationException | IllegalAccessException | NoClassDefFoundError cause) { + throw new IllegalStateException(INCOMPATIBLE_ERROR_MESSAGE, cause); + } + } + } +} diff --git a/plugin-gradle/CHANGES.md b/plugin-gradle/CHANGES.md index 27c78dde65..83287f62bb 100644 --- a/plugin-gradle/CHANGES.md +++ b/plugin-gradle/CHANGES.md @@ -6,6 +6,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ### Added - Add `groupArtifact(String)` to `palantirJavaFormat()`. ([#3179](https://github.com/diffplug/spotless/pull/3179)) - `SpotlessApply` writes a report of the files it rewrote to `build/spotless/-changed-files.txt`, configurable via `changedFilesReport`. The report is a task output, so tasks which take it as an input automatically depend on the apply task. ([#2715](https://github.com/diffplug/spotless/issues/2715)) +- Add `replaceStaticImports()` for Java, which replaces static imports with regular imports and qualified references, such as `Assertions.assertTrue(x)`, using the compile classpath to resolve names. Pass the static imports to keep, such as `'org.assertj.core.api.Assertions.*'`. ([#1379](https://github.com/diffplug/spotless/issues/1379)) ### Changes - `SpotlessApply` now only reports that it did work (and is otherwise `UP-TO-DATE`) when it actually rewrote a file. ([#2715](https://github.com/diffplug/spotless/issues/2715)) ### Fixed diff --git a/plugin-gradle/README.md b/plugin-gradle/README.md index e762f1d5c5..60c3c1503b 100644 --- a/plugin-gradle/README.md +++ b/plugin-gradle/README.md @@ -79,7 +79,7 @@ Spotless supports all of Gradle's built-in performance features (incremental bui - [Git hook (optional)](#git-hook) - [Linting](#linting) - **Languages** - - [Java](#java) ([removeUnusedImports](#removeunusedimports), [forbidWildcardImports](#forbidwildcardimports), [expandWildcardImports](#expandwildcardimports), [forbidModuleImports](#forbidmoduleimports), [shortenFullyQualifiedTypes](#shortenfullyqualifiedtypes), [google-java-format](#google-java-format), [eclipse jdt](#eclipse-jdt), [clang-format](#clang-format), [prettier](#prettier), [palantir-java-format](#palantir-java-format), [prince-of-space](#prince-of-space), [formatAnnotations](#formatAnnotations), [cleanthat](#cleanthat), [tabletest-formatter](#tabletest-formatter), [IntelliJ IDEA](#intellij-idea)) + - [Java](#java) ([removeUnusedImports](#removeunusedimports), [forbidWildcardImports](#forbidwildcardimports), [expandWildcardImports](#expandwildcardimports), [forbidModuleImports](#forbidmoduleimports), [shortenFullyQualifiedTypes](#shortenfullyqualifiedtypes), [replaceStaticImports](#replacestaticimports), [google-java-format](#google-java-format), [eclipse jdt](#eclipse-jdt), [clang-format](#clang-format), [prettier](#prettier), [palantir-java-format](#palantir-java-format), [prince-of-space](#prince-of-space), [formatAnnotations](#formatAnnotations), [cleanthat](#cleanthat), [tabletest-formatter](#tabletest-formatter), [IntelliJ IDEA](#intellij-idea)) - [Groovy](#groovy) ([eclipse groovy](#eclipse-groovy)) - [Kotlin](#kotlin) ([ktfmt](#ktfmt), [ktlint](#ktlint), [diktat](#diktat), [tabletest-formatter](#tabletest-formatter-1), [prettier](#prettier)) - [Scala](#scala) ([scalafmt](#scalafmt)) @@ -234,6 +234,7 @@ spotless { forbidWildcardImports() // or expandWildcardImports, see below forbidModuleImports() shortenFullyQualifiedTypes() // replaces fully-qualified type names with simple names + imports + replaceStaticImports() // replaces static imports with qualified references + imports, see below // Cleanthat will refactor your code, but it may break your style: apply it before your formatter cleanthat() // has its own section below @@ -371,6 +372,71 @@ A name is left fully-qualified whenever shortening it could change what the code Types in `java.lang` and in the file's own package are shortened without adding an import. +### replaceStaticImports + +Replaces static imports with regular imports and qualified references, for codebases that prefer `Assertions.assertTrue(x)` to a bare `assertTrue(x)`. + +Like [`expandWildcardImports`](#expandwildcardimports), it uses [JavaParser](https://javaparser.org/) and your compile classpath to work out what each name refers to, so it needs the `java` plugin. New imports are appended after the existing ones, so run it before `importOrder()`: + +```gradle +spotless { + java { + replaceStaticImports() + importOrder() + removeUnusedImports() + } +} +``` + +Before: + +```java +package com.acme; + +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TimeoutTest { + void defaultTimeout() { + assertEquals(30_000, SECONDS.toMillis(30)); + } +} +``` + +After: + +```java +package com.acme; + +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Assertions; + +class TimeoutTest { + void defaultTimeout() { + Assertions.assertEquals(30_000, TimeUnit.SECONDS.toMillis(30)); + } +} +``` + +It never changes what the code means, so a static import is only replaced when every use of it can be resolved: + +- a name hidden by a local variable, or by a method, field or nested class of the enclosing class, is not a use of the import and stays as it is +- an enum constant used as a `case` label of a `switch` on that enum stays unqualified, since qualified ones only compile from Java 21 on +- when the simple name of the class is already taken in the file, the fully qualified name is used, e.g. `java.util.Date.from(instant)` +- a static import of a nested class becomes a regular import of that class, e.g. `import java.util.Map.Entry;` +- a static import that the classpath cannot resolve, or whose names are also supplied by another imported class, is left alone +- so is a static import with a use that cannot be resolved with certainty, for example in a class whose supertypes are not on the classpath or that uses Lombok, inside a `spotless:off` region, or in a Javadoc reference + +It relies on the classpath to know what names mean: + +- JDK classes are those of the JDK that runs the build, so run the build with the JDK that the project compiles against, or a newer one +- all source sets share one classpath, as with `expandWildcardImports` +- classes that are not on the classpath, such as generated sources, are assumed not to exist: a generated class in the same package named like a class that it qualifies with, such as `Math`, would take over `Math.max` +- of the regions that `toggleOffOn` restores, it only recognises those between `spotless:off` and `spotless:on`, or `@formatter:off` and `@formatter:on` + +To keep some static imports, such as AssertJ's, list them: `replaceStaticImports('org.assertj.core.api.Assertions.*', 'java.util.concurrent.TimeUnit.SECONDS')`. `Type.*`, or just `Type`, keeps every static import from that class. `Type.member` keeps the static import of that member, and an on-demand `import static Type.*;` if the file uses that member through it. + + ### google-java-format [homepage](https://github.com/google/google-java-format). [changelog](https://github.com/google/google-java-format/releases). diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java index ed7fa4151f..d8341117fb 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/JavaExtension.java @@ -16,13 +16,14 @@ package com.diffplug.gradle.spotless; import static com.diffplug.gradle.spotless.PluginGradlePreconditions.requireElementsNonNull; -import static java.util.stream.Collectors.toSet; +import static java.util.stream.Collectors.toCollection; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; @@ -47,6 +48,7 @@ import com.diffplug.spotless.java.PalantirJavaFormatStep; import com.diffplug.spotless.java.PrinceOfSpaceStep; import com.diffplug.spotless.java.RemoveUnusedImportsStep; +import com.diffplug.spotless.java.ReplaceStaticImportsStep; import com.diffplug.spotless.java.ShortenFullyQualifiedTypesStep; import com.diffplug.spotless.java.TableTestFormatterStep; @@ -179,13 +181,28 @@ public void forbidModuleImports() { } public void expandWildcardImports() { - SourceSetContainer sourceSets = getSourceSets(getProject(), "expansion of wildcards requires the 'java' plugin to be applied"); - Set typeSolverClasspath = sourceSets.stream().flatMap(s -> s.getAllJava().getSrcDirs().stream()).collect(toSet()); + addStep(ExpandWildcardImportsStep.create(typeSolverClasspath("expansion of wildcards requires the 'java' plugin to be applied"), provisioner())); + } + + /** + * Replaces static imports with regular imports and qualified references, such as {@code Assertions.assertTrue(x)}. + * + * @param excludes static imports to keep, such as {@code org.assertj.core.api.Assertions.*} for every static import + * from that class, or {@code java.util.concurrent.TimeUnit.SECONDS} for the import of that member + */ + public void replaceStaticImports(String... excludes) { + addStep(ReplaceStaticImportsStep.create(typeSolverClasspath("replacing static imports requires the 'java' plugin to be applied"), List.of(excludes), provisioner())); + } + + /** The source directories and compile classpath of every source set, which JavaParser uses to resolve names. */ + private Set typeSolverClasspath(String message) { + SourceSetContainer sourceSets = getSourceSets(getProject(), message); + Set typeSolverClasspath = sourceSets.stream().flatMap(s -> s.getAllJava().getSrcDirs().stream()).collect(toCollection(LinkedHashSet::new)); sourceSets.stream() .map(SourceSet::getCompileClasspath) .flatMap(classpath -> classpath.getFiles().stream()) .forEach(typeSolverClasspath::add); - addStep(ExpandWildcardImportsStep.create(typeSolverClasspath, provisioner())); + return typeSolverClasspath; } /** Uses the google-java-format jar to format source code. */ diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/JavaDefaultTargetTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/JavaDefaultTargetTest.java index 60762dce8f..9662a60f96 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/JavaDefaultTargetTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/JavaDefaultTargetTest.java @@ -208,6 +208,58 @@ void expandWildcardImportsIgnoresUnrelatedConfigurations() throws IOException { assertFile("src/main/java/test.java").sameAsResource("java/googlejavaformat/JavaCodeUnformatted.test"); } + @Test + void replaceStaticImports() throws IOException { + setFile("build.gradle").toLines( + "plugins {", + " id 'java'", + " id 'com.diffplug.spotless'", + "}", + "", + "repositories { mavenCentral() }", + "", + "spotless {", + " java {", + " target file('src/main/java/p/A.java')", + " replaceStaticImports('java.lang.Math.*')", + " }", + "}"); + // only resolvable through the source sets + setFile("src/main/java/q/Codes.java").toLines( + "package q;", + "", + "public final class Codes {", + " public static final int OK = 0;", + "}"); + setFile("src/main/java/p/A.java").toLines( + "package p;", + "", + "import static java.lang.Math.max;", + "import static java.util.Objects.requireNonNull;", + "import static q.Codes.OK;", + "", + "class A {", + " int f(Object o) {", + " requireNonNull(o);", + " return max(OK, 1);", + " }", + "}"); + gradleRunner().withArguments("spotlessApply").build(); + assertFile("src/main/java/p/A.java").hasLines( + "package p;", + "", + "import static java.lang.Math.max;", + "import java.util.Objects;", + "import q.Codes;", + "", + "class A {", + " int f(Object o) {", + " Objects.requireNonNull(o);", + " return max(Codes.OK, 1);", + " }", + "}"); + } + /** * Triggers the special case in {@link FormatExtension#setupTask(SpotlessTask)} with {@code toggleFence} and * {@code targetExcludeContentPattern} both being not {@code null}. diff --git a/plugin-maven/CHANGES.md b/plugin-maven/CHANGES.md index 7120684723..270fb9f345 100644 --- a/plugin-maven/CHANGES.md +++ b/plugin-maven/CHANGES.md @@ -7,6 +7,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( - Add a `` parameter to ``. ([#3179](https://github.com/diffplug/spotless/pull/3179)) - Add a `spotless:report` goal that puts a Spotless page in the Maven site. ([#3175](https://github.com/diffplug/spotless/pull/3175)) List `spotless-maven-plugin` under `` and run `mvn site`: the page shows which files need formatting, with a colored diff for each, and their lint problems. It works with `maven-site-plugin` 3.12.1 and 3.20.0 or later. +- Add `` for Java, which replaces static imports with regular imports and qualified references, such as `Assertions.assertTrue(x)`, using the project's source roots and dependencies to resolve names. Static imports to keep go in ``. ([#1379](https://github.com/diffplug/spotless/issues/1379)) ### Fixed - GrEclipse no longer leaves a `file%3A...` directory in the working directory. ([#2019](https://github.com/diffplug/spotless/issues/2019)) - DBeaver SQL formatter no longer prints an `IndexOutOfBoundsException` when a file starts with a keyword like `SET`. ([#1552](https://github.com/diffplug/spotless/issues/1552)) diff --git a/plugin-maven/README.md b/plugin-maven/README.md index cb94daa3de..c38227bccd 100644 --- a/plugin-maven/README.md +++ b/plugin-maven/README.md @@ -40,7 +40,7 @@ user@machine repo % mvn spotless:check - [Git hook (optional)](#git-hook) - [Binding to maven phase](#binding-to-maven-phase) - **Languages** - - [Java](#java) ([removeUnusedImports](#removeunusedimports), [forbidWildcardImports](#forbidwildcardimports), [expandWildcardImports](#expandwildcardimports), [forbidModuleImports](#forbidmoduleimports), [shortenFullyQualifiedTypes](#shortenfullyqualifiedtypes), [google-java-format](#google-java-format), [eclipse jdt](#eclipse-jdt), [prettier](#prettier), [palantir-java-format](#palantir-java-format), [prince-of-space](#prince-of-space), [formatAnnotations](#formatAnnotations), [cleanthat](#cleanthat), [tabletest-formatter](#tabletest-formatter), [IntelliJ IDEA](#intellij-idea)) + - [Java](#java) ([removeUnusedImports](#removeunusedimports), [forbidWildcardImports](#forbidwildcardimports), [expandWildcardImports](#expandwildcardimports), [forbidModuleImports](#forbidmoduleimports), [shortenFullyQualifiedTypes](#shortenfullyqualifiedtypes), [replaceStaticImports](#replacestaticimports), [google-java-format](#google-java-format), [eclipse jdt](#eclipse-jdt), [prettier](#prettier), [palantir-java-format](#palantir-java-format), [prince-of-space](#prince-of-space), [formatAnnotations](#formatAnnotations), [cleanthat](#cleanthat), [tabletest-formatter](#tabletest-formatter), [IntelliJ IDEA](#intellij-idea)) - [Groovy](#groovy) ([eclipse groovy](#eclipse-groovy)) - [Kotlin](#kotlin) ([ktfmt](#ktfmt), [ktlint](#ktlint), [diktat](#diktat), [tabletest-formatter](#tabletest-formatter-1), [prettier](#prettier)) - [Scala](#scala) ([scalafmt](#scalafmt)) @@ -238,6 +238,7 @@ any other maven phase (i.e. compile) then it can be configured as below; + @@ -335,6 +336,76 @@ A name is left fully-qualified whenever shortening it could change what the code Types in `java.lang` and in the file's own package are shortened without adding an import. +### replaceStaticImports + +Replaces static imports with regular imports and qualified references, for codebases that prefer `Assertions.assertTrue(x)` to a bare `assertTrue(x)`. + +Like [`expandWildcardImports`](#expandwildcardimports), it uses [JavaParser](https://javaparser.org/) and your project's source roots and dependencies to work out what each name refers to. New imports are appended after the existing ones, so run it before ``: + +```xml + + + +``` + +Before: + +```java +package com.acme; + +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TimeoutTest { + void defaultTimeout() { + assertEquals(30_000, SECONDS.toMillis(30)); + } +} +``` + +After: + +```java +package com.acme; + +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Assertions; + +class TimeoutTest { + void defaultTimeout() { + Assertions.assertEquals(30_000, TimeUnit.SECONDS.toMillis(30)); + } +} +``` + +It never changes what the code means, so a static import is only replaced when every use of it can be resolved: + +- a name hidden by a local variable, or by a method, field or nested class of the enclosing class, is not a use of the import and stays as it is +- an enum constant used as a `case` label of a `switch` on that enum stays unqualified, since qualified ones only compile from Java 21 on +- when the simple name of the class is already taken in the file, the fully qualified name is used, e.g. `java.util.Date.from(instant)` +- a static import of a nested class becomes a regular import of that class, e.g. `import java.util.Map.Entry;` +- a static import that the classpath cannot resolve, or whose names are also supplied by another imported class, is left alone +- so is a static import with a use that cannot be resolved with certainty, for example in a class whose supertypes are not on the classpath or that uses Lombok, inside a `spotless:off` region, or in a Javadoc reference + +It relies on the classpath to know what names mean: + +- JDK classes are those of the JDK that runs Maven, so run Maven with the JDK that the project compiles against, or a newer one +- main and test sources share one classpath, as with `expandWildcardImports` +- classes that are not on the classpath, such as generated sources, are assumed not to exist: a generated class in the same package named like a class that it qualifies with, such as `Math`, would take over `Math.max` +- of the regions that `` restores, it only recognises those between `spotless:off` and `spotless:on`, or `@formatter:off` and `@formatter:on` + +To keep some static imports, such as AssertJ's, list them. `Type.*`, or just `Type`, keeps every static import from that class. `Type.member` keeps the static import of that member, and an on-demand `import static Type.*;` if the file uses that member through it: + +```xml + + + org.assertj.core.api.Assertions.* + java.util.concurrent.TimeUnit.SECONDS + + +``` + + ### google-java-format [homepage](https://github.com/google/google-java-format). [changelog](https://github.com/google/google-java-format/releases). [code](https://github.com/diffplug/spotless/blob/main/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/GoogleJavaFormat.java). diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java index e7401be073..5a9d81793f 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java @@ -428,8 +428,19 @@ private FormatterConfig getFormatterConfig() { final Optional userRatchetFrom = Optional.ofNullable((String) mavenSession.getUserProperties().get("ratchetFrom")); final Optional optionalRatchetFrom = Optional.ofNullable(this.ratchetFrom) .filter(ratchet -> !RATCHETFROM_NONE.equals(ratchet)); - // Lazy: only resolve dependencies when the expandWildcardImports step actually requests the classpath. - Supplier> projectClasspathSupplier = () -> computeTypeSolverClasspath(resolver); + // Lazy: only resolve dependencies when a step that resolves names, such as expandWildcardImports, actually requests the + // classpath, and only once, however many steps request it. + Supplier> projectClasspathSupplier = new Supplier<>() { + private Set classpath; + + @Override + public synchronized Set get() { + if (classpath == null) { + classpath = computeTypeSolverClasspath(resolver); + } + return classpath; + } + }; return new FormatterConfig(baseDir, encoding, lineEndings, userRatchetFrom, optionalRatchetFrom, provisioner, p2Provisioner, fileLocator, formatterStepFactories, Optional.ofNullable(setLicenseHeaderYearsFromGitHistory), lintSuppressions, Optional.of(projectClasspathSupplier)); } @@ -455,7 +466,7 @@ private Set computeTypeSolverClasspath(ArtifactResolver resolver) { Set dependencyJars = resolver.resolveProjectDependencies(project, repositories); classpath.addAll(dependencyJars); } catch (Exception e) { - getLog().warn("Could not resolve project dependencies for expandWildcardImports: " + e.getMessage()); + getLog().warn("Could not resolve project dependencies for expandWildcardImports or replaceStaticImports: " + e.getMessage()); } return classpath; diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Java.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Java.java index 996dbefea7..038428ac9a 100644 --- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Java.java +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/Java.java @@ -107,6 +107,10 @@ public void addShortenFullyQualifiedTypes(ShortenFullyQualifiedTypes shortenFull addStepFactory(shortenFullyQualifiedTypes); } + public void addReplaceStaticImports(ReplaceStaticImports replaceStaticImports) { + addStepFactory(replaceStaticImports); + } + private static String fileMask(Path path) { String dir = path.toString(); if (!dir.endsWith(File.separator)) { diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/ReplaceStaticImports.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/ReplaceStaticImports.java new file mode 100644 index 0000000000..b615ded0b3 --- /dev/null +++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/java/ReplaceStaticImports.java @@ -0,0 +1,43 @@ +/* + * Copyright 2026 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.maven.java; + +import java.io.File; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.function.Supplier; + +import org.apache.maven.plugins.annotations.Parameter; + +import com.diffplug.spotless.FormatterStep; +import com.diffplug.spotless.java.ReplaceStaticImportsStep; +import com.diffplug.spotless.maven.FormatterStepConfig; +import com.diffplug.spotless.maven.FormatterStepFactory; + +public class ReplaceStaticImports implements FormatterStepFactory { + /** Static imports to keep: {@code org.assertj.core.api.Assertions.*} for every static import from that class, or {@code java.util.concurrent.TimeUnit.SECONDS} for the import of that member. */ + @Parameter + private String[] excludes; + + @Override + public FormatterStep newFormatterStep(FormatterStepConfig config) { + Set classpath = config.getProjectClasspathSupplier() + .map(Supplier::get) + .orElse(Collections.emptySet()); + return ReplaceStaticImportsStep.create(classpath, excludes == null ? List.of() : List.of(excludes), config.getProvisioner()); + } +} diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/ReplaceStaticImportsStepTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/ReplaceStaticImportsStepTest.java new file mode 100644 index 0000000000..645325177d --- /dev/null +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/ReplaceStaticImportsStepTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 2026 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.maven.java; + +import org.junit.jupiter.api.Test; + +import com.diffplug.spotless.maven.MavenIntegrationHarness; + +class ReplaceStaticImportsStepTest extends MavenIntegrationHarness { + + @Test + void replaceStaticImports() throws Exception { + writePomWithJavaSteps("java.lang.Math.*"); + // only resolvable through the project's source roots + setFile("src/main/java/q/Codes.java").toContent(""" + package q; + + public final class Codes { + public static final int OK = 0; + } + """); + String path = "src/main/java/p/A.java"; + setFile(path).toContent(""" + package p; + + import static java.lang.Math.max; + import static java.util.Objects.requireNonNull; + import static q.Codes.OK; + + class A { + int f(Object o) { + requireNonNull(o); + return max(OK, 1); + } + } + """); + + mavenRunner().withArguments("spotless:apply").runNoError(); + + assertFile(path).hasContent(""" + package p; + + import static java.lang.Math.max; + import java.util.Objects; + import q.Codes; + + class A { + int f(Object o) { + Objects.requireNonNull(o); + return max(Codes.OK, 1); + } + } + """); + } +} diff --git a/testlib/src/main/resources/java/replacestaticimports/AmbiguousOnDemandFormatted.test b/testlib/src/main/resources/java/replacestaticimports/AmbiguousOnDemandFormatted.test new file mode 100644 index 0000000000..86a8404a97 --- /dev/null +++ b/testlib/src/main/resources/java/replacestaticimports/AmbiguousOnDemandFormatted.test @@ -0,0 +1,11 @@ +package p; + +import java.awt.*; +import java.util.*; +import java.util.List; + +class A { + Object f() { + return List.of(1); + } +} diff --git a/testlib/src/main/resources/java/replacestaticimports/AmbiguousOnDemandUnformatted.test b/testlib/src/main/resources/java/replacestaticimports/AmbiguousOnDemandUnformatted.test new file mode 100644 index 0000000000..17fdf14991 --- /dev/null +++ b/testlib/src/main/resources/java/replacestaticimports/AmbiguousOnDemandUnformatted.test @@ -0,0 +1,12 @@ +package p; + +import java.awt.*; +import java.util.*; + +import static java.util.List.of; + +class A { + Object f() { + return of(1); + } +} diff --git a/testlib/src/main/resources/java/replacestaticimports/ExcludedMemberUsedThroughOnDemandImport.test b/testlib/src/main/resources/java/replacestaticimports/ExcludedMemberUsedThroughOnDemandImport.test new file mode 100644 index 0000000000..b3bb9f01d1 --- /dev/null +++ b/testlib/src/main/resources/java/replacestaticimports/ExcludedMemberUsedThroughOnDemandImport.test @@ -0,0 +1,9 @@ +package p; + +import static java.util.concurrent.TimeUnit.*; + +class A { + long f() { + return SECONDS.toMillis(1); + } +} diff --git a/testlib/src/main/resources/java/replacestaticimports/JavaLangWithInvisibleOnDemandCompetitorFormatted.test b/testlib/src/main/resources/java/replacestaticimports/JavaLangWithInvisibleOnDemandCompetitorFormatted.test new file mode 100644 index 0000000000..dd161feae8 --- /dev/null +++ b/testlib/src/main/resources/java/replacestaticimports/JavaLangWithInvisibleOnDemandCompetitorFormatted.test @@ -0,0 +1,7 @@ +package q; + +import x.*; + +class Main { + int m = java.lang.Math.max(1, 2); +} diff --git a/testlib/src/main/resources/java/replacestaticimports/JavaLangWithInvisibleOnDemandCompetitorUnformatted.test b/testlib/src/main/resources/java/replacestaticimports/JavaLangWithInvisibleOnDemandCompetitorUnformatted.test new file mode 100644 index 0000000000..3cd5c0d080 --- /dev/null +++ b/testlib/src/main/resources/java/replacestaticimports/JavaLangWithInvisibleOnDemandCompetitorUnformatted.test @@ -0,0 +1,9 @@ +package q; + +import x.*; + +import static java.lang.Math.max; + +class Main { + int m = max(1, 2); +} diff --git a/testlib/src/main/resources/java/replacestaticimports/OnDemandJavaLangFormatted.test b/testlib/src/main/resources/java/replacestaticimports/OnDemandJavaLangFormatted.test new file mode 100644 index 0000000000..b6e57f270f --- /dev/null +++ b/testlib/src/main/resources/java/replacestaticimports/OnDemandJavaLangFormatted.test @@ -0,0 +1,7 @@ +package p; + +class A { + double f(double a, double b) { + return Math.max(a, b) * Math.PI; + } +} diff --git a/testlib/src/main/resources/java/replacestaticimports/OnDemandJavaLangUnformatted.test b/testlib/src/main/resources/java/replacestaticimports/OnDemandJavaLangUnformatted.test new file mode 100644 index 0000000000..93db85a4b0 --- /dev/null +++ b/testlib/src/main/resources/java/replacestaticimports/OnDemandJavaLangUnformatted.test @@ -0,0 +1,9 @@ +package p; + +import static java.lang.Math.*; + +class A { + double f(double a, double b) { + return max(a, b) * PI; + } +} diff --git a/testlib/src/main/resources/java/replacestaticimports/SameDeclarationThroughTwoImportsFormatted.test b/testlib/src/main/resources/java/replacestaticimports/SameDeclarationThroughTwoImportsFormatted.test new file mode 100644 index 0000000000..d501f5684b --- /dev/null +++ b/testlib/src/main/resources/java/replacestaticimports/SameDeclarationThroughTwoImportsFormatted.test @@ -0,0 +1,8 @@ +package p; + +import q.Matchers; +import q.Mocks; + +class A { + String s = Mocks.when(Matchers.any()); +} diff --git a/testlib/src/main/resources/java/replacestaticimports/SameDeclarationThroughTwoImportsUnformatted.test b/testlib/src/main/resources/java/replacestaticimports/SameDeclarationThroughTwoImportsUnformatted.test new file mode 100644 index 0000000000..367bf21cf1 --- /dev/null +++ b/testlib/src/main/resources/java/replacestaticimports/SameDeclarationThroughTwoImportsUnformatted.test @@ -0,0 +1,8 @@ +package p; + +import static q.Matchers.any; +import static q.Mocks.*; + +class A { + String s = when(any()); +} diff --git a/testlib/src/main/resources/java/replacestaticimports/SingleAndOnDemandFormatted.test b/testlib/src/main/resources/java/replacestaticimports/SingleAndOnDemandFormatted.test new file mode 100644 index 0000000000..21aa5cf073 --- /dev/null +++ b/testlib/src/main/resources/java/replacestaticimports/SingleAndOnDemandFormatted.test @@ -0,0 +1,9 @@ +package p; + +import java.util.Objects; + +class A { + Object f(Object o) { + return Objects.requireNonNull(Objects.isNull(o) ? null : o); + } +} diff --git a/testlib/src/main/resources/java/replacestaticimports/SingleAndOnDemandUnformatted.test b/testlib/src/main/resources/java/replacestaticimports/SingleAndOnDemandUnformatted.test new file mode 100644 index 0000000000..5ff44759c1 --- /dev/null +++ b/testlib/src/main/resources/java/replacestaticimports/SingleAndOnDemandUnformatted.test @@ -0,0 +1,10 @@ +package p; + +import static java.util.Objects.requireNonNull; +import static java.util.Objects.*; + +class A { + Object f(Object o) { + return requireNonNull(isNull(o) ? null : o); + } +} diff --git a/testlib/src/main/resources/java/replacestaticimports/SingleImportOfAFieldShadowsOnDemandFormatted.test b/testlib/src/main/resources/java/replacestaticimports/SingleImportOfAFieldShadowsOnDemandFormatted.test new file mode 100644 index 0000000000..8a1cfa01ae --- /dev/null +++ b/testlib/src/main/resources/java/replacestaticimports/SingleImportOfAFieldShadowsOnDemandFormatted.test @@ -0,0 +1,8 @@ +package q; + +import p.A; +import p.B; + +class Main { + String s = B.X + A.a(); +} diff --git a/testlib/src/main/resources/java/replacestaticimports/SingleImportOfAFieldShadowsOnDemandUnformatted.test b/testlib/src/main/resources/java/replacestaticimports/SingleImportOfAFieldShadowsOnDemandUnformatted.test new file mode 100644 index 0000000000..166ba31aab --- /dev/null +++ b/testlib/src/main/resources/java/replacestaticimports/SingleImportOfAFieldShadowsOnDemandUnformatted.test @@ -0,0 +1,8 @@ +package q; + +import static p.A.*; +import static p.B.X; + +class Main { + String s = X + a(); +} diff --git a/testlib/src/main/resources/java/replacestaticimports/UnresolvableOnDemandImport.test b/testlib/src/main/resources/java/replacestaticimports/UnresolvableOnDemandImport.test new file mode 100644 index 0000000000..5cc96e75ee --- /dev/null +++ b/testlib/src/main/resources/java/replacestaticimports/UnresolvableOnDemandImport.test @@ -0,0 +1,10 @@ +package p; + +import static java.util.Objects.requireNonNull; +import static org.example.Missing.*; + +class A { + Object f(Object o) { + return requireNonNull(o); + } +} diff --git a/testlib/src/main/resources/java/replacestaticimports/UnresolvableSingleImportOfTheSameName.test b/testlib/src/main/resources/java/replacestaticimports/UnresolvableSingleImportOfTheSameName.test new file mode 100644 index 0000000000..36e86483b0 --- /dev/null +++ b/testlib/src/main/resources/java/replacestaticimports/UnresolvableSingleImportOfTheSameName.test @@ -0,0 +1,10 @@ +package p; + +import static java.util.Objects.*; +import static org.example.Missing.requireNonNull; + +class A { + Object f(Object o) { + return isNull(o) ? null : requireNonNull(o); + } +} diff --git a/testlib/src/test/java/com/diffplug/spotless/java/ReplaceStaticImportsStepTest.java b/testlib/src/test/java/com/diffplug/spotless/java/ReplaceStaticImportsStepTest.java new file mode 100644 index 0000000000..9bc9031715 --- /dev/null +++ b/testlib/src/test/java/com/diffplug/spotless/java/ReplaceStaticImportsStepTest.java @@ -0,0 +1,1767 @@ +/* + * Copyright 2026 DiffPlug + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.diffplug.spotless.java; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.File; +import java.io.IOException; +import java.io.Serializable; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import javax.tools.DiagnosticCollector; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.StandardJavaFileManager; +import javax.tools.ToolProvider; + +import org.junit.jupiter.api.Test; + +import com.diffplug.spotless.FormatterStep; +import com.diffplug.spotless.ResourceHarness; +import com.diffplug.spotless.SerializableEqualityTester; +import com.diffplug.spotless.StepHarness; +import com.diffplug.spotless.TestProvisioner; + +/** + * Tests for {@code replaceStaticImports}. The step must never produce code that does not compile or + * behaves differently, so most tests are about the cases where a static import has to stay, or where + * a name must not be qualified. {@link StepHarness#test} checks that the result is idempotent, and + * {@link #assertCompiles} compiles inputs and outputs with the JDK's own compiler. + */ +class ReplaceStaticImportsStepTest extends ResourceHarness { + private static final Pattern PACKAGE_DECLARATION = Pattern.compile("(?m)^package\\s+([\\w.]+)\\s*;"); + private static final Pattern TYPE_DECLARATION = Pattern.compile("(?m)^\\s*(public\\s+)?(?:(?:abstract|final|sealed|non-sealed|static)\\s+)*(?:class|interface|enum|record|@interface)\\s+(\\w+)"); + private int compilations; + + /** A step whose classpath is the {@code src} directory of the test folder, plus the JDK. */ + private FormatterStep step(String... excludes) { + return ReplaceStaticImportsStep.create(Set.of(newFile("src")), List.of(excludes), TestProvisioner.mavenCentral()); + } + + /** Writes a source file that the type solver, and the compiler, can see. */ + private void source(String path, String content) throws IOException { + setFile("src/" + path).toContent(content); + } + + /** + * In a real project, the file being formatted is in a source directory on the classpath, which tells the step + * which types its package has. The tests format strings, so they also write them there. + */ + private void inASourceDirectory(String source) throws IOException { + Matcher packageDeclaration = PACKAGE_DECLARATION.matcher(source); + String directory = packageDeclaration.find() ? packageDeclaration.group(1).replace('.', '/') + "/" : ""; + setFile("src/" + directory + typeName(source) + ".java").toContent(source); + } + + /** Checks the step's output, that it is idempotent, and that both the input and the output compile. */ + private void assertReplaced(String before, String after) throws IOException { + inASourceDirectory(before); + StepHarness.forStep(step()).test(before, after); + assertCompiles(before); + assertCompiles(after); + } + + private void assertReplacedResource(String before, String after) throws IOException { + assertReplaced(getTestResource(before), getTestResource(after)); + } + + /** Checks that the step leaves a file that compiles alone. */ + private void assertUnchanged(String source) throws IOException { + inASourceDirectory(source); + StepHarness.forStep(step()).testUnaffected(source); + assertCompiles(source); + } + + /** For files that cannot compile here, because they refer to types that are deliberately missing. */ + private void assertUnchangedWithoutCompiling(String source) throws IOException { + inASourceDirectory(source); + StepHarness.forStep(step()).testUnaffected(source); + } + + /** The name of the public type of the source, or else of its first type, which names its file. */ + private static String typeName(String source) { + String typeName = "A"; + boolean found = false; + Matcher declaration = TYPE_DECLARATION.matcher(source); + while (declaration.find()) { + if (!found || declaration.group(1) != null) { + typeName = declaration.group(2); + found = true; + if (declaration.group(1) != null) { + break; + } + } + } + return typeName; + } + + /** A jar holding the given sources, compiled by the JDK's compiler. */ + private File jar(String name, String path, String source) throws IOException { + File sources = newFile("jar-sources/" + name); + File sourceFile = new File(sources, path); + Files.createDirectories(sourceFile.getParentFile().toPath()); + Files.write(sourceFile.toPath(), source.getBytes(StandardCharsets.UTF_8)); + File classes = newFile("jar-classes/" + name); + Files.createDirectories(classes.toPath()); + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + try (StandardJavaFileManager files = compiler.getStandardFileManager(null, Locale.ROOT, StandardCharsets.UTF_8)) { + assertThat(compiler.getTask(null, files, null, List.of("-d", classes.getPath()), null, files.getJavaFileObjects(sourceFile)).call()).isTrue(); + } + File jar = newFile("libs/" + name + ".jar"); + Files.createDirectories(jar.getParentFile().toPath()); + try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(jar.toPath()))) { + try (Stream classFiles = Files.walk(classes.toPath())) { + for (Path classFile : (Iterable) classFiles.filter(Files::isRegularFile)::iterator) { + zip.putNextEntry(new ZipEntry(classes.toPath().relativize(classFile).toString().replace(File.separatorChar, '/'))); + zip.write(Files.readAllBytes(classFile)); + zip.closeEntry(); + } + } + } + return jar; + } + + /** Compiles the source with the JDK's compiler against the {@code src} folder, to prove that it is valid Java. */ + private void assertCompiles(String source) throws IOException { + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + assertThat(compiler).as("these tests need a JDK").isNotNull(); + File dir = newFile("compile/" + compilations++); + File file = new File(dir, typeName(source) + ".java"); + File classes = new File(dir, "classes"); + Files.createDirectories(classes.toPath()); + Files.createDirectories(newFile("src").toPath()); + Files.write(file.toPath(), source.getBytes(StandardCharsets.UTF_8)); + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + try (StandardJavaFileManager files = compiler.getStandardFileManager(diagnostics, Locale.ROOT, StandardCharsets.UTF_8)) { + // javac-only holds types that the compiler sees but the type solver does not, such as generated code + String sourcepath = newFile("src").getPath() + File.pathSeparator + newFile("javac-only").getPath(); + List options = List.of("-d", classes.getPath(), "-sourcepath", sourcepath, "-proc:none", "-Xlint:none"); + boolean compiled = compiler.getTask(null, files, diagnostics, options, null, files.getJavaFileObjects(file)).call(); + assertThat(compiled).as("does not compile: %s%n%s", diagnostics.getDiagnostics(), source).isTrue(); + } + } + + @Test + void enumConstantFromTheIssue() throws IOException { + source("org/enums/Value.java", """ + package org.enums; + + public enum Value { + SOME_ENUM_VALUE, OTHER_VALUE + } + """); + assertReplaced(""" + package com.example; + + import static org.enums.Value.SOME_ENUM_VALUE; + + public class Test { + public void method() { + var example = SOME_ENUM_VALUE; + } + } + """, """ + package com.example; + + import org.enums.Value; + + public class Test { + public void method() { + var example = Value.SOME_ENUM_VALUE; + } + } + """); + } + + @Test + void staticMethodGetsQualifiedAndItsTypeImported() throws IOException { + assertReplaced(""" + package p; + + import java.util.List; + + import static java.util.Objects.requireNonNull; + + class A { + List f(List list) { + return requireNonNull(list).isEmpty() ? null : requireNonNull(list); + } + } + """, """ + package p; + + import java.util.List; + import java.util.Objects; + + class A { + List f(List list) { + return Objects.requireNonNull(list).isEmpty() ? null : Objects.requireNonNull(list); + } + } + """); + } + + @Test + void onDemandImportFromJavaLangNeedsNoNewImport() throws IOException { + // in a resource file, because the build forbids wildcard imports even inside text blocks + assertReplacedResource("java/replacestaticimports/OnDemandJavaLangUnformatted.test", "java/replacestaticimports/OnDemandJavaLangFormatted.test"); + } + + @Test + void enumCaseLabelsStayUnqualified() throws IOException { + // a qualified enum constant is not a valid case label before Java 21 + assertReplaced(""" + package p; + + import static java.util.concurrent.TimeUnit.SECONDS; + + import java.util.concurrent.TimeUnit; + + class A { + \tlong f(TimeUnit unit) { + \t\tswitch (unit) { + \t\tcase SECONDS: + \t\t\treturn SECONDS.toMillis(1); + \t\tdefault: + \t\t\treturn 0; + \t\t} + \t} + + \tString g(TimeUnit unit) { + \t\treturn switch (unit) { + \t\tcase SECONDS -> "s"; + \t\tdefault -> "?"; + \t\t}; + \t} + } + """, """ + package p; + + import java.util.concurrent.TimeUnit; + + class A { + \tlong f(TimeUnit unit) { + \t\tswitch (unit) { + \t\tcase SECONDS: + \t\t\treturn TimeUnit.SECONDS.toMillis(1); + \t\tdefault: + \t\t\treturn 0; + \t\t} + \t} + + \tString g(TimeUnit unit) { + \t\treturn switch (unit) { + \t\tcase SECONDS -> "s"; + \t\tdefault -> "?"; + \t\t}; + \t} + } + """); + } + + @Test + void constantCaseLabelGetsQualified() throws IOException { + source("q/Codes.java", """ + package q; + + public final class Codes { + public static final int OK = 0; + } + """); + assertReplaced(""" + package p; + + import static q.Codes.OK; + + class A { + String f(int code) { + switch (code) { + case OK: + return "ok"; + default: + return "?"; + } + } + } + """, """ + package p; + + import q.Codes; + + class A { + String f(int code) { + switch (code) { + case Codes.OK: + return "ok"; + default: + return "?"; + } + } + } + """); + } + + @Test + void localVariableHidesTheImport() throws IOException { + assertReplaced(""" + package p; + + import static java.lang.Math.PI; + + class A { + double f() { + double PI = 3; + return PI; + } + + double g() { + return PI; + } + } + """, """ + package p; + + class A { + double f() { + double PI = 3; + return PI; + } + + double g() { + return Math.PI; + } + } + """); + } + + @Test + void variableNamedLikeAnImportedMethodIsNotAUse() throws IOException { + assertReplaced(""" + package p; + + import static java.lang.Math.max; + + class A { + int f(int a, int b) { + int max = max(a, b); + return max; + } + } + """, """ + package p; + + class A { + int f(int a, int b) { + int max = Math.max(a, b); + return max; + } + } + """); + } + + @Test + void methodOfTheClassHidesTheImport() throws IOException { + // JLS 15.12.1: a method of an enclosing class hides a static import of the same name, so the import is unused + assertReplaced(""" + package p; + + import static java.util.Objects.isNull; + + class A { + boolean isNull(Object o) { + return o == null; + } + + boolean f(Object o) { + return isNull(o); + } + } + """, """ + package p; + + class A { + boolean isNull(Object o) { + return o == null; + } + + boolean f(Object o) { + return isNull(o); + } + } + """); + } + + @Test + void inheritedMethodHidesTheImport() throws IOException { + source("q/Base.java", """ + package q; + + public class Base { + protected static void check(boolean condition) {} + } + """); + source("q/Checks.java", """ + package q; + + public final class Checks { + public static void check(boolean condition) {} + } + """); + assertReplaced(""" + package p; + + import static q.Checks.check; + + import q.Base; + + class A extends Base { + void f() { + check(true); + } + } + """, """ + package p; + + import q.Base; + + class A extends Base { + void f() { + check(true); + } + } + """); + } + + @Test + void unresolvableSupertypeKeepsTheImport() throws IOException { + // the missing supertype could declare a requireNonNull method that hides the import + assertUnchangedWithoutCompiling(""" + package p; + + import static java.util.Objects.requireNonNull; + + class A extends Missing { + Object f(Object o) { + return requireNonNull(o); + } + } + """); + } + + @Test + void unresolvableImportIsLeftAlone() throws IOException { + assertUnchangedWithoutCompiling(""" + package p; + + import static org.junit.Assert.assertTrue; + + class A { + void f() { + assertTrue(true); + } + } + """); + } + + @Test + void overloadsFromTwoImportedTypesAreLeftAlone() throws IOException { + // valueOf("1") is Integer.valueOf(String); picking the overload is left to the compiler + assertUnchanged(""" + package p; + + import static java.lang.Integer.valueOf; + import static java.lang.String.valueOf; + + class A { + Object f() { + return valueOf("1"); + } + } + """); + } + + @Test + void secondTypeWithTheSameSimpleNameIsFullyQualified() throws IOException { + assertReplaced(""" + package p; + + import static java.sql.Date.valueOf; + import static java.util.Date.from; + import java.time.Instant; + + class A { + long f(Instant instant) { + return valueOf("2020-01-01").getTime() + from(instant).getTime(); + } + } + """, """ + package p; + + import java.time.Instant; + import java.sql.Date; + + class A { + long f(Instant instant) { + return Date.valueOf("2020-01-01").getTime() + java.util.Date.from(instant).getTime(); + } + } + """); + } + + @Test + void typeDeclaredInTheFileForcesTheFullyQualifiedName() throws IOException { + assertReplaced(""" + package p; + + import static java.util.Objects.requireNonNull; + + class A { + Object f(Object o) { + return requireNonNull(o); + } + } + + class Objects {} + """, """ + package p; + + class A { + Object f(Object o) { + return java.util.Objects.requireNonNull(o); + } + } + + class Objects {} + """); + } + + @Test + void unusedTypeOfTheSamePackageIsShadowedByTheNewImport() throws IOException { + source("p/Objects.java", """ + package p; + + class Objects {} + """); + assertReplaced(""" + package p; + + import static java.util.Objects.requireNonNull; + + class A { + Object f(Object o) { + return requireNonNull(o); + } + } + """, """ + package p; + + import java.util.Objects; + + class A { + Object f(Object o) { + return Objects.requireNonNull(o); + } + } + """); + } + + @Test + void usedTypeOfTheSamePackageForcesTheFullyQualifiedName() throws IOException { + source("p/Objects.java", """ + package p; + + class Objects {} + """); + assertReplaced(""" + package p; + + import static java.util.Objects.requireNonNull; + + class A { + Object f(Object o) { + return requireNonNull(new Objects()); + } + } + """, """ + package p; + + class A { + Object f(Object o) { + return java.util.Objects.requireNonNull(new Objects()); + } + } + """); + } + + @Test + void staticImportOfANestedTypeBecomesARegularImport() throws IOException { + assertReplaced(""" + package p; + + import static java.util.Map.Entry; + + import java.util.Map; + + class A { + Entry first(Map map) { + return map.entrySet().iterator().next(); + } + } + """, """ + package p; + + import java.util.Map; + import java.util.Map.Entry; + + class A { + Entry first(Map map) { + return map.entrySet().iterator().next(); + } + } + """); + } + + @Test + void memberOfANestedTypeIsQualifiedThroughItsOuterType() throws IOException { + assertReplaced(""" + package p; + + import static java.util.Map.Entry.comparingByKey; + + import java.util.Comparator; + import java.util.Map; + + class A { + Comparator> byKey() { + return comparingByKey(); + } + } + """, """ + package p; + + import java.util.Comparator; + import java.util.Map; + + class A { + Comparator> byKey() { + return Map.Entry.comparingByKey(); + } + } + """); + } + + @Test + void interfaceConstant() throws IOException { + source("q/Limits.java", """ + package q; + + public interface Limits { + int MAX = 5; + } + """); + assertReplaced(""" + package p; + + import static q.Limits.MAX; + + class A { + int f() { + return MAX; + } + } + """, """ + package p; + + import q.Limits; + + class A { + int f() { + return Limits.MAX; + } + } + """); + } + + @Test + void constantInAnAnnotation() throws IOException { + source("q/Names.java", """ + package q; + + public final class Names { + public static final String UNCHECKED = "unchecked"; + } + """); + assertReplaced(""" + package p; + + import static q.Names.UNCHECKED; + + class A { + @SuppressWarnings(UNCHECKED) + void f() {} + } + """, """ + package p; + + import q.Names; + + class A { + @SuppressWarnings(Names.UNCHECKED) + void f() {} + } + """); + } + + @Test + void usesInLambdasAndAnonymousClasses() throws IOException { + assertReplaced(""" + package p; + + import static java.util.Objects.requireNonNull; + + import java.util.function.Function; + + class A { + Function f = o -> requireNonNull(o); + Runnable r = new Runnable() { + @Override + public void run() { + requireNonNull(f); + } + }; + } + """, """ + package p; + + import java.util.function.Function; + import java.util.Objects; + + class A { + Function f = o -> Objects.requireNonNull(o); + Runnable r = new Runnable() { + @Override + public void run() { + Objects.requireNonNull(f); + } + }; + } + """); + } + + @Test + void singleAndOnDemandImportOfTheSameType() throws IOException { + assertReplacedResource("java/replacestaticimports/SingleAndOnDemandUnformatted.test", "java/replacestaticimports/SingleAndOnDemandFormatted.test"); + } + + @Test + void unusedStaticImportIsRemoved() throws IOException { + assertReplaced(""" + package p; + + import static java.util.Objects.requireNonNull; + + class A {} + """, """ + package p; + + class A {} + """); + } + + @Test + void filesWithoutStaticImportsOrThatDoNotParseAreUnchanged() throws IOException { + assertUnchanged(""" + package p; + + import java.util.Objects; + + class A { + Object f(Object o) { + return Objects.requireNonNull(o); + } + } + """); + assertUnchangedWithoutCompiling(""" + package p; + + import static java.util.Objects.requireNonNull; + + class A { + Object f(Object o) { + return requireNonNull(o) + """); + } + + @Test + void nullClasspathIsRejected() { + assertThrows(NullPointerException.class, () -> ReplaceStaticImportsStep.create(null, TestProvisioner.mavenCentral())); + } + + @Test + void enumLabelOfASwitchOnAnotherTypeIsAUse() throws IOException { + // Java 21 allows enum constants as labels of a switch on any type; there, the label is an ordinary name + String before = """ + package p; + + import static java.util.concurrent.TimeUnit.SECONDS; + + class A { + String f(Object o) { + return switch (o) { + case SECONDS -> "s"; + default -> "?"; + }; + } + } + """; + String after = """ + package p; + + import java.util.concurrent.TimeUnit; + + class A { + String f(Object o) { + return switch (o) { + case TimeUnit.SECONDS -> "s"; + default -> "?"; + }; + } + } + """; + inASourceDirectory(before); + StepHarness.forStep(step()).test(before, after); + if (Runtime.version().feature() >= 21) { + assertCompiles(before); + assertCompiles(after); + } + } + + @Test + void staticInterfaceMethodsAreNotInherited() throws IOException { + // JLS 8.4.8: Comparator.comparing is not a member of a class implementing Comparator, so it comes from the import + assertReplaced(""" + package p; + + import static java.util.Comparator.comparing; + + import java.util.Comparator; + + class ByLength implements Comparator { + public int compare(String a, String b) { + return Integer.compare(a.length(), b.length()); + } + + Comparator natural() { + return comparing((String s) -> s); + } + } + """, """ + package p; + + import java.util.Comparator; + + class ByLength implements Comparator { + public int compare(String a, String b) { + return Integer.compare(a.length(), b.length()); + } + + Comparator natural() { + return Comparator.comparing((String s) -> s); + } + } + """); + } + + @Test + void privateMethodOfTheSuperclassDoesNotHideTheImport() throws IOException { + source("q/PrivateBase.java", """ + package q; + + public class PrivateBase { + private static void check(boolean condition) {} + } + """); + source("q/Checks.java", """ + package q; + + public final class Checks { + public static void check(boolean condition) {} + } + """); + assertReplaced(""" + package p; + + import static q.Checks.check; + + import q.PrivateBase; + + class A extends PrivateBase { + void f() { + check(true); + } + } + """, """ + package p; + + import q.PrivateBase; + import q.Checks; + + class A extends PrivateBase { + void f() { + Checks.check(true); + } + } + """); + } + + @Test + void inheritedMemberTypeWithTheSameNameForcesTheFullyQualifiedName() throws IOException { + source("q/BaseWithObjects.java", """ + package q; + + public class BaseWithObjects { + public static class Objects {} + } + """); + assertReplaced(""" + package p; + + import static java.util.Objects.requireNonNull; + + import q.BaseWithObjects; + + class A extends BaseWithObjects { + Object f(Object o) { + return requireNonNull(o); + } + } + """, """ + package p; + + import q.BaseWithObjects; + + class A extends BaseWithObjects { + Object f(Object o) { + return java.util.Objects.requireNonNull(o); + } + } + """); + } + + @Test + void unresolvableAncestorOfASupertypeKeepsTheImport() throws IOException { + // JavaParser silently skips supertypes it cannot resolve, which could declare a requireNonNull method + source("q/Middle.java", """ + package q; + + public class Middle extends Missing {} + """); + assertUnchangedWithoutCompiling(""" + package p; + + import static java.util.Objects.requireNonNull; + + import q.Middle; + + class A extends Middle { + Object f(Object o) { + return requireNonNull(o); + } + } + """); + } + + @Test + void instanceOverloadOfTheImportedTypeKeepsTheImport() throws IOException { + // Mixed.foo("x") would pick the instance method foo(String), which does not compile in a static context + source("q/Mixed.java", """ + package q; + + public class Mixed { + public static String foo(Object o) { + return "static"; + } + + public String foo(String s) { + return "instance"; + } + } + """); + assertUnchanged(""" + package p; + + import static q.Mixed.foo; + + class A { + String f() { + return foo("x"); + } + } + """); + } + + @Test + void simpleNameThatTwoOnDemandImportsSupplyGetsItsOwnImport() throws IOException { + // List is both java.util.List and java.awt.List: a single-type import makes List.of unambiguous + assertReplacedResource("java/replacestaticimports/AmbiguousOnDemandUnformatted.test", "java/replacestaticimports/AmbiguousOnDemandFormatted.test"); + } + + @Test + void fieldUsedAsTheScopeOfAMethodReference() throws IOException { + source("q/Holder.java", """ + package q; + + import java.util.ArrayList; + import java.util.List; + + public final class Holder { + public static final List NAMES = new ArrayList<>(); + } + """); + assertReplaced(""" + package p; + + import static q.Holder.NAMES; + + import java.util.function.Consumer; + + class A { + Consumer adder = NAMES::add; + } + """, """ + package p; + + import java.util.function.Consumer; + import q.Holder; + + class A { + Consumer adder = Holder.NAMES::add; + } + """); + } + + @Test + void referenceInADocCommentKeepsTheImport() throws IOException { + assertUnchanged(""" + package p; + + import static java.util.concurrent.TimeUnit.SECONDS; + + /** Gives up after a few {@link SECONDS}. */ + class A {} + """); + } + + @Test + void useInsideSpotlessOffKeepsTheImport() throws IOException { + // toggleOffOn() would restore the unqualified use, while the import would stay deleted + assertUnchanged(""" + package p; + + import static java.util.Objects.requireNonNull; + + class A { + // spotless:off + Object f(Object o) { return requireNonNull(o); } + // spotless:on + } + """); + } + + @Test + void unresolvableSingleImportOfTheSameNameKeepsTheOthers() throws IOException { + assertUnchangedWithoutCompiling(getTestResource("java/replacestaticimports/UnresolvableSingleImportOfTheSameName.test")); + } + + @Test + void unresolvableOnDemandImportLeavesTheFileAlone() throws IOException { + // it could supply any name in the file + assertUnchangedWithoutCompiling(getTestResource("java/replacestaticimports/UnresolvableOnDemandImport.test")); + } + + @Test + void nestedTypeOfThisFileIsQualifiedWithItsOwnName() throws IOException { + String before = """ + package p; + + import static p.A.Color.RED; + + class A { + enum Color { + RED, GREEN + } + + Color color = RED; + } + """; + // the type solver sees the file through the source directory, as it does in a real project + source("p/A.java", before); + assertReplaced(before, """ + package p; + + class A { + enum Color { + RED, GREEN + } + + Color color = Color.RED; + } + """); + } + + @Test + void memberTypeInheritedByTheImportedTypeKeepsTheImport() throws IOException { + // `import q.SubHolder.Kind;` would not compile: an import needs the canonical name, q.SuperHolder.Kind + source("q/SuperHolder.java", """ + package q; + + public class SuperHolder { + public static class Kind {} + } + """); + source("q/SubHolder.java", """ + package q; + + public class SubHolder extends SuperHolder {} + """); + assertUnchanged(""" + package p; + + import static q.SubHolder.Kind; + + class A { + Kind kind; + } + """); + } + + @Test + void fieldNamedLikeANestedTypeKeepsTheImport() throws IOException { + // JLS 6.5.2: in Outer.Inner.m(), Outer.Inner would be the field, not the nested class + source("q/Outer.java", """ + package q; + + public class Outer { + public static final int Inner = 0; + + public static class Inner { + public static String m() { + return "m"; + } + } + } + """); + assertUnchanged(""" + package p; + + import static q.Outer.Inner.m; + + class A { + String s = m(); + } + """); + } + + @Test + void classWithLombokAnnotationsKeepsTheImport() throws IOException { + // Lombok adds members that JavaParser cannot see, and that could hide the import + assertUnchangedWithoutCompiling(""" + package p; + + import static java.util.Objects.requireNonNull; + + import lombok.Data; + + @Data + class A { + Object f(Object o) { + return requireNonNull(o); + } + } + """); + } + + @Test + void excludedImportsAreKept() throws IOException { + String before = """ + package p; + + import static java.lang.Math.max; + import static java.util.Objects.requireNonNull; + + class A { + int f(Object o) { + requireNonNull(o); + return max(1, 2); + } + } + """; + String after = """ + package p; + + import static java.util.Objects.requireNonNull; + + class A { + int f(Object o) { + requireNonNull(o); + return Math.max(1, 2); + } + } + """; + inASourceDirectory(before); + StepHarness.forStep(step("java.util.Objects.*")).test(before, after); + StepHarness.forStep(step("java.util.Objects.requireNonNull")).test(before, after); + StepHarness.forStep(step("java.util.Objects")).test(before, after); + StepHarness.forStep(step("java.util.Objects.*", "java.lang.Math.*")).testUnaffected(before); + assertCompiles(after); + } + + @Test + void equality() throws IOException { + File jar = newFile("libs/a.jar"); + Files.createDirectories(jar.getParentFile().toPath()); + Files.write(jar.toPath(), new byte[]{1, 2, 3}); + new SerializableEqualityTester() { + Set classpath = Set.of(); + List excludes = List.of(); + + @Override + protected void setupTest(API api) { + api.areDifferentThan(); + excludes = List.of("java.util.Objects.*"); + api.areDifferentThan(); + excludes = List.of("java.util.Objects.*", "java.lang.Math.max"); + api.areDifferentThan(); + classpath = Set.of(jar); + api.areDifferentThan(); + } + + @Override + protected Serializable create() { + return ReplaceStaticImportsStep.create(classpath, excludes, TestProvisioner.mavenCentral()); + } + }.testEquals(); + } + + @Test + void equalityDependsOnTheContentOfTheJarsNotOnWhereTheyAre() throws IOException { + File here = newFile("here/lib.jar"); + File there = newFile("there/lib.jar"); + File other = newFile("other/lib.jar"); + for (File jar : List.of(here, there, other)) { + Files.createDirectories(jar.getParentFile().toPath()); + Files.write(jar.toPath(), new byte[]{jar == other ? (byte) 2 : (byte) 1}); + } + assertEquals(ReplaceStaticImportsStep.create(Set.of(here), List.of("b.B.*", "a.A.*"), TestProvisioner.mavenCentral()), + ReplaceStaticImportsStep.create(Set.of(there), List.of("a.A.*", "b.B.*"), TestProvisioner.mavenCentral())); + assertNotEquals(ReplaceStaticImportsStep.create(Set.of(here), TestProvisioner.mavenCentral()), + ReplaceStaticImportsStep.create(Set.of(other), TestProvisioner.mavenCentral())); + } + + @Test + void sameDeclarationReachedThroughTwoImportsIsQualifiedWithItsDeclaringType() throws IOException { + // like Mockito, which inherits any() from ArgumentMatchers: both imports reach the same method + source("q/Matchers.java", """ + package q; + + public class Matchers { + public static T any() { + return null; + } + } + """); + source("q/Mocks.java", """ + package q; + + public class Mocks extends Matchers { + public static T when(T call) { + return call; + } + } + """); + assertReplacedResource("java/replacestaticimports/SameDeclarationThroughTwoImportsUnformatted.test", "java/replacestaticimports/SameDeclarationThroughTwoImportsFormatted.test"); + } + + @Test + void trailingCommentGoesWithTheImport() throws IOException { + assertReplaced(""" + package p; + + import static java.util.Objects.requireNonNull; // NOPMD + + class A { + Object f(Object o) { + return requireNonNull(o); + } + } + """, """ + package p; + + import java.util.Objects; + + class A { + Object f(Object o) { + return Objects.requireNonNull(o); + } + } + """); + } + + @Test + void javaLangTypeThatAnInvisibleOnDemandImportCouldShadowIsFullyQualified() throws IOException { + // javac sees x.Math, the type solver does not: `Math.max` would be ambiguous, and an import of + // java.lang.Math would not last, because removeUnusedImports() deletes java.lang imports + setFile("javac-only/x/Math.java").toContent("package x;\n\npublic class Math {}\n"); + assertReplacedResource("java/replacestaticimports/JavaLangWithInvisibleOnDemandCompetitorUnformatted.test", "java/replacestaticimports/JavaLangWithInvisibleOnDemandCompetitorFormatted.test"); + } + + @Test + void classHeaderIsOutsideTheScopeOfTheClassMembers() throws IOException { + // JLS 6.3: NAME in the annotation of Impl is the import, while NAME in its body is the field Impl inherits + source("p/Base.java", """ + package p; + + public class Base { + public static final String NAME = "base"; + } + """); + source("p/Other.java", """ + package p; + + public final class Other { + public static final String NAME = "unchecked"; + } + """); + assertReplaced(""" + package q; + + import static p.Other.NAME; + + import p.Base; + + @SuppressWarnings(NAME) + class Impl extends Base { + String name = NAME; + } + """, """ + package q; + + import p.Base; + import p.Other; + + @SuppressWarnings(Other.NAME) + class Impl extends Base { + String name = NAME; + } + """); + } + + @Test + void singleImportOfAFieldShadowsAnOnDemandOne() throws IOException { + source("p/A.java", """ + package p; + + public class A { + public static final String X = "A.X"; + + public static String a() { + return "a"; + } + } + """); + source("p/B.java", """ + package p; + + public class B { + public static final String X = "B.X"; + } + """); + assertReplacedResource("java/replacestaticimports/SingleImportOfAFieldShadowsOnDemandUnformatted.test", "java/replacestaticimports/SingleImportOfAFieldShadowsOnDemandFormatted.test"); + } + + @Test + void typeNamedBeforeSuperIsAType() throws IOException { + source("p/Registry.java", """ + package p; + + public final class Registry { + public interface Listener { + default int id() { + return 1; + } + } + } + """); + assertReplaced(""" + package q; + + import static p.Registry.Listener; + + class Impl implements Listener { + public int id() { + return Listener.super.id() + 1; + } + } + """, """ + package q; + + import p.Registry.Listener; + + class Impl implements Listener { + public int id() { + return Listener.super.id() + 1; + } + } + """); + } + + @Test + void excludedMemberKeepsTheOnDemandImportThatSuppliesIt() throws IOException { + String source = getTestResource("java/replacestaticimports/ExcludedMemberUsedThroughOnDemandImport.test"); + inASourceDirectory(source); + StepHarness.forStep(step("java.util.concurrent.TimeUnit.SECONDS")).testUnaffected(source); + } + + @Test + void nameSpelledWithAUnicodeEscapeKeepsTheImport() throws IOException { + // javac reads max as max, so the import is still in use + assertUnchanged(""" + package p; + + import static java.lang.Math.max; + + class A { + int a = \\u006dax(1, 2); + } + """); + } + + @Test + void newImportStartsALineWhenTheLastImportSharesItsLine() throws IOException { + assertReplaced(""" + package p; import java.util.List; import static java.util.concurrent.TimeUnit.SECONDS; class A { Object f(List l) { return SECONDS; } } + """, """ + package p; import java.util.List; + import java.util.concurrent.TimeUnit; class A { Object f(List l) { return TimeUnit.SECONDS; } } + """); + } + + @Test + void editInsideASpotlessOffRegionLeavesTheFileAlone() throws IOException { + // the new import would go inside the region, and toggleOffOn() would throw it away + assertUnchanged(""" + package p; + + import static java.util.concurrent.TimeUnit.SECONDS; + import java.util.List; // spotless:off + // spotless:on + + class A { + Object f(List l) { + return SECONDS; + } + } + """); + } + + @Test + void moduleInfoIsLeftAlone() throws IOException { + StepHarness.forStep(step()).testUnaffected(""" + import static java.util.Map.Entry; + + module m { + uses Entry; + } + """); + } + + @Test + void patternVariableInAConditionalHidesTheImport() throws IOException { + // JavaParser does not see `out` in the then-operand, but javac does + assertUnchanged(""" + package p; + + import static java.lang.System.out; + + import java.io.PrintStream; + + class A { + PrintStream target(Object sink) { + return sink instanceof PrintStream out ? out : null; + } + } + """); + } + + @Test + void memberTypeInheritedFromASuperclassHidesTheNestedTypeOfThisFile() throws IOException { + // inside Worker, State is Thread.State, so the constant is qualified through Job + assertReplaced(""" + package p; + + import static p.Job.State.DONE; + + public class Job { + enum State { + WAITING, DONE + } + + volatile State state; + + class Worker extends Thread { + public void run() { + state = DONE; + } + } + } + """, """ + package p; + + public class Job { + enum State { + WAITING, DONE + } + + volatile State state; + + class Worker extends Thread { + public void run() { + state = Job.State.DONE; + } + } + } + """); + } + + @Test + void unresolvableImportOfTheSameSimpleNameForcesTheFullyQualifiedName() throws IOException { + // javac sees com.acme.forum.Thread, the type solver does not + setFile("javac-only/com/acme/forum/Thread.java").toContent("package com.acme.forum;\n\npublic class Thread {}\n"); + assertReplaced(""" + package p; + + import static java.lang.Thread.sleep; + + import com.acme.forum.Thread; + + class A { + void f(Thread thread) throws InterruptedException { + sleep(10); + } + } + """, """ + package p; + + import com.acme.forum.Thread; + + class A { + void f(Thread thread) throws InterruptedException { + java.lang.Thread.sleep(10); + } + } + """); + } + + @Test + void loopVariableIsNotInScopeAfterTheLoop() throws IOException { + // the last PI is the import, though JavaParser resolves it to the loop variable + assertUnchanged(""" + package p; + + import static java.lang.Math.PI; + + class A { + double f(double[] xs) { + double s = 0; + for (double PI : xs) { + s += PI; + } + return s + PI; + } + } + """); + } + + @Test + void cloneIsNotAMemberOfAnInterface() throws IOException { + source("q/Copies.java", """ + package q; + + public final class Copies { + public static T clone(T value) { + return value; + } + } + """); + assertReplaced(""" + package p; + + import static q.Copies.clone; + + public interface A { + default String copy(String s) { + return clone(s); + } + } + """, """ + package p; + + import q.Copies; + + public interface A { + default String copy(String s) { + return Copies.clone(s); + } + } + """); + } + + @Test + void typeParameterShadowsTheSimpleName() throws IOException { + assertReplaced(""" + package p; + + import static java.lang.Math.max; + + public class A { + int f(int a, int b) { + return max(a, b); + } + } + """, """ + package p; + + public class A { + int f(int a, int b) { + return java.lang.Math.max(a, b); + } + } + """); + } + + @Test + void fieldHiddenByAPrivateFieldOnTheWayKeepsTheImport() throws IOException { + // Mid's private NAME hides Base.NAME, so A inherits neither and NAME is the import + source("q/Base.java", "package q;\n\npublic class Base {\n public static final String NAME = \"base\";\n}\n"); + source("q/Mid.java", "package q;\n\npublic class Mid extends Base {\n private static final String NAME = \"mid\";\n}\n"); + source("q/Names.java", "package q;\n\npublic final class Names {\n public static final String NAME = \"names\";\n}\n"); + assertUnchanged(""" + package p; + + import static q.Names.NAME; + + import q.Mid; + + class A extends Mid { + String name() { + return NAME; + } + } + """); + } + + @Test + void stackOverflowInJavaParserLeavesTheFileAlone() throws IOException { + assertUnchanged(""" + package p; + + import static p.A.Color; + import static p.A.Color.RED; + + public class A { + enum Color { + RED, GREEN + } + } + + class B { + Object f() { + return RED; + } + } + """); + } + + @Test + void enumSwitchWhoseSelectorJavaParserCannotTypeKeepsTheImport() throws IOException { + // a qualified label would only compile from Java 21 on + assertUnchanged(""" + package p; + + import static java.util.concurrent.TimeUnit.SECONDS; + + import java.util.Collections; + import java.util.List; + import java.util.concurrent.TimeUnit; + + class A { + int f(List units) { + switch (Collections.max(units)) { + case SECONDS: + return 1; + default: + return 0; + } + } + } + """); + } + + @Test + void classInTwoJarsKeepsTheImport() throws IOException { + // only version 2 of lib.Base has describe(Object), which hides the import: the compiler may see either version + File one = jar("lib-1", "lib/Base.java", "package lib;\n\npublic class Base {}\n"); + File two = jar("lib-2", "lib/Base.java", "package lib;\n\npublic class Base {\n public String describe(Object o) {\n return \"base\";\n }\n}\n"); + source("q/Util.java", """ + package q; + + public final class Util { + public static String describe(Object o) { + return "util"; + } + } + """); + String source = """ + package p; + + import static q.Util.describe; + + import lib.Base; + + class A extends Base { + String run() { + return describe(this); + } + } + """; + inASourceDirectory(source); + StepHarness.forStep(ReplaceStaticImportsStep.create(Set.of(newFile("src"), one, two), TestProvisioner.mavenCentral())).testUnaffected(source); + } +}