Repository navigation
Description
What happens
The IntelliJ plugin formats in one of two ways. With the Java-based formatter, BootstrappingFormatterService starts a new JVM for every Reformat; with the native binary, NativeImageFormatterService starts the binary. Either way each call pays for a process, and an import optimizer (#222) would pay it again, inside a read action.
Times of one call on JDK 21, macOS aarch64, with 21.0.2:
| How the formatter runs | JavaInputAstVisitor.java, 4,026 lines |
A 5-line file |
|---|---|---|
| A new JVM for each call (today's Java-based mode) | 0.97 s | 0.3 s |
| Native binary | 0.28 s | 0.02 s |
| In the IDE's JVM, first call | 0.65 s | |
| In the IDE's JVM, warm (median of 30) | 124 ms to format, 9 ms for fixImports |
How google-java-format does it
It formats in the IDE's own JVM, never in a process of its own. Its README asks users to add six --add-exports jdk.compiler/...=ALL-UNNAMED lines to the IDE's VM options, and JreConfigurationChecker shows those instructions when the javac classes cannot be reached.
Formatting in the IDE's JVM without editing VM options
IntelliJ IDEA 2024.2.6 starts its JVM with, among the additionalJvmArguments of its product-info.json, --add-opens=java.base/java.lang=ALL-UNNAMED and --add-opens=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED. With java.lang open, a plugin can call Module.implAddExports and export the javac packages the formatter needs to the class loader it loads the formatter into. Tried in a JVM started with those two flags only, not in a running IDE yet: the formatter loaded into a URLClassLoader of its own formatted the file above byte for byte as the command line does, at the times in the table.
Proposal
Let the plugin run the formatter in the fastest way available, falling back to the next:
- In the IDE's JVM, when the javac packages can be exported to the formatter's class loader, or already are. One class loader per formatter version, as
FormatterServiceLoaderin the Gradle plugin keeps one per set of jars. A formatter bug then happens inside the IDE, and the javac of the IDE's runtime decides which syntax parses, as it does today. - A formatter daemon, as Gradle has one: a JVM per formatter version that stays up and takes files over its standard input. As fast as the in-process mode once warm, isolated from the IDE, and free to run on a newer JDK than the IDE's. It needs a server mode in
Main, a protocol, restarts and cleanup. Worth it only if the in-process mode turns out not to work. - The native binary, as today. No JVM to start, slower than warm JIT-compiled code on big files, and its parser is the one of GraalVM 25.
- A new JVM for each call, as today, when nothing else is possible.
Open questions
Module.implAddExportsis not public API; if JetBrains stops openingjava.lang, the plugin falls back to the next mode.- Which mode the plugin's settings show and which it picks by itself.
Activity