diff --git a/java-frontend-semsitter/pom.xml b/java-frontend-semsitter/pom.xml
index 1aff2e46b6c..5b55f92b446 100644
--- a/java-frontend-semsitter/pom.xml
+++ b/java-frontend-semsitter/pom.xml
@@ -18,6 +18,10 @@
org.sonarsource.semsitter
analyzer-wire
+
+ com.google.code.gson
+ gson
+
org.junit.jupiter
junit-jupiter
diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterClient.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterClient.java
new file mode 100644
index 00000000000..5c26e3966d4
--- /dev/null
+++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterClient.java
@@ -0,0 +1,228 @@
+/*
+ * SonarQube Java
+ * Copyright (C) SonarSource Sàrl
+ * mailto:info AT sonarsource DOT com
+ *
+ * You can redistribute and/or modify this program under the terms of
+ * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ * See the Sonar Source-Available License for more details.
+ *
+ * You should have received a copy of the Sonar Source-Available License
+ * along with this program; if not, see https://sonarsource.com/license/ssal/
+ */
+package org.sonar.java.semsitter;
+
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.google.protobuf.CodedInputStream;
+import java.io.BufferedWriter;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStreamWriter;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import org.sonarsource.semsitter.wire.Document;
+
+/**
+ * Client of one SemSitter Java analyzer server process. Control messages are JSON lines. A {@code get-file} answer
+ * carries a {@link Document} and a {@code get-types} answer carries a JSON object, each prefixed by the byte count
+ * the header names. The process starts with the client and ends with {@link #close()}.
+ */
+public final class SemSitterClient implements AutoCloseable {
+
+ static final String PROTOCOL_MAJOR = "2";
+
+ private static final List SERVER_FLAGS = List.of("--server", "--lang", "java", "--modifiers", "--structural",
+ "--decl-location", "--field-items", "--field-reference-edges", "--override-edges");
+
+ private final Process process;
+ private final BufferedWriter toServer;
+ private final InputStream fromServer;
+ private int nextId = 1;
+
+ private SemSitterClient(Process process) {
+ this.process = process;
+ this.toServer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8));
+ this.fromServer = process.getInputStream();
+ }
+
+ /**
+ * Starts the server on the sources of {@code projectRoot} and checks that it speaks this protocol.
+ */
+ public static SemSitterClient start(Path executable, Path projectRoot) throws IOException {
+ return start(command(List.of(executable.toAbsolutePath().toString()), projectRoot));
+ }
+
+ static SemSitterClient start(List command) throws IOException {
+ Process process = new ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.INHERIT).start();
+ SemSitterClient client = new SemSitterClient(process);
+ try {
+ String protocol = client.send(client.command("hello")).get("protocol").getAsString();
+ if (!protocol.startsWith(PROTOCOL_MAJOR + ".")) {
+ throw new IOException("Unsupported SemSitter protocol " + protocol);
+ }
+ } catch (IOException | RuntimeException e) {
+ process.destroyForcibly();
+ throw e;
+ }
+ return client;
+ }
+
+ static List command(List launcher, Path projectRoot) {
+ String root = projectRoot.toAbsolutePath().toString();
+ List command = new ArrayList<>(launcher);
+ command.addAll(SERVER_FLAGS);
+ command.addAll(List.of("--src", root, "--project-root", root));
+ return command;
+ }
+
+ public void setSettings(Map> settings) throws IOException {
+ JsonObject request = command("set-settings");
+ JsonObject values = new JsonObject();
+ settings.forEach((key, list) -> {
+ JsonArray array = new JsonArray();
+ list.forEach(array::add);
+ values.add(key, array);
+ });
+ request.add("settings", values);
+ send(request);
+ }
+
+ /**
+ * Scans {@code files}, or the source roots when empty.
+ * @return how many files the server scanned
+ */
+ public int fullGen(Collection files) throws IOException {
+ JsonObject request = command("full-gen");
+ if (!files.isEmpty()) {
+ JsonArray array = new JsonArray();
+ files.forEach(array::add);
+ request.add("files", array);
+ }
+ return send(request).get("files").getAsInt();
+ }
+
+ public Document getFile(String path, int ahead) throws IOException {
+ JsonObject request = command("get-file");
+ request.addProperty("path", path);
+ request.addProperty("ahead", ahead);
+ CodedInputStream input = CodedInputStream.newInstance(exchange(request).payload);
+ input.setRecursionLimit(Integer.MAX_VALUE);
+ return Document.parseFrom(input);
+ }
+
+ /**
+ * @return the JSON object of declarations, as {@code types.schema.json} describes it
+ */
+ public byte[] getTypes(Collection names) throws IOException {
+ JsonObject request = command("get-types");
+ JsonArray array = new JsonArray();
+ names.forEach(array::add);
+ request.add("names", array);
+ return exchange(request).payload;
+ }
+
+ public Map hasPackage(Collection names) throws IOException {
+ JsonObject request = command("has-package");
+ JsonArray array = new JsonArray();
+ names.forEach(array::add);
+ request.add("names", array);
+ Map found = new LinkedHashMap<>();
+ for (Map.Entry entry : send(request).getAsJsonObject("packages").entrySet()) {
+ found.put(entry.getKey(), entry.getValue().getAsBoolean());
+ }
+ return found;
+ }
+
+ private JsonObject command(String name) {
+ JsonObject request = new JsonObject();
+ request.addProperty("cmd", name);
+ return request;
+ }
+
+ private synchronized JsonObject send(JsonObject request) throws IOException {
+ return exchange(request).header;
+ }
+
+ private Answer exchange(JsonObject request) throws IOException {
+ int id = nextId;
+ nextId++;
+ request.addProperty("id", id);
+ try {
+ toServer.write(request.toString());
+ toServer.write('\n');
+ toServer.flush();
+ String text = readLine(fromServer);
+ JsonObject header = JsonParser.parseString(text).getAsJsonObject();
+ byte[] payload = new byte[0];
+ if (header.has("payload_bytes")) {
+ payload = fromServer.readNBytes(header.get("payload_bytes").getAsInt());
+ }
+ if (header.get("id").getAsInt() != id) {
+ throw new IOException("SemSitter server answered request " + header.get("id") + " instead of " + id);
+ }
+ if (!header.get("ok").getAsBoolean()) {
+ throw new IOException("SemSitter server: " + header.get("error").getAsString());
+ }
+ return new Answer(header, payload);
+ } catch (IOException e) {
+ String message = e.getMessage().startsWith("SemSitter") ? e.getMessage() : ("SemSitter server: " + e.getMessage());
+ throw new IOException(message, e);
+ }
+ }
+
+ /**
+ * Asks the server to quit and waits for it, forcing it to stop when it does not answer.
+ */
+ @Override
+ public void close() {
+ try {
+ if (process.isAlive()) {
+ send(command("quit"));
+ toServer.close();
+ if (!process.waitFor(10, TimeUnit.SECONDS)) {
+ process.destroyForcibly();
+ }
+ }
+ } catch (IOException e) {
+ process.destroyForcibly();
+ } catch (InterruptedException e) {
+ process.destroyForcibly();
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ private static String readLine(InputStream in) throws IOException {
+ ByteArrayOutputStream line = new ByteArrayOutputStream();
+ for (int b = in.read(); b != '\n'; b = in.read()) {
+ if (b < 0) {
+ throw new IOException("SemSitter server closed its output");
+ }
+ line.write(b);
+ }
+ return line.toString(StandardCharsets.UTF_8);
+ }
+
+ private static final class Answer {
+ private final JsonObject header;
+ private final byte[] payload;
+
+ private Answer(JsonObject header, byte[] payload) {
+ this.header = header;
+ this.payload = payload;
+ }
+ }
+}
diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/FakeServer.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/FakeServer.java
new file mode 100644
index 00000000000..b53b951cf2d
--- /dev/null
+++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/FakeServer.java
@@ -0,0 +1,123 @@
+/*
+ * SonarQube Java
+ * Copyright (C) SonarSource Sàrl
+ * mailto:info AT sonarsource DOT com
+ *
+ * You can redistribute and/or modify this program under the terms of
+ * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ * See the Sonar Source-Available License for more details.
+ *
+ * You should have received a copy of the Sonar Source-Available License
+ * along with this program; if not, see https://sonarsource.com/license/ssal/
+ */
+package org.sonar.java.semsitter;
+
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import java.io.ByteArrayOutputStream;
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.UncheckedIOException;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.sonarsource.semsitter.wire.Document;
+import org.sonarsource.semsitter.wire.Node;
+
+/**
+ * Stand-in for the SemSitter server, run as a separate process by the tests. The first argument is the protocol
+ * version it announces. {@code --exit-after-hello} stops after the handshake and {@code --wrong-id} answers
+ * {@code get-file} with another id. A requested path ending with {@code Deep.java} gets a tree nested
+ * {@link #DEEP_TREE_DEPTH} levels deep.
+ */
+public final class FakeServer {
+
+ static final int DEEP_TREE_DEPTH = 1_000;
+
+ private FakeServer() {
+ }
+
+ public static void main(String[] args) {
+ try (InputStream in = new FileInputStream(FileDescriptor.in); OutputStream out = new FileOutputStream(FileDescriptor.out)) {
+ serve(List.of(args), in, out);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ private static void serve(List args, InputStream in, OutputStream out) throws IOException {
+ String line;
+ while ((line = readLine(in)) != null) {
+ JsonObject request = JsonParser.parseString(line).getAsJsonObject();
+ JsonObject header = new JsonObject();
+ header.addProperty("id", args.contains("--wrong-id") && "get-file".equals(request.get("cmd").getAsString()) ? 0 : request.get("id").getAsInt());
+ header.addProperty("ok", true);
+ byte[] payload = answer(request, header, args.get(0));
+ if (payload.length > 0) {
+ header.addProperty("payload_bytes", payload.length);
+ }
+ out.write(header.toString().getBytes(StandardCharsets.UTF_8));
+ out.write('\n');
+ out.write(payload);
+ out.flush();
+ if ("quit".equals(request.get("cmd").getAsString()) || ("hello".equals(request.get("cmd").getAsString()) && args.contains("--exit-after-hello"))) {
+ return;
+ }
+ }
+ }
+
+ private static byte[] answer(JsonObject request, JsonObject header, String protocol) {
+ switch (request.get("cmd").getAsString()) {
+ case "hello" -> header.addProperty("protocol", protocol);
+ case "set-settings" -> header.add("settings", request.get("settings"));
+ case "full-gen" -> header.addProperty("files", request.has("files") ? request.getAsJsonArray("files").size() : 0);
+ case "get-file" -> {
+ String path = request.get("path").getAsString();
+ if (path.endsWith("Nope.java")) {
+ header.addProperty("ok", false);
+ header.addProperty("error", "no such file " + path);
+ return new byte[0];
+ }
+ header.addProperty("format", "protobuf");
+ Node.Builder tree = Node.newBuilder().setKind("program");
+ if (path.endsWith("Deep.java")) {
+ for (int depth = 0; depth < DEEP_TREE_DEPTH; depth++) {
+ tree = Node.newBuilder().setKind("parenthesized_expression").addChildren(tree);
+ }
+ }
+ return Document.newBuilder().setPath(path).setTree(tree).build().toByteArray();
+ }
+ case "get-types" -> {
+ header.addProperty("format", "json");
+ return "{\"java.lang.String\":{\"kind\":\"class\"}}".getBytes(StandardCharsets.UTF_8);
+ }
+ case "has-package" -> {
+ JsonObject packages = new JsonObject();
+ request.getAsJsonArray("names").forEach(name -> packages.addProperty(name.getAsString(), name.getAsString().startsWith("java")));
+ header.add("packages", packages);
+ }
+ default -> {
+ // a quit request has no result beyond ok
+ }
+ }
+ return new byte[0];
+ }
+
+ private static String readLine(InputStream in) throws IOException {
+ ByteArrayOutputStream line = new ByteArrayOutputStream();
+ for (int b = in.read(); b != '\n'; b = in.read()) {
+ if (b < 0) {
+ return line.size() == 0 ? null : line.toString(StandardCharsets.UTF_8);
+ }
+ line.write(b);
+ }
+ return line.toString(StandardCharsets.UTF_8);
+ }
+}
diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterClientE2ETest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterClientE2ETest.java
new file mode 100644
index 00000000000..a910ef183cf
--- /dev/null
+++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterClientE2ETest.java
@@ -0,0 +1,65 @@
+/*
+ * SonarQube Java
+ * Copyright (C) SonarSource Sàrl
+ * mailto:info AT sonarsource DOT com
+ *
+ * You can redistribute and/or modify this program under the terms of
+ * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ * See the Sonar Source-Available License for more details.
+ *
+ * You should have received a copy of the Sonar Source-Available License
+ * along with this program; if not, see https://sonarsource.com/license/ssal/
+ */
+package org.sonar.java.semsitter;
+
+import com.google.gson.JsonParser;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.api.io.TempDir;
+import org.sonarsource.semsitter.wire.Document;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * Drives the real udg-java-server, whose path is given by {@code -Dsemsitter.executable}.
+ */
+@EnabledIfSystemProperty(named = "semsitter.executable", matches = ".+")
+class SemSitterClientE2ETest {
+
+ @TempDir
+ Path project;
+
+ @Test
+ void serves_files_and_types_of_a_project() throws IOException {
+ Path pkg = Files.createDirectories(project.resolve("p"));
+ Files.writeString(pkg.resolve("A.java"), "package p;\nimport java.util.List;\npublic class A extends B { List xs; int f() { return g(); } }\n");
+ Files.writeString(pkg.resolve("B.java"), "package p;\nclass B { int g() { return 1; } }\n");
+
+ try (SemSitterClient client = SemSitterClient.start(Path.of(System.getProperty("semsitter.executable")), project)) {
+ client.setSettings(Map.of("jvm.java_version", List.of("17")));
+ assertThat(client.fullGen(List.of())).isEqualTo(2);
+
+ Document document = client.getFile("p/A.java", 0);
+ assertThat(document.getPath()).isEqualTo("p/A.java");
+ assertThat(document.getSemantic()).isTrue();
+ assertThat(document.getHasError()).isFalse();
+ assertThat(document.getTree().getKind()).isEqualTo("program");
+
+ String types = new String(client.getTypes(List.of("p.B", "java.lang.String", "x.Missing")), StandardCharsets.UTF_8);
+ assertThat(JsonParser.parseString(types).getAsJsonObject().keySet()).contains("java.lang.String");
+ assertThat(client.hasPackage(List.of("p", "zz"))).containsEntry("p", true).containsEntry("zz", false);
+ assertThatThrownBy(() -> client.getFile("p/Nope.java", 0)).isInstanceOf(IOException.class);
+ }
+ }
+}
diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterClientTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterClientTest.java
new file mode 100644
index 00000000000..37ec9a14046
--- /dev/null
+++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterClientTest.java
@@ -0,0 +1,116 @@
+/*
+ * SonarQube Java
+ * Copyright (C) SonarSource Sàrl
+ * mailto:info AT sonarsource DOT com
+ *
+ * You can redistribute and/or modify this program under the terms of
+ * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ * See the Sonar Source-Available License for more details.
+ *
+ * You should have received a copy of the Sonar Source-Available License
+ * along with this program; if not, see https://sonarsource.com/license/ssal/
+ */
+package org.sonar.java.semsitter;
+
+import com.google.gson.JsonParser;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import org.junit.jupiter.api.Test;
+import org.sonarsource.semsitter.wire.Node;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class SemSitterClientTest {
+
+ private static final Path ROOT = Path.of("project").toAbsolutePath();
+
+ @Test
+ void command_starts_the_server_on_the_project_root() {
+ assertThat(SemSitterClient.command(List.of("/bin/udg-java-server"), ROOT))
+ .startsWith("/bin/udg-java-server", "--server", "--lang", "java")
+ .endsWith("--src", ROOT.toString(), "--project-root", ROOT.toString());
+ }
+
+ @Test
+ void start_takes_the_executable_path() {
+ Path missing = Path.of("missing-semsitter-executable");
+ assertThatThrownBy(() -> SemSitterClient.start(missing, ROOT)).isInstanceOf(IOException.class);
+ }
+
+ @Test
+ void requests_are_answered_in_order() throws IOException {
+ try (SemSitterClient client = fakeServer("2.1.0")) {
+ client.setSettings(Map.of("jvm.libraries", List.of("a.jar", "b.jar")));
+ assertThat(client.fullGen(List.of("p/A.java", "p/B.java"))).isEqualTo(2);
+ assertThat(client.getFile("p/A.java", 1).getPath()).isEqualTo("p/A.java");
+ assertThat(JsonParser.parseString(new String(client.getTypes(List.of("java.lang.String")), StandardCharsets.UTF_8)).getAsJsonObject()
+ .getAsJsonObject("java.lang.String").get("kind").getAsString()).isEqualTo("class");
+ assertThat(client.hasPackage(List.of("java.util", "zz"))).containsExactlyInAnyOrderEntriesOf(Map.of("java.util", true, "zz", false));
+ }
+ }
+
+ @Test
+ void server_error_fails_the_request_only() throws IOException {
+ try (SemSitterClient client = fakeServer("2.0.0")) {
+ assertThatThrownBy(() -> client.getFile("p/Nope.java", 0))
+ .isInstanceOf(IOException.class)
+ .hasMessage("SemSitter server: no such file p/Nope.java");
+ assertThat(client.getFile("p/A.java", 0).getPath()).isEqualTo("p/A.java");
+ }
+ }
+
+ @Test
+ void deeply_nested_document_is_read() throws IOException {
+ try (SemSitterClient client = fakeServer("2.0.0")) {
+ Node node = client.getFile("p/Deep.java", 0).getTree();
+ int depth = 0;
+ while (node.getChildrenCount() > 0) {
+ node = node.getChildren(0);
+ depth++;
+ }
+ assertThat(depth).isEqualTo(FakeServer.DEEP_TREE_DEPTH);
+ assertThat(node.getKind()).isEqualTo("program");
+ }
+ }
+
+ @Test
+ void other_protocol_major_is_rejected() {
+ assertThatThrownBy(() -> fakeServer("1.8.0"))
+ .isInstanceOf(IOException.class)
+ .hasMessage("Unsupported SemSitter protocol 1.8.0");
+ }
+
+ @Test
+ void answer_to_another_request_is_rejected() throws IOException {
+ try (SemSitterClient client = fakeServer("2.0.0", "--wrong-id")) {
+ assertThatThrownBy(() -> client.getFile("p/A.java", 0))
+ .isInstanceOf(IOException.class)
+ .hasMessage("SemSitter server answered request 0 instead of 2");
+ }
+ }
+
+ @Test
+ void server_exit_fails_the_next_request() throws IOException {
+ try (SemSitterClient client = fakeServer("2.0.0", "--exit-after-hello")) {
+ assertThatThrownBy(() -> client.fullGen(List.of())).isInstanceOf(IOException.class);
+ }
+ }
+
+ private static SemSitterClient fakeServer(String... args) throws IOException {
+ List launcher = new ArrayList<>(List.of(
+ Path.of(System.getProperty("java.home"), "bin", "java").toString(),
+ "-cp", System.getProperty("java.class.path"),
+ FakeServer.class.getName()));
+ launcher.addAll(List.of(args));
+ return SemSitterClient.start(SemSitterClient.command(launcher, ROOT));
+ }
+}