From f6c9efcb61ecea016065a11ed93e521dfd46b036 Mon Sep 17 00:00:00 2001 From: rombirli Date: Wed, 25 Nov 2026 10:09:25 +0100 Subject: [PATCH 1/2] JAVA-7395 Derive the SemSitter project root and settings and cache session types --- .../org/sonar/java/semsitter/ProjectRoot.java | 68 ++++++++++++ .../java/semsitter/SemSitterSettings.java | 62 +++++++++++ .../sonar/java/semsitter/SessionTypes.java | 103 ++++++++++++++++++ .../sonar/java/semsitter/ProjectRootTest.java | 76 +++++++++++++ .../java/semsitter/SemSitterSettingsTest.java | 64 +++++++++++ .../java/semsitter/SessionTypesTest.java | 85 +++++++++++++++ 6 files changed, 458 insertions(+) create mode 100644 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/ProjectRoot.java create mode 100644 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterSettings.java create mode 100644 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SessionTypes.java create mode 100644 java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ProjectRootTest.java create mode 100644 java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterSettingsTest.java create mode 100644 java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SessionTypesTest.java diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/ProjectRoot.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/ProjectRoot.java new file mode 100644 index 00000000000..ea60528a438 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/ProjectRoot.java @@ -0,0 +1,68 @@ +/* + * 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.nio.file.Path; +import java.util.Collection; +import java.util.Iterator; +import java.util.Optional; +import javax.annotation.Nullable; + +/** + * The directory a SemSitter server is started on. + */ +final class ProjectRoot { + + private ProjectRoot() { + } + + /** + * @return the deepest directory that contains every file, none when there is no file or the files share no directory, + * like files on two Windows drives + */ + static Optional commonAncestor(Collection files) { + Iterator paths = files.iterator(); + if (!paths.hasNext()) { + return Optional.empty(); + } + Path common = directory(paths.next()); + while (common != null && paths.hasNext()) { + common = shared(common, directory(paths.next())); + } + return Optional.ofNullable(common); + } + + private static Path directory(Path file) { + return file.toAbsolutePath().normalize().getParent(); + } + + @Nullable + private static Path shared(Path first, Path second) { + Path candidate = first; + while (candidate != null && !second.startsWith(candidate)) { + candidate = candidate.getParent(); + } + return candidate; + } + + /** + * @return the path of {@code file} below {@code root}, written with {@code /} on every platform, as the server names files + */ + static String relative(Path root, Path file) { + return root.relativize(file.toAbsolutePath().normalize()).toString().replace('\\', '/'); + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterSettings.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterSettings.java new file mode 100644 index 00000000000..d6ab3a39e46 --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterSettings.java @@ -0,0 +1,62 @@ +/* + * 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.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.sonar.plugins.java.api.JavaVersion; + +/** + * The session settings SemSitter needs to analyze a project the way the ECJ based frontend does. + */ +final class SemSitterSettings { + + static final String LIBRARIES = "jvm.libraries"; + static final String JAVA_VERSION = "jvm.java_version"; + static final String ENABLE_PREVIEW = "jvm.enable_preview"; + + private SemSitterSettings() { + } + + /** + * The libraries are the runtime image of {@code javaHome}, which is the JDK ECJ resolves against, followed by the + * classpath, so that JDK classes win over a library copy as they do on the boot classpath. The language level and + * the preview flag are only given when the project sets them. + */ + static Map> of(JavaVersion javaVersion, List classpath, Path javaHome) { + Map> settings = new LinkedHashMap<>(); + List libraries = new ArrayList<>(); + Path image = javaHome.resolve("lib").resolve("modules"); + if (Files.isRegularFile(image)) { + libraries.add(image.toString()); + } + classpath.stream().map(File::getAbsolutePath).forEach(libraries::add); + settings.put(LIBRARIES, libraries); + if (javaVersion.isSet()) { + settings.put(JAVA_VERSION, List.of(String.valueOf(javaVersion.asInt()))); + } + if (javaVersion.arePreviewFeaturesEnabled()) { + settings.put(ENABLE_PREVIEW, List.of("true")); + } + return settings; + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SessionTypes.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SessionTypes.java new file mode 100644 index 00000000000..7caf46844ee --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SessionTypes.java @@ -0,0 +1,103 @@ +/* + * 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.JsonElement; +import com.google.gson.JsonObject; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; + +/** + * The type declarations a server session answered so far. The server sends a declaration once per session, while each + * file is translated against its own semantic model, so a declaration sent for one file is kept to be given again to + * the next files that name it. + */ +final class SessionTypes { + + private static final String[] SUPERTYPE_KEYS = {"super", "interfaces"}; + + private final Function, JsonObject> server; + private final Map declarations = new HashMap<>(); + private final Set undeclared = new HashSet<>(); + + SessionTypes(Function, JsonObject> server) { + this.server = server; + } + + /** + * The declarations of {@code names} and of their supertypes. Only the names never asked before go to the server; a + * name it does not declare is not asked again. + */ + JsonObject get(Set names) { + Set missing = new LinkedHashSet<>(); + for (String name : names) { + String erased = erase(name); + if (!declarations.containsKey(erased) && !undeclared.contains(erased)) { + missing.add(erased); + } + } + if (!missing.isEmpty()) { + for (Map.Entry entry : server.apply(missing).entrySet()) { + declarations.put(entry.getKey(), entry.getValue().getAsJsonObject()); + } + missing.stream().filter(name -> !declarations.containsKey(name)).forEach(undeclared::add); + } + JsonObject found = new JsonObject(); + Deque queue = new ArrayDeque<>(); + names.forEach(name -> queue.add(erase(name))); + while (!queue.isEmpty()) { + String name = queue.poll(); + JsonObject declaration = declarations.get(name); + if (declaration == null || found.has(name)) { + continue; + } + found.add(name, declaration); + for (String key : SUPERTYPE_KEYS) { + supertypes(declaration.get(key)).forEach(supertype -> queue.add(erase(supertype))); + } + } + return found; + } + + private static Set supertypes(JsonElement value) { + Set names = new LinkedHashSet<>(); + if (value == null || value.isJsonNull()) { + return names; + } + if (value.isJsonArray()) { + value.getAsJsonArray().forEach(element -> { + if (element.isJsonPrimitive()) { + names.add(element.getAsString()); + } + }); + } else if (value.isJsonPrimitive()) { + names.add(value.getAsString()); + } + return names; + } + + /** The name without the generic arity suffix ({@code `1}) SemSitter ids may carry. */ + static String erase(String name) { + return name.replaceAll("`\\d+", ""); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ProjectRootTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ProjectRootTest.java new file mode 100644 index 00000000000..7c1c4905a2b --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ProjectRootTest.java @@ -0,0 +1,76 @@ +/* + * 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.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import static org.assertj.core.api.Assertions.assertThat; + +class ProjectRootTest { + + private static final Path BASE = Path.of("project").toAbsolutePath(); + + @Test + void single_file_root_is_its_directory() { + assertThat(ProjectRoot.commonAncestor(List.of(BASE.resolve("src/p/A.java")))).contains(BASE.resolve("src/p")); + } + + @Test + void root_is_the_deepest_shared_directory() { + List files = List.of(BASE.resolve("src/p/A.java"), BASE.resolve("src/p/q/B.java"), BASE.resolve("src/r/C.java")); + + assertThat(ProjectRoot.commonAncestor(files)).contains(BASE.resolve("src")); + } + + @Test + void dots_in_paths_are_resolved() { + List files = List.of(BASE.resolve("src/p/../p/A.java"), BASE.resolve("src/./p/B.java")); + + assertThat(ProjectRoot.commonAncestor(files)).contains(BASE.resolve("src/p")); + } + + @Test + void relative_paths_are_made_absolute() { + assertThat(ProjectRoot.commonAncestor(List.of(Path.of("src/A.java")))).contains(Path.of("src").toAbsolutePath()); + } + + @Test + void no_file_has_no_root() { + assertThat(ProjectRoot.commonAncestor(List.of())).isEmpty(); + } + + @Test + void files_sharing_no_directory_have_no_root(@TempDir Path temp) throws IOException { + try (FileSystem otherDrive = FileSystems.newFileSystem(temp.resolve("drive.zip"), Map.of("create", "true"))) { + List files = List.of(BASE.resolve("src/A.java"), otherDrive.getPath("/src/B.java")); + + assertThat(ProjectRoot.commonAncestor(files)).isEmpty(); + } + } + + @Test + void relative_path_is_written_with_slashes_below_the_root() { + assertThat(ProjectRoot.relative(BASE, BASE.resolve("src").resolve("p").resolve("A.java"))).isEqualTo("src/p/A.java"); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterSettingsTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterSettingsTest.java new file mode 100644 index 00000000000..b3058fe7f8f --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterSettingsTest.java @@ -0,0 +1,64 @@ +/* + * 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.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.sonar.java.model.JavaVersionImpl; + +import static org.assertj.core.api.Assertions.assertThat; + +class SemSitterSettingsTest { + + @TempDir + Path javaHome; + + @Test + void libraries_are_the_classpath_when_the_jdk_has_no_runtime_image() { + List classpath = List.of(new File("a.jar"), new File("b.jar")); + + assertThat(SemSitterSettings.of(new JavaVersionImpl(), classpath, javaHome)) + .containsOnlyKeys(SemSitterSettings.LIBRARIES) + .containsEntry(SemSitterSettings.LIBRARIES, List.of(new File("a.jar").getAbsolutePath(), new File("b.jar").getAbsolutePath())); + } + + @Test + void runtime_image_of_the_jdk_comes_before_the_classpath() throws IOException { + Path image = Files.createDirectories(javaHome.resolve("lib")).resolve("modules"); + Files.writeString(image, "image"); + + assertThat(SemSitterSettings.of(new JavaVersionImpl(), List.of(new File("a.jar")), javaHome).get(SemSitterSettings.LIBRARIES)) + .containsExactly(image.toString(), new File("a.jar").getAbsolutePath()); + } + + @Test + void language_level_is_given_only_when_the_project_sets_it() { + assertThat(SemSitterSettings.of(new JavaVersionImpl(), List.of(), javaHome)).doesNotContainKey(SemSitterSettings.JAVA_VERSION); + assertThat(SemSitterSettings.of(new JavaVersionImpl(17), List.of(), javaHome)).containsEntry(SemSitterSettings.JAVA_VERSION, List.of("17")); + } + + @Test + void preview_flag_is_given_only_when_preview_features_are_enabled() { + assertThat(SemSitterSettings.of(new JavaVersionImpl(25), List.of(), javaHome)).doesNotContainKey(SemSitterSettings.ENABLE_PREVIEW); + assertThat(SemSitterSettings.of(new JavaVersionImpl(25, true), List.of(), javaHome)).containsEntry(SemSitterSettings.ENABLE_PREVIEW, List.of("true")); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SessionTypesTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SessionTypesTest.java new file mode 100644 index 00000000000..5974143b020 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SessionTypesTest.java @@ -0,0 +1,85 @@ +/* + * 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.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SessionTypesTest { + + private static final Map DECLARATIONS = Map.of( + "p.Child", "{\"kind\":\"class\",\"super\":\"p.Parent`1\",\"interfaces\":[\"p.Marker\"]}", + "p.Parent", "{\"kind\":\"class\",\"super\":\"java.lang.Object\",\"interfaces\":null}", + "p.Marker", "{\"kind\":\"interface\"}", + "java.lang.Object", "{\"kind\":\"class\"}"); + + private final List> asked = new ArrayList<>(); + private final Set sent = new HashSet<>(); + + private final SessionTypes types = new SessionTypes(names -> { + asked.add(Set.copyOf(names)); + JsonObject answer = new JsonObject(); + for (String name : names) { + if (DECLARATIONS.containsKey(name) && sent.add(name)) { + answer.add(name, JsonParser.parseString(DECLARATIONS.get(name))); + supertypesOf(name).forEach(supertype -> { + if (sent.add(supertype)) { + answer.add(supertype, JsonParser.parseString(DECLARATIONS.get(supertype))); + } + }); + } + } + return answer; + }); + + @Test + void a_declaration_sent_once_is_given_again_with_its_supertypes() { + assertThat(types.get(Set.of("p.Child")).keySet()).containsExactlyInAnyOrder("p.Child", "p.Parent", "p.Marker", "java.lang.Object"); + assertThat(types.get(Set.of("p.Child")).keySet()).containsExactlyInAnyOrder("p.Child", "p.Parent", "p.Marker", "java.lang.Object"); + assertThat(types.get(Set.of("p.Parent")).keySet()).containsExactlyInAnyOrder("p.Parent", "java.lang.Object"); + assertThat(asked).containsExactly(Set.of("p.Child")); + } + + @Test + void a_name_the_server_does_not_declare_is_asked_once() { + assertThat(types.get(Set.of("x.Missing")).keySet()).isEmpty(); + assertThat(types.get(Set.of("x.Missing", "p.Marker")).keySet()).containsExactly("p.Marker"); + assertThat(asked).containsExactly(Set.of("x.Missing"), Set.of("p.Marker")); + } + + @Test + void the_generic_arity_suffix_is_not_part_of_the_name() { + assertThat(SessionTypes.erase("p.Map`2.Entry`2")).isEqualTo("p.Map.Entry"); + assertThat(types.get(Set.of("p.Parent`1")).keySet()).containsExactlyInAnyOrder("p.Parent", "java.lang.Object"); + } + + private static List supertypesOf(String name) { + return switch (name) { + case "p.Child" -> List.of("p.Parent", "p.Marker", "java.lang.Object"); + case "p.Parent" -> List.of("java.lang.Object"); + default -> List.of(); + }; + } +} From 0c19a7f320902124aa47a797fe7ae8696d27c8d4 Mon Sep 17 00:00:00 2001 From: rombirli Date: Wed, 25 Nov 2026 10:09:26 +0100 Subject: [PATCH 2/2] JAVA-7395 Add SemSitterParser, reporting the files it does not support as parse errors --- java-frontend-semsitter/pom.xml | 5 + .../java/semsitter/DocumentTranslator.java | 44 ++ .../sonar/java/semsitter/ParseProgress.java | 105 +++++ .../sonar/java/semsitter/SemSitterParser.java | 227 ++++++++++ .../UnsupportedConstructException.java | 28 ++ .../sonar/java/semsitter/ScriptedServer.java | 114 +++++ .../java/semsitter/SemSitterParserTest.java | 390 ++++++++++++++++++ 7 files changed, 913 insertions(+) create mode 100644 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/DocumentTranslator.java create mode 100644 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/ParseProgress.java create mode 100644 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterParser.java create mode 100644 java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/UnsupportedConstructException.java create mode 100644 java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ScriptedServer.java create mode 100644 java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterParserTest.java diff --git a/java-frontend-semsitter/pom.xml b/java-frontend-semsitter/pom.xml index e5fbd335a99..0f94896d2cf 100644 --- a/java-frontend-semsitter/pom.xml +++ b/java-frontend-semsitter/pom.xml @@ -47,6 +47,11 @@ sensor-test-fixtures test + + org.sonarsource.api.plugin + sonar-plugin-api-test-fixtures + test + ch.qos.logback logback-classic diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/DocumentTranslator.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/DocumentTranslator.java new file mode 100644 index 00000000000..047da9fa83d --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/DocumentTranslator.java @@ -0,0 +1,44 @@ +/* + * 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 java.util.Set; +import javax.annotation.Nullable; +import org.sonar.java.model.JParseResult; +import org.sonarsource.semsitter.wire.Document; + +/** + * Turns the document a SemSitter server answered for one file into the tree the checks run on. + */ +@FunctionalInterface +public interface DocumentTranslator { + + JParseResult translate(Document document, ServerLoaders loaders, boolean noLibraries, int javaVersion); + + /** What the server answers while the session is open. Both answers are null once it is closed. */ + interface ServerLoaders { + + /** The declarations of the named types. */ + @Nullable + JsonObject types(Set names); + + /** Whether the package {@code name} exists. */ + @Nullable + Boolean hasPackage(String name); + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/ParseProgress.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/ParseProgress.java new file mode 100644 index 00000000000..d5f826df78e --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/ParseProgress.java @@ -0,0 +1,105 @@ +/* + * 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.util.List; +import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.java.AnalysisProgress; +import org.sonar.java.model.JParser; +import org.sonarsource.analyzer.commons.ProgressReport; + +/** + * Progress of the files one call of {@link SemSitterParser#parse} goes through. File by file it is a + * {@link ProgressReport} over these files. In batch mode the calls are the batches of one analysis, so, like the + * default frontend, it logs the start on the first batch, the end on the last one, and in between the share of the + * whole analysis that is done. + */ +abstract class ParseProgress { + + static final long PERIOD_MILLIS = TimeUnit.SECONDS.toMillis(10); + + abstract void nextFile(); + + abstract void end(boolean completed); + + static ParseProgress start(JParser.Mode mode, List files, AnalysisProgress analysisProgress) { + return mode == JParser.Mode.BATCH ? new Batch(analysisProgress, files.size(), PERIOD_MILLIS) : new FileByFile(files); + } + + private static final class FileByFile extends ParseProgress { + private final ProgressReport report = new ProgressReport("Report about progress of Java AST analyzer", PERIOD_MILLIS); + + private FileByFile(List files) { + report.start(files.stream().map(InputFile::toString).toList()); + } + + @Override + void nextFile() { + report.nextFile(); + } + + @Override + void end(boolean completed) { + if (completed) { + report.stop(); + } else { + report.cancel(); + } + } + } + + static final class Batch extends ParseProgress { + private static final Logger LOG = LoggerFactory.getLogger(Batch.class); + + private final AnalysisProgress analysisProgress; + private final int files; + private final long periodNanos; + private int done; + private long lastLog; + + Batch(AnalysisProgress analysisProgress, int files, long periodMillis) { + this.analysisProgress = analysisProgress; + this.files = files; + this.periodNanos = TimeUnit.MILLISECONDS.toNanos(periodMillis); + this.lastLog = System.nanoTime(); + if (analysisProgress.isFirstBatch()) { + LOG.info("Starting batch processing."); + } + } + + @Override + void nextFile() { + done++; + long now = System.nanoTime(); + if (now - lastLog >= periodNanos) { + lastLog = now; + LOG.info("{}% analyzed", (int) (analysisProgress.toGlobalPercentage(done / (double) files) * 100)); + } + } + + @Override + void end(boolean completed) { + if (completed && analysisProgress.isLastBatch()) { + LOG.info("100% analyzed"); + LOG.info("Batch processing: Done."); + } + } + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterParser.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterParser.java new file mode 100644 index 00000000000..c102822859a --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterParser.java @@ -0,0 +1,227 @@ +/* + * 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 com.google.gson.stream.JsonReader; +import com.sonar.sslr.api.RecognitionException; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CancellationException; +import java.util.function.BiConsumer; +import java.util.function.BooleanSupplier; +import javax.annotation.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.java.AnalysisProgress; +import org.sonar.java.ExecutionTimeReport; +import org.sonar.java.model.JParseResult; +import org.sonar.java.model.JParser; +import org.sonar.plugins.java.api.JavaVersion; +import org.sonarsource.semsitter.wire.Document; + +/** + * The {@link JParser} backed by a SemSitter server. One server serves one call of {@link #parse}: it is started on the + * common directory of the files, scans them all, and answers one document per file, which the {@link DocumentTranslator} + * turns into the tree the checks run on. This frontend never hands files to another one: a server that cannot start + * fails the analysis, and a file the translator does not support yet is reported as a parse error. + */ +public final class SemSitterParser implements JParser { + + /** Starts a server on a project root. */ + @FunctionalInterface + public interface Launcher { + SemSitterApi start(Path projectRoot) throws IOException; + } + + private static final Logger LOG = LoggerFactory.getLogger(SemSitterParser.class); + + static final int FILES_AHEAD = 64; + + private final Mode mode; + private final JavaVersion javaVersion; + private final List classpath; + private final Launcher launcher; + private final DocumentTranslator translator; + private final Path javaHome; + + public SemSitterParser(Mode mode, JavaVersion javaVersion, List classpath, Launcher launcher, DocumentTranslator translator) { + this(mode, javaVersion, classpath, launcher, translator, Path.of(System.getProperty("java.home"))); + } + + SemSitterParser(Mode mode, JavaVersion javaVersion, List classpath, Launcher launcher, DocumentTranslator translator, Path javaHome) { + this.mode = mode; + this.javaVersion = javaVersion; + this.classpath = classpath; + this.launcher = launcher; + this.translator = translator; + this.javaHome = javaHome; + } + + @Override + public void parse(Iterable inputFiles, BooleanSupplier isCanceled, AnalysisProgress analysisProgress, BiConsumer action) { + List files = new ArrayList<>(); + inputFiles.forEach(files::add); + if (files.isEmpty()) { + return; + } + Path root = ProjectRoot.commonAncestor(files.stream().map(InputFile::path).toList()) + .orElseThrow(() -> new IllegalStateException("The files share no directory to start the SemSitter server on.")); + files.sort(Comparator.comparing(file -> ProjectRoot.relative(root, file.path()))); + scan(open(root, files), files, isCanceled, analysisProgress, action); + } + + private void scan(Session session, List files, BooleanSupplier isCanceled, AnalysisProgress analysisProgress, + BiConsumer action) { + ExecutionTimeReport executionTimeReport = new ExecutionTimeReport(); + ParseProgress progress = ParseProgress.start(mode, files, analysisProgress); + boolean completed = false; + try (session) { + boolean cancelled = false; + for (InputFile file : files) { + if (isCanceled.getAsBoolean()) { + if (mode == Mode.BATCH) { + throw new CancellationException("Analysis cancelled"); + } + cancelled = true; + break; + } + executionTimeReport.start(file); + action.accept(file, translate(session, file)); + executionTimeReport.end(); + progress.nextFile(); + } + completed = !cancelled; + } finally { + progress.end(completed); + if (mode == Mode.BATCH) { + executionTimeReport.reportAsBatch(); + } else { + executionTimeReport.report(); + } + } + } + + private static JParseResult translate(Session session, InputFile file) { + try { + return session.parse(file); + } catch (UnsupportedConstructException unsupported) { + return JParseResult.failure(new RecognitionException(0, unsupported.getMessage(), unsupported)); + } + } + + private Session open(Path root, List files) { + SemSitterApi api = null; + try { + api = launcher.start(root); + api.setSettings(SemSitterSettings.of(javaVersion, classpath, javaHome)); + api.fullGen(files.stream().map(file -> ProjectRoot.relative(root, file.path())).toList()); + return new Session(api, root, javaVersion.isNotSet() ? Integer.MAX_VALUE : javaVersion.asInt(), classpath.isEmpty(), translator); + } catch (IOException | RuntimeException e) { + if (api != null) { + api.close(); + } + throw new IllegalStateException("The SemSitter server could not start: " + e.getMessage(), e); + } + } + + /** The open server and what parsing one file against it needs. */ + private static final class Session implements AutoCloseable, DocumentTranslator.ServerLoaders { + private final SemSitterApi api; + private final Path root; + private final int javaVersion; + private final boolean noLibraries; + private final DocumentTranslator translator; + private final SessionTypes types; + private volatile boolean open = true; + + private Session(SemSitterApi api, Path root, int javaVersion, boolean noLibraries, DocumentTranslator translator) { + this.api = api; + this.root = root; + this.javaVersion = javaVersion; + this.noLibraries = noLibraries; + this.translator = translator; + this.types = new SessionTypes(this::serverTypes); + } + + private JParseResult parse(InputFile file) { + if (!file.filename().endsWith(".java")) { + return JParseResult.failure(new RecognitionException(1, "Parse error: unsupported file suffix for " + file.filename())); + } + try { + Document document = api.getFile(ProjectRoot.relative(root, file.path()), FILES_AHEAD); + return translator.translate(document, this, noLibraries, javaVersion); + } catch (UnsupportedConstructException unsupported) { + throw unsupported; + } catch (RecognitionException syntaxError) { + return JParseResult.failure(syntaxError); + } catch (IOException | RuntimeException failure) { + LOG.error("SemSitter: unable to parse file {}", file, failure); + return JParseResult.failure(new RecognitionException(-1, "SemSitter: unable to parse file.", failure)); + } + } + + @Nullable + @Override + public JsonObject types(Set names) { + if (!open) { + return null; + } + return types.get(names); + } + + private JsonObject serverTypes(Set names) { + try { + JsonReader reader = new JsonReader(new InputStreamReader(new ByteArrayInputStream(api.getTypes(names)), StandardCharsets.UTF_8)); + reader.setNestingLimit(Integer.MAX_VALUE); + return JsonParser.parseReader(reader).getAsJsonObject(); + } catch (IOException failure) { + throw new UncheckedIOException(failure); + } + } + + @Nullable + @Override + public Boolean hasPackage(String name) { + if (!open) { + return null; + } + try { + return api.hasPackage(List.of(name)).get(name); + } catch (IOException failure) { + throw new UncheckedIOException(failure); + } + } + + @Override + public void close() { + open = false; + api.close(); + } + } +} diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/UnsupportedConstructException.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/UnsupportedConstructException.java new file mode 100644 index 00000000000..36adadfb36b --- /dev/null +++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/UnsupportedConstructException.java @@ -0,0 +1,28 @@ +/* + * 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; + +/** + * Thrown by a {@link DocumentTranslator} for a construct it cannot translate. The file is then reported as a parse + * error, like a file the default frontend cannot parse, and the analysis goes on with the other files. + */ +public final class UnsupportedConstructException extends RuntimeException { + + public UnsupportedConstructException(String construct) { + super("Unsupported construct: " + construct); + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ScriptedServer.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ScriptedServer.java new file mode 100644 index 00000000000..979095fa883 --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ScriptedServer.java @@ -0,0 +1,114 @@ +/* + * 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.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.sonarsource.semsitter.wire.Document; +import org.sonarsource.semsitter.wire.Node; + +/** + * An in-memory {@link SemSitterApi}: it answers {@code get-file} from the documents it was given and records every request. + * With {@code declarations}, {@code get-types} answers each declaration once, as the server does in a session; without, + * it answers {@code types}. + */ +final class ScriptedServer implements SemSitterApi { + + final List requests = new ArrayList<>(); + final List scanned = new ArrayList<>(); + final Set failing = new HashSet<>(); + final Map documents = new HashMap<>(); + final Map packages = new HashMap<>(); + String types = "{}"; + final Map declarations = new HashMap<>(); + private final Set sentTypes = new HashSet<>(); + Map> settings; + int ahead = -1; + boolean closed; + IOException settingsFailure; + IOException loaderFailure; + + static Document emptyFile(String path) { + return Document.newBuilder().setPath(path).setSemantic(true).setTree(Node.newBuilder().setKind("program")).build(); + } + + @Override + public void setSettings(Map> settings) throws IOException { + requests.add("set-settings"); + if (settingsFailure != null) { + throw settingsFailure; + } + this.settings = settings; + } + + @Override + public int fullGen(Collection files) { + requests.add("full-gen"); + scanned.addAll(files); + return files.size(); + } + + @Override + public Document getFile(String path, int ahead) throws IOException { + requests.add("get-file " + path); + this.ahead = ahead; + if (failing.contains(path)) { + throw new IOException("SemSitter server: no such file " + path); + } + return documents.getOrDefault(path, emptyFile(path)); + } + + @Override + public byte[] getTypes(Collection names) throws IOException { + requests.add("get-types"); + if (loaderFailure != null) { + throw loaderFailure; + } + if (declarations.isEmpty()) { + return types.getBytes(StandardCharsets.UTF_8); + } + JsonObject answer = new JsonObject(); + names.stream().filter(declarations::containsKey).filter(sentTypes::add) + .forEach(name -> answer.add(name, JsonParser.parseString(declarations.get(name)))); + return answer.toString().getBytes(StandardCharsets.UTF_8); + } + + @Override + public Map hasPackage(Collection names) throws IOException { + requests.add("has-package"); + if (loaderFailure != null) { + throw loaderFailure; + } + Map answer = new HashMap<>(); + names.forEach(name -> answer.put(name, packages.getOrDefault(name, false))); + return answer; + } + + @Override + public void close() { + closed = true; + } +} diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterParserTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterParserTest.java new file mode 100644 index 00000000000..eb9f3e6269b --- /dev/null +++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterParserTest.java @@ -0,0 +1,390 @@ +/* + * 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.sonar.sslr.api.RecognitionException; +import com.sonarsource.scanner.engine.sensor.test.fixtures.TestInputFileBuilder; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CancellationException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BooleanSupplier; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.slf4j.event.Level; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.testfixtures.log.LogTesterJUnit5; +import org.sonar.java.AnalysisProgress; +import org.sonar.java.model.JParseResult; +import org.sonar.java.model.JParser; +import org.sonar.java.model.JavaTree; +import org.sonar.java.model.JavaVersionImpl; +import org.sonarsource.semsitter.wire.Document; +import org.sonarsource.semsitter.wire.Node; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class SemSitterParserTest { + + @RegisterExtension + LogTesterJUnit5 logTester = new LogTesterJUnit5().setLevel(Level.DEBUG); + + @TempDir + Path project; + + private final ScriptedServer server = new ScriptedServer(); + private final Map results = new LinkedHashMap<>(); + + private final Set unsupported = new HashSet<>(); + + @Test + void every_file_is_parsed_against_one_server_started_on_the_common_directory() throws Exception { + InputFile b = file("src/p/B.java"); + InputFile a = file("src/p/q/A.java"); + AtomicInteger starts = new AtomicInteger(); + Path[] startedOn = new Path[1]; + + parser(JParser.Mode.FILE_BY_FILE, new JavaVersionImpl(17), List.of(new File("lib.jar")), root -> { + starts.incrementAndGet(); + startedOn[0] = root; + return server; + }).parse(List.of(b, a), () -> false, new AnalysisProgress(2), this::collect); + + assertThat(starts).hasValue(1); + assertThat(realPath(startedOn[0])).isEqualTo(realPath(project.resolve("src").resolve("p"))); + assertThat(server.scanned).containsExactly("B.java", "q/A.java"); + assertThat(server.requests).containsExactly("set-settings", "full-gen", "get-file B.java", "get-file q/A.java"); + assertThat(server.closed).isTrue(); + assertThat(results.keySet()).containsExactly("B.java", "A.java"); + for (JParseResult result : results.values()) { + assertThat(result.get()).isInstanceOf(JavaTree.CompilationUnitTreeImpl.class); + } + } + + @Test + void files_are_parsed_in_the_order_the_server_scans_them() { + InputFile z = file("Z.java"); + InputFile a = file("A.java"); + + parser(JParser.Mode.BATCH, new JavaVersionImpl(), List.of(), root -> server).parse(List.of(z, a), () -> false, new AnalysisProgress(2), this::collect); + + assertThat(server.requests).containsExactly("set-settings", "full-gen", "get-file A.java", "get-file Z.java"); + assertThat(server.ahead).isEqualTo(SemSitterParser.FILES_AHEAD); + } + + @Test + void every_file_gets_the_types_the_server_already_sent_for_another_file() { + server.declarations.put("org.junit.Test", "{\"kind\":\"annotation\"}"); + Map> declared = new LinkedHashMap<>(); + DocumentTranslator recording = (document, loaders, noLibraries, javaVersion) -> { + declared.put(document.getPath(), loaders.types(Set.of("org.junit.Test")).keySet()); + return JParseResult.failure(new RecognitionException(1, "translated")); + }; + + new SemSitterParser(JParser.Mode.BATCH, new JavaVersionImpl(), List.of(), root -> server, recording, project.resolve("no-jdk")) + .parse(List.of(file("ATest.java"), file("BTest.java")), () -> false, new AnalysisProgress(2), this::collect); + + assertThat(declared).containsOnlyKeys("ATest.java", "BTest.java").allSatisfy((path, types) -> assertThat(types).containsExactly("org.junit.Test")); + assertThat(server.requests).containsOnlyOnce("get-types"); + } + + @Test + void loaders_answer_while_the_session_is_open_and_nothing_once_it_is_closed() { + server.packages.put("p", true); + List sessions = new ArrayList<>(); + List answers = new ArrayList<>(); + DocumentTranslator recording = (document, loaders, noLibraries, javaVersion) -> { + sessions.add(loaders); + answers.add(loaders.hasPackage("p")); + answers.add(loaders.hasPackage("zz")); + return JParseResult.failure(new RecognitionException(1, "translated")); + }; + + new SemSitterParser(JParser.Mode.BATCH, new JavaVersionImpl(), List.of(), root -> server, recording, project.resolve("no-jdk")) + .parse(List.of(file("A.java")), () -> false, new AnalysisProgress(1), this::collect); + + assertThat(answers).containsExactly(true, false); + assertThat(sessions.getFirst().types(Set.of("java.lang.String"))).isNull(); + assertThat(sessions.getFirst().hasPackage("p")).isNull(); + } + + @Test + void file_fails_alone_when_the_server_cannot_answer_a_loader() { + server.loaderFailure = new IOException("broken pipe"); + DocumentTranslator loading = (document, loaders, noLibraries, javaVersion) -> { + if ("A.java".equals(document.getPath())) { + loaders.types(Set.of("java.lang.String")); + } else { + loaders.hasPackage("p"); + } + return JParseResult.failure(new RecognitionException(1, "translated")); + }; + + new SemSitterParser(JParser.Mode.FILE_BY_FILE, new JavaVersionImpl(), List.of(), root -> server, loading, project.resolve("no-jdk")) + .parse(List.of(file("A.java"), file("B.java")), () -> false, new AnalysisProgress(2), this::collect); + + assertThatThrownBy(results.get("A.java")::get).hasMessageContaining("SemSitter: unable to parse file."); + assertThatThrownBy(results.get("B.java")::get).hasMessageContaining("SemSitter: unable to parse file."); + } + + @Test + void session_settings_describe_the_project() { + parser(JParser.Mode.BATCH, new JavaVersionImpl(21), List.of(new File("lib.jar")), root -> server) + .parse(List.of(file("A.java")), () -> false, new AnalysisProgress(1), this::collect); + + assertThat(server.settings).containsEntry(SemSitterSettings.JAVA_VERSION, List.of("21")); + assertThat(server.settings.get(SemSitterSettings.LIBRARIES)).contains(new File("lib.jar").getAbsolutePath()); + } + + @Test + void nothing_is_started_without_files() { + AtomicInteger starts = new AtomicInteger(); + + parser(JParser.Mode.BATCH, new JavaVersionImpl(), List.of(), (SemSitterParser.Launcher) root -> { + starts.incrementAndGet(); + return server; + }).parse(List.of(), () -> false, new AnalysisProgress(0), this::collect); + + assertThat(starts).hasValue(0); + assertThat(results).isEmpty(); + } + + @Test + void the_analysis_fails_when_the_server_cannot_start() { + SemSitterParser parser = parser(JParser.Mode.BATCH, new JavaVersionImpl(), List.of(), (SemSitterParser.Launcher) root -> { + throw new IOException("no executable"); + }); + List files = List.of(file("A.java"), file("B.java")); + AnalysisProgress progress = new AnalysisProgress(2); + + assertThatThrownBy(() -> parser.parse(files, () -> false, progress, this::collect)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("The SemSitter server could not start: no executable"); + assertThat(results).isEmpty(); + } + + @Test + void the_analysis_fails_and_the_server_stops_when_the_session_cannot_be_prepared() { + server.settingsFailure = new IOException("rejected"); + SemSitterParser parser = parser(JParser.Mode.FILE_BY_FILE, new JavaVersionImpl(), List.of(), root -> server); + List files = List.of(file("A.java")); + AnalysisProgress progress = new AnalysisProgress(1); + + assertThatThrownBy(() -> parser.parse(files, () -> false, progress, this::collect)).hasMessage("The SemSitter server could not start: rejected"); + assertThat(results).isEmpty(); + assertThat(server.closed).isTrue(); + assertThat(server.requests).containsExactly("set-settings"); + } + + @Test + void file_the_server_cannot_answer_fails_alone() throws Exception { + server.failing.add("A.java"); + + parser(JParser.Mode.FILE_BY_FILE, new JavaVersionImpl(), List.of(), root -> server) + .parse(List.of(file("A.java"), file("B.java")), () -> false, new AnalysisProgress(2), this::collect); + + assertThatThrownBy(results.get("A.java")::get) + .isInstanceOf(RecognitionException.class) + .hasMessageContaining("SemSitter: unable to parse file."); + assertThat(results.get("B.java").get()).isNotNull(); + } + + @Test + void syntax_error_of_the_translator_is_the_parse_error_of_the_file() { + server.documents.put("A.java", Document.newBuilder().setPath("A.java").setHasError(true) + .setTree(Node.newBuilder().setKind("program")).build()); + + parser(JParser.Mode.FILE_BY_FILE, new JavaVersionImpl(), List.of(), root -> server) + .parse(List.of(file("A.java")), () -> false, new AnalysisProgress(1), this::collect); + + assertThatThrownBy(results.get("A.java")::get) + .isInstanceOf(RecognitionException.class) + .hasMessage("Syntax error in A.java"); + } + + @Test + void a_file_the_translator_does_not_support_is_a_parse_error_and_the_others_are_parsed() throws Exception { + unsupported.add("A.java"); + + parser(JParser.Mode.FILE_BY_FILE, new JavaVersionImpl(), List.of(), root -> server) + .parse(List.of(file("A.java"), file("B.java")), () -> false, new AnalysisProgress(2), this::collect); + + assertThat(results.keySet()).containsExactly("A.java", "B.java"); + assertThatThrownBy(results.get("A.java")::get) + .isInstanceOf(RecognitionException.class) + .hasMessage("Unsupported construct: lambda") + .hasCauseInstanceOf(UnsupportedConstructException.class); + assertThat(results.get("B.java").get()).isInstanceOf(JavaTree.CompilationUnitTreeImpl.class); + } + + @Test + void batches_log_the_progress_of_the_whole_analysis() { + AnalysisProgress analysisProgress = new AnalysisProgress(4); + SemSitterParser parser = parser(JParser.Mode.BATCH, new JavaVersionImpl(), List.of(), root -> server); + + analysisProgress.startBatch(2); + parser.parse(List.of(file("A.java"), file("B.java")), () -> false, analysisProgress, this::collect); + analysisProgress.endBatch(); + assertThat(logTester.logs(Level.INFO)).contains("Starting batch processing.").doesNotContain("100% analyzed", "Batch processing: Done."); + + analysisProgress.startBatch(2); + parser.parse(List.of(file("C.java"), file("D.java")), () -> false, analysisProgress, this::collect); + analysisProgress.endBatch(); + assertThat(logTester.logs(Level.INFO)) + .containsOnlyOnce("Starting batch processing.") + .containsSubsequence("Starting batch processing.", "100% analyzed", "Batch processing: Done."); + } + + @Test + void batch_logs_the_share_of_the_analysis_done_once_a_period_has_passed() { + AnalysisProgress analysisProgress = new AnalysisProgress(4); + analysisProgress.startBatch(2); + analysisProgress.endBatch(); + analysisProgress.startBatch(2); + + ParseProgress progress = new ParseProgress.Batch(analysisProgress, 2, 0); + progress.nextFile(); + progress.end(false); + + assertThat(logTester.logs(Level.INFO)).containsExactly("75% analyzed"); + } + + @Test + void file_with_another_suffix_is_not_parsed() { + parser(JParser.Mode.FILE_BY_FILE, new JavaVersionImpl(), List.of(), root -> server) + .parse(List.of(file("A.jav")), () -> false, new AnalysisProgress(1), this::collect); + + assertThatThrownBy(results.get("A.jav")::get) + .isInstanceOf(RecognitionException.class) + .hasMessage("Parse error: unsupported file suffix for A.jav"); + assertThat(server.requests).doesNotContain("get-file A.jav"); + } + + @Test + void file_by_file_stops_quietly_when_the_analysis_is_cancelled() { + BooleanSupplier cancelAfterFirst = () -> !results.isEmpty(); + + parser(JParser.Mode.FILE_BY_FILE, new JavaVersionImpl(), List.of(), root -> server) + .parse(List.of(file("A.java"), file("B.java")), cancelAfterFirst, new AnalysisProgress(2), this::collect); + + assertThat(results.keySet()).containsExactly("A.java"); + assertThat(server.closed).isTrue(); + } + + @Test + void batch_raises_a_cancellation_and_still_stops_the_server() { + BooleanSupplier cancelAfterFirst = () -> !results.isEmpty(); + SemSitterParser parser = parser(JParser.Mode.BATCH, new JavaVersionImpl(), List.of(), root -> server); + List files = List.of(file("A.java"), file("B.java")); + AnalysisProgress progress = new AnalysisProgress(2); + + assertThatThrownBy(() -> parser.parse(files, cancelAfterFirst, progress, this::collect)).isInstanceOf(CancellationException.class); + + assertThat(results.keySet()).containsExactly("A.java"); + assertThat(server.closed).isTrue(); + } + + @Test + void files_sharing_no_directory_fail_the_analysis() throws IOException { + try (FileSystem otherDrive = FileSystems.newFileSystem(project.resolve("drive.zip"), Map.of("create", "true"))) { + InputFile elsewhere = new TestInputFileBuilder("module", "B.java") + .setModuleBaseDir(otherDrive.getPath("/")) + .setCharset(StandardCharsets.UTF_8) + .setLanguage("java") + .setContents("class B {}") + .build(); + + SemSitterParser parser = parser(JParser.Mode.BATCH, new JavaVersionImpl(), List.of(), root -> server); + List files = List.of(file("A.java"), elsewhere); + AnalysisProgress progress = new AnalysisProgress(2); + + assertThatThrownBy(() -> parser.parse(files, () -> false, progress, this::collect)) + .hasMessage("The files share no directory to start the SemSitter server on."); + } + + assertThat(server.requests).isEmpty(); + } + + @Test + void server_stops_when_the_callback_fails() { + SemSitterParser parser = parser(JParser.Mode.BATCH, new JavaVersionImpl(), List.of(), root -> server); + List files = List.of(file("A.java")); + AnalysisProgress progress = new AnalysisProgress(1); + + assertThatThrownBy(() -> parser.parse(files, () -> false, progress, (input, result) -> { + throw new IllegalStateException("check failed"); + })).isInstanceOf(IllegalStateException.class); + + assertThat(server.closed).isTrue(); + } + + private SemSitterParser parser(JParser.Mode mode, JavaVersionImpl version, List classpath, SemSitterParser.Launcher launcher) { + return new SemSitterParser(mode, version, classpath, launcher, this::translate, project.resolve("no-jdk")); + } + + private JParseResult translate(Document document, DocumentTranslator.ServerLoaders loaders, boolean noLibraries, int javaVersion) { + if (unsupported.contains(document.getPath())) { + throw new UnsupportedConstructException("lambda"); + } + if (document.getHasError()) { + throw new RecognitionException(1, "Syntax error in " + document.getPath()); + } + return JParseResult.success(JParser.parse(file(document.getPath()), List.of(), new JavaVersionImpl())); + } + + private void collect(InputFile file, JParseResult result) { + results.put(file.filename(), result); + } + + /** + * The real path of {@code path}, resolved from the nearest existing parent so a short Windows name and a + * macOS {@code /var} symlink compare equal to the path the scanner reports. + */ + private static Path realPath(Path path) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + Path existing = absolute; + while (existing != null && !Files.exists(existing)) { + existing = existing.getParent(); + } + if (existing == null) { + return absolute; + } + return existing.toRealPath().resolve(existing.relativize(absolute)); + } + + private InputFile file(String relativePath) { + return new TestInputFileBuilder("module", relativePath) + .setModuleBaseDir(project) + .setCharset(StandardCharsets.UTF_8) + .setLanguage("java") + .setContents("class A {}") + .build(); + } +}