Skip to content
67 changes: 67 additions & 0 deletions docs/decisions/ADR-005-formatting-inside-the-ide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# ADR-005: The IntelliJ plugin formats inside the IDE's JVM, and offers a JVM of its own and the native binary

## Status
Accepted

## Date
2026-11-22

## Context

The plugin started a process for every Reformat and every Optimize imports: a new JVM on the IDE's runtime, or the native binary. Optimize imports runs under a read action, and "Optimize imports on the fly" runs while typing ([ADR-003](ADR-003-imports-in-intellij-idea.md), #253).

One call on JDK 21, macOS aarch64, with 21.0.2 (#223):

| How the formatter runs | `JavaInputAstVisitor.java`, 4,026 lines | A 5-line file |
|---|---|---|
| A new JVM for each call | 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` | |

The formatter parses with javac's own classes, in packages that module `jdk.compiler` exports to nobody. A JVM started for the formatter gets `--add-exports`; the IDE's JVM is already running. google-java-format formats inside the IDE and asks its users to add six `--add-exports` lines to the IDE's VM options.

IntelliJ IDEA starts its JVM with `--add-opens=java.base/java.lang=ALL-UNNAMED`: it is among the `additionalJvmArguments` of `product-info.json` in 2024.2.6, the oldest IDE the plugin supports, and in 2026.3. With `java.lang` open, a plugin can call `Module.implAddExports`, the method `--add-exports` ends in, for one class loader's module. Tried on Temurin 21.0.12 and on the JBR 25.0.4 of 2026.3, in a JVM started with that flag alone: the formatter, in a class loader of its own, formats as the command line does, and javac stays unexported to every other class loader.

## Decision

- **Three ways to run the formatter, one of them chosen per project** on the settings page: in the IDE process, in a separate JVM, as the native binary.
- **In the IDE process is the default.** A project whose settings switch the native binary on keeps it; every other project moves from a JVM for each call into the IDE.
- **The plugin exports javac to the formatter itself**, with `Module.implAddExports`, to the formatter's class loader only. Nobody edits VM options. The settings page offers the IDE process only where `JavacAccess` finds that it can: `jdk.compiler` is there, and either javac is exported already or `java.lang` is open.
- **The formatter is loaded apart from the IDE.** Its class loader's parent is the JDK's platform class loader, which finds javac and nothing of the IDE. From the plugin come only the types the two exchange: the classes of `open-java-format-spi`, and Guava, which their signatures name. One class loader per set of formatter jars, kept across projects and calls.
- **The IDE process is the faster way, never the only one.** A file that the formatter fails on there with an `Error`, a stack overflow for one, is formatted in a separate JVM on the IDE's runtime. A formatter that does not load or link there sends every file to a separate JVM until the IDE restarts, and logs an error once, for the plugin's error reports.
- **A file with a syntax error is left alone without a message** inside the IDE too, as `FormatterCommandRunner` leaves it: a file is rarely free of them while it is typed in.
- **A separate JVM runs on a JDK the user chooses**: the IDE's runtime, which is the default and what the plugin ran on before, the project SDK, or a JDK registered in the IDE. Only Java 21 or later can be chosen.
- **What cannot run falls back, and says so in `idea.log` and under Active formatter**: the IDE process to a separate JVM, a JDK that cannot run the formatter to the IDE's runtime, a missing native binary to a separate JVM as before. No balloon for the first two.

## Alternatives Considered

### A formatter daemon, as Gradle has one
- Pros: as fast once warm; a formatter bug stays out of the IDE; it can run on a newer JDK than the IDE's.
- Cons: a server mode in `Main`, a protocol, restarts and cleanup.
- Rejected: worth it only if formatting inside the IDE turned out not to work.

### Ask users to add `--add-exports` to the IDE's VM options, as google-java-format does
- Pros: public flags only.
- Cons: every user edits a file per IDE installation, and javac is exported to every plugin.
- Rejected as the way in; a user who did add the flags gets the IDE process without `implAddExports` being called.

### Load the formatter with the plugin's class loader as the parent, as the Gradle plugin does
- Pros: a plain `URLClassLoader`.
- Cons: every class the IDE has wins over the formatter's own copy: Jackson of another version, for one, and whatever a later IDE adds.
- Rejected: the IDE's class path is not ours to know.

### Keep a JVM for each call as the default, and the IDE process as an option
- Pros: a formatter bug cannot touch the IDE until a user opts in.
- Cons: the projects that wait 0.3 s to 1 s a file, and for imports while typing, stay there unless they find the setting.
- Rejected: the time is what #223 is about.

## Consequences

- `Module.implAddExports` is not public API. If JetBrains stops opening `java.lang`, or a JDK drops the method, the IDE process is greyed out with the reason, and those projects format in a separate JVM as before.
- The javac of the IDE's runtime decides which syntax parses inside the IDE: Java 21 in 2024.2, Java 25 in 2026.3. A project with newer syntax chooses a separate JVM on a newer JDK.
- A formatter bug that throws no `Error`, such as one that never returns, now happens inside the IDE.
- A formatter from a build is loaded into the IDE's JVM where it used to be run by a JVM of its own. Both happen only in a trusted project.
- A formatter from a build that needs a newer Guava than the plugin's can fail to link inside the IDE. It then runs in a separate JVM, on its own jars alone, and so does every other project's formatter until the IDE restarts: one failure switches the IDE process off for the session.
- `formatterMode` alone says how a project formats, as `in-process`, `jvm` or `native`, and a setting of one mode has that mode at the start of its name: `jvmJdk`, `nativeImagePath`. A mode added later, such as a daemon with a JDK of its own, then has settings no other mode reads.
- `useNativeImage`, which a file from before the modes has, is read once, as the native mode, and not written again. A plugin from before the modes that reads a file written since finds no `useNativeImage`, and formats in a JVM of its own.
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* 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.palantir.javaformat.intellij;

import com.palantir.javaformat.java.FormatterDiagnostic;
import com.palantir.javaformat.java.FormatterException;
import com.palantir.javaformat.java.FormatterService;
import com.palantir.javaformat.java.JavaFormatterOptions;
import com.palantir.javaformat.java.Replacement;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Set;

/**
* Loads the formatter from its jars into the IDE's JVM, apart from the IDE.
*
* <p>Its parent is the JDK's platform class loader, which finds the JDK, javac included, and nothing of the IDE: the
* formatter's jars are everything it runs with in a JVM of its own, and the IDE has other versions of the same
* libraries. Only the types the plugin and the formatter exchange come from the plugin: the service interface with
* the types it names, and Guava, whose {@code ImmutableList} and {@code Range} are in its signatures. The copies of
* those in the formatter's jars are never loaded.
*/
final class FormatterClassLoader extends URLClassLoader {

static {
registerAsParallelCapable();
}

/** The classes of open-java-format-spi. They share a package with the formatter's own, so they go by name. */
private static final Set<String> SPI = Set.of(
FormatterDiagnostic.class.getName(),
FormatterException.class.getName(),
FormatterService.class.getName(),
JavaFormatterOptions.class.getName(),
Replacement.class.getName());

private final ClassLoader plugin;

FormatterClassLoader(URL[] formatterJars, ClassLoader plugin) {
super("open-java-format", formatterJars, ClassLoader.getPlatformClassLoader());
this.plugin = plugin;
}

@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
return isShared(name) ? plugin.loadClass(name) : super.loadClass(name, resolve);
}

static boolean isShared(String className) {
if (className.startsWith("com.google.common.")) {
return true;
}
var nested = className.indexOf('$');
return SPI.contains(nested < 0 ? className : className.substring(0, nested));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* 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.palantir.javaformat.intellij;

import java.nio.file.Path;
import org.jspecify.annotations.Nullable;

/** The JDK a project names for the formatter's own JVM. {@link FormatterJdks} finds the java it stands for. */
sealed interface FormatterJdk {

/** What a JDK comes to on this machine, in this project. */
sealed interface Resolved {}

/** java: the executable. javaVersion: the version of Java it runs, such as 21. */
record Usable(Path java, int javaVersion) implements Resolved {}

/** reason: a clause that says why, such as "the project has no SDK". */
record Unusable(String reason) implements Resolved {}

/** The runtime the IDE itself runs on: always there, and always recent enough for the formatter. */
record IdeRuntime() implements FormatterJdk {
@Override
public @Nullable String stored() {
return null;
}
}

/** Whichever SDK the project has, as it changes. */
record ProjectSdk() implements FormatterJdk {
@Override
public String stored() {
return PROJECT_SDK;
}
}

/** A JDK registered in the IDE, by the name it has there. */
record Named(String name) implements FormatterJdk {
@Override
public String stored() {
return name;
}
}

// Not a name a JDK can have by accident: the IDE's own settings mark their special values with '#' too.
String PROJECT_SDK = "#PROJECT_SDK";

/** What .idea/open-java-format.xml holds for this JDK; nothing for the IDE's runtime, which is the default. */
@Nullable
String stored();

static FormatterJdk parse(@Nullable String stored) {
if (stored == null || stored.isBlank()) {
return new IdeRuntime();
}
return stored.equals(PROJECT_SDK) ? new ProjectSdk() : new Named(stored);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/*
* 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.palantir.javaformat.intellij;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.ProjectJdkTable;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.util.lang.JavaVersion;
import com.palantir.javaformat.intellij.FormatterJdk.IdeRuntime;
import com.palantir.javaformat.intellij.FormatterJdk.Named;
import com.palantir.javaformat.intellij.FormatterJdk.ProjectSdk;
import com.palantir.javaformat.intellij.FormatterJdk.Resolved;
import com.palantir.javaformat.intellij.FormatterJdk.Unusable;
import com.palantir.javaformat.intellij.FormatterJdk.Usable;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.List;
import java.util.OptionalInt;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jspecify.annotations.Nullable;

/** The JDKs the formatter's own JVM can run on: the IDE's runtime, the project SDK and the JDKs the IDE knows. */
final class FormatterJdks {

/** The formatter is compiled for Java 21. */
static final int MINIMUM_JAVA = 21;

private FormatterJdks() {}

/** The runtime the IDE runs on. Every IDE this plugin supports runs on Java 21 or later. */
static Usable ideRuntime() {
return new Usable(
javaIn(Path.of(System.getProperty("java.home"))),
Runtime.version().feature());
}

/** What the settings page lists: the IDE's runtime, the project SDK, and the JDKs by name. */
static List<FormatterJdk> choices() {
return Stream.<FormatterJdk>concat(
Stream.of(new IdeRuntime(), new ProjectSdk()),
ProjectJdkTable.getInstance().getSdksOfType(JavaSdk.getInstance()).stream()
.map(Sdk::getName)
.sorted(String.CASE_INSENSITIVE_ORDER)
.map(Named::new))
.toList();
}

/** A line of that list. detail: what the name stands for, shown beside it in grey. */
record Label(String name, String detail) {}

static Label label(Project project, FormatterJdk jdk) {
return switch (jdk) {
case IdeRuntime ideRuntime -> new Label("IDE runtime", "Java " + System.getProperty("java.version"));
case ProjectSdk projectSdk -> {
var sdk = projectSdk(project);
yield new Label(
"Project SDK",
sdk == null
? "none"
: Stream.of(sdk.getName(), java(sdk))
.filter(part -> !part.isEmpty())
.collect(Collectors.joining(", ")));
}
case Named named -> {
var sdk = ProjectJdkTable.getInstance().findJdk(named.name());
yield new Label(named.name(), sdk == null ? "not found" : java(sdk));
}
};
}

/**
* The java a JDK stands for. It is looked up for every file formatted in a JVM of its own, so that a project SDK
* that changes, or a JDK that is removed, shows at once.
*/
static Resolved resolve(Project project, FormatterJdk jdk) {
return switch (jdk) {
case IdeRuntime ideRuntime -> ideRuntime();
case ProjectSdk projectSdk -> {
var sdk = projectSdk(project);
yield sdk == null ? new Unusable("the project has no SDK") : resolve(sdk);
}
case Named named -> {
var sdk = ProjectJdkTable.getInstance().findJdk(named.name());
yield sdk == null ? new Unusable("there is no JDK named " + named.name()) : resolve(sdk);
}
};
}

private static Resolved resolve(Sdk sdk) {
// A project SDK can be one for another language.
if (!(sdk.getSdkType() instanceof JavaSdk)) {
return new Unusable(sdk.getName() + " is not a JDK");
}
var javaVersion = javaVersion(sdk);
if (javaVersion.isEmpty()) {
return new Unusable("the Java version of " + sdk.getName() + " is not known");
}
if (javaVersion.getAsInt() < MINIMUM_JAVA) {
return new Unusable(sdk.getName() + " is Java " + javaVersion.getAsInt() + ", and the formatter needs Java "
+ MINIMUM_JAVA + " or later");
}
var java = executable(sdk);
// Not on this machine, for one: a JDK in WSL or in a container has no java that the IDE can start.
if (java == null || !Files.isExecutable(java)) {
return new Unusable(sdk.getName() + " has no java to run in " + sdk.getHomePath());
}
return new Usable(java, javaVersion.getAsInt());
}

private static @Nullable Sdk projectSdk(Project project) {
return ProjectRootManager.getInstance(project).getProjectSdk();
}

private static OptionalInt javaVersion(Sdk sdk) {
var versionString = sdk.getVersionString();
var version = versionString == null ? null : JavaVersion.tryParse(versionString);
return version == null ? OptionalInt.empty() : OptionalInt.of(version.feature);
}

/** "Java 21", or nothing for a JDK whose version is not known. */
private static String java(Sdk sdk) {
var javaVersion = javaVersion(sdk);
return javaVersion.isPresent() ? "Java " + javaVersion.getAsInt() : "";
}

private static @Nullable Path executable(Sdk sdk) {
var home = sdk.getHomePath();
if (home == null) {
return null;
}
try {
return javaIn(Path.of(home));
} catch (InvalidPathException e) {
return null;
}
}

private static Path javaIn(Path home) {
return home.resolve("bin").resolve(SystemInfo.isWindows ? "java.exe" : "java");
}
}
Loading
Loading