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.
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-11-25 20:01:26 +08:00
1 джерело e5c5915f2e
коміт 536f85b9df
35 files changed
+5040 -50

No files matched your search

+40
Переглянути файл
@@ -0,0 +1,40 @@
# Java build
The IDE's own build of Maven and Gradle modules (`ide_build::jbuild`). The jar holds two parts:
- `ai.openidea.javac.Server` (`src/`): a resident javac. OpenIDEA starts one per JDK (and
`.mvn/jvm.config`) as `java -cp openidea-java-build.jar ai.openidea.javac.Server` and keeps it
running between builds. It reads one JSON request per line on stdin and answers on stdout:
| Request | Meaning |
| ------------------------------------------------------------------------ | ----------------------------------------------- |
| `{"id":1,"op":"compile","options":[…],"sources":[…],"encoding":"UTF-8"}` | Compile with javac (`ToolProvider`), in process |
| `{"op":"cancel","id":1}` | Stop that compilation at javac's next phase |
| `{"op":"exit"}` | Finish the queued requests, then exit |
Replies carry the request's `id`: `diagnostic` (1-based line, 0-based UTF-16 column),
`output` (a class file and the source it came from), `generated` (a source an annotation
processor wrote), `output-text`, then `done`. `ready` and `fatal` concern the server.
- `ai.openidea.javac.maven.BuildModel` (`maven/`): a Maven core extension, loaded with
`-Dmaven.ext.class.path`. With `-Dopenidea.build.output=<dir>` it redirects every project's
output to `<dir>/<groupId>.<artifactId>/classes|test-classes`, and resolves reactor
projects to those folders. With `-Dopenidea.build.model=<file>` it writes, after the build,
each project's source roots, classpaths, resources and the configuration maven-compiler-plugin's
mojos get (including the resolved `annotationProcessorPaths`), as JSON.
OpenIDEA runs `mvn process-resources resources:testResources` with the extension when the POMs,
settings or generator inputs change, then compiles the launch's modules with the server.
Gradle builds get the same model from an init script instead
(`crates/ide-build/src/jbuild/gradle-build.init.gradle`, task `openideaBuildModel`, with
`-Popenidea.build.output` and `-Popenidea.build.model`), when Settings › Gradle › Build and run
using is set to the IDE.
The jar is committed and embedded by `ide-sdk` (`java_build_jar`). It is built with `--release 8`
against Maven 3.9.11, whose files `build-dependencies.sha256` pins. Rebuild it after changing
the source:
```sh
JAVA_HOME=<JDK 11+> python3 build.py <apache-maven-3.9.11 folder>
```
+52
Переглянути файл
@@ -0,0 +1,52 @@
0addec670fedcd3f113c5c8091d783280d23f75e3acb841b61a9cdb079376a08 maven/aopalliance-1.0.jar
876eab6a83daecad5ca67eb9fcabb063c97b5aeb8cf1fca7a989ecde17522051 maven/asm-9.8.jar
d3d530d0f28fd0fbbffe2b0b338f70e8cb96f1605579e2e3abd4db29cac24e69 maven/commons-cli-1.9.0.jar
ba005f304cef92a3dede24a38ad5ac9b8afccf0d8f75839d6c1338634cf7f6e4 maven/commons-codec-1.18.0.jar
6661d5335090a5fc61dd869d2095bc6c1e2156e3aa47a6e4ababdf64c99a7889 maven/error_prone_annotations-2.38.0.jar
cbfc3906b19b8f55dd7cfd6dfe0aa4532e834250d7f080bd8d211a3e246b59cb maven/failureaccess-1.0.3.jar
94855942d4992f112946d3de1c334e709237b8126d8130bf07807c018a4a2120 maven/gson-2.13.1.jar
f3d7f57f67fd622f4d468dfdd692b3a5e3909246c28017ac3263405f0fe617ed maven/guava-33.4.8-jre.jar
142ad4475e19524d2fe3ac995b3f7cbc962fc726f2edb9dbdccc61feab9b2bf9 maven/guice-5.1.0-classes.jar
c8bc7e1c51a6d4ce72f40d2ebbabf1c4b68bfe76e732104b04381b493478e9d6 maven/httpclient-4.5.14.jar
6c9b3dd142a09dc468e23ad39aad6f75a0f2b85125104469f026e52a474e464f maven/httpcore-4.4.16.jar
0b7b8b003a90ea491579b62f5118828e45112914c65589b00faa49d6ec785839 maven/jansi-2.4.2.jar
e04ba5195bcd555dc95650f7cc614d151e4bcd52d29a10b8aa2197f3ab89ab9b maven/javax.annotation-api-1.3.2.jar
91c77044a50c481636c32d916fd89c9118a72195390452c81065080f957de7ff maven/javax.inject-1.jar
ab57ca8fd223772c17365d121f59e94ecbf0ae59d08c03a3cb5b81071c019195 maven/jcl-over-slf4j-1.7.36.jar
1fad6e6be7557781e4d33729d49ae1cdc8fdda6fe477bb0cc68ce351eafdfbab maven/jspecify-1.0.0.jar
0bfd1c121f907642344311d81e4dfd93eba6c24dc712cc0aeae273eb22833022 maven/maven-artifact-3.9.11.jar
5b1de1560ec19c4c69a655f986455888f3a0bcc3c160cac1f1edb87de3825f77 maven/maven-builder-support-3.9.11.jar
b0e2865fc808fd9fb3bee95bf37c0609eeb20c59bf1e6b958b37b365ee11f52e maven/maven-compat-3.9.11.jar
93d3c0523dda6c86c6620d9e692e7df39d0e2e4e4cd860061a8c0d274c2ad185 maven/maven-core-3.9.11.jar
7e15e05035331d0a7e0fe56d7354b2b30e15c0a8c60863cbf28df25190e197db maven/maven-embedder-3.9.11.jar
163aa596f976264384efeb50b4cb8a806086fd64a9b755ad1f69195fed3998ad maven/maven-model-3.9.11.jar
c4c72accdcd848332c1a37995610a6a369d49fdaabc43e85f0022a5b77de3ba7 maven/maven-model-builder-3.9.11.jar
8e985a56412564cf687040efed8bcd3a63eac2202a824bb01e1d5ece2b87458f maven/maven-plugin-api-3.9.11.jar
f8655f5f0060e0032944f2a23688d186e140d2184749bcfa1927f83cd6a8b1a2 maven/maven-repository-metadata-3.9.11.jar
c0ce14849298720dcf3b09fe9e263b3c576d2d6cd43c61f8aa9d6117e04e5e47 maven/maven-resolver-api-1.9.24.jar
18b7d557c41379db8b157ba95263c676f52c293f5416b67bd1db083e99b30383 maven/maven-resolver-connector-basic-1.9.24.jar
3cd88edda00c46242cdbe57aefb47703519d176d9e8a500333de15faf41b0e1d maven/maven-resolver-impl-1.9.24.jar
a222b0a5ca4c145e8e0f45207a23bcce18bdbe1f1c980e4e9fb332591ee8c91a maven/maven-resolver-named-locks-1.9.24.jar
b5d6e52ae1ecf1cb62ede2234234ba3093149524066488e84415187ce478c582 maven/maven-resolver-provider-3.9.11.jar
e3153906e93333c106ee18babb72ba7984ccb15e9116ea08f88c71b8d9387e01 maven/maven-resolver-spi-1.9.24.jar
b09268d41e1dfcae15a829d45a512ca29d62b727421d3bd6383ac6252e5e960f maven/maven-resolver-transport-file-1.9.24.jar
a0de339a8dd3473d9abaa1cf974507f38783e26af31d36a90c1e59cc8714ded0 maven/maven-resolver-transport-http-1.9.24.jar
78ed57fa2123a2d84fad7a0b15ca73b89df47c10294d02d6f8121c4d0e5050cb maven/maven-resolver-transport-wagon-1.9.24.jar
aeb7e776a8c47b1c317a2581f299e2525b044cb8abde31164e970bbbefab12b1 maven/maven-resolver-util-1.9.24.jar
026718d47d19e360d978857bc63d3dc065884fc2c801563d8a2a77b5ab74ccf8 maven/maven-settings-3.9.11.jar
33c96e4ca5a15b7c93180f6b2f8deb15f511dfc15dda0d2b671c968b22108972 maven/maven-settings-builder-3.9.11.jar
b613357e1bad4dfc1dead801691c9460f9585fe7c6b466bc25186212d7d18487 maven/maven-shared-utils-3.4.2.jar
76d9fa894fa61d1492877ca599cb5ab28ca4573d5f389d6c12a8233b995335f9 maven/maven-slf4j-provider-3.9.11.jar
1cbd7a965a5e2a9ea823bab311962a4e5aa5c240705bdbad5a52b40ffdfa1004 maven/org.eclipse.sisu.inject-0.9.0.M4.jar
b90579bc652eac7331436e0a25533fce14130b9c6e015f2dd3a3d4bb07e942b7 maven/org.eclipse.sisu.plexus-0.9.0.M4.jar
9a7f1b5c5a9effd61eadfd8731452a2f76a8e79111fac391ef75ea801bea203a maven/plexus-cipher-2.0.jar
50edb93c73786e62822b4fe1336e22880fdf147191373cf5c911370e16748fcf maven/plexus-component-annotations-2.2.0.jar
ab2a8715570438a2e4164d85ad3e8d489eabc38ea5093c2eb8ab7f58403535b5 maven/plexus-interpolation-1.28.jar
873139960c4c780176dda580b003a2c4bf82188bdce5bb99234e224ef7acfceb maven/plexus-sec-dispatcher-2.0.jar
27ef130e32c236090e408fb5498d94cb9ea26d14070fb1c8985d607b62d098d1 maven/plexus-utils-3.6.0.jar
d3ef575e3e4979678dc01bf1dcce51021493b4d11fb7f1be8ad982877c16a1c0 maven/slf4j-api-1.7.36.jar
afc9216fa97b78dad227b4a8d4d67b9897bf113a57f80598d62993841113e103 maven/wagon-file-3.5.3.jar
d2b6e48c9fcbe579e1858c622d14464011ff265fa6e28e794004a6882154a509 maven/wagon-http-3.5.3.jar
8e7da766f55164fde8779aaaa125832506c2848cab4876b5305138873e28037f maven/wagon-http-shared-3.5.3.jar
5e72000338945ed3e96f8e4f578d1d0672e1af7e19c0e9014197ae5b31af3ef4 maven/wagon-provider-api-3.5.3.jar
1ad3292cd563381e3fd632f3fded1988f9e9b2be7a9f3db63ff4c4cedba13fa5 maven/plexus-classworlds-2.9.0.jar
+38
Переглянути файл
@@ -0,0 +1,38 @@
"""Build the committed jar: python3 build.py /path/to/apache-maven-3.9.11 [--record-dependencies].
One jar, two parts, Java 8 bytecode:
- `src`: the resident javac server (`ai.openidea.javac.Server`), JDK classes only.
- `maven`: the prepare run's Maven extension (`ai.openidea.javac.maven.BuildModel`), compiled
against Maven 3.9.11's API jars, pinned by build-dependencies.sha256.
Archive order and timestamps are deterministic. Use a JDK that still compiles `--release 8`."""
import hashlib
import os
import pathlib
import subprocess
import sys
import tempfile
import zipfile
root = pathlib.Path(__file__).resolve().parent
maven = pathlib.Path(sys.argv[1]).resolve()
jars = sorted((maven / 'lib').glob('*.jar')) + sorted((maven / 'boot').glob('*.jar'))
actual = ''.join(f'{hashlib.sha256(p.read_bytes()).hexdigest()} maven/{p.name}\n' for p in jars)
if '--record-dependencies' in sys.argv:
(root / 'build-dependencies.sha256').write_text(actual)
if (root / 'build-dependencies.sha256').read_text() != actual:
sys.exit('Build dependencies differ from build-dependencies.sha256')
java_home = os.environ.get('JAVA_HOME')
javac = str(pathlib.Path(java_home) / 'bin' / 'javac') if java_home else 'javac'
with tempfile.TemporaryDirectory() as output:
for source, classpath in [('src', []), ('maven', jars)]:
subprocess.run([javac, '--release', '8', '-Xlint:-options', '-proc:none', '-encoding', 'UTF-8', '-g',
'-classpath', os.pathsep.join(map(str, classpath)), '-d', output,
*map(str, sorted((root / source).rglob('*.java')))], check=True)
files = {p.relative_to(output).as_posix(): p.read_bytes() for p in pathlib.Path(output).rglob('*.class')}
files['META-INF/sisu/javax.inject.Named'] = b'ai.openidea.javac.maven.BuildModel\n'
files['META-INF/MANIFEST.MF'] = b'Manifest-Version: 1.0\nMain-Class: ai.openidea.javac.Server\n\n'
staged = root / 'openidea-java-build.jar.pending'
with zipfile.ZipFile(staged, 'w', zipfile.ZIP_DEFLATED) as jar:
for name, data in sorted(files.items()):
jar.writestr(zipfile.ZipInfo(name, (2026, 1, 1, 0, 0, 0)), data)
staged.replace(root / 'openidea-java-build.jar')
+501
Переглянути файл
@@ -0,0 +1,501 @@
package ai.openidea.javac.maven;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.maven.AbstractMavenLifecycleParticipant;
import org.apache.maven.MavenExecutionException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.lifecycle.LifecycleExecutor;
import org.apache.maven.lifecycle.MavenExecutionPlan;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugin.MavenPluginManager;
import org.apache.maven.plugin.Mojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.project.DefaultDependencyResolutionRequest;
import org.apache.maven.project.DependencyResolutionResult;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectDependenciesResolver;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.collection.CollectRequest;
import org.eclipse.aether.graph.DependencyNode;
import org.eclipse.aether.graph.Exclusion;
import org.eclipse.aether.repository.WorkspaceReader;
import org.eclipse.aether.repository.WorkspaceRepository;
import org.eclipse.aether.resolution.ArtifactResult;
import org.eclipse.aether.resolution.DependencyRequest;
import org.eclipse.aether.resolution.DependencyResult;
/**
* Records how each project of the session compiles, for the IDE's own Java build. Loaded only
* by the IDE's prepare run ({@code -Dmaven.ext.class.path=<jar> -Dopenidea.build.model=<file>
* process-resources resources:testResources}): generated sources exist and resources are
* processed, and nothing is compiled. Test source generators run after {@code compile} in
* Maven's lifecycle, so they don't run; the source roots build-helper adds are read from its
* configuration, and any other generator is listed so the IDE leaves those tests to Maven.
*
* <p>Per project and source set (main, test): the source roots (including the ones generated
* sources added), the output directory, the compile classpath with reactor projects as their
* output directories (never their jars), the runtime classpath, the compiler plugin's resolved
* configuration (release, encoding, arguments, annotation processor path) and the resources.
* Executions bound to the compile phases that are not javac (Kotlin, AspectJ, bytecode
* enhancers) are listed, so the IDE leaves such projects to Maven.
*/
@Named("openidea-build-model")
@Singleton
public final class BuildModel extends AbstractMavenLifecycleParticipant {
private static final String COMPILER = "org.apache.maven.plugins:maven-compiler-plugin";
/** Test phases before test-compile, which the prepare run doesn't reach. */
private static final Set<String> TEST_GENERATE_PHASES = new HashSet<>(Arrays.asList(
"generate-test-sources", "process-test-sources", "generate-test-resources", "process-test-resources"));
/** Phases whose executions change what the compile phases produce. */
private static final Set<String> COMPILE_PHASES =
new HashSet<>(Arrays.asList("compile", "process-classes", "test-compile", "process-test-classes"));
/** Executions in those phases that don't change the classes the IDE compiles. */
private static final Set<String> HARMLESS = new HashSet<>(Arrays.asList(
"org.jacoco:jacoco-maven-plugin", "org.apache.maven.plugins:maven-enforcer-plugin",
"org.codehaus.mojo:animal-sniffer-maven-plugin", "org.apache.maven.plugins:maven-checkstyle-plugin",
"com.github.spotbugs:spotbugs-maven-plugin", "org.apache.maven.plugins:maven-pmd-plugin",
"com.diffplug.spotless:spotless-maven-plugin", "org.apache.maven.plugins:maven-dependency-plugin",
"org.apache.maven.plugins:maven-resources-plugin", "org.codehaus.mojo:build-helper-maven-plugin",
"pl.project13.maven:git-commit-id-plugin", "io.github.git-commit-id:git-commit-id-maven-plugin"));
private final LifecycleExecutor lifecycle;
private final MavenPluginManager plugins;
private final BuildPluginManager buildPlugins;
private final ProjectDependenciesResolver dependencies;
private final RepositorySystem repositories;
@Inject
public BuildModel(LifecycleExecutor lifecycle, MavenPluginManager plugins, BuildPluginManager buildPlugins,
ProjectDependenciesResolver dependencies, RepositorySystem repositories) {
this.lifecycle = lifecycle;
this.plugins = plugins;
this.buildPlugins = buildPlugins;
this.dependencies = dependencies;
this.repositories = repositories;
}
/**
* With {@code -Dopenidea.build.output=<dir>}, every project's classes and resources go to
* {@code <dir>/<groupId>.<artifactId>/classes} (and {@code test-classes}): the IDE's outputs,
* apart from what a terminal build or the language server writes to {@code target}.
*/
@Override public void afterProjectsRead(MavenSession session) {
String output = session.getUserProperties().getProperty("openidea.build.output");
if (output == null) return;
for (MavenProject project : session.getProjects()) {
File dir = new File(output, project.getGroupId() + "." + project.getArtifactId());
project.getBuild().setOutputDirectory(new File(dir, "classes").getAbsolutePath());
project.getBuild().setTestOutputDirectory(new File(dir, "test-classes").getAbsolutePath());
}
}
@Override public void afterSessionEnd(MavenSession session) throws MavenExecutionException {
String destination = session.getUserProperties().getProperty("openidea.build.model");
if (destination == null) return;
StringBuilder json = new StringBuilder("{\"version\":1,\"projects\":[");
boolean first = true;
MavenProject current = session.getCurrentProject();
try {
for (MavenProject project : session.getProjects()) {
if (!first) json.append(',');
first = false;
project(json, session, project);
}
} finally {
session.setCurrentProject(current);
}
json.append("]}");
File target = new File(destination);
try {
File parent = target.getAbsoluteFile().getParentFile();
parent.mkdirs();
File temp = File.createTempFile("build-model", ".json", parent);
try (Writer out = new OutputStreamWriter(Files.newOutputStream(temp.toPath()), StandardCharsets.UTF_8)) {
out.write(json.toString());
}
Files.move(temp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} catch (IOException e) {
throw new MavenExecutionException("Cannot write the IDE build model: " + e.getMessage(), e);
}
}
private void project(StringBuilder json, MavenSession session, MavenProject project) {
session.setCurrentProject(project);
json.append("{\"dir\":").append(q(project.getBasedir().getAbsolutePath()))
.append(",\"groupId\":").append(q(project.getGroupId()))
.append(",\"artifactId\":").append(q(project.getArtifactId()))
.append(",\"version\":").append(q(project.getVersion()))
.append(",\"packaging\":").append(q(project.getPackaging()));
List<String> problems = new ArrayList<>();
Map<String, Mojo> compilers = new HashMap<>();
List<MojoExecution> configured = new ArrayList<>();
List<String> others = new ArrayList<>();
List<String> testGenerators = new ArrayList<>();
List<String> testRoots = new ArrayList<>(project.getTestCompileSourceRoots());
try {
MavenExecutionPlan plan = lifecycle.calculateExecutionPlan(session, true, "test-compile");
for (MojoExecution execution : plan.getMojoExecutions()) {
String plugin = execution.getGroupId() + ":" + execution.getArtifactId();
String phase = execution.getLifecyclePhase();
if (COMPILER.equals(plugin) && ("compile".equals(execution.getGoal()) || "testCompile".equals(execution.getGoal()))) {
if (compilers.containsKey(execution.getGoal())) {
others.add(plugin + ":" + execution.getGoal() + "@" + execution.getExecutionId());
continue;
}
try {
buildPlugins.getPluginRealm(session, execution.getMojoDescriptor().getPluginDescriptor());
Mojo mojo = plugins.getConfiguredMojo(Mojo.class, session, execution);
compilers.put(execution.getGoal(), mojo);
configured.add(execution);
} catch (Exception e) {
problems.add("Cannot read the " + execution.getGoal() + " configuration: " + e);
}
} else if (phase != null && COMPILE_PHASES.contains(phase) && !HARMLESS.contains(plugin)) {
others.add(plugin + ":" + execution.getGoal() + "@" + execution.getExecutionId());
} else if (phase != null && TEST_GENERATE_PHASES.contains(phase)) {
String goal = plugin + ":" + execution.getGoal();
if (goal.equals("org.apache.maven.plugins:maven-resources-plugin:testResources")) continue;
if (goal.equals("org.codehaus.mojo:build-helper-maven-plugin:add-test-source")) {
try {
buildPlugins.getPluginRealm(session, execution.getMojoDescriptor().getPluginDescriptor());
Mojo mojo = plugins.getConfiguredMojo(Mojo.class, session, execution);
Object sources = get(mojo, "sources");
if (sources instanceof File[])
for (File f : (File[]) sources) testRoots.add(f.getAbsolutePath());
plugins.releaseMojo(mojo, execution);
continue;
} catch (Exception e) {
problems.add("Cannot read build-helper's test sources: " + e);
}
}
testGenerators.add(goal + "@" + execution.getExecutionId());
}
}
} catch (Exception e) {
problems.add("Cannot plan the build: " + e);
}
Set<String> reactor = new HashSet<>();
for (MavenProject p : session.getProjects()) reactor.add(p.getGroupId() + ":" + p.getArtifactId());
RepositorySystemSession repo = reactorSession(session);
List<String> compile = new ArrayList<>();
List<String> runtime = new ArrayList<>();
List<String> test = new ArrayList<>();
try {
DependencyResolutionResult result =
dependencies.resolve(new DefaultDependencyResolutionRequest(project, repo));
classpaths(result.getDependencyGraph(), compile, runtime, test);
for (Exception e : result.getCollectionErrors()) problems.add(e.getMessage());
} catch (Exception e) {
problems.add("Cannot resolve the dependencies: " + rootMessage(e));
org.apache.maven.project.DependencyResolutionException failure = cause(e);
if (failure != null && failure.getResult() != null && failure.getResult().getDependencyGraph() != null)
classpaths(failure.getResult().getDependencyGraph(), compile, runtime, test);
}
json.append(",\"main\":");
sourceSet(json, session, project, compilers.get("compile"), null, compile, runtime, problems);
json.append(",\"test\":");
List<String> testClasspath = new ArrayList<>();
testClasspath.add(project.getBuild().getOutputDirectory());
testClasspath.addAll(test);
sourceSet(json, session, project, compilers.get("testCompile"), testRoots, testClasspath, testClasspath, problems);
json.append(",\"otherCompilers\":").append(strings(others));
json.append(",\"testGenerators\":").append(strings(testGenerators));
json.append(",\"problems\":").append(strings(problems)).append('}');
for (int i = 0; i < configured.size(); i++) {
Mojo mojo = compilers.get(configured.get(i).getGoal());
if (mojo != null) plugins.releaseMojo(mojo, configured.get(i));
}
}
/** `testRoots`: the test source roots, `null` for the main source set. */
private void sourceSet(StringBuilder json, MavenSession session, MavenProject project, Mojo compiler,
List<String> testRoots, List<String> classpath, List<String> runtime, List<String> problems) {
boolean test = testRoots != null;
List<String> roots = test ? testRoots : project.getCompileSourceRoots();
String output = test ? project.getBuild().getTestOutputDirectory() : project.getBuild().getOutputDirectory();
json.append("{\"sourceRoots\":").append(strings(roots))
.append(",\"output\":").append(q(output))
.append(",\"classpath\":").append(strings(classpath))
.append(",\"runtimeClasspath\":").append(strings(runtime))
.append(",\"resources\":");
List<Resource> resources = test ? project.getTestResources() : project.getResources();
json.append('[');
for (int i = 0; i < resources.size(); i++) {
Resource r = resources.get(i);
if (i > 0) json.append(',');
json.append("{\"directory\":").append(q(new File(project.getBasedir(), r.getDirectory()).isAbsolute()
? r.getDirectory() : new File(project.getBasedir(), r.getDirectory()).getAbsolutePath()))
.append(",\"filtering\":").append(r.isFiltering())
.append(",\"targetPath\":").append(q(r.getTargetPath()))
.append(",\"includes\":").append(strings(r.getIncludes()))
.append(",\"excludes\":").append(strings(r.getExcludes())).append('}');
}
json.append(']');
json.append(",\"compiler\":");
if (compiler == null) {
json.append("null}");
return;
}
json.append('{');
String goal = test ? "testCompile" : "compile";
field(json, "compilerId", get(compiler, "compilerId"));
field(json, "source", get(compiler, test ? "testSource" : "source", "source"));
field(json, "target", get(compiler, test ? "testTarget" : "target", "target"));
field(json, "release", get(compiler, test ? "testRelease" : "release", "release"));
field(json, "encoding", get(compiler, "encoding"));
field(json, "parameters", get(compiler, "parameters"));
field(json, "debug", get(compiler, "debug"));
field(json, "debuglevel", get(compiler, "debuglevel"));
field(json, "proc", get(compiler, "proc"));
field(json, "enablePreview", get(compiler, "enablePreview"));
field(json, "fork", get(compiler, "fork"));
field(json, "executable", get(compiler, "executable"));
field(json, "skip", get(compiler, test ? "skip" : "skipMain"));
field(json, "showWarnings", get(compiler, "showWarnings"));
field(json, "showDeprecation", get(compiler, "showDeprecation"));
field(json, "generatedSourcesDirectory",
get(compiler, test ? "generatedTestSourcesDirectory" : "generatedSourcesDirectory"));
field(json, "includes", get(compiler, test ? "testIncludes" : "includes"));
field(json, "excludes", get(compiler, test ? "testExcludes" : "excludes"));
field(json, "annotationProcessors", get(compiler, "annotationProcessors"));
field(json, "compilerArgs", get(compiler, "compilerArgs"));
field(json, "compilerArgument", get(compiler, "compilerArgument"));
field(json, "compilerArguments", get(compiler, "compilerArguments"));
field(json, "multiReleaseOutput", get(compiler, "multiReleaseOutput"));
Object paths = get(compiler, "annotationProcessorPaths");
if (paths instanceof Collection && !((Collection<?>) paths).isEmpty()) {
try {
Object useDepMgmt = get(compiler, "annotationProcessorPathsUseDepMgmt");
field(json, "processorPath", processorPath(session, project, (Collection<?>) paths,
Boolean.TRUE.equals(useDepMgmt)));
} catch (Exception e) {
problems.add("Cannot resolve the annotation processor path of " + goal + ": " + rootMessage(e));
field(json, "processorPathError", rootMessage(e));
}
}
if (json.charAt(json.length() - 1) == ',') json.setLength(json.length() - 1);
json.append("}}");
}
/** The classpaths of the resolved graph, in Maven's order: compile, runtime, test scopes. */
private static void classpaths(DependencyNode root, List<String> compile, List<String> runtime, List<String> test) {
List<DependencyNode> nodes = new ArrayList<>();
collect(root, nodes, new HashSet<>());
for (DependencyNode node : nodes) {
if (node.getDependency() == null || node.getArtifact() == null) continue;
File file = node.getArtifact().getFile();
if (file == null) continue;
String scope = node.getDependency().getScope();
String path = file.getAbsolutePath();
if (!"test".equals(scope) && !"runtime".equals(scope)) compile.add(path);
if (!"test".equals(scope) && !"provided".equals(scope) && !"system".equals(scope)) runtime.add(path);
test.add(path);
}
}
/** Pre-order, as Maven lists `project.getArtifacts()` for classpaths. */
private static void collect(DependencyNode node, List<DependencyNode> out, Set<String> seen) {
for (DependencyNode child : node.getChildren()) {
Artifact a = child.getArtifact();
String key = a == null ? String.valueOf(System.identityHashCode(child))
: a.getGroupId() + ":" + a.getArtifactId() + ":" + a.getExtension() + ":" + a.getClassifier();
if (seen.add(key)) out.add(child);
}
for (DependencyNode child : node.getChildren()) collect(child, out, seen);
}
/**
* A repository session that resolves reactor projects to their output directories, as the
* IDE compiles against them: before (and without) any packaging, and even before they exist.
*/
private static RepositorySystemSession reactorSession(MavenSession session) {
final Map<String, MavenProject> byKey = new HashMap<>();
for (MavenProject p : session.getProjects())
byKey.put(p.getGroupId() + ":" + p.getArtifactId() + ":" + p.getVersion(), p);
final WorkspaceReader fallback = session.getRepositorySession().getWorkspaceReader();
final WorkspaceRepository repository = new WorkspaceRepository("openidea-reactor");
WorkspaceReader reader = new WorkspaceReader() {
@Override public WorkspaceRepository getRepository() {
return repository;
}
@Override public File findArtifact(Artifact artifact) {
MavenProject p = byKey.get(artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getBaseVersion());
if (p == null) return fallback == null ? null : fallback.findArtifact(artifact);
if ("pom".equals(artifact.getExtension())) return p.getFile();
boolean tests = "tests".equals(artifact.getClassifier()) || "test-jar".equals(artifact.getProperty("type", ""));
File dir = new File(tests ? p.getBuild().getTestOutputDirectory() : p.getBuild().getOutputDirectory());
dir.mkdirs();
return dir;
}
@Override public List<String> findVersions(Artifact artifact) {
MavenProject p = byKey.get(artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getBaseVersion());
if (p != null) return java.util.Collections.singletonList(p.getVersion());
return fallback == null ? java.util.Collections.<String>emptyList() : fallback.findVersions(artifact);
}
};
DefaultRepositorySystemSession copy = new DefaultRepositorySystemSession(session.getRepositorySession());
copy.setWorkspaceReader(reader);
return copy;
}
/** maven-compiler-plugin's `annotationProcessorPaths`, resolved with their dependencies as the plugin does. */
private List<String> processorPath(MavenSession session, MavenProject project, Collection<?> coordinates,
boolean useDepMgmt) throws Exception {
Map<String, String> managed = new HashMap<>();
if (project.getDependencyManagement() != null)
for (Dependency d : project.getDependencyManagement().getDependencies())
managed.put(d.getGroupId() + ":" + d.getArtifactId(), d.getVersion());
CollectRequest request = new CollectRequest();
request.setRepositories(project.getRemoteProjectRepositories());
for (Object c : coordinates) {
String group = (String) get(c, "groupId");
String artifact = (String) get(c, "artifactId");
String version = (String) get(c, "version");
if (version == null) version = managed.get(group + ":" + artifact);
if (version == null) throw new IllegalStateException("No version for " + group + ":" + artifact);
String classifier = (String) get(c, "classifier");
String type = (String) get(c, "type");
List<Exclusion> exclusions = new ArrayList<>();
Object declared = get(c, "exclusions");
if (declared instanceof Collection)
for (Object e : (Collection<?>) declared)
exclusions.add(new Exclusion((String) get(e, "groupId"), (String) get(e, "artifactId"), "*", "*"));
DefaultArtifact a = new DefaultArtifact(group, artifact, classifier == null ? "" : classifier,
type == null || "jar".equals(type) ? "jar" : type, version);
request.addDependency(new org.eclipse.aether.graph.Dependency(a, "runtime", false, exclusions));
}
if (useDepMgmt && project.getDependencyManagement() != null) {
for (Dependency d : project.getDependencyManagement().getDependencies()) {
request.addManagedDependency(new org.eclipse.aether.graph.Dependency(new DefaultArtifact(d.getGroupId(),
d.getArtifactId(), d.getClassifier() == null ? "" : d.getClassifier(),
d.getType() == null ? "jar" : d.getType(), d.getVersion()), d.getScope()));
}
}
DependencyResult result =
repositories.resolveDependencies(reactorSession(session), new DependencyRequest(request, null));
Set<String> out = new LinkedHashSet<>();
for (ArtifactResult r : result.getArtifactResults())
if (r.getArtifact() != null && r.getArtifact().getFile() != null) out.add(r.getArtifact().getFile().getAbsolutePath());
return new ArrayList<>(out);
}
private static org.apache.maven.project.DependencyResolutionException cause(Throwable e) {
for (Throwable t = e; t != null; t = t.getCause())
if (t instanceof org.apache.maven.project.DependencyResolutionException)
return (org.apache.maven.project.DependencyResolutionException) t;
return null;
}
private static String rootMessage(Throwable e) {
Throwable t = e;
while (t.getCause() != null && t.getCause() != t) t = t.getCause();
return t.getMessage() == null ? t.toString() : t.getMessage();
}
/** The first of `names` that a field of the mojo (or its superclasses) has, read reflectively. */
private static Object get(Object target, String... names) {
for (String name : names) {
for (Class<?> c = target.getClass(); c != null && c != Object.class; c = c.getSuperclass()) {
try {
Field f = c.getDeclaredField(name);
f.setAccessible(true);
Object value = f.get(target);
if (value != null || names.length == 1) return value;
break;
} catch (NoSuchFieldException e) {
// Try the superclass.
} catch (IllegalAccessException | RuntimeException e) {
return null;
}
}
}
return null;
}
private static void field(StringBuilder json, String name, Object value) {
if (value == null) return;
json.append(q(name)).append(':').append(value(value)).append(',');
}
private static String value(Object value) {
if (value == null) return "null";
if (value instanceof Boolean || value instanceof Number) return value.toString();
if (value instanceof File) return q(((File) value).getAbsolutePath());
if (value instanceof Collection) {
StringBuilder b = new StringBuilder("[");
for (Object o : (Collection<?>) value) {
if (b.length() > 1) b.append(',');
b.append(value(o));
}
return b.append(']').toString();
}
if (value instanceof Object[]) return value(Arrays.asList((Object[]) value));
if (value instanceof Map) {
StringBuilder b = new StringBuilder("{");
for (Map.Entry<?, ?> e : new LinkedHashMap<>((Map<?, ?>) value).entrySet()) {
if (b.length() > 1) b.append(',');
b.append(q(String.valueOf(e.getKey()))).append(':').append(q(e.getValue() == null ? null : String.valueOf(e.getValue())));
}
return b.append('}').toString();
}
return q(value.toString());
}
private static String strings(Collection<String> values) {
StringBuilder b = new StringBuilder("[");
if (values != null) {
for (String s : values) {
if (b.length() > 1) b.append(',');
b.append(q(s));
}
}
return b.append(']').toString();
}
static String q(String s) {
if (s == null) return "null";
StringBuilder b = new StringBuilder(s.length() + 2).append('"');
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"': b.append("\\\""); break;
case '\\': b.append("\\\\"); break;
case '\n': b.append("\\n"); break;
case '\r': b.append("\\r"); break;
case '\t': b.append("\\t"); break;
default:
if (c < 0x20) b.append(String.format("\\u%04x", (int) c));
else b.append(c);
}
}
return b.append('"').toString();
}
}
Бінарний файл не відображається.
+459
Переглянути файл
@@ -0,0 +1,459 @@
package ai.openidea.javac;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
/**
* A resident javac for the IDE's Java build: one JVM per JDK, compiling requests one at a
* time with the JDK's own compiler, in process, annotation processors included.
*
* <p>Protocol: one JSON object per line. Requests on stdin:
* {@code {"id":1,"op":"compile","options":[...],"sources":[...],"encoding":"UTF-8"}},
* {@code {"op":"cancel","id":1}}, {@code {"op":"exit"}}. Replies on stdout, all carrying the
* request {@code id}: {@code diagnostic} (severity, path, 1-based line, UTF-16 column and end,
* code, message), {@code output} (a class or resource file written, with the source it came
* from), {@code generated} (a source an annotation processor wrote), {@code output-text}
* (javac's own printed text), then one {@code done} (success, cancelled).
*/
public final class Server {
private static final Object OUT_LOCK = new Object();
private static PrintWriter out;
public static void main(String[] args) throws IOException {
out = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8), false);
// Anything else printing to stdout would break the protocol.
System.setOut(System.err);
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
send("{\"kind\":\"fatal\",\"message\":" + Json.quote("This Java runtime has no compiler (a JRE, not a JDK)") + "}");
System.exit(2);
}
send("{\"kind\":\"ready\",\"version\":" + Json.quote(System.getProperty("java.version")) + "}");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
final AtomicReference<Request> running = new AtomicReference<>();
final java.util.concurrent.BlockingQueue<Request> queue = new java.util.concurrent.LinkedBlockingQueue<>();
Thread worker = new Thread(() -> {
while (true) {
Request request;
try {
request = queue.take();
} catch (InterruptedException e) {
return;
}
if (request.exit) return;
running.set(request);
try {
compile(compiler, request);
} catch (Throwable t) {
StringWriter trace = new StringWriter();
t.printStackTrace(new PrintWriter(trace));
send("{\"id\":" + request.id + ",\"kind\":\"diagnostic\",\"severity\":\"error\",\"message\":"
+ Json.quote("javac crashed: " + trace) + "}");
send("{\"id\":" + request.id + ",\"kind\":\"done\",\"success\":false,\"cancelled\":false}");
} finally {
running.set(null);
}
}
}, "javac");
worker.start();
String line;
while ((line = in.readLine()) != null) {
if (line.trim().isEmpty()) continue;
Map<String, Object> message;
try {
message = Json.parseObject(line);
} catch (RuntimeException e) {
send("{\"kind\":\"fatal\",\"message\":" + Json.quote("Bad request: " + e.getMessage()) + "}");
continue;
}
String op = (String) message.get("op");
if ("cancel".equals(op)) {
Request current = running.get();
long id = ((Number) message.get("id")).longValue();
if (current != null && current.id == id) current.cancelled = true;
for (Request queued : queue) if (queued.id == id) queued.cancelled = true;
} else if ("exit".equals(op)) {
break;
} else if ("compile".equals(op)) {
queue.add(Request.of(message));
}
}
Request exit = new Request();
exit.exit = true;
// Requests already sent finish first; the host cancels the ones it no longer wants.
queue.add(exit);
try {
worker.join();
} catch (InterruptedException ignored) {
}
System.exit(0);
}
static void send(String json) {
synchronized (OUT_LOCK) {
out.print(json);
out.print('\n');
out.flush();
}
}
static final class Request {
long id;
List<String> options = new ArrayList<>();
List<String> sources = new ArrayList<>();
String encoding;
volatile boolean cancelled;
boolean exit;
@SuppressWarnings("unchecked")
static Request of(Map<String, Object> message) {
Request r = new Request();
r.id = ((Number) message.get("id")).longValue();
Object options = message.get("options");
if (options != null) for (Object o : (List<Object>) options) r.options.add((String) o);
Object sources = message.get("sources");
if (sources != null) for (Object o : (List<Object>) sources) r.sources.add((String) o);
r.encoding = (String) message.get("encoding");
return r;
}
}
/** Thrown from the task listener to stop a cancelled compilation. */
static final class Cancelled extends RuntimeException {
private static final long serialVersionUID = 1L;
Cancelled() {
super("cancelled", null, false, false);
}
}
private static void compile(JavaCompiler compiler, final Request request) throws IOException {
final long id = request.id;
if (request.cancelled) {
send("{\"id\":" + id + ",\"kind\":\"done\",\"success\":false,\"cancelled\":true}");
return;
}
Charset charset = request.encoding == null ? StandardCharsets.UTF_8 : Charset.forName(request.encoding);
final int[] errors = {0};
DiagnosticListener<JavaFileObject> diagnostics = d -> {
if (d.getKind() == Diagnostic.Kind.ERROR) errors[0]++;
send(diagnostic(id, d));
};
StandardJavaFileManager standard = compiler.getStandardFileManager(diagnostics, Locale.ROOT, charset);
JavaFileManager manager = new Recording(standard, id);
List<File> files = new ArrayList<>();
for (String source : request.sources) files.add(new File(source));
Iterable<? extends JavaFileObject> units = standard.getJavaFileObjectsFromFiles(files);
StringWriter printed = new StringWriter();
boolean success = false;
boolean cancelled = false;
try {
JavaCompiler.CompilationTask task =
compiler.getTask(printed, manager, diagnostics, request.options, null, units);
stopWhenCancelled(task, request);
success = Boolean.TRUE.equals(task.call()) && errors[0] == 0;
} catch (RuntimeException e) {
if (isCancelled(e)) {
cancelled = true;
} else if (e instanceof IllegalArgumentException) {
// An option javac doesn't know (a newer --release than this JDK has).
send("{\"id\":" + id + ",\"kind\":\"diagnostic\",\"severity\":\"error\",\"message\":"
+ Json.quote(e.getMessage()) + "}");
} else {
throw e;
}
} finally {
try {
manager.close();
} catch (IOException ignored) {
}
}
String text = printed.toString();
if (!text.isEmpty()) send("{\"id\":" + id + ",\"kind\":\"output-text\",\"text\":" + Json.quote(text) + "}");
send("{\"id\":" + id + ",\"kind\":\"done\",\"success\":" + success + ",\"cancelled\":" + cancelled + "}");
}
/**
* Stops the compilation at its next phase once {@code request} is cancelled, through
* {@code com.sun.source.util.TaskListener} (reflectively: Java 8's {@code --release} API has no
* {@code jdk.compiler}).
*/
private static void stopWhenCancelled(JavaCompiler.CompilationTask task, final Request request) {
try {
Class<?> listener = Class.forName("com.sun.source.util.TaskListener", false, task.getClass().getClassLoader());
Object proxy = java.lang.reflect.Proxy.newProxyInstance(listener.getClassLoader(), new Class<?>[] {listener},
(self, method, args) -> {
if (method.getDeclaringClass() == Object.class) {
switch (method.getName()) {
case "hashCode": return System.identityHashCode(self);
case "equals": return self == args[0];
default: return "cancellation listener";
}
}
if (request.cancelled) throw new Cancelled();
return null;
});
task.getClass().getMethod("addTaskListener", listener).invoke(task, proxy);
} catch (ReflectiveOperationException | RuntimeException e) {
// Not javac's task: cancellation then waits for the compilation to end.
}
}
private static boolean isCancelled(Throwable e) {
for (Throwable t = e; t != null; t = t.getCause()) if (t instanceof Cancelled) return true;
return false;
}
private static String diagnostic(long id, Diagnostic<? extends JavaFileObject> d) {
StringBuilder json = new StringBuilder("{\"id\":").append(id).append(",\"kind\":\"diagnostic\",\"severity\":");
String severity;
switch (d.getKind()) {
case ERROR: severity = "error"; break;
case WARNING:
case MANDATORY_WARNING: severity = "warning"; break;
default: severity = "info";
}
json.append(Json.quote(severity));
JavaFileObject source = d.getSource();
if (source != null) {
json.append(",\"path\":").append(Json.quote(path(source.toUri())));
long start = d.getStartPosition();
long end = d.getEndPosition();
int[] startCol = start >= 0 ? lineColumn(source, start) : null;
int[] endCol = end >= 0 ? lineColumn(source, end) : null;
if (startCol != null) json.append(",\"line\":").append(startCol[0]).append(",\"column\":").append(startCol[1]);
else if (d.getLineNumber() > 0) json.append(",\"line\":").append(d.getLineNumber());
if (endCol != null) json.append(",\"endLine\":").append(endCol[0]).append(",\"endColumn\":").append(endCol[1]);
}
if (d.getCode() != null) json.append(",\"code\":").append(Json.quote(d.getCode()));
json.append(",\"message\":").append(Json.quote(d.getMessage(Locale.ROOT)));
return json.append('}').toString();
}
/** 1-based line and 0-based UTF-16 column of a char offset (Java chars are UTF-16 units). */
private static int[] lineColumn(JavaFileObject source, long offset) {
CharSequence text;
try {
text = source.getCharContent(true);
} catch (IOException | RuntimeException e) {
return null;
}
if (offset > text.length()) return null;
int line = 1;
int lineStart = 0;
for (int i = 0; i < offset; i++) {
char c = text.charAt(i);
if (c == '\n' || (c == '\r' && (i + 1 >= text.length() || text.charAt(i + 1) != '\n'))) {
line++;
lineStart = i + 1;
}
}
return new int[] {line, (int) offset - lineStart};
}
static String path(URI uri) {
if ("file".equals(uri.getScheme())) return new File(uri).getPath();
return uri.toString();
}
/** Reports every file the compiler writes and the source it came from. */
static final class Recording extends ForwardingJavaFileManager<JavaFileManager> {
private final long id;
Recording(JavaFileManager manager, long id) {
super(manager);
this.id = id;
}
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind,
FileObject sibling) throws IOException {
JavaFileObject file = super.getJavaFileForOutput(location, className, kind, sibling);
report(location, file, sibling, kind == JavaFileObject.Kind.SOURCE);
return file;
}
@Override
public FileObject getFileForOutput(Location location, String packageName, String relativeName,
FileObject sibling) throws IOException {
FileObject file = super.getFileForOutput(location, packageName, relativeName, sibling);
report(location, file, sibling, location == StandardLocation.SOURCE_OUTPUT);
return file;
}
private void report(Location location, FileObject file, FileObject sibling, boolean generatedSource) {
StringBuilder json = new StringBuilder("{\"id\":").append(id).append(",\"kind\":")
.append(Json.quote(generatedSource ? "generated" : "output"))
.append(",\"path\":").append(Json.quote(path(file.toUri())));
if (sibling != null && sibling.toUri().getScheme() != null)
json.append(",\"source\":").append(Json.quote(path(sibling.toUri())));
json.append(",\"location\":").append(Json.quote(location.getName()));
send(json.append('}').toString());
}
}
/** Just enough JSON for the protocol: objects, arrays, strings, numbers, booleans, null. */
static final class Json {
private final String text;
private int at;
private Json(String text) {
this.text = text;
}
@SuppressWarnings("unchecked")
static Map<String, Object> parseObject(String text) {
Json json = new Json(text);
Object value = json.value();
json.space();
if (!(value instanceof Map) || json.at != text.length()) throw new IllegalArgumentException("not one JSON object");
return (Map<String, Object>) value;
}
static String quote(String s) {
if (s == null) return "null";
StringBuilder b = new StringBuilder(s.length() + 2).append('"');
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"': b.append("\\\""); break;
case '\\': b.append("\\\\"); break;
case '\n': b.append("\\n"); break;
case '\r': b.append("\\r"); break;
case '\t': b.append("\\t"); break;
default:
if (c < 0x20) b.append(String.format("\\u%04x", (int) c));
else b.append(c);
}
}
return b.append('"').toString();
}
private void space() {
while (at < text.length() && Character.isWhitespace(text.charAt(at))) at++;
}
private char peek() {
space();
if (at >= text.length()) throw new IllegalArgumentException("unexpected end");
return text.charAt(at);
}
private void expect(char c) {
if (peek() != c) throw new IllegalArgumentException("expected '" + c + "' at " + at);
at++;
}
private Object value() {
char c = peek();
if (c == '{') {
at++;
Map<String, Object> map = new java.util.LinkedHashMap<>();
if (peek() == '}') {
at++;
return map;
}
while (true) {
String key = string();
expect(':');
map.put(key, value());
if (peek() == ',') {
at++;
continue;
}
expect('}');
return map;
}
}
if (c == '[') {
at++;
List<Object> list = new ArrayList<>();
if (peek() == ']') {
at++;
return list;
}
while (true) {
list.add(value());
if (peek() == ',') {
at++;
continue;
}
expect(']');
return list;
}
}
if (c == '"') return string();
if (text.startsWith("true", at)) {
at += 4;
return Boolean.TRUE;
}
if (text.startsWith("false", at)) {
at += 5;
return Boolean.FALSE;
}
if (text.startsWith("null", at)) {
at += 4;
return null;
}
int start = at;
while (at < text.length() && "+-0123456789.eE".indexOf(text.charAt(at)) >= 0) at++;
if (start == at) throw new IllegalArgumentException("unexpected '" + c + "' at " + at);
String number = text.substring(start, at);
return number.contains(".") || number.contains("e") || number.contains("E")
? (Object) Double.parseDouble(number) : (Object) Long.parseLong(number);
}
private String string() {
expect('"');
StringBuilder b = new StringBuilder();
while (true) {
if (at >= text.length()) throw new IllegalArgumentException("unterminated string");
char c = text.charAt(at++);
if (c == '"') return b.toString();
if (c != '\\') {
b.append(c);
continue;
}
char e = text.charAt(at++);
switch (e) {
case 'n': b.append('\n'); break;
case 'r': b.append('\r'); break;
case 't': b.append('\t'); break;
case 'b': b.append('\b'); break;
case 'f': b.append('\f'); break;
case 'u':
b.append((char) Integer.parseInt(text.substring(at, at + 4), 16));
at += 4;
break;
default: b.append(e);
}
}
}
}
private Server() {
}
}