diff --git a/java-frontend-semsitter/pom.xml b/java-frontend-semsitter/pom.xml new file mode 100644 index 00000000000..b89b7c46f7b --- /dev/null +++ b/java-frontend-semsitter/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + + org.sonarsource.java + java + 9.1.0-SNAPSHOT + + + java-frontend-semsitter + + SonarQube Java :: SemSitter Front-end + Code Analyzer for Java :: Front-end based on SemSitter + + + + ${project.groupId} + java-frontend + ${project.version} + + + org.sonarsource.api.plugin + sonar-plugin-api + provided + + + org.slf4j + slf4j-api + provided + + + org.sonarsource.semsitter + analyzer-wire + [2,3-alpha) + + + com.google.code.gson + gson + + + org.sonarsource.scanner.engine + plugin-api-scanner-impl + test + + + org.sonarsource.scanner.engine + sensor-test-fixtures + test + + + ch.qos.logback + logback-classic + test + + + org.junit.jupiter + junit-jupiter + test + + + org.assertj + assertj-core + test + + + diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterApi.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterApi.java new file mode 100644 index 00000000000..cebd73d1696 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterApi.java @@ -0,0 +1,45 @@ +/* + * 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.util.Collection; +import java.util.List; +import java.util.Map; +import org.sonarsource.semsitter.wire.Document; + +/** + * What the SemSitter frontend asks of a running SemSitter server. {@link SemSitterClient} answers it over a process. + */ +public interface SemSitterApi extends AutoCloseable { + + void setSettings(Map> settings) throws IOException; + + int fullGen(Collection files) throws IOException; + + Document getFile(String path, int ahead) throws IOException; + + /** + * @return the JSON object of declarations, as {@code types.schema.json} describes it + */ + byte[] getTypes(Collection names) throws IOException; + + Map hasPackage(Collection names) throws IOException; + + @Override + void close(); +} 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..92e01cffdb9 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterClient.java @@ -0,0 +1,247 @@ +/* + * 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 SemSitterApi { + + /** Deeper documents are rejected with an {@link IOException} before parsing them could overflow the stack. */ + static final int MAX_TREE_DEPTH = 1_000; + + 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 waits for it to answer {@code hello}. + */ + 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 { + client.send(request("hello")); + } catch (IOException | RuntimeException e) { + client.close(); + 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; + } + + @Override + public void setSettings(Map> settings) throws IOException { + JsonObject request = request("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 + */ + @Override + public int fullGen(Collection files) throws IOException { + JsonObject request = request("full-gen"); + if (!files.isEmpty()) { + JsonArray array = new JsonArray(); + files.forEach(array::add); + request.add("files", array); + } + return send(request).get("files").getAsInt(); + } + + @Override + public Document getFile(String path, int ahead) throws IOException { + JsonObject request = request("get-file"); + request.addProperty("path", path); + request.addProperty("ahead", ahead); + CodedInputStream input = CodedInputStream.newInstance(exchange(request).payload); + input.setRecursionLimit(MAX_TREE_DEPTH); + return Document.parseFrom(input); + } + + /** + * @return the JSON object of declarations, as {@code types.schema.json} describes it + */ + @Override + public byte[] getTypes(Collection names) throws IOException { + JsonObject request = request("get-types"); + JsonArray array = new JsonArray(); + names.forEach(array::add); + request.add("names", array); + return exchange(request).payload; + } + + @Override + public Map hasPackage(Collection names) throws IOException { + JsonObject request = request("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 static JsonObject request(String name) { + JsonObject request = new JsonObject(); + request.addProperty("cmd", name); + return request; + } + + private JsonObject send(JsonObject request) throws IOException { + return exchange(request).header; + } + + private int write(JsonObject request) throws IOException { + int id = nextId; + nextId++; + request.addProperty("id", id); + toServer.write(request.toString()); + toServer.write('\n'); + toServer.flush(); + return id; + } + + private synchronized Answer exchange(JsonObject request) throws IOException { + try { + int id = write(request); + String text = readLine(fromServer); + JsonObject header = JsonParser.parseString(text).getAsJsonObject(); + byte[] payload = new byte[0]; + if (header.has("payload_bytes")) { + int expected = header.get("payload_bytes").getAsInt(); + payload = fromServer.readNBytes(expected); + if (payload.length != expected) { + throw new IOException("SemSitter server sent " + payload.length + " of " + expected + " payload bytes"); + } + } + 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); + } catch (RuntimeException e) { + throw new IOException("SemSitter server sent a malformed answer: " + e.getMessage(), e); + } + } + + private synchronized void quit() throws IOException { + write(request("quit")); + toServer.close(); + } + + /** + * Asks the server to quit without waiting for its answer, then waits for it to exit and forces it to stop when it + * does not. + */ + @Override + public void close() { + try { + if (process.isAlive()) { + quit(); + 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..c49b4495348 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/FakeServer.java @@ -0,0 +1,135 @@ +/* + * 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. {@code --exit-after-hello} stops after the + * handshake and {@code --wrong-id} answers {@code get-file} with another id. {@code --garbage} answers {@code get-file} with a line that is not a JSON object + * and {@code --silent-quit} never answers {@code quit}, exiting only when its input closes. + * {@code --truncate} announces one payload byte more than it sends, then exits. A + * requested path ending with {@code Deep.java} gets a tree nested {@link #DEEP_TREE_DEPTH} levels deep, one ending + * with {@code TooDeep.java} a tree deeper than the client accepts. + */ +public final class FakeServer { + + static final int DEEP_TREE_DEPTH = 900; + + 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(); + String cmd = request.get("cmd").getAsString(); + if (args.contains("--silent-quit") && "quit".equals(cmd)) { + continue; + } + if (args.contains("--garbage") && "get-file".equals(cmd)) { + out.write("garbage\n".getBytes(StandardCharsets.UTF_8)); + out.flush(); + continue; + } + 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); + boolean truncated = payload.length > 0 && args.contains("--truncate"); + if (payload.length > 0) { + header.addProperty("payload_bytes", truncated ? payload.length + 1 : payload.length); + } + out.write(header.toString().getBytes(StandardCharsets.UTF_8)); + out.write('\n'); + out.write(payload); + out.flush(); + if (truncated || "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) { + switch (request.get("cmd").getAsString()) { + 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")) { + int levels = path.endsWith("TooDeep.java") ? SemSitterClient.MAX_TREE_DEPTH + 1 : DEEP_TREE_DEPTH; + for (int depth = 0; depth < levels; 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/ProtocolTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ProtocolTest.java new file mode 100644 index 00000000000..681e035df9b --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ProtocolTest.java @@ -0,0 +1,51 @@ +/* + * 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.io.InputStream; +import org.junit.jupiter.api.Test; +import org.sonarsource.semsitter.wire.Document; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Checks that the wire classes still read a document written by the real server. {@code real-server-document.bin} is the + * {@code get-file} answer for {@code p/A.java}, taken from the real server and re-written as is. Replace it by a new + * answer of the real server when the server changes its output on purpose. + */ +class ProtocolTest { + + @Test + void document_of_the_real_server_is_read() throws IOException { + Document document; + try (InputStream in = ProtocolTest.class.getResourceAsStream("real-server-document.bin")) { + document = Document.parseFrom(in); + } + + assertThat(document.getUnknownFields().asMap()).isEmpty(); + assertThat(document.getPath()).isEqualTo("p/A.java"); + assertThat(document.getSemantic()).isTrue(); + assertThat(document.getHasError()).isFalse(); + assertThat(document.getTree().getKind()).isEqualTo("program"); + assertThat(document.getTree().getChildren(0).getKind()).isEqualTo("package_declaration"); + assertThat(document.getSymbolsList()).extracting(symbol -> symbol.getId() + " " + symbol.getKind()) + .containsExactly("p.A#() constructor", "p.A type", "p.A#xs field", "p.A#f() method"); + assertThat(document.getFactsList()).extracting(fact -> fact.getKey() + " " + fact.getValue().getKind()) + .contains("java.util.List`1 interface", "p.A class", "p.A#f() method"); + } +} 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..ed4af20bcf8 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterClientTest.java @@ -0,0 +1,144 @@ +/* + * 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.junit.jupiter.api.Timeout; +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()) { + 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()) { + 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()) { + 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 too_deeply_nested_document_is_an_io_error() throws IOException { + try (SemSitterClient client = fakeServer()) { + assertThatThrownBy(() -> client.getFile("p/TooDeep.java", 0)).isInstanceOf(IOException.class); + assertThat(client.getFile("p/A.java", 0).getPath()).isEqualTo("p/A.java"); + } + } + + @Test + void truncated_payload_is_an_io_error() throws IOException { + try (SemSitterClient client = fakeServer("--truncate")) { + assertThatThrownBy(() -> client.getFile("p/A.java", 0)) + .isInstanceOf(IOException.class) + .hasMessageMatching("SemSitter server sent \\d+ of \\d+ payload bytes"); + } + } + + @Test + void answer_to_another_request_is_rejected() throws IOException { + try (SemSitterClient client = fakeServer("--wrong-id")) { + assertThatThrownBy(() -> client.getFile("p/A.java", 0)) + .isInstanceOf(IOException.class) + .hasMessage("SemSitter server answered request 0 instead of 2"); + } + } + + @Test + void malformed_answer_is_an_io_error() throws IOException { + try (SemSitterClient client = fakeServer("--garbage")) { + assertThatThrownBy(() -> client.getFile("p/A.java", 0)) + .isInstanceOf(IOException.class) + .hasMessageStartingWith("SemSitter server sent a malformed answer"); + } + } + + @Test + @Timeout(5) + void close_does_not_wait_for_the_quit_answer() throws IOException { + SemSitterClient client = fakeServer("--silent-quit"); + client.close(); + assertThatThrownBy(() -> client.fullGen(List.of())).isInstanceOf(IOException.class); + } + + @Test + void server_exit_fails_the_next_request() throws IOException { + try (SemSitterClient client = fakeServer("--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)); + } +} diff --git a/java-frontend-semsitter/src/test/resources/org/sonar/java/semsitter/real-server-document.bin b/java-frontend-semsitter/src/test/resources/org/sonar/java/semsitter/real-server-document.bin new file mode 100644 index 00000000000..f7682f4adf5 Binary files /dev/null and b/java-frontend-semsitter/src/test/resources/org/sonar/java/semsitter/real-server-document.bin differ diff --git a/pom.xml b/pom.xml index 7a7d7d4c128..b72acd45865 100644 --- a/pom.xml +++ b/pom.xml @@ -51,6 +51,7 @@ java-checks-test-sources java-frontend + java-frontend-semsitter java-checks-testkit java-checks java-checks-aws