Файли
openidea/src/features/debugger/java.ts
T
l0ng-ai 536f85b9df feat(java): build Maven and Gradle modules with a resident, incremental javac build service (#5854)
Implements #4078 steps 2–4: an IDE-owned Java build service that compiles Maven and Gradle modules with a resident javac, class by class, for launches and the Build menu.

## What changes

- **Model.** The build tool records each project's source roots, compile/runtime classpaths, resources and the compiler configuration it actually uses (release/source/target, encoding, `-parameters`, debug level, `proc`, compiler args, includes/excludes, resolved annotation processor path):
  - Maven: a core extension (`java/java-build`, `BuildModel`) during `process-resources resources:testResources`.
  - Gradle: an init script (`gradle-build.init.gradle`) with an `openideaBuildModel` task that runs source generators and `processResources`.

  The prepare run happens only when what the model is built from changes: build scripts, settings, toolchains, the launcher, the JDK, generator inputs (`src/*/proto`, `antlr4`…), or a generated root that is gone.
- **Outputs.** Every project writes to `<cache>/java-build/<build>/out/<group>.<name>/classes|test-classes`, and dependencies on other projects of the build resolve to those folders. jdtls and a terminal `mvn`/`gradle` never write the classes a launch runs.
- **Compile.** A resident javac process per JDK (and `.mvn/jvm.config`) compiles source sets in dependency order, without `-am` or the full lifecycle.
- **Class-level incremental compilation.** Each source set records, per class: its source, supertypes, the classes its constant pool references, and fingerprints of its API and compile-time constants (read from the class files, private and synthetic members excluded).
  - A build compiles the changed sources.
  - It then compiles, round after round, the sources of classes that reference a class whose API changed (or one of its subclasses), and the sources a new class could shadow.
  - Downstream sets follow an API change log.
  - A changed constant recompiles the set and everything compiled against it.
  - Sources a failed compile left behind stay dirty.
  - Sets whose annotation processors aggregate compile from scratch.
- **Build menu.**
  - Build Project and Build Module compile with the service.
  - Recompile compiles the file with the service and publishes javac's diagnostics.
- **Events.** Steps, positioned javac diagnostics and progress stream on the `BuildEvent` channel from #5801.
- **When it applies.**
  - Maven modules, unless Settings › Maven › *Delegate IDE build/run actions to Maven* is on.
  - Gradle modules when Settings › Gradle › *Build and run using* is the IDE.
  - Debug launches keep jdtls' build, because java-debug's HotSwap reloads what jdtls compiles.
  - jdtls keeps autobuild on: cross-module diagnostics depend on it (verified with a real jdtls, see the ignored test below).
- **Fallback.** These go to the build tool's own build:
  - modules that need it: another compiler (Kotlin, Groovy, AspectJ…), a non-javac compiler id, multi-release output, Java modules, unresolvable dependencies or processor paths, composite Gradle builds;
  - a failed prepare run.

The javac server and the Maven extension are built reproducibly with `--release 8` against Maven 3.9.11 (`java/java-build/build.py`, dependencies pinned) and embedded by `ide-sdk`.

## Tests

- `ide-build` `jbuild::tests`, run against a real Maven/Gradle and JDK (skipped when missing):
  - first build, no-op build, only changed files recompile;
  - API changes reach dependents, including through subclasses and across modules;
  - constant changes recompile dependents;
  - resource changes run only the resources step;
  - deleted sources, compile errors with positions, the test source set;
  - Recompile and Build Project;
  - Gradle projects;
  - fallback for Gradle projects with other compilers;
  - plus class-file parsing, the API change log, javac options and Ant patterns.
- `ide-host` `tests/java_build.rs`: Maven and Gradle launches through `java_resolve_launch` compile with javac into the IDE's outputs, and Build Project reports javac's errors.
- `tests/workspaces.rs`: a Maven that writes no build model falls back to `mvn -pl app -am`.
- `ide-lsp` (ignored, needs jdtls): jdtls reports cross-module errors in open and closed files with autobuild on.
2026-11-25 20:01:26 +08:00

313 рядки
12 KiB
TypeScript

/**
* Java debugging through Microsoft java-debug, a jdtls bundle: jdtls starts its
* DAP server (`vscode.java.startDebugSession`) and the session connects to that
* port (`debugServer`). Application configurations are launched by java-debug;
* JVMs started by Maven / Gradle with a JDWP agent are attached to. Modules that
* jdtls doesn't serve debug with java-analyzer's own adapter (`java-analyzer dap`).
*/
import { executeAction } from "@/platform/actions";
import { call, commands, IpcError, nextRequestId, type LaunchConfig, type RunConfig } from "@/platform/ipc";
import {
consoleVmArgs,
formatCompileErrors,
isJvmApplication,
joinJavaArgs,
parseJavaArgs,
prepareJavaLaunch,
remoteJavaAgentNote,
type JavaPreparation,
} from "@/platform/javaLaunch";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { withEnvFiles } from "./launch";
export const JAVA_ADAPTER = "java-debug";
export const KOTLIN_ADAPTER = "kotlin-debug-adapter";
export const JAVA_ANALYZER_ADAPTER = "java-analyzer";
const KOTLIN_LSP = "kotlin-lsp";
export function isJavaDebuggable(rc: RunConfig): boolean {
return isJvmApplication(rc) && [JAVA_ADAPTER, KOTLIN_ADAPTER].includes(rc.debugAdapter ?? JAVA_ADAPTER);
}
function join(base: string, p: string) {
if (p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p)) return p;
const rel = p.replace(/^\.\//, "");
return rel === "." || rel === "" ? base : `${base.replace(/\/$/, "")}/${rel}`;
}
/** Last path segment: jdtls names a Java project after the folder it imported. */
function baseName(p: string): string {
const s = p.replace(/[\\/]+$/, "");
const cut = Math.max(s.lastIndexOf("/"), s.lastIndexOf("\\"));
return cut >= 0 ? s.slice(cut + 1) : s;
}
/** The name jdtls knows this folder's Java project by: Eclipse's project descriptor for an Eclipse
* project, the Maven artifactId for a module (jdtls names those after the artifact, not the
* folder), and the folder name when neither says anything.
*/
export async function javaProjectName(root: string): Promise<string> {
const descriptor = await readText(join(root, ".project"));
const eclipse = /<name>([^<]+)<\/name>/.exec(descriptor)?.[1]?.trim();
if (eclipse) return eclipse;
const pom = await readText(join(root, "pom.xml"));
// A child module's own <artifactId> follows the <parent> block, which names the parent.
const own = pom.replace(/<parent>[\s\S]*?<\/parent>/, "");
const artifact = /<artifactId>\s*([^<\s]+)\s*<\/artifactId>/.exec(own)?.[1];
if (artifact && !artifact.includes("${")) return artifact;
return baseName(root);
}
/** A file of the project, or "" when it is missing (or when there is no filesystem bridge). */
async function readText(path: string): Promise<string> {
try {
return await call(commands.fsReadText(path));
} catch {
return "";
}
}
/** Conventional JVM source sets, including Kotlin kept in a Java source directory.
* A mixed module uses Kotlin's adapter, which also accepts Java line breakpoints.
*/
export async function moduleHasKotlinSources(cwd: string): Promise<boolean> {
const pending = [join(cwd, "src")];
while (pending.length) {
const path = pending.pop()!;
// oxlint-disable-next-line no-await-in-loop -- source-set traversal uses a shared pending stack and returns as soon as a .kt file is found
const entries = await call(commands.fsReadDir(path)).catch(() => []);
for (const entry of entries) {
if (entry.excluded) continue;
if ((entry.kind === "file" || entry.targetKind === "file") && entry.name.endsWith(".kt")) return true;
// Do not follow directory symlinks: a source tree can link back to a parent.
if (entry.kind === "dir") pending.push(entry.path);
}
}
return false;
}
/**
* Whether the debugger for the JVMs of `module` is installed. Maven / Gradle start those JVMs
* before the debugger attaches, so a missing Kotlin debugger is offered here, before the build
* runs: "Install and Debug" installs it and calls `retry`. An installed kotlin-lsp debugs Kotlin
* itself (the backend falls back to kotlin-debug-adapter only when it can't).
*/
export async function jvmAttachDebuggerReady(module: string, root: string, retry: () => void): Promise<boolean> {
if (!(await moduleHasKotlinSources(module ? join(root, module) : root))) return true;
const tools = await call(commands.toolsList()).catch(() => []);
const missing = (name: string) => tools.find((t) => t.name === name)?.status === "missing";
if (!missing(KOTLIN_ADAPTER) || !missing(KOTLIN_LSP)) return true;
notifications().notify({
group: "run",
level: "warning",
key: "debug.start",
title: "The Kotlin debugger is not installed",
body: "This module has Kotlin sources, so debugging it needs the Kotlin debugger (kotlin-debug-adapter).",
sticky: true,
actions: [
{ label: "Install and Debug", run: () => void executeAction("tools.install", KOTLIN_ADAPTER).then(retry) },
],
});
return false;
}
/** java-debug missing from jdtls: offer the one-click install (jdtls restarts with the bundle). */
function offerInstall(e: unknown): never {
if (e instanceof IpcError && e.kind === "unavailable" && /java-debug|debugger/i.test(e.message)) {
notifications().notify({
group: "run",
level: "warning",
key: "debug.java-debug-missing",
title: "The Java debugger is not installed",
body: "Debugging Java needs Microsoft java-debug, loaded into the Java language server. Install it and debug again once jdtls has restarted.",
sticky: true,
actions: [{ label: "Install", run: () => void executeAction("tools.install", JAVA_ADAPTER) }],
});
}
throw e;
}
async function debugServer(module: string, signal?: AbortSignal): Promise<number> {
try {
return await call(commands.javaDebugServer(module));
} catch (e) {
signal?.throwIfAborted();
offerInstall(e);
}
}
/** Launch request for an Application configuration (`java … -cp ${classpath} Main args`). */
export async function javaLaunchConfig(
rc: RunConfig,
root: string,
preparation?: JavaPreparation,
): Promise<LaunchConfig> {
rc = await withEnvFiles(rc, root);
const parsed = parseJavaArgs(rc.args);
if (!parsed.mainClass) throw new Error(`No main class in '${rc.name}'`);
preparation?.signal.throwIfAborted();
const { module, info, resolved } = await prepareJavaLaunch(rc, {
...(preparation ?? {
request: nextRequestId(),
signal: new AbortController().signal,
saveAll: async () => {
await maybeEditorService()?.saveAll();
},
}),
debug: true,
});
const cwd = resolved.cwd ? join(root, resolved.cwd) : root;
if (info.errorCount > 0 && !preparation?.report)
notifications().notify({
group: "run",
level: "warning",
key: "debug.java-compile-errors",
title: `'${rc.name}' has compile errors; debugging the last compiled classes`,
body: formatCompileErrors(info).trimEnd(),
});
const kotlin = rc.debugAdapter === KOTLIN_ADAPTER || (await moduleHasKotlinSources(join(root, module)));
preparation?.signal.throwIfAborted();
const classPaths = parsed.explicitClasspath
? parsed.explicitClasspath.split(info.pathListSeparator)
: info.classPaths;
// java-debug starts the JVM itself, bypassing the Run process that echoes its
// command line. Echo the equivalent launch here so Debug and Run stay comparable.
preparation?.report?.(`${joinJavaArgs([resolved.command, ...resolved.args])}\n`);
const agentNote = await remoteJavaAgentNote(rc);
if (agentNote) preparation?.report?.(agentNote);
if (kotlin) {
return {
name: rc.name,
adapter: KOTLIN_ADAPTER,
request: "launch",
program: null,
args: [],
cwd,
env: { ...rc.env },
extraJson: JSON.stringify({
projectRoot: join(root, module),
mainClass: parsed.mainClass,
classPaths,
modulePaths: info.modulePaths,
javaExec: resolved.command,
vmArguments: [...consoleVmArgs(rc), ...parsed.vmArgs],
programArgs: parsed.programArgs,
}),
};
}
if ((await call(commands.javaDebugAdapter(module))) === JAVA_ANALYZER_ADAPTER) {
preparation?.signal.throwIfAborted();
return {
name: rc.name,
adapter: JAVA_ANALYZER_ADAPTER,
request: "launch",
program: null,
args: [],
cwd,
env: { ...rc.env },
extraJson: JSON.stringify({
projectRoot: join(root, module),
mainClass: parsed.mainClass,
classPaths,
modulePaths: info.modulePaths,
javaExec: resolved.command === "java" ? undefined : resolved.command,
vmArgs: [...consoleVmArgs(rc), ...parsed.vmArgs],
args: parsed.programArgs,
}),
};
}
const port = await debugServer(module, preparation?.signal);
preparation?.signal.throwIfAborted();
// java-debug resolves the Java project for Evaluate on its own from `mainClass` only when
// the class belongs to a project it knows; name the project it imported so that works for
// classes compiled outside the language server's build (plain folders, custom outputs).
const project = await javaProjectName(info.projectRoot ?? root);
return {
name: rc.name,
adapter: JAVA_ADAPTER,
request: "launch",
program: null,
// java-debug takes `args` / `vmArgs` as strings.
args: [],
cwd,
env: { ...rc.env },
extraJson: JSON.stringify({
debugServer: port,
mainClass: parsed.mainClass,
classPaths,
modulePaths: info.modulePaths,
projectName: project,
javaExec: resolved.command === "java" ? undefined : resolved.command,
vmArgs: joinJavaArgs([...consoleVmArgs(rc), ...parsed.vmArgs]),
args: joinJavaArgs(parsed.programArgs),
// java-debug spawns the JVM itself: it must shorten a classpath too long for the OS the same way Run does.
shortenCommandLine: info.shortenCommandLine ?? "none",
console: "internalConsole",
stopOnEntry: false,
}),
};
}
export interface JavaAttachTarget {
name: string;
/** Module directory (relative to the project root) whose jdtls resolves sources. */
module: string;
hostName: string;
port: number;
}
export function isJavaAttachTarget(
arg: unknown,
): arg is JavaAttachTarget & { process?: number | null; runConfig?: RunConfig } {
return !!arg && typeof arg === "object" && "port" in arg && typeof (arg as { port: unknown }).port === "number";
}
/** Attach request for a JVM listening with a JDWP agent. */
export async function javaAttachConfig(target: JavaAttachTarget, root: string): Promise<LaunchConfig> {
const cwd = target.module ? join(root, target.module) : root;
if (await moduleHasKotlinSources(cwd)) {
return {
name: target.name,
adapter: KOTLIN_ADAPTER,
request: "attach",
program: null,
args: [],
cwd,
env: {},
extraJson: JSON.stringify({ projectRoot: cwd, hostName: target.hostName, port: target.port, timeout: 30_000 }),
};
}
if ((await call(commands.javaDebugAdapter(target.module))) === JAVA_ANALYZER_ADAPTER) {
return {
name: target.name,
adapter: JAVA_ANALYZER_ADAPTER,
request: "attach",
program: null,
args: [],
cwd,
env: {},
extraJson: JSON.stringify({ projectRoot: cwd, hostName: target.hostName, port: target.port, timeout: 30_000 }),
};
}
const port = await debugServer(target.module);
// java-debug resolves the Java project for Evaluate from `mainClass` only when the class is in
// a project it imported; a JDWP attach cannot even see the main class, so name the project the
// language server imported (the directory name of the module it opened).
const project = await javaProjectName(cwd);
return {
name: target.name,
adapter: JAVA_ADAPTER,
request: "attach",
program: null,
args: [],
cwd: target.module ? join(root, target.module) : root,
env: {},
extraJson: JSON.stringify({
debugServer: port,
hostName: target.hostName,
port: target.port,
timeout: 30_000,
projectName: project,
}),
};
}