diff --git a/java-frontend-semsitter/pom.xml b/java-frontend-semsitter/pom.xml
index 5b55f92b446..465e976dccc 100644
--- a/java-frontend-semsitter/pom.xml
+++ b/java-frontend-semsitter/pom.xml
@@ -14,6 +14,21 @@
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
@@ -22,6 +37,21 @@
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
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..ddf77c14f85
--- /dev/null
+++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/DocumentTranslator.java
@@ -0,0 +1,34 @@
+/*
+ * 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 java.util.function.Function;
+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. The loaders give the
+ * declarations of the named types and whether a package exists, as the server answers them while the session is open.
+ */
+@FunctionalInterface
+public interface DocumentTranslator {
+
+ JParseResult translate(Document document, Function, JsonObject> types, Function packages, boolean noLibraries,
+ int javaVersion);
+}
diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/FeatureFlags.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/FeatureFlags.java
new file mode 100644
index 00000000000..aeb3272dc19
--- /dev/null
+++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/FeatureFlags.java
@@ -0,0 +1,34 @@
+/*
+ * 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;
+
+/**
+ * Remote switches that decide which behavior an analysis gets.
+ */
+public interface FeatureFlags {
+
+ /** Opens a flag service for one project. */
+ @FunctionalInterface
+ interface Connector {
+ FeatureFlags connect(String clientSideId, String projectKey);
+ }
+
+ /**
+ * @return the value of the flag, or {@code defaultValue} when the service cannot tell
+ */
+ boolean isEnabled(String flagKey, boolean defaultValue);
+}
diff --git a/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/LaunchDarklyFeatureFlags.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/LaunchDarklyFeatureFlags.java
new file mode 100644
index 00000000000..1f85e7a9d0f
--- /dev/null
+++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/LaunchDarklyFeatureFlags.java
@@ -0,0 +1,95 @@
+/*
+ * 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 com.google.gson.JsonParser;
+import java.io.IOException;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.Base64;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * {@link FeatureFlags} read from LaunchDarkly through its client-side evaluation endpoint, which keeps the plugin free of
+ * the LaunchDarkly SDK and of everything the SDK drags along. The flags of a project are fetched once when the service
+ * is opened, no analytics event is sent, and a service that does not answer in time leaves every flag at its default.
+ */
+public final class LaunchDarklyFeatureFlags implements FeatureFlags {
+
+ static final String PROJECT_KIND = "project";
+ static final String ENDPOINT = "https://clientsdk.launchdarkly.com";
+ static final Duration TIMEOUT = Duration.ofSeconds(3);
+
+ private static final Logger LOG = LoggerFactory.getLogger(LaunchDarklyFeatureFlags.class);
+
+ private final JsonObject flags;
+
+ LaunchDarklyFeatureFlags(JsonObject flags) {
+ this.flags = flags;
+ }
+
+ public static FeatureFlags connect(String clientSideId, String projectKey) {
+ return connect(URI.create(ENDPOINT), clientSideId, projectKey);
+ }
+
+ static FeatureFlags connect(URI endpoint, String clientSideId, String projectKey) {
+ try {
+ return new LaunchDarklyFeatureFlags(fetch(endpoint, clientSideId, projectKey));
+ } catch (IOException | RuntimeException e) {
+ LOG.debug("LaunchDarkly is not reachable, every flag keeps its default value: {}", e.getMessage());
+ return new LaunchDarklyFeatureFlags(new JsonObject());
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return new LaunchDarklyFeatureFlags(new JsonObject());
+ }
+ }
+
+ private static JsonObject fetch(URI endpoint, String clientSideId, String projectKey) throws IOException, InterruptedException {
+ JsonObject context = new JsonObject();
+ context.addProperty("kind", PROJECT_KIND);
+ context.addProperty("key", projectKey);
+ String encodedContext = Base64.getUrlEncoder().encodeToString(context.toString().getBytes(StandardCharsets.UTF_8));
+ URI uri = URI.create(endpoint + "/sdk/evalx/" + clientSideId + "/contexts/" + encodedContext);
+ HttpRequest request = HttpRequest.newBuilder(uri).timeout(TIMEOUT).GET().build();
+ HttpClient client = HttpClient.newBuilder().connectTimeout(TIMEOUT).build();
+ HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
+ if (response.statusCode() != 200) {
+ throw new IOException("unexpected status " + response.statusCode());
+ }
+ return JsonParser.parseString(response.body()).getAsJsonObject();
+ }
+
+ @Override
+ public boolean isEnabled(String flagKey, boolean defaultValue) {
+ JsonElement flag = flags.get(flagKey);
+ if (flag == null || !flag.isJsonObject()) {
+ return defaultValue;
+ }
+ JsonElement value = flag.getAsJsonObject().get("value");
+ if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isBoolean()) {
+ return defaultValue;
+ }
+ return value.getAsBoolean();
+ }
+}
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..97ec23992e5
--- /dev/null
+++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/ProjectRoot.java
@@ -0,0 +1,59 @@
+/*
+ * 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;
+
+/**
+ * The directory a SemSitter server is started on.
+ */
+final class ProjectRoot {
+
+ private ProjectRoot() {
+ }
+
+ /**
+ * @return the deepest directory that contains every file, or the file system root of the first file when they share none
+ */
+ static Path commonAncestor(Collection files) {
+ Path common = null;
+ for (Path file : files) {
+ Path directory = file.toAbsolutePath().normalize().getParent();
+ common = common == null ? directory : shared(common, directory);
+ }
+ if (common == null) {
+ throw new IllegalArgumentException("No file to find a project root for");
+ }
+ return common;
+ }
+
+ private static Path shared(Path first, Path second) {
+ Path candidate = first;
+ while (candidate != null && !second.startsWith(candidate)) {
+ candidate = candidate.getParent();
+ }
+ return candidate == null ? first.getRoot() : 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/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
index 5c26e3966d4..aa217bb7e9a 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
@@ -41,7 +41,7 @@
* 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 {
+public final class SemSitterClient implements SemSitterApi {
static final String PROTOCOL_MAJOR = "2";
@@ -89,6 +89,7 @@ static List command(List launcher, Path projectRoot) {
return command;
}
+ @Override
public void setSettings(Map> settings) throws IOException {
JsonObject request = command("set-settings");
JsonObject values = new JsonObject();
@@ -105,6 +106,7 @@ public void setSettings(Map> settings) throws IOException {
* 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 = command("full-gen");
if (!files.isEmpty()) {
@@ -115,6 +117,7 @@ public int fullGen(Collection files) throws IOException {
return send(request).get("files").getAsInt();
}
+ @Override
public Document getFile(String path, int ahead) throws IOException {
JsonObject request = command("get-file");
request.addProperty("path", path);
@@ -127,6 +130,7 @@ public Document getFile(String path, int ahead) throws IOException {
/**
* @return the JSON object of declarations, as {@code types.schema.json} describes it
*/
+ @Override
public byte[] getTypes(Collection names) throws IOException {
JsonObject request = command("get-types");
JsonArray array = new JsonArray();
@@ -135,6 +139,7 @@ public byte[] getTypes(Collection names) throws IOException {
return exchange(request).payload;
}
+ @Override
public Map hasPackage(Collection names) throws IOException {
JsonObject request = command("has-package");
JsonArray array = new JsonArray();
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..e7244acfc55
--- /dev/null
+++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterParser.java
@@ -0,0 +1,230 @@
+/*
+ * 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.concurrent.TimeUnit;
+import java.util.function.BiConsumer;
+import java.util.function.BooleanSupplier;
+import java.util.function.Supplier;
+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.analyzer.commons.ProgressReport;
+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. When the server cannot be started the files go to the {@code fallback} parser,
+ * so a missing executable never costs an analysis.
+ */
+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 Supplier fallback;
+ private final DocumentTranslator translator;
+ private final Path javaHome;
+
+ public SemSitterParser(Mode mode, JavaVersion javaVersion, List classpath, Launcher launcher, Supplier fallback, DocumentTranslator translator) {
+ this(mode, javaVersion, classpath, launcher, fallback, translator, Path.of(System.getProperty("java.home")));
+ }
+
+ SemSitterParser(Mode mode, JavaVersion javaVersion, List classpath, Launcher launcher, Supplier fallback, DocumentTranslator translator,
+ Path javaHome) {
+ this.mode = mode;
+ this.javaVersion = javaVersion;
+ this.classpath = classpath;
+ this.launcher = launcher;
+ this.fallback = fallback;
+ 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());
+ files.sort(Comparator.comparing(file -> ProjectRoot.relative(root, file.path())));
+ Session session = open(root, files);
+ if (session == null) {
+ fallback.get().parse(files, isCanceled, analysisProgress, action);
+ return;
+ }
+ scan(session, files, isCanceled, action);
+ }
+
+ private void scan(Session session, List files, BooleanSupplier isCanceled, BiConsumer action) {
+ ExecutionTimeReport executionTimeReport = new ExecutionTimeReport();
+ ProgressReport progressReport = new ProgressReport("Report about progress of Java AST analyzer", TimeUnit.SECONDS.toMillis(10));
+ progressReport.start(files.stream().map(InputFile::toString).toList());
+ boolean completed = false;
+ try (session) {
+ for (InputFile file : files) {
+ if (isCanceled.getAsBoolean()) {
+ if (mode == Mode.BATCH) {
+ throw new CancellationException("Analysis cancelled");
+ }
+ break;
+ }
+ executionTimeReport.start(file);
+ action.accept(file, session.parse(file));
+ executionTimeReport.end();
+ progressReport.nextFile();
+ }
+ completed = true;
+ } finally {
+ if (completed) {
+ progressReport.stop();
+ } else {
+ progressReport.cancel();
+ }
+ if (mode == Mode.BATCH) {
+ executionTimeReport.reportAsBatch();
+ } else {
+ executionTimeReport.report();
+ }
+ }
+ }
+
+ @Nullable
+ 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) {
+ LOG.warn("SemSitter frontend could not start, falling back to the default one: {}", e.getMessage());
+ if (api != null) {
+ api.close();
+ }
+ return null;
+ }
+ }
+
+ /** The open server and what parsing one file against it needs. */
+ private static final class Session implements AutoCloseable {
+ 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::types, this::hasPackage, noLibraries, javaVersion);
+ } 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));
+ }
+ }
+
+ /** The declarations of the named types, or null once the server is closed: a type met after that stays as it was. */
+ @Nullable
+ private 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
+ private 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/SemSitterParserProvider.java b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterParserProvider.java
new file mode 100644
index 00000000000..45b4716ad55
--- /dev/null
+++ b/java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterParserProvider.java
@@ -0,0 +1,118 @@
+/*
+ * 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.Path;
+import java.util.List;
+import java.util.Optional;
+import java.util.function.Supplier;
+import java.util.function.UnaryOperator;
+import javax.annotation.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.sonar.api.config.Configuration;
+import org.sonar.java.jdt.JDTParser;
+import org.sonar.java.model.JParser;
+import org.sonar.java.model.JParserProvider;
+import org.sonar.plugins.java.api.JavaVersion;
+
+/**
+ * Offers the SemSitter frontend when the analysis is allowed to use it. It is allowed when a SemSitter executable is
+ * known and either {@value #ENABLED_PROPERTY} says so or, when that property is not set, the LaunchDarkly flag
+ * {@value #FLAG_KEY} is on for the project. Anything that goes wrong while asking leaves the default frontend in use.
+ */
+public final class SemSitterParserProvider implements JParserProvider {
+
+ public static final String FLAG_KEY = "sonar-java-semsitter-frontend";
+ public static final String ENABLED_PROPERTY = "sonar.java.semsitter.enabled";
+ public static final String EXECUTABLE_PROPERTY = "sonar.java.semsitter.executable";
+ public static final String CLIENT_ID_PROPERTY = "sonar.java.semsitter.launchDarkly.clientSideId";
+ public static final String EXECUTABLE_ENVIRONMENT = "SEMSITTER_ANALYZER";
+ public static final String CLIENT_ID_ENVIRONMENT = "SONAR_JAVA_LAUNCHDARKLY_CLIENT_ID";
+ static final boolean FLAG_DEFAULT = false;
+
+ private static final Logger LOG = LoggerFactory.getLogger(SemSitterParserProvider.class);
+ private static final String PROJECT_KEY_PROPERTY = "sonar.projectKey";
+ private static final String UNKNOWN_PROJECT = "unknown";
+
+ private final FeatureFlags.Connector flags;
+ private final UnaryOperator environment;
+ @Nullable
+ private final DocumentTranslator translator;
+ private volatile boolean enabled;
+ private volatile Path executable;
+
+ public SemSitterParserProvider() {
+ this(LaunchDarklyFeatureFlags::connect, System::getenv, null);
+ }
+
+ SemSitterParserProvider(FeatureFlags.Connector flags, UnaryOperator environment, @Nullable DocumentTranslator translator) {
+ this.flags = flags;
+ this.environment = environment;
+ this.translator = translator;
+ }
+
+ @Override
+ public void configure(Configuration configuration) {
+ enabled = false;
+ executable = null;
+ Optional path = firstNonBlank(configuration.get(EXECUTABLE_PROPERTY), Optional.ofNullable(environment.apply(EXECUTABLE_ENVIRONMENT)));
+ if (path.isEmpty()) {
+ return;
+ }
+ executable = Path.of(path.get());
+ enabled = configuration.getBoolean(ENABLED_PROPERTY).orElseGet(() -> isFlagOn(configuration));
+ if (enabled) {
+ LOG.info("The Java analyzer will use the SemSitter frontend.");
+ }
+ }
+
+ private boolean isFlagOn(Configuration configuration) {
+ Optional clientId = firstNonBlank(configuration.get(CLIENT_ID_PROPERTY), Optional.ofNullable(environment.apply(CLIENT_ID_ENVIRONMENT)));
+ if (clientId.isEmpty()) {
+ return FLAG_DEFAULT;
+ }
+ String project = configuration.get(PROJECT_KEY_PROPERTY).orElse(UNKNOWN_PROJECT);
+ try {
+ return flags.connect(clientId.get(), project).isEnabled(FLAG_KEY, FLAG_DEFAULT);
+ } catch (RuntimeException e) {
+ LOG.warn("The SemSitter frontend flag could not be read, the default frontend is used: {}", e.getMessage());
+ return FLAG_DEFAULT;
+ }
+ }
+
+ private static Optional firstNonBlank(Optional first, Optional second) {
+ return first.filter(value -> !value.isBlank()).or(() -> second.filter(value -> !value.isBlank()));
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return enabled;
+ }
+
+ @Override
+ public JParser create(JParser.Mode mode, JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage,
+ boolean shouldUseJdkReleaseOption) {
+ Path server = executable;
+ Supplier defaultParser = () -> JDTParser.create(mode, javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption);
+ if (translator == null) {
+ return defaultParser.get();
+ }
+ return new SemSitterParser(mode, javaVersion, classpath, root -> SemSitterClient.start(server, root), defaultParser, translator);
+ }
+}
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/main/resources/META-INF/services/org.sonar.java.model.JParserProvider b/java-frontend-semsitter/src/main/resources/META-INF/services/org.sonar.java.model.JParserProvider
new file mode 100644
index 00000000000..af4b455c6fb
--- /dev/null
+++ b/java-frontend-semsitter/src/main/resources/META-INF/services/org.sonar.java.model.JParserProvider
@@ -0,0 +1 @@
+org.sonar.java.semsitter.SemSitterParserProvider
diff --git a/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/LaunchDarklyFeatureFlagsTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/LaunchDarklyFeatureFlagsTest.java
new file mode 100644
index 00000000000..0e16ec4cf1a
--- /dev/null
+++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/LaunchDarklyFeatureFlagsTest.java
@@ -0,0 +1,136 @@
+/*
+ * 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 com.sun.net.httpserver.HttpServer;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.List;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+class LaunchDarklyFeatureFlagsTest {
+
+ private static final String FLAG = "sonar-java-semsitter-frontend";
+
+ private final List requests = new ArrayList<>();
+ private HttpServer server;
+ private int status;
+ private String body;
+
+ @BeforeEach
+ void startServer() throws IOException {
+ status = 200;
+ body = "{}";
+ server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
+ server.createContext("/", exchange -> {
+ requests.add(exchange.getRequestURI().getPath());
+ byte[] answer = body.getBytes(StandardCharsets.UTF_8);
+ exchange.sendResponseHeaders(status, answer.length);
+ exchange.getResponseBody().write(answer);
+ exchange.close();
+ });
+ server.start();
+ }
+
+ @AfterEach
+ void stopServer() {
+ server.stop(0);
+ }
+
+ @Test
+ void flag_on_is_read() {
+ body = "{\"" + FLAG + "\":{\"value\":true,\"version\":3}}";
+
+ assertThat(flags("my-project").isEnabled(FLAG, false)).isTrue();
+ }
+
+ @Test
+ void flag_off_is_read() {
+ body = "{\"" + FLAG + "\":{\"value\":false,\"version\":3}}";
+
+ assertThat(flags("my-project").isEnabled(FLAG, true)).isFalse();
+ }
+
+ @Test
+ void request_targets_the_client_side_id_and_the_project_context() {
+ flags("my-project");
+
+ assertThat(requests).hasSize(1);
+ String[] path = requests.get(0).split("/");
+ assertThat(path).startsWith("", "sdk", "evalx", "client-id", "contexts");
+ String context = new String(Base64.getUrlDecoder().decode(path[5]), StandardCharsets.UTF_8);
+ assertThat(JsonParser.parseString(context).getAsJsonObject().get("kind").getAsString()).isEqualTo("project");
+ assertThat(JsonParser.parseString(context).getAsJsonObject().get("key").getAsString()).isEqualTo("my-project");
+ }
+
+ @Test
+ void unknown_flag_has_the_default_value() {
+ FeatureFlags flags = flags("p");
+
+ assertThat(flags.isEnabled("missing", true)).isTrue();
+ assertThat(flags.isEnabled("missing", false)).isFalse();
+ }
+
+ @Test
+ void flag_that_is_not_a_boolean_has_the_default_value() {
+ body = "{\"" + FLAG + "\":{\"value\":\"yes\"},\"other\":3}";
+ FeatureFlags flags = flags("p");
+
+ assertThat(flags.isEnabled(FLAG, true)).isTrue();
+ assertThat(flags.isEnabled(FLAG, false)).isFalse();
+ assertThat(flags.isEnabled("other", false)).isFalse();
+ }
+
+ @Test
+ void failing_service_leaves_the_default_value() {
+ status = 500;
+ body = "{\"" + FLAG + "\":{\"value\":true}}";
+ FeatureFlags flags = flags("p");
+
+ assertThat(flags.isEnabled(FLAG, false)).isFalse();
+ assertThat(flags.isEnabled(FLAG, true)).isTrue();
+ }
+
+ @Test
+ void malformed_answer_leaves_the_default_value() {
+ body = "not json";
+
+ assertThat(flags("p").isEnabled(FLAG, true)).isTrue();
+ }
+
+ @Test
+ void unreachable_service_leaves_the_default_value() {
+ server.stop(0);
+
+ assertThat(flags("p").isEnabled(FLAG, true)).isTrue();
+ assertThat(flags("p").isEnabled(FLAG, false)).isFalse();
+ }
+
+ private FeatureFlags flags(String project) {
+ return LaunchDarklyFeatureFlags.connect(URI.create("http://127.0.0.1:" + server.getAddress().getPort()), "client-id", project);
+ }
+}
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..5712f8f48b0
--- /dev/null
+++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ProjectRootTest.java
@@ -0,0 +1,63 @@
+/*
+ * 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.List;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+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")))).isEqualTo(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)).isEqualTo(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)).isEqualTo(BASE.resolve("src/p"));
+ }
+
+ @Test
+ void relative_paths_are_made_absolute() {
+ assertThat(ProjectRoot.commonAncestor(List.of(Path.of("src/A.java")))).isEqualTo(Path.of("src").toAbsolutePath());
+ }
+
+ @Test
+ void no_file_has_no_root() {
+ assertThatThrownBy(() -> ProjectRoot.commonAncestor(List.of())).isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @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/ScriptedServer.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ScriptedServer.java
new file mode 100644
index 00000000000..e8ece7393a6
--- /dev/null
+++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/ScriptedServer.java
@@ -0,0 +1,107 @@
+/*
+ * 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;
+
+ 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) {
+ requests.add("get-types");
+ 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) {
+ requests.add("has-package");
+ 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/SemSitterParserProviderTest.java b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterParserProviderTest.java
new file mode 100644
index 00000000000..72b522a996a
--- /dev/null
+++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterParserProviderTest.java
@@ -0,0 +1,209 @@
+/*
+ * 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.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.function.UnaryOperator;
+import org.junit.jupiter.api.Test;
+import org.sonar.api.config.Configuration;
+import org.sonar.java.model.JParser;
+import org.sonar.java.model.JavaVersionImpl;
+import org.sonar.scanner.plugin.api.impl.config.MapSettings;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+class SemSitterParserProviderTest {
+
+ private final List connections = new ArrayList<>();
+ private boolean flagValue;
+ private RuntimeException connectionFailure;
+ private final DocumentTranslator translator = (document, types, packages, noLibraries, javaVersion) -> {
+ throw new UnsupportedOperationException();
+ };
+
+ private final FeatureFlags.Connector connector = (clientId, projectKey) -> {
+ if (connectionFailure != null) {
+ throw connectionFailure;
+ }
+ connections.add(clientId + "@" + projectKey);
+ return new FeatureFlags() {
+ @Override
+ public boolean isEnabled(String flagKey, boolean defaultValue) {
+ return flagKey.equals(SemSitterParserProvider.FLAG_KEY) && flagValue;
+ }
+ };
+ };
+
+ @Test
+ void provider_is_disabled_until_configured() {
+ assertThat(provider(Map.of()).isEnabled()).isFalse();
+ }
+
+ @Test
+ void provider_is_disabled_without_executable_and_never_asks_the_flag_service() {
+ SemSitterParserProvider provider = provider(Map.of());
+ flagValue = true;
+
+ provider.configure(settings(Map.of(SemSitterParserProvider.CLIENT_ID_PROPERTY, "sdk")));
+
+ assertThat(provider.isEnabled()).isFalse();
+ assertThat(connections).isEmpty();
+ }
+
+ @Test
+ void blank_executable_is_ignored() {
+ SemSitterParserProvider provider = provider(Map.of());
+
+ provider.configure(settings(Map.of(SemSitterParserProvider.EXECUTABLE_PROPERTY, " ", SemSitterParserProvider.ENABLED_PROPERTY, "true")));
+
+ assertThat(provider.isEnabled()).isFalse();
+ }
+
+ @Test
+ void explicit_property_enables_without_the_flag_service() {
+ SemSitterParserProvider provider = provider(Map.of());
+
+ provider.configure(settings(Map.of(SemSitterParserProvider.EXECUTABLE_PROPERTY, "/bin/semsitter", SemSitterParserProvider.ENABLED_PROPERTY, "true")));
+
+ assertThat(provider.isEnabled()).isTrue();
+ assertThat(connections).isEmpty();
+ }
+
+ @Test
+ void explicit_property_disables_even_when_the_flag_is_on() {
+ SemSitterParserProvider provider = provider(Map.of());
+ flagValue = true;
+
+ provider.configure(settings(Map.of(
+ SemSitterParserProvider.EXECUTABLE_PROPERTY, "/bin/semsitter",
+ SemSitterParserProvider.ENABLED_PROPERTY, "false",
+ SemSitterParserProvider.CLIENT_ID_PROPERTY, "sdk")));
+
+ assertThat(provider.isEnabled()).isFalse();
+ assertThat(connections).isEmpty();
+ }
+
+ @Test
+ void executable_can_come_from_the_environment() {
+ SemSitterParserProvider provider = provider(Map.of(SemSitterParserProvider.EXECUTABLE_ENVIRONMENT, "/bin/semsitter"));
+
+ provider.configure(settings(Map.of(SemSitterParserProvider.ENABLED_PROPERTY, "true")));
+
+ assertThat(provider.isEnabled()).isTrue();
+ }
+
+ @Test
+ void without_property_nor_client_id_the_default_frontend_stays() {
+ SemSitterParserProvider provider = provider(Map.of());
+
+ provider.configure(settings(Map.of(SemSitterParserProvider.EXECUTABLE_PROPERTY, "/bin/semsitter")));
+
+ assertThat(provider.isEnabled()).isEqualTo(SemSitterParserProvider.FLAG_DEFAULT);
+ assertThat(connections).isEmpty();
+ }
+
+ @Test
+ void flag_on_for_the_project_enables() {
+ SemSitterParserProvider provider = provider(Map.of());
+ flagValue = true;
+
+ provider.configure(settings(Map.of(
+ SemSitterParserProvider.EXECUTABLE_PROPERTY, "/bin/semsitter",
+ SemSitterParserProvider.CLIENT_ID_PROPERTY, "sdk",
+ "sonar.projectKey", "my-project")));
+
+ assertThat(provider.isEnabled()).isTrue();
+ assertThat(connections).containsExactly("sdk@my-project");
+ }
+
+ @Test
+ void flag_off_keeps_the_default_frontend() {
+ SemSitterParserProvider provider = provider(Map.of());
+ flagValue = false;
+
+ provider.configure(settings(Map.of(SemSitterParserProvider.EXECUTABLE_PROPERTY, "/bin/semsitter", SemSitterParserProvider.CLIENT_ID_PROPERTY, "sdk")));
+
+ assertThat(provider.isEnabled()).isFalse();
+ }
+
+ @Test
+ void client_id_can_come_from_the_environment_and_the_project_may_be_unknown() {
+ SemSitterParserProvider provider = provider(Map.of(SemSitterParserProvider.CLIENT_ID_ENVIRONMENT, "env-sdk"));
+ flagValue = true;
+
+ provider.configure(settings(Map.of(SemSitterParserProvider.EXECUTABLE_PROPERTY, "/bin/semsitter")));
+
+ assertThat(provider.isEnabled()).isTrue();
+ assertThat(connections).containsExactly("env-sdk@unknown");
+ }
+
+ @Test
+ void flag_service_failure_keeps_the_default_frontend() {
+ SemSitterParserProvider provider = provider(Map.of());
+ connectionFailure = new IllegalStateException("offline");
+
+ provider.configure(settings(Map.of(SemSitterParserProvider.EXECUTABLE_PROPERTY, "/bin/semsitter", SemSitterParserProvider.CLIENT_ID_PROPERTY, "sdk")));
+
+ assertThat(provider.isEnabled()).isFalse();
+ }
+
+ @Test
+ void configuring_again_forgets_the_previous_analysis() {
+ SemSitterParserProvider provider = provider(Map.of());
+ provider.configure(settings(Map.of(SemSitterParserProvider.EXECUTABLE_PROPERTY, "/bin/semsitter", SemSitterParserProvider.ENABLED_PROPERTY, "true")));
+ assertThat(provider.isEnabled()).isTrue();
+
+ provider.configure(settings(Map.of()));
+
+ assertThat(provider.isEnabled()).isFalse();
+ }
+
+ @Test
+ void created_parser_is_the_semsitter_parser_once_a_translator_is_available() {
+ SemSitterParserProvider provider = new SemSitterParserProvider(connector, Map.of()::get, translator);
+ provider.configure(settings(Map.of(SemSitterParserProvider.EXECUTABLE_PROPERTY, Path.of("semsitter").toString(), SemSitterParserProvider.ENABLED_PROPERTY, "true")));
+
+ JParser parser = provider.create(JParser.Mode.BATCH, new JavaVersionImpl(17), List.of(new File("a.jar")), false, true);
+
+ assertThat(parser).isInstanceOf(SemSitterParser.class);
+ }
+
+ @Test
+ void created_parser_is_the_default_frontend_without_a_translator() {
+ SemSitterParserProvider provider = provider(Map.of());
+ provider.configure(settings(Map.of(SemSitterParserProvider.EXECUTABLE_PROPERTY, Path.of("semsitter").toString(), SemSitterParserProvider.ENABLED_PROPERTY, "true")));
+
+ JParser parser = provider.create(JParser.Mode.BATCH, new JavaVersionImpl(17), List.of(new File("a.jar")), false, true);
+
+ assertThat(parser).isNotInstanceOf(SemSitterParser.class);
+ }
+
+ private SemSitterParserProvider provider(Map environment) {
+ UnaryOperator lookup = environment::get;
+ return new SemSitterParserProvider(connector, lookup, null);
+ }
+
+ private static Configuration settings(Map properties) {
+ MapSettings settings = new MapSettings();
+ properties.forEach(settings::setProperty);
+ return settings.asConfig();
+ }
+}
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..d45c4711b0b
--- /dev/null
+++ b/java-frontend-semsitter/src/test/java/org/sonar/java/semsitter/SemSitterParserTest.java
@@ -0,0 +1,250 @@
+/*
+ * 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.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+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.io.TempDir;
+import org.sonar.api.batch.fs.InputFile;
+import org.sonar.java.AnalysisProgress;
+import org.sonar.java.model.JParseResult;
+import org.sonar.java.model.JParser;
+import org.sonar.java.model.JavaVersionImpl;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class SemSitterParserTest {
+
+ @TempDir
+ Path project;
+
+ private final ScriptedServer server = new ScriptedServer();
+ private final List fallbackFiles = new ArrayList<>();
+ private final Map results = new LinkedHashMap<>();
+
+ private final JParser fallback = (files, canceled, progress, action) -> files.forEach(fallbackFiles::add);
+
+ private final DocumentTranslator translator = (document, types, packages, noLibraries, javaVersion) -> JParseResult.failure(new RecognitionException(1, "translated"));
+
+ @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()) {
+ assertThatThrownBy(result::get).isInstanceOf(RecognitionException.class).hasMessage("translated");
+ }
+ assertThat(fallbackFiles).isEmpty();
+ }
+
+ @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, types, packages, noLibraries, javaVersion) -> {
+ declared.put(document.getPath(), types.apply(Set.of("org.junit.Test")).keySet());
+ return JParseResult.failure(new RecognitionException(1, "translated"));
+ };
+
+ new SemSitterParser(JParser.Mode.BATCH, new JavaVersionImpl(), List.of(), root -> server, () -> fallback, 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 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 default_frontend_parses_the_files_when_the_server_cannot_start() {
+ InputFile a = file("A.java");
+ InputFile b = file("B.java");
+
+ parser(JParser.Mode.BATCH, new JavaVersionImpl(), List.of(), (SemSitterParser.Launcher) root -> {
+ throw new IOException("no executable");
+ }).parse(List.of(a, b), () -> false, new AnalysisProgress(2), this::collect);
+
+ assertThat(fallbackFiles).containsExactly(a, b);
+ assertThat(results).isEmpty();
+ }
+
+ @Test
+ void default_frontend_parses_the_files_and_the_server_stops_when_the_session_cannot_be_prepared() {
+ server.settingsFailure = new IOException("rejected");
+ InputFile a = file("A.java");
+
+ parser(JParser.Mode.FILE_BY_FILE, new JavaVersionImpl(), List.of(), root -> server).parse(List.of(a), () -> false, new AnalysisProgress(1), this::collect);
+
+ assertThat(fallbackFiles).containsExactly(a);
+ 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.");
+ assertThatThrownBy(results.get("B.java")::get).isInstanceOf(RecognitionException.class).hasMessage("translated");
+ }
+
+ @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 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, () -> fallback, translator, project.resolve("no-jdk"));
+ }
+
+ 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();
+ }
+}
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();
+ };
+ }
+}
diff --git a/java-frontend/src/main/java/org/sonar/java/model/JParser.java b/java-frontend/src/main/java/org/sonar/java/model/JParser.java
index 41f697f0a4c..6790f7ff981 100644
--- a/java-frontend/src/main/java/org/sonar/java/model/JParser.java
+++ b/java-frontend/src/main/java/org/sonar/java/model/JParser.java
@@ -23,7 +23,6 @@
import java.util.function.BooleanSupplier;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.java.AnalysisProgress;
-import org.sonar.java.jdt.JDTParser;
import org.sonar.plugins.java.api.JavaVersion;
public interface JParser {
@@ -39,7 +38,7 @@ public JParser create(JavaVersion javaVersion, List classpath) {
}
public JParser create(JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage, boolean shouldUseJdkReleaseOption) {
- return JDTParser.create(this, javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption);
+ return JParserProviders.create(this, javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption);
}
}
diff --git a/java-frontend/src/main/java/org/sonar/java/model/JParserProvider.java b/java-frontend/src/main/java/org/sonar/java/model/JParserProvider.java
new file mode 100644
index 00000000000..de110d8517b
--- /dev/null
+++ b/java-frontend/src/main/java/org/sonar/java/model/JParserProvider.java
@@ -0,0 +1,39 @@
+/*
+ * 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.model;
+
+import java.io.File;
+import java.util.List;
+import org.sonar.api.config.Configuration;
+import org.sonar.plugins.java.api.JavaVersion;
+
+/**
+ * A frontend that can stand in for the default one. Implementations are discovered with {@link java.util.ServiceLoader}
+ * and consulted every time a {@link JParser} is created, so the frontend can change between analyses without any
+ * caller knowing about it.
+ */
+public interface JParserProvider {
+
+ /** Called once at the start of each analysis, before any parser is created. */
+ void configure(Configuration configuration);
+
+ /** Whether the parsers of this provider must be used for the analysis in progress. */
+ boolean isEnabled();
+
+ JParser create(JParser.Mode mode, JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage,
+ boolean shouldUseJdkReleaseOption);
+}
diff --git a/java-frontend/src/main/java/org/sonar/java/model/JParserProviders.java b/java-frontend/src/main/java/org/sonar/java/model/JParserProviders.java
new file mode 100644
index 00000000000..9ebed01c0ed
--- /dev/null
+++ b/java-frontend/src/main/java/org/sonar/java/model/JParserProviders.java
@@ -0,0 +1,80 @@
+/*
+ * 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.model;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.ServiceLoader;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.sonar.api.config.Configuration;
+import org.sonar.java.jdt.JDTParser;
+import org.sonar.plugins.java.api.JavaVersion;
+
+/**
+ * Chooses the frontend that parses the files: the first enabled {@link JParserProvider}, and the ECJ based frontend
+ * when none is enabled or the chosen one cannot be created.
+ */
+public final class JParserProviders {
+
+ private static final Logger LOG = LoggerFactory.getLogger(JParserProviders.class);
+
+ private static final List DISCOVERED = discover();
+
+ private JParserProviders() {
+ }
+
+ private static List discover() {
+ List providers = new ArrayList<>();
+ ServiceLoader.load(JParserProvider.class, JParserProviders.class.getClassLoader()).forEach(providers::add);
+ return List.copyOf(providers);
+ }
+
+ public static void configure(Configuration configuration) {
+ configure(DISCOVERED, configuration);
+ }
+
+ static void configure(List providers, Configuration configuration) {
+ for (JParserProvider provider : providers) {
+ try {
+ provider.configure(configuration);
+ } catch (RuntimeException e) {
+ LOG.warn("Frontend {} could not be configured and is skipped: {}", provider.getClass().getSimpleName(), e.getMessage());
+ }
+ }
+ }
+
+ static JParser create(JParser.Mode mode, JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage,
+ boolean shouldUseJdkReleaseOption) {
+ return create(DISCOVERED, mode, javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption);
+ }
+
+ static JParser create(List providers, JParser.Mode mode, JavaVersion javaVersion, List classpath,
+ boolean shouldIgnoreUnnamedModuleForSplitPackage, boolean shouldUseJdkReleaseOption) {
+ for (JParserProvider provider : providers) {
+ try {
+ if (provider.isEnabled()) {
+ return provider.create(mode, javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption);
+ }
+ } catch (RuntimeException e) {
+ LOG.warn("Frontend {} is unavailable, falling back to the default one: {}", provider.getClass().getSimpleName(), e.getMessage());
+ }
+ }
+ return JDTParser.create(mode, javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption);
+ }
+}
diff --git a/java-frontend/src/test/java/org/sonar/java/model/JParserProvidersTest.java b/java-frontend/src/test/java/org/sonar/java/model/JParserProvidersTest.java
new file mode 100644
index 00000000000..797a4eab873
--- /dev/null
+++ b/java-frontend/src/test/java/org/sonar/java/model/JParserProvidersTest.java
@@ -0,0 +1,156 @@
+/*
+ * 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.model;
+
+import java.io.File;
+import java.util.List;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.slf4j.event.Level;
+import org.sonar.api.config.Configuration;
+import org.sonar.java.jdt.JDTParser;
+import org.sonar.java.testing.ThreadLocalLogTester;
+import org.sonar.plugins.java.api.JavaVersion;
+import org.sonar.scanner.plugin.api.impl.config.MapSettings;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+class JParserProvidersTest {
+
+ @RegisterExtension
+ public ThreadLocalLogTester logTester = new ThreadLocalLogTester().setLevel(Level.INFO);
+
+ private static final JavaVersion VERSION = new JavaVersionImpl(17);
+
+ @Test
+ void default_frontend_is_used_without_providers() {
+ JParser parser = JParserProviders.create(List.of(), JParser.Mode.BATCH, VERSION, List.of(), false, true);
+
+ assertThat(parser).isInstanceOf(JDTParser.class);
+ }
+
+ @Test
+ void default_frontend_is_used_when_no_provider_is_enabled() {
+ StubProvider disabled = new StubProvider(false);
+
+ JParser parser = JParserProviders.create(List.of(disabled), JParser.Mode.FILE_BY_FILE, VERSION, List.of(), false, true);
+
+ assertThat(parser).isInstanceOf(JDTParser.class);
+ assertThat(disabled.created).isZero();
+ }
+
+ @Test
+ void first_enabled_provider_creates_the_parser_with_the_requested_arguments() {
+ StubProvider disabled = new StubProvider(false);
+ StubProvider enabled = new StubProvider(true);
+ StubProvider later = new StubProvider(true);
+ List classpath = List.of(new File("a.jar"));
+
+ JParser parser = JParserProviders.create(List.of(disabled, enabled, later), JParser.Mode.FILE_BY_FILE, VERSION, classpath, true, true);
+
+ assertThat(parser).isSameAs(enabled.parser);
+ assertThat(enabled.mode).isEqualTo(JParser.Mode.FILE_BY_FILE);
+ assertThat(enabled.javaVersion).isSameAs(VERSION);
+ assertThat(enabled.classpath).isEqualTo(classpath);
+ assertThat(enabled.ignoreUnnamedModule).isTrue();
+ assertThat(disabled.created).isZero();
+ assertThat(later.created).isZero();
+ }
+
+ @Test
+ void default_frontend_is_used_when_the_enabled_provider_cannot_create_its_parser() {
+ StubProvider broken = new StubProvider(true);
+ broken.failure = new IllegalStateException("no executable");
+
+ JParser parser = JParserProviders.create(List.of(broken), JParser.Mode.BATCH, VERSION, List.of(), false, true);
+
+ assertThat(parser).isInstanceOf(JDTParser.class);
+ assertThat(logTester.logs(Level.WARN)).containsExactly("Frontend StubProvider is unavailable, falling back to the default one: no executable");
+ }
+
+ @Test
+ void default_frontend_is_used_when_the_provider_cannot_tell_whether_it_is_enabled() {
+ StubProvider broken = new StubProvider(true);
+ broken.enabledFailure = new IllegalStateException("flag service down");
+
+ JParser parser = JParserProviders.create(List.of(broken), JParser.Mode.BATCH, VERSION, List.of(), false, true);
+
+ assertThat(parser).isInstanceOf(JDTParser.class);
+ }
+
+ @Test
+ void every_provider_is_configured_even_when_one_fails() {
+ StubProvider failing = new StubProvider(true);
+ failing.failure = new IllegalArgumentException("bad settings");
+ StubProvider healthy = new StubProvider(true);
+ Configuration configuration = new MapSettings().asConfig();
+
+ JParserProviders.configure(List.of(failing, healthy), configuration);
+
+ assertThat(failing.configuration).isSameAs(configuration);
+ assertThat(healthy.configuration).isSameAs(configuration);
+ assertThat(logTester.logs(Level.WARN)).containsExactly("Frontend StubProvider could not be configured and is skipped: bad settings");
+ }
+
+ private static final class StubProvider implements JParserProvider {
+ private final boolean enabled;
+ private final JParser parser = (files, canceled, progress, action) -> {
+ };
+ private RuntimeException failure;
+ private RuntimeException enabledFailure;
+ private Configuration configuration;
+ private int created;
+ private JParser.Mode mode;
+ private JavaVersion javaVersion;
+ private List classpath;
+ private boolean ignoreUnnamedModule;
+
+ private StubProvider(boolean enabled) {
+ this.enabled = enabled;
+ }
+
+ @Override
+ public void configure(Configuration configuration) {
+ this.configuration = configuration;
+ if (failure != null) {
+ throw failure;
+ }
+ }
+
+ @Override
+ public boolean isEnabled() {
+ if (enabledFailure != null) {
+ throw enabledFailure;
+ }
+ return enabled;
+ }
+
+ @Override
+ public JParser create(JParser.Mode mode, JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage,
+ boolean shouldUseJdkReleaseOption) {
+ if (failure != null) {
+ throw failure;
+ }
+ created++;
+ this.mode = mode;
+ this.javaVersion = javaVersion;
+ this.classpath = classpath;
+ this.ignoreUnnamedModule = shouldIgnoreUnnamedModuleForSplitPackage;
+ return parser;
+ }
+ }
+}
diff --git a/sonar-java-plugin/license-resources/bsd-3-clause.txt b/sonar-java-plugin/license-resources/bsd-3-clause.txt
new file mode 100644
index 00000000000..19b305b0006
--- /dev/null
+++ b/sonar-java-plugin/license-resources/bsd-3-clause.txt
@@ -0,0 +1,32 @@
+Copyright 2008 Google Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+Code generated by the Protocol Buffer compiler is owned by the owner
+of the input file used when generating it. This code is not
+standalone and requires a support library to be linked with it. This
+support library is itself covered by the above license.
diff --git a/sonar-java-plugin/license-resources/ssal.txt b/sonar-java-plugin/license-resources/ssal.txt
new file mode 100644
index 00000000000..28723feb3de
--- /dev/null
+++ b/sonar-java-plugin/license-resources/ssal.txt
@@ -0,0 +1,184 @@
+SONAR Source-Available License v1.0
+Last Updated November 13, 2024
+
+1. DEFINITIONS
+
+"Agreement" means this Sonar Source-Available License v1.0
+
+"Competing" means marketing a product or service as a substitute for the
+functionality or value of SonarQube. A product or service may compete regardless
+of how it is designed or deployed. For example, a product or service may compete
+even if it provides its functionality via any kind of interface (including
+services, libraries, or plug-ins), even if it is ported to a different platform
+or programming language, and even if it is provided free of charge.
+
+"Contribution" means:
+
+ a) in the case of the initial Contributor, the initial content Distributed under
+this Agreement, and
+
+ b) in the case of each subsequent Contributor:
+ i) changes to the Program, and
+ ii) additions to the Program;
+
+where such changes and/or additions to the Program originate from and are
+Distributed by that particular Contributor. A Contribution "originates" from a
+Contributor if it was added to the Program by such Contributor itself or anyone
+acting on such Contributor's behalf. Contributions do not include changes or
+additions to the Program that are not Modified Works.
+
+"Contributor" means any person or entity that Distributes the Program.
+
+"Derivative Works" shall mean any work, whether in Source Code or other form,
+that is based on (or derived from) the Program and for which the editorial
+revisions, annotations, elaborations, or other modifications represent, as a
+whole, an original work of authorship.
+
+"Distribute" means the acts of a) distributing or b) making available in any
+manner that enables the transfer of a copy.
+
+"Licensed Patents" mean patent claims licensable by a Contributor that are
+necessarily infringed by the use or sale of its Contribution alone or when
+combined with the Program.
+
+"Modified Works" shall mean any work in Source Code or other form that results
+from an addition to, deletion from, or modification of the contents of the
+Program, including, for purposes of clarity, any new file in Source Code form
+that contains any contents of the Program. Modified Works shall not include
+works that contain only declarations, interfaces, types, classes, structures, or
+files of the Program solely in each case in order to link to, bind by name, or
+subclass the Program or Modified Works thereof.
+
+"Non-competitive Purpose" means any purpose except for (a) providing to others
+any product or service that includes or offers the same or substantially similar
+functionality as SonarQube, (b) Competing with SonarQube, and/or (c) employing,
+using, or engaging artificial intelligence technology that is not part of the
+Program to ingest, interpret, analyze, train on, or interact with the data
+provided by the Program, or to engage with the Program in any manner.
+
+"Notices" means any legal statements or attributions included with the Program,
+including, without limitation, statements concerning copyright, patent,
+trademark, disclaimers of warranty, or limitations of liability
+
+"Program" means the Contributions Distributed in accordance with this Agreement.
+
+"Recipient" means anyone who receives the Program under this Agreement,
+including Contributors.
+
+"SonarQube" means an open-source or commercial edition of software offered by
+SonarSource that is branded "SonarQube".
+
+"SonarSource" means SonarSource SA, a Swiss company registered in Switzerland
+under UID No. CHE-114.587.664.
+
+"Source Code" means the form of a Program preferred for making modifications,
+including but not limited to software source code, documentation source, and
+configuration files.
+
+2. GRANT OF RIGHTS
+
+ a) Subject to the terms of this Agreement, each Contributor hereby grants
+Recipient a non-exclusive, worldwide, royalty-free copyright license, for any
+Non-competitive Purpose, to reproduce, prepare Derivative Works of, publicly
+display, publicly perform, Distribute and sublicense the Contribution of such
+Contributor, if any, and such Derivative Works.
+
+ b) Subject to the terms of this Agreement, each Contributor hereby grants
+Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed
+Patents, for any Non-competitive Purpose, to make, use, sell, offer to sell,
+import, and otherwise transfer the Contribution of such Contributor, if any, in
+Source Code or other form. This patent license shall apply to the combination of
+the Contribution and the Program if, at the time the Contribution is added by
+the Contributor, such addition of the Contribution causes such combination to be
+covered by the Licensed Patents. The patent license shall not apply to any other
+combinations that include the Contribution.
+
+ c) Recipient understands that although each Contributor grants the licenses to
+its Contributions set forth herein, no assurances are provided by any
+Contributor that the Program does not infringe the patent or other intellectual
+property rights of any other entity. Each Contributor disclaims any liability to
+Recipient for claims brought by any other entity based on infringement of
+intellectual property rights or otherwise. As a condition to exercising the
+rights and licenses granted hereunder, each Recipient hereby assumes sole
+responsibility to secure any other intellectual property rights needed, if any.
+For example, if a third-party patent license is required to allow Recipient to
+Distribute the Program, it is Recipient's responsibility to acquire that license
+before distributing the Program.
+
+ d) Each Contributor represents that to its knowledge it has sufficient copyright
+rights in its Contribution, if any, to grant the copyright license set forth in
+this Agreement.
+
+3. REQUIREMENTS
+
+3.1 If a Contributor Distributes the Program in any form, then the Program must
+also be made available as Source Code, in accordance with section 3.2, and the
+Contributor must accompany the Program with a statement that the Source Code for
+the Program is available under this Agreement, and inform Recipients how to
+obtain it in a reasonable manner on or through a medium customarily used for
+software exchange; and
+
+3.2 When the Program is Distributed as Source Code:
+
+ a) it must be made available under this Agreement, and
+
+ b) a copy of this Agreement must be included with each copy of the Program.
+
+3.3 Contributors may not remove or alter any Notices contained within the
+Program from any copy of the Program which they Distribute, provided that
+Contributors may add their own appropriate Notices.
+
+4. NO WARRANTY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY
+APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES
+OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
+LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
+MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
+responsible for determining the appropriateness of using and distributing the
+Program and assumes all risks associated with its exercise of rights under this
+Agreement, including but not limited to the risks and costs of program errors,
+compliance with applicable laws, damage to or loss of data, programs or
+equipment, and unavailability or interruption of operations.
+
+5. DISCLAIMER OF LIABILITY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY
+APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF
+THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF
+THE POSSIBILITY OF SUCH DAMAGES.
+
+6. GENERAL
+
+If any provision of this Agreement is invalid or unenforceable under applicable
+law, it shall not affect the validity or enforceability of the remainder of the
+terms of this Agreement, and without further action by the parties hereto, such
+provision shall be reformed to the minimum extent necessary to make such
+provision valid and enforceable.
+
+If Recipient institutes patent litigation against any entity (including a
+cross-claim or counterclaim in a lawsuit) alleging that the Program itself
+(excluding combinations of the Program with other software or hardware)
+infringes such Recipient’s patent(s), then such Recipient’s rights granted under
+Section 2(b) shall terminate as of the date such litigation is filed.
+
+All Recipient’s rights under this Agreement shall terminate if it fails to
+comply with any of the material terms or conditions of this Agreement and does
+not cure such failure in a reasonable period of time after becoming aware of
+such noncompliance. If all Recipient’s rights under this Agreement terminate,
+Recipient agrees to cease use and distribution of the Program as soon as
+reasonably practicable. However, Recipient’s obligations under this Agreement
+and any licenses granted by Recipient relating to the Program shall continue and
+survive.
+
+Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives
+no rights or licenses to the intellectual property of any Contributor under this
+Agreement, whether expressly, by implication, estoppel, or otherwise. All rights
+in the Program not expressly granted under this Agreement are reserved. Nothing
+in this Agreement is intended to be enforceable by any entity that is not a
+Contributor or Recipient. No third-party beneficiary rights are created under
+this Agreement.
diff --git a/sonar-java-plugin/pom.xml b/sonar-java-plugin/pom.xml
index b218f8dd3df..87a72bcf243 100644
--- a/sonar-java-plugin/pom.xml
+++ b/sonar-java-plugin/pom.xml
@@ -39,6 +39,11 @@
java-frontend
${project.version}
+
+ ${project.groupId}
+ java-frontend-semsitter
+ ${project.version}
+
${project.groupId}
java-checks
@@ -184,7 +189,7 @@
- 21500000
+ 24000000
19000000
${project.build.directory}/${project.build.finalName}.jar
@@ -233,6 +238,12 @@
**
+
+ org.sonarsource.java:java-frontend-semsitter
+
+ **
+
+
xerces:xercesImpl
@@ -301,6 +312,14 @@
http://www.opensource.org/licenses/bsd-license.php
${project.baseUri}/license-resources/bsd.txt
+
+ https://opensource.org/licenses/BSD-3-Clause
+ ${project.baseUri}/license-resources/bsd-3-clause.txt
+
+
+ https://sonarsource.com/license/ssal/
+ ${project.baseUri}/license-resources/ssal.txt
+
diff --git a/sonar-java-plugin/src/main/java/org/sonar/plugins/java/JavaSensor.java b/sonar-java-plugin/src/main/java/org/sonar/plugins/java/JavaSensor.java
index 1c7f63d5757..f0cf2e572a1 100644
--- a/sonar-java-plugin/src/main/java/org/sonar/plugins/java/JavaSensor.java
+++ b/sonar-java-plugin/src/main/java/org/sonar/plugins/java/JavaSensor.java
@@ -43,6 +43,7 @@
import org.sonar.java.filters.PostAnalysisIssueFilter;
import org.sonar.java.jsp.Jasper;
import org.sonar.java.model.GeneratedFile;
+import org.sonar.java.model.JParserProviders;
import org.sonar.java.model.JavaVersionImpl;
import org.sonar.java.model.springcontext.SpringContextGatheringModel;
import org.sonar.java.model.springcontext.SpringContextModelGatherers;
@@ -128,6 +129,10 @@ public void execute(SensorContext context) {
telemetry.aggregateAsSortedSet(JAVA_SCANNER_APP, context.config().get("sonar.scanner.app").orElse("none"));
telemetry.aggregateAsFlag(JAVA_IS_AUTOSCAN, sonarComponents.isAutoScan());
+ if (!sonarComponents.isSonarLintContext()) {
+ JParserProviders.configure(context.config());
+ }
+
JavaFrontend frontend = new JavaFrontend(javaVersion,
sonarComponents,
measurer,
diff --git a/sonar-java-plugin/src/main/resources/licenses/THIRD_PARTY_LICENSES/com.google.protobuf.protobuf-java-LICENSE.txt b/sonar-java-plugin/src/main/resources/licenses/THIRD_PARTY_LICENSES/com.google.protobuf.protobuf-java-LICENSE.txt
new file mode 100644
index 00000000000..19b305b0006
--- /dev/null
+++ b/sonar-java-plugin/src/main/resources/licenses/THIRD_PARTY_LICENSES/com.google.protobuf.protobuf-java-LICENSE.txt
@@ -0,0 +1,32 @@
+Copyright 2008 Google Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+Code generated by the Protocol Buffer compiler is owned by the owner
+of the input file used when generating it. This code is not
+standalone and requires a support library to be linked with it. This
+support library is itself covered by the above license.
diff --git a/sonar-java-plugin/src/main/resources/licenses/THIRD_PARTY_LICENSES/org.sonarsource.semsitter.analyzer-wire-LICENSE.txt b/sonar-java-plugin/src/main/resources/licenses/THIRD_PARTY_LICENSES/org.sonarsource.semsitter.analyzer-wire-LICENSE.txt
new file mode 100644
index 00000000000..28723feb3de
--- /dev/null
+++ b/sonar-java-plugin/src/main/resources/licenses/THIRD_PARTY_LICENSES/org.sonarsource.semsitter.analyzer-wire-LICENSE.txt
@@ -0,0 +1,184 @@
+SONAR Source-Available License v1.0
+Last Updated November 13, 2024
+
+1. DEFINITIONS
+
+"Agreement" means this Sonar Source-Available License v1.0
+
+"Competing" means marketing a product or service as a substitute for the
+functionality or value of SonarQube. A product or service may compete regardless
+of how it is designed or deployed. For example, a product or service may compete
+even if it provides its functionality via any kind of interface (including
+services, libraries, or plug-ins), even if it is ported to a different platform
+or programming language, and even if it is provided free of charge.
+
+"Contribution" means:
+
+ a) in the case of the initial Contributor, the initial content Distributed under
+this Agreement, and
+
+ b) in the case of each subsequent Contributor:
+ i) changes to the Program, and
+ ii) additions to the Program;
+
+where such changes and/or additions to the Program originate from and are
+Distributed by that particular Contributor. A Contribution "originates" from a
+Contributor if it was added to the Program by such Contributor itself or anyone
+acting on such Contributor's behalf. Contributions do not include changes or
+additions to the Program that are not Modified Works.
+
+"Contributor" means any person or entity that Distributes the Program.
+
+"Derivative Works" shall mean any work, whether in Source Code or other form,
+that is based on (or derived from) the Program and for which the editorial
+revisions, annotations, elaborations, or other modifications represent, as a
+whole, an original work of authorship.
+
+"Distribute" means the acts of a) distributing or b) making available in any
+manner that enables the transfer of a copy.
+
+"Licensed Patents" mean patent claims licensable by a Contributor that are
+necessarily infringed by the use or sale of its Contribution alone or when
+combined with the Program.
+
+"Modified Works" shall mean any work in Source Code or other form that results
+from an addition to, deletion from, or modification of the contents of the
+Program, including, for purposes of clarity, any new file in Source Code form
+that contains any contents of the Program. Modified Works shall not include
+works that contain only declarations, interfaces, types, classes, structures, or
+files of the Program solely in each case in order to link to, bind by name, or
+subclass the Program or Modified Works thereof.
+
+"Non-competitive Purpose" means any purpose except for (a) providing to others
+any product or service that includes or offers the same or substantially similar
+functionality as SonarQube, (b) Competing with SonarQube, and/or (c) employing,
+using, or engaging artificial intelligence technology that is not part of the
+Program to ingest, interpret, analyze, train on, or interact with the data
+provided by the Program, or to engage with the Program in any manner.
+
+"Notices" means any legal statements or attributions included with the Program,
+including, without limitation, statements concerning copyright, patent,
+trademark, disclaimers of warranty, or limitations of liability
+
+"Program" means the Contributions Distributed in accordance with this Agreement.
+
+"Recipient" means anyone who receives the Program under this Agreement,
+including Contributors.
+
+"SonarQube" means an open-source or commercial edition of software offered by
+SonarSource that is branded "SonarQube".
+
+"SonarSource" means SonarSource SA, a Swiss company registered in Switzerland
+under UID No. CHE-114.587.664.
+
+"Source Code" means the form of a Program preferred for making modifications,
+including but not limited to software source code, documentation source, and
+configuration files.
+
+2. GRANT OF RIGHTS
+
+ a) Subject to the terms of this Agreement, each Contributor hereby grants
+Recipient a non-exclusive, worldwide, royalty-free copyright license, for any
+Non-competitive Purpose, to reproduce, prepare Derivative Works of, publicly
+display, publicly perform, Distribute and sublicense the Contribution of such
+Contributor, if any, and such Derivative Works.
+
+ b) Subject to the terms of this Agreement, each Contributor hereby grants
+Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed
+Patents, for any Non-competitive Purpose, to make, use, sell, offer to sell,
+import, and otherwise transfer the Contribution of such Contributor, if any, in
+Source Code or other form. This patent license shall apply to the combination of
+the Contribution and the Program if, at the time the Contribution is added by
+the Contributor, such addition of the Contribution causes such combination to be
+covered by the Licensed Patents. The patent license shall not apply to any other
+combinations that include the Contribution.
+
+ c) Recipient understands that although each Contributor grants the licenses to
+its Contributions set forth herein, no assurances are provided by any
+Contributor that the Program does not infringe the patent or other intellectual
+property rights of any other entity. Each Contributor disclaims any liability to
+Recipient for claims brought by any other entity based on infringement of
+intellectual property rights or otherwise. As a condition to exercising the
+rights and licenses granted hereunder, each Recipient hereby assumes sole
+responsibility to secure any other intellectual property rights needed, if any.
+For example, if a third-party patent license is required to allow Recipient to
+Distribute the Program, it is Recipient's responsibility to acquire that license
+before distributing the Program.
+
+ d) Each Contributor represents that to its knowledge it has sufficient copyright
+rights in its Contribution, if any, to grant the copyright license set forth in
+this Agreement.
+
+3. REQUIREMENTS
+
+3.1 If a Contributor Distributes the Program in any form, then the Program must
+also be made available as Source Code, in accordance with section 3.2, and the
+Contributor must accompany the Program with a statement that the Source Code for
+the Program is available under this Agreement, and inform Recipients how to
+obtain it in a reasonable manner on or through a medium customarily used for
+software exchange; and
+
+3.2 When the Program is Distributed as Source Code:
+
+ a) it must be made available under this Agreement, and
+
+ b) a copy of this Agreement must be included with each copy of the Program.
+
+3.3 Contributors may not remove or alter any Notices contained within the
+Program from any copy of the Program which they Distribute, provided that
+Contributors may add their own appropriate Notices.
+
+4. NO WARRANTY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY
+APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES
+OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
+LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
+MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
+responsible for determining the appropriateness of using and distributing the
+Program and assumes all risks associated with its exercise of rights under this
+Agreement, including but not limited to the risks and costs of program errors,
+compliance with applicable laws, damage to or loss of data, programs or
+equipment, and unavailability or interruption of operations.
+
+5. DISCLAIMER OF LIABILITY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY
+APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF
+THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF
+THE POSSIBILITY OF SUCH DAMAGES.
+
+6. GENERAL
+
+If any provision of this Agreement is invalid or unenforceable under applicable
+law, it shall not affect the validity or enforceability of the remainder of the
+terms of this Agreement, and without further action by the parties hereto, such
+provision shall be reformed to the minimum extent necessary to make such
+provision valid and enforceable.
+
+If Recipient institutes patent litigation against any entity (including a
+cross-claim or counterclaim in a lawsuit) alleging that the Program itself
+(excluding combinations of the Program with other software or hardware)
+infringes such Recipient’s patent(s), then such Recipient’s rights granted under
+Section 2(b) shall terminate as of the date such litigation is filed.
+
+All Recipient’s rights under this Agreement shall terminate if it fails to
+comply with any of the material terms or conditions of this Agreement and does
+not cure such failure in a reasonable period of time after becoming aware of
+such noncompliance. If all Recipient’s rights under this Agreement terminate,
+Recipient agrees to cease use and distribution of the Program as soon as
+reasonably practicable. However, Recipient’s obligations under this Agreement
+and any licenses granted by Recipient relating to the Program shall continue and
+survive.
+
+Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives
+no rights or licenses to the intellectual property of any Contributor under this
+Agreement, whether expressly, by implication, estoppel, or otherwise. All rights
+in the Program not expressly granted under this Agreement are reserved. Nothing
+in this Agreement is intended to be enforceable by any entity that is not a
+Contributor or Recipient. No third-party beneficiary rights are created under
+this Agreement.