Skip to content

Add a replaceStaticImports step for Java - #3185

Open
patpatpat123 wants to merge 1 commit into
diffplug:mainfrom
patpatpat123:replace-static-imports
Open

patpatpat123 wants to merge 1 commit into
diffplug:mainfrom
patpatpat123:replace-static-imports

Conversation

@patpatpat123

Copy link
Copy Markdown
Contributor

Hi! This adds replaceStaticImports, the step #1379 asked for back in 2022. It replaces static imports with regular imports and qualified references:

// before
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;

assertEquals(30_000, SECONDS.toMillis(30));

// after
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Assertions;

Assertions.assertEquals(30_000, TimeUnit.SECONDS.toMillis(30));

In Gradle it's replaceStaticImports(), or replaceStaticImports('org.assertj.core.api.Assertions.*') to keep some static imports. In Maven it's <replaceStaticImports/>, with an optional <excludes> list.

Closes #1379.

Why it's doable now

The blocker in the issue was that Spotless never gave a step the project's classpath, which you need to know what a bare max(...) or SECONDS refers to. expandWildcardImports added that plumbing to both plugins, so this step reuses it.

Keeping it safe

A step like this must never produce code that doesn't compile, or that compiles but means something else. So each static import is either replaced completely or left exactly as it is.

The hard part is deciding what a bare name refers to. JavaParser's own resolution isn't reliable enough for that: it picks between imports in source order, misses some pattern variables, keeps for loop variables in scope after the loop, doesn't see member types inherited from superclasses, and silently skips supertypes it can't resolve. So the step applies the JLS scoping rules itself and mostly asks JavaParser about types:

  • a method, field or nested class that an enclosing class declares or inherits hides a static import of the same name, and so does a local variable. Private members and static interface methods aren't inherited, so they don't hide anything
  • a class whose supertypes can't all be resolved, that uses Lombok, or that extends a class found in two jars on the classpath has members the step can't see, so the imports stay
  • if two imported types supply a name, or an import that can't be resolved might, the imports stay, unless they all reach the very same declaration (Mockito.* and ArgumentMatchers.any, for example)
  • enum constants used as case labels of a switch on that enum stay unqualified, because qualified labels need Java 21. In a Java 21 switch on another type they're ordinary names
  • if qualifying a call as T.foo(x) could make one of T's instance overloads the best match, that import stays
  • the qualifier is the simple class name only when that can't be ambiguous or capture another name in the file. Otherwise it's the fully qualified name. java.lang types never get an import, because removeUnusedImports() would delete it
  • uses inside spotless:off regions, Javadoc references, names spelled with unicode escapes, and module-info.java keep their imports

Static imports of nested classes become regular imports (import java.util.Map.Entry;). New imports are appended after the existing ones, so like shortenFullyQualifiedTypes it's meant to run before importOrder().

It's a big PR, mostly because of these checks. The class Javadoc of ReplaceStaticImportsFormatterFunc walks through the approach.

Error Prone's take on static imports

This came up in the issue thread, so I looked into it. Error Prone has no rule against static imports in general. BadImport (on by default, as a warning) only qualifies a fixed list of generic names such as of, copyOf, valueOf, builder, INSTANCE, or nested Builder/Type/Key, because the class name gives the reader context there. Its BadEnclosingTypes option can be pointed at whole classes, but that runs inside a full compile and leaves the static import line behind for a separate cleanup pass. Google Java Style is fine with single static imports too.

So this step is an opt-in preference that goes further than both. Where they overlap, they agree: nested classes become regular imports, and enum labels stay unqualified.

Testing

  • Step tests: 65 of them. Every input and expected output is compiled with the JDK's own javac, and StepHarness checks idempotency. There's also an equality() test.
  • Integration tests: for Gradle and Maven, covering excludes and resolving types from the project's own sources.
  • Trying to break it: I spent a while trying to break the design and then the code. That gave 99 tricky cases, and then 27 concrete problems in the implementation, each one reproduced. All of them are fixed with a regression test, or reduced and documented where a full fix would need plumbing through both plugins.
  • Regression gate: at the end I ran all 929 resulting cases through the real step. That's the 99 cases plus every reproduction and variant from the reviews. Each input and output was compiled with javac and the bytecode compared: qualifying a static reference doesn't change what javac emits, so identical bytecode means identical behaviour.
    • 857 of the inputs compile, and the step rewrote 595 of them.
    • No output fails to compile, nothing crashes, and every result is idempotent.
    • All but one keep identical bytecode. The exception is the documented assumption below: a generated class in the same package named like java.lang.Math.

Notes for review

  • Assumptions: the README's new section lists what the step relies on. JDK classes are those of the JDK that runs the build. All source sets share one classpath, as with expandWildcardImports. Only the default toggleOffOn markers (and @formatter:off/@formatter:on) are recognised. Classes that aren't on the classpath, such as generated sources, are assumed not to exist.
  • Shared helper: the JavaParser and type-solver setup moved into a small SymbolResolution helper. expandWildcardImports uses it with unchanged behaviour.
  • Equality state: it follows CONTRIBUTING's two-state pattern: jar contents through FileSignature, the paths transient, plus the JDK version.
  • Memory: the formatter function releases JavaParser's static facade cache when it's closed, which otherwise keeps every type solver alive for as long as the daemon runs. expandWildcardImports has the same leak, and I'm happy to apply the same fix there in a follow-up.
  • Classpath resolution: like expandWildcardImports, the Gradle plugin resolves the compile classpath when the DSL method runs. Making both of them lazy seemed like a separate change. Maven now resolves the classpath once per execution, however many steps ask for it.
  • No lints: the step never reports any. When it can't be sure, it leaves the import alone.

Thanks for maintaining Spotless, and I'm happy to adjust anything!

Replaces static imports with regular imports and qualified references,
so that assertTrue(x) becomes Assertions.assertTrue(x). Available as
replaceStaticImports() in Gradle and <replaceStaticImports/> 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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Replace static imports with non-static imports

1 participant