From 50add01d4a6538dc6c4f57119132f61394557291 Mon Sep 17 00:00:00 2001 From: rombirli Date: Fri, 20 Nov 2026 08:42:26 +0100 Subject: [PATCH 1/4] SONARJAVA-7339 Add the SemSitter server client --- .../sonar/java/semsitter/SemSitterClient.java | 160 ++++++++++++++++++ .../org/sonar/java/semsitter/FakeServer.java | 104 ++++++++++++ .../semsitter/SemSitterClientE2ETest.java | 67 ++++++++ .../java/semsitter/SemSitterClientTest.java | 102 +++++++++++ 4 files changed, 433 insertions(+) create mode 100644 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterClient.java create mode 100644 java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/FakeServer.java create mode 100644 java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterClientE2ETest.java create mode 100644 java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterClientTest.java 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..04bb08f5869 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterClient.java @@ -0,0 +1,160 @@ +/* + * 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 java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import org.sonar.java.semsitter.protocol.Document; +import org.sonar.java.semsitter.protocol.FullGenRequest; +import org.sonar.java.semsitter.protocol.FullGenResponse; +import org.sonar.java.semsitter.protocol.GetFileRequest; +import org.sonar.java.semsitter.protocol.GetTypesRequest; +import org.sonar.java.semsitter.protocol.HasPackageRequest; +import org.sonar.java.semsitter.protocol.HelloRequest; +import org.sonar.java.semsitter.protocol.QuitRequest; +import org.sonar.java.semsitter.protocol.Request; +import org.sonar.java.semsitter.protocol.Response; +import org.sonar.java.semsitter.protocol.SetSettingsRequest; +import org.sonar.java.semsitter.protocol.SetSettingsResponse; +import org.sonar.java.semsitter.protocol.StringList; +import org.sonar.java.semsitter.protocol.TypesResponse; + +/** + * Client of one SemSitter Java analyzer server process. The process starts with the client and ends with + * {@link #close()}; requests are answered one at a time, in order. + */ +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 OutputStream toServer; + private final InputStream fromServer; + private int nextId = 1; + + private SemSitterClient(Process process) { + this.process = process; + this.toServer = new BufferedOutputStream(process.getOutputStream()); + this.fromServer = new BufferedInputStream(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(Request.newBuilder().setHello(HelloRequest.getDefaultInstance())).getHello().getProtocol(); + 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 SetSettingsResponse setSettings(Map> settings) throws IOException { + SetSettingsRequest.Builder request = SetSettingsRequest.newBuilder(); + settings.forEach((key, values) -> request.putSettings(key, StringList.newBuilder().addAllValues(values).build())); + return send(Request.newBuilder().setSetSettings(request)).getSetSettings(); + } + + /** + * Scans {@code files}, or the source roots when empty. + */ + public FullGenResponse fullGen(Collection files) throws IOException { + return send(Request.newBuilder().setFullGen(FullGenRequest.newBuilder().addAllFiles(files))).getFullGen(); + } + + public Document getFile(String path, int ahead) throws IOException { + return send(Request.newBuilder().setGetFile(GetFileRequest.newBuilder().setPath(path).setAhead(ahead))).getDocument(); + } + + public TypesResponse getTypes(Collection names) throws IOException { + return send(Request.newBuilder().setGetTypes(GetTypesRequest.newBuilder().addAllNames(names))).getTypes(); + } + + public Map hasPackage(Collection names) throws IOException { + return send(Request.newBuilder().setHasPackage(HasPackageRequest.newBuilder().addAllNames(names))).getHasPackage().getPackagesMap(); + } + + private synchronized Response send(Request.Builder request) throws IOException { + int id = nextId; + nextId++; + request.setId(id).build().writeDelimitedTo(toServer); + toServer.flush(); + Response response = Response.parseDelimitedFrom(fromServer); + if (response == null) { + throw new IOException("SemSitter server closed its output"); + } + if (response.getId() != id) { + throw new IOException("SemSitter server answered request " + response.getId() + " instead of " + id); + } + if (response.getResultCase() == Response.ResultCase.ERROR) { + throw new IOException("SemSitter server: " + response.getError()); + } + return response; + } + + /** + * 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(Request.newBuilder().setQuit(QuitRequest.getDefaultInstance())); + toServer.close(); + if (!process.waitFor(10, TimeUnit.SECONDS)) { + process.destroyForcibly(); + } + } + } catch (IOException e) { + process.destroyForcibly(); + } catch (InterruptedException e) { + process.destroyForcibly(); + Thread.currentThread().interrupt(); + } + } +} 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..27f2fb44ee0 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/FakeServer.java @@ -0,0 +1,104 @@ +/* + * 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 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.util.List; +import java.util.TreeMap; +import org.sonar.java.semsitter.protocol.Document; +import org.sonar.java.semsitter.protocol.FullGenResponse; +import org.sonar.java.semsitter.protocol.HasPackageResponse; +import org.sonar.java.semsitter.protocol.HelloResponse; +import org.sonar.java.semsitter.protocol.Node; +import org.sonar.java.semsitter.protocol.Request; +import org.sonar.java.semsitter.protocol.Response; +import org.sonar.java.semsitter.protocol.SetSettingsResponse; +import org.sonar.java.semsitter.protocol.TypeDeclaration; +import org.sonar.java.semsitter.protocol.TypesResponse; + +/** + * 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} and {@code --wrong-id} make it misbehave. + */ +public final class FakeServer { + + 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 { + Request request; + while ((request = Request.parseDelimitedFrom(in)) != null) { + Response.Builder response = Response.newBuilder().setId(args.contains("--wrong-id") && request.hasGetFile() ? 0 : request.getId()); + answer(request, response, args.get(0)); + response.build().writeDelimitedTo(out); + out.flush(); + if (request.hasQuit() || (request.hasHello() && args.contains("--exit-after-hello"))) { + return; + } + } + } + + private static void answer(Request request, Response.Builder response, String protocol) { + switch (request.getCommandCase()) { + case HELLO -> response.setHello(HelloResponse.newBuilder().setProtocol(protocol)); + case SET_SETTINGS -> response.setSetSettings(SetSettingsResponse.newBuilder() + .addAllDiagnostics(new TreeMap<>(request.getSetSettings().getSettingsMap()).entrySet().stream() + .map(e -> e.getKey() + "=" + String.join(",", e.getValue().getValuesList())) + .toList())); + case FULL_GEN -> response.setFullGen(FullGenResponse.newBuilder().setFiles(request.getFullGen().getFilesCount())); + case GET_FILE -> { + String path = request.getGetFile().getPath(); + if (path.endsWith("Nope.java")) { + response.setError("no such file " + path); + } else { + response.setDocument(Document.newBuilder().setPath(path).setTree(Node.newBuilder().setKind("program"))); + } + } + case GET_TYPES -> { + TypesResponse.Builder types = TypesResponse.newBuilder(); + for (String name : request.getGetTypes().getNamesList()) { + if (name.startsWith("x.")) { + types.addMissing(name); + } else { + types.putDeclarations(name, TypeDeclaration.newBuilder().setOrigin("jdk").setKind("class").build()); + } + } + response.setTypes(types); + } + case HAS_PACKAGE -> { + HasPackageResponse.Builder packages = HasPackageResponse.newBuilder(); + request.getHasPackage().getNamesList().forEach(name -> packages.putPackages(name, name.startsWith("java"))); + response.setHasPackage(packages); + } + default -> response.clearResult(); + } + } +} 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..e32abe482af --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterClientE2ETest.java @@ -0,0 +1,67 @@ +/* + * 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 java.io.IOException; +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.sonar.java.semsitter.protocol.Document; +import org.sonar.java.semsitter.protocol.TypesResponse; + +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()).getFiles()).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"); + + TypesResponse types = client.getTypes(List.of("p.B", "java.lang.String", "x.Missing")); + assertThat(types.getProjectList()).containsExactly("p.B"); + assertThat(types.getMissingList()).containsExactly("x.Missing"); + assertThat(types.getDeclarationsOrThrow("java.lang.String").getKind()).isEqualTo("class"); + + 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..ded937d569e --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterClientTest.java @@ -0,0 +1,102 @@ +/* + * 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 java.io.IOException; +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.sonar.java.semsitter.protocol.TypesResponse; + +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")) { + assertThat(client.setSettings(Map.of("jvm.libraries", List.of("a.jar", "b.jar"))).getDiagnosticsList()) + .containsExactly("jvm.libraries=a.jar,b.jar"); + assertThat(client.fullGen(List.of("p/A.java", "p/B.java")).getFiles()).isEqualTo(2); + assertThat(client.getFile("p/A.java", 1).getPath()).isEqualTo("p/A.java"); + TypesResponse types = client.getTypes(List.of("java.lang.String", "x.Missing")); + assertThat(types.getDeclarationsMap()).containsOnlyKeys("java.lang.String"); + assertThat(types.getMissingList()).containsExactly("x.Missing"); + 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 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)); + } +} From 1bb8174b842924633ad2d3178ed977ffd0aea94c Mon Sep 17 00:00:00 2001 From: rombirli Date: Fri, 20 Nov 2026 09:31:39 +0100 Subject: [PATCH 2/4] SONARJAVA-7339 Speak JSON control lines and read protobuf documents --- java-frontend-semsitter/pom.xml | 4 + .../sonar/java/semsitter/SemSitterClient.java | 151 ++++++++++++------ .../org/sonar/java/semsitter/FakeServer.java | 102 ++++++------ .../semsitter/SemSitterClientE2ETest.java | 14 +- .../java/semsitter/SemSitterClientTest.java | 13 +- 5 files changed, 176 insertions(+), 108 deletions(-) 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 index 04bb08f5869..456716a4494 100644 --- 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 @@ -16,35 +16,29 @@ */ package org.sonar.java.semsitter; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.io.BufferedWriter; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; +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.sonar.java.semsitter.protocol.Document; -import org.sonar.java.semsitter.protocol.FullGenRequest; -import org.sonar.java.semsitter.protocol.FullGenResponse; -import org.sonar.java.semsitter.protocol.GetFileRequest; -import org.sonar.java.semsitter.protocol.GetTypesRequest; -import org.sonar.java.semsitter.protocol.HasPackageRequest; -import org.sonar.java.semsitter.protocol.HelloRequest; -import org.sonar.java.semsitter.protocol.QuitRequest; -import org.sonar.java.semsitter.protocol.Request; -import org.sonar.java.semsitter.protocol.Response; -import org.sonar.java.semsitter.protocol.SetSettingsRequest; -import org.sonar.java.semsitter.protocol.SetSettingsResponse; -import org.sonar.java.semsitter.protocol.StringList; -import org.sonar.java.semsitter.protocol.TypesResponse; +import org.sonarsource.semsitter.wire.Document; /** - * Client of one SemSitter Java analyzer server process. The process starts with the client and ends with - * {@link #close()}; requests are answered one at a time, in order. + * 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 { @@ -54,14 +48,14 @@ public final class SemSitterClient implements AutoCloseable { "--decl-location", "--field-items", "--field-reference-edges", "--override-edges"); private final Process process; - private final OutputStream toServer; + private final BufferedWriter toServer; private final InputStream fromServer; private int nextId = 1; private SemSitterClient(Process process) { this.process = process; - this.toServer = new BufferedOutputStream(process.getOutputStream()); - this.fromServer = new BufferedInputStream(process.getInputStream()); + this.toServer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8)); + this.fromServer = process.getInputStream(); } /** @@ -75,7 +69,7 @@ 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(Request.newBuilder().setHello(HelloRequest.getDefaultInstance())).getHello().getProtocol(); + String protocol = client.send(client.command("hello")).get("protocol").getAsString(); if (!protocol.startsWith(PROTOCOL_MAJOR + ".")) { throw new IOException("Unsupported SemSitter protocol " + protocol); } @@ -94,47 +88,96 @@ static List command(List launcher, Path projectRoot) { return command; } - public SetSettingsResponse setSettings(Map> settings) throws IOException { - SetSettingsRequest.Builder request = SetSettingsRequest.newBuilder(); - settings.forEach((key, values) -> request.putSettings(key, StringList.newBuilder().addAllValues(values).build())); - return send(Request.newBuilder().setSetSettings(request)).getSetSettings(); + 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 FullGenResponse fullGen(Collection files) throws IOException { - return send(Request.newBuilder().setFullGen(FullGenRequest.newBuilder().addAllFiles(files))).getFullGen(); + 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 { - return send(Request.newBuilder().setGetFile(GetFileRequest.newBuilder().setPath(path).setAhead(ahead))).getDocument(); + JsonObject request = command("get-file"); + request.addProperty("path", path); + request.addProperty("ahead", ahead); + return Document.parseFrom(exchange(request).payload); } - public TypesResponse getTypes(Collection names) throws IOException { - return send(Request.newBuilder().setGetTypes(GetTypesRequest.newBuilder().addAllNames(names))).getTypes(); + /** + * @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 { - return send(Request.newBuilder().setHasPackage(HasPackageRequest.newBuilder().addAllNames(names))).getHasPackage().getPackagesMap(); + 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 Response send(Request.Builder request) throws IOException { + private synchronized JsonObject send(JsonObject request) throws IOException { + return exchange(request).header; + } + + private Answer exchange(JsonObject request) throws IOException { int id = nextId; nextId++; - request.setId(id).build().writeDelimitedTo(toServer); - toServer.flush(); - Response response = Response.parseDelimitedFrom(fromServer); - if (response == null) { - throw new IOException("SemSitter server closed its output"); - } - if (response.getId() != id) { - throw new IOException("SemSitter server answered request " + response.getId() + " instead of " + id); - } - if (response.getResultCase() == Response.ResultCase.ERROR) { - throw new IOException("SemSitter server: " + response.getError()); + 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) { + throw new IOException(e.getMessage().startsWith("SemSitter") ? e.getMessage() : "SemSitter server: " + e.getMessage(), e); } - return response; } /** @@ -144,7 +187,7 @@ private synchronized Response send(Request.Builder request) throws IOException { public void close() { try { if (process.isAlive()) { - send(Request.newBuilder().setQuit(QuitRequest.getDefaultInstance())); + send(command("quit")); toServer.close(); if (!process.waitFor(10, TimeUnit.SECONDS)) { process.destroyForcibly(); @@ -157,4 +200,18 @@ public void close() { 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 record Answer(JsonObject header, byte[] 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 index 27f2fb44ee0..6acb0d3a3cb 100644 --- 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 @@ -16,6 +16,9 @@ */ 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; @@ -23,22 +26,15 @@ import java.io.InputStream; import java.io.OutputStream; import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; import java.util.List; -import java.util.TreeMap; -import org.sonar.java.semsitter.protocol.Document; -import org.sonar.java.semsitter.protocol.FullGenResponse; -import org.sonar.java.semsitter.protocol.HasPackageResponse; -import org.sonar.java.semsitter.protocol.HelloResponse; -import org.sonar.java.semsitter.protocol.Node; -import org.sonar.java.semsitter.protocol.Request; -import org.sonar.java.semsitter.protocol.Response; -import org.sonar.java.semsitter.protocol.SetSettingsResponse; -import org.sonar.java.semsitter.protocol.TypeDeclaration; -import org.sonar.java.semsitter.protocol.TypesResponse; +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} and {@code --wrong-id} make it misbehave. + * version it announces. {@code --exit-after-hello} stops after the handshake and {@code --wrong-id} answers + * {@code get-file} with another id. */ public final class FakeServer { @@ -54,51 +50,65 @@ public static void main(String[] args) { } private static void serve(List args, InputStream in, OutputStream out) throws IOException { - Request request; - while ((request = Request.parseDelimitedFrom(in)) != null) { - Response.Builder response = Response.newBuilder().setId(args.contains("--wrong-id") && request.hasGetFile() ? 0 : request.getId()); - answer(request, response, args.get(0)); - response.build().writeDelimitedTo(out); + 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 (request.hasQuit() || (request.hasHello() && args.contains("--exit-after-hello"))) { + if ("quit".equals(request.get("cmd").getAsString()) || ("hello".equals(request.get("cmd").getAsString()) && args.contains("--exit-after-hello"))) { return; } } } - private static void answer(Request request, Response.Builder response, String protocol) { - switch (request.getCommandCase()) { - case HELLO -> response.setHello(HelloResponse.newBuilder().setProtocol(protocol)); - case SET_SETTINGS -> response.setSetSettings(SetSettingsResponse.newBuilder() - .addAllDiagnostics(new TreeMap<>(request.getSetSettings().getSettingsMap()).entrySet().stream() - .map(e -> e.getKey() + "=" + String.join(",", e.getValue().getValuesList())) - .toList())); - case FULL_GEN -> response.setFullGen(FullGenResponse.newBuilder().setFiles(request.getFullGen().getFilesCount())); - case GET_FILE -> { - String path = request.getGetFile().getPath(); + 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")) { - response.setError("no such file " + path); - } else { - response.setDocument(Document.newBuilder().setPath(path).setTree(Node.newBuilder().setKind("program"))); + header.addProperty("ok", false); + header.addProperty("error", "no such file " + path); + return new byte[0]; } + header.addProperty("format", "protobuf"); + return Document.newBuilder().setPath(path).setTree(Node.newBuilder().setKind("program")).build().toByteArray(); } - case GET_TYPES -> { - TypesResponse.Builder types = TypesResponse.newBuilder(); - for (String name : request.getGetTypes().getNamesList()) { - if (name.startsWith("x.")) { - types.addMissing(name); - } else { - types.putDeclarations(name, TypeDeclaration.newBuilder().setOrigin("jdk").setKind("class").build()); - } - } - response.setTypes(types); + 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 } - case HAS_PACKAGE -> { - HasPackageResponse.Builder packages = HasPackageResponse.newBuilder(); - request.getHasPackage().getNamesList().forEach(name -> packages.putPackages(name, name.startsWith("java"))); - response.setHasPackage(packages); + } + 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); } - default -> response.clearResult(); + 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 index e32abe482af..a910ef183cf 100644 --- 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 @@ -16,7 +16,9 @@ */ 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; @@ -24,8 +26,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfSystemProperty; import org.junit.jupiter.api.io.TempDir; -import org.sonar.java.semsitter.protocol.Document; -import org.sonar.java.semsitter.protocol.TypesResponse; +import org.sonarsource.semsitter.wire.Document; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -47,7 +48,7 @@ void serves_files_and_types_of_a_project() throws IOException { 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()).getFiles()).isEqualTo(2); + assertThat(client.fullGen(List.of())).isEqualTo(2); Document document = client.getFile("p/A.java", 0); assertThat(document.getPath()).isEqualTo("p/A.java"); @@ -55,11 +56,8 @@ void serves_files_and_types_of_a_project() throws IOException { assertThat(document.getHasError()).isFalse(); assertThat(document.getTree().getKind()).isEqualTo("program"); - TypesResponse types = client.getTypes(List.of("p.B", "java.lang.String", "x.Missing")); - assertThat(types.getProjectList()).containsExactly("p.B"); - assertThat(types.getMissingList()).containsExactly("x.Missing"); - assertThat(types.getDeclarationsOrThrow("java.lang.String").getKind()).isEqualTo("class"); - + 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 index ded937d569e..77189d02a74 100644 --- 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 @@ -16,13 +16,14 @@ */ 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.sonar.java.semsitter.protocol.TypesResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -47,13 +48,11 @@ void start_takes_the_executable_path() { @Test void requests_are_answered_in_order() throws IOException { try (SemSitterClient client = fakeServer("2.1.0")) { - assertThat(client.setSettings(Map.of("jvm.libraries", List.of("a.jar", "b.jar"))).getDiagnosticsList()) - .containsExactly("jvm.libraries=a.jar,b.jar"); - assertThat(client.fullGen(List.of("p/A.java", "p/B.java")).getFiles()).isEqualTo(2); + 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"); - TypesResponse types = client.getTypes(List.of("java.lang.String", "x.Missing")); - assertThat(types.getDeclarationsMap()).containsOnlyKeys("java.lang.String"); - assertThat(types.getMissingList()).containsExactly("x.Missing"); + 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)); } } From 9679d0259a865094ac96e696837ab2fb4eb3961d Mon Sep 17 00:00:00 2001 From: rombirli Date: Fri, 20 Nov 2026 09:36:14 +0100 Subject: [PATCH 3/4] SONARJAVA-7339 Keep the client answer type free of generated array equality --- .../org/sonar/java/semsitter/SemSitterClient.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) 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 index 456716a4494..1c41aade0a7 100644 --- 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 @@ -176,7 +176,8 @@ private Answer exchange(JsonObject request) throws IOException { } return new Answer(header, payload); } catch (IOException e) { - throw new IOException(e.getMessage().startsWith("SemSitter") ? e.getMessage() : "SemSitter server: " + e.getMessage(), e); + String message = e.getMessage().startsWith("SemSitter") ? e.getMessage() : ("SemSitter server: " + e.getMessage()); + throw new IOException(message, e); } } @@ -212,6 +213,13 @@ private static String readLine(InputStream in) throws IOException { return line.toString(StandardCharsets.UTF_8); } - private record Answer(JsonObject header, byte[] payload) { + 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; + } } } From 44acda072d2cb1e0c0f1f3e5bce42b025937ad9f Mon Sep 17 00:00:00 2001 From: rombirli Date: Fri, 20 Nov 2026 16:35:09 +0100 Subject: [PATCH 4/4] SONARJAVA-7339 Read documents of any nesting depth --- .../org/sonar/java/semsitter/SemSitterClient.java | 5 ++++- .../java/org/sonar/java/semsitter/FakeServer.java | 13 +++++++++++-- .../sonar/java/semsitter/SemSitterClientTest.java | 15 +++++++++++++++ 3 files changed, 30 insertions(+), 3 deletions(-) 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 index 1c41aade0a7..5c26e3966d4 100644 --- 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 @@ -20,6 +20,7 @@ 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; @@ -118,7 +119,9 @@ public Document getFile(String path, int ahead) throws IOException { JsonObject request = command("get-file"); request.addProperty("path", path); request.addProperty("ahead", ahead); - return Document.parseFrom(exchange(request).payload); + CodedInputStream input = CodedInputStream.newInstance(exchange(request).payload); + input.setRecursionLimit(Integer.MAX_VALUE); + return Document.parseFrom(input); } /** 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 index 6acb0d3a3cb..b53b951cf2d 100644 --- 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 @@ -34,10 +34,13 @@ /** * 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. + * {@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() { } @@ -83,7 +86,13 @@ private static byte[] answer(JsonObject request, JsonObject header, String proto return new byte[0]; } header.addProperty("format", "protobuf"); - return Document.newBuilder().setPath(path).setTree(Node.newBuilder().setKind("program")).build().toByteArray(); + 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"); 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 index 77189d02a74..37ec9a14046 100644 --- 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 @@ -24,6 +24,7 @@ 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; @@ -67,6 +68,20 @@ void server_error_fails_the_request_only() throws IOException { } } + @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"))