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..ae90ba98ef1 --- /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. At most one provider may be enabled at a time. */ + 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..cf4d99140b1 --- /dev/null +++ b/java-frontend/src/main/java/org/sonar/java/model/JParserProviders.java @@ -0,0 +1,69 @@ +/* + * 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 java.util.ServiceLoader; +import java.util.stream.Collectors; +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 one enabled {@link JParserProvider}, or the ECJ based frontend when + * none is enabled. Several enabled providers fail the analysis, since the discovery order is not a priority. The + * frontends are independent: a provider that fails to load, to configure or to create its parser fails the analysis + * instead of handing the files to another frontend. + */ +public final class JParserProviders { + + private static List configured = List.of(); + + private JParserProviders() { + } + + /** Loads and configures fresh providers for the current analysis. Nothing is loaded where no analysis configures them. */ + public static void configure(Configuration configuration) { + List discovered = ServiceLoader.load(JParserProvider.class, JParserProviders.class.getClassLoader()) + .stream().map(ServiceLoader.Provider::get).toList(); + configured = configure(discovered, configuration); + } + + private static List configure(List providers, Configuration configuration) { + providers.forEach(provider -> provider.configure(configuration)); + return providers; + } + + static JParser create(JParser.Mode mode, JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage, + boolean shouldUseJdkReleaseOption) { + return create(configured, mode, javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption); + } + + private static JParser create(List providers, JParser.Mode mode, JavaVersion javaVersion, List classpath, + boolean shouldIgnoreUnnamedModuleForSplitPackage, boolean shouldUseJdkReleaseOption) { + List enabled = providers.stream().filter(JParserProvider::isEnabled).toList(); + if (enabled.size() > 1) { + String names = enabled.stream().map(provider -> provider.getClass().getName()).collect(Collectors.joining(", ")); + throw new IllegalStateException("Several parser providers are enabled but at most one is allowed: " + names); + } + if (enabled.isEmpty()) { + return JDTParser.create(mode, javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption); + } + return enabled.getFirst().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..d6e340617c7 --- /dev/null +++ b/java-frontend/src/test/java/org/sonar/java/model/JParserProvidersTest.java @@ -0,0 +1,125 @@ +/* + * 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 java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.sonar.api.config.Configuration; +import org.sonar.java.jdt.JDTParser; +import org.sonar.java.model.RegisteredParserProviders.CreatedParser; +import org.sonar.plugins.java.api.JavaVersion; +import org.sonar.scanner.plugin.api.impl.config.MapSettings; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class JParserProvidersTest { + + private static final JavaVersion VERSION = new JavaVersionImpl(17); + + @AfterEach + void forgetTheAnalysis() { + JParserProviders.configure(settings(Map.of())); + } + + @Test + void discovered_provider_creates_the_parser_with_the_requested_arguments() { + List classpath = List.of(new File("a.jar")); + JParserProviders.configure(settings(Map.of("alpha.enabled", "true"))); + + JParser parser = JParserProviders.create(JParser.Mode.FILE_BY_FILE, VERSION, classpath, true, true); + + assertThat(parser).isEqualTo(new CreatedParser("alpha", JParser.Mode.FILE_BY_FILE, VERSION, classpath, true)); + } + + @Test + void discovered_provider_that_is_not_enabled_is_skipped_for_a_later_one() { + JParserProviders.configure(settings(Map.of("alpha.enabled", "false", "beta.enabled", "true"))); + + JParser parser = JParserProviders.create(JParser.Mode.BATCH, VERSION, List.of(), false, true); + + assertThat(parser).isEqualTo(new CreatedParser("beta", JParser.Mode.BATCH, VERSION, List.of(), false)); + } + + @Test + void every_discovered_provider_is_configured() { + JParserProviders.configure(settings(Map.of("beta.enabled", "true"))); + assertThat(JParserProviders.create(JParser.Mode.BATCH, VERSION, List.of(), false, true)).isEqualTo(new CreatedParser("beta", JParser.Mode.BATCH, VERSION, List.of(), false)); + + JParserProviders.configure(settings(Map.of("alpha.enabled", "true"))); + assertThat(JParserProviders.create(JParser.Mode.BATCH, VERSION, List.of(), false, true)).isEqualTo(new CreatedParser("alpha", JParser.Mode.BATCH, VERSION, List.of(), false)); + } + + @Test + void a_provider_that_cannot_be_configured_fails_the_analysis() { + Configuration configuration = settings(Map.of("alpha.fail", "configure")); + + assertThatThrownBy(() -> JParserProviders.configure(configuration)).hasMessage("alpha fails at configure"); + } + + @Test + void configuring_again_forgets_the_previous_analysis() { + JParserProviders.configure(settings(Map.of("alpha.enabled", "true"))); + + JParserProviders.configure(settings(Map.of())); + + assertThat(JParserProviders.create(JParser.Mode.BATCH, VERSION, List.of(), false, true)).isInstanceOf(JDTParser.class); + } + + @Test + void default_frontend_is_used_when_no_discovered_provider_is_enabled() { + JParserProviders.configure(settings(Map.of())); + + assertThat(JParserProviders.create(JParser.Mode.BATCH, VERSION, List.of(), false, true)).isInstanceOf(JDTParser.class); + } + + @Test + void several_enabled_providers_fail_the_analysis() { + JParserProviders.configure(settings(Map.of("alpha.enabled", "true", "beta.enabled", "true"))); + + assertThatThrownBy(() -> JParserProviders.create(JParser.Mode.BATCH, VERSION, List.of(), false, true)) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("Several parser providers are enabled but at most one is allowed: ") + .hasMessageContaining("RegisteredParserProviders$Alpha") + .hasMessageContaining("RegisteredParserProviders$Beta"); + } + + @Test + void an_enabled_provider_that_cannot_create_its_parser_fails_instead_of_falling_back() { + JParserProviders.configure(settings(Map.of("alpha.enabled", "true", "alpha.fail", "create"))); + + assertThatThrownBy(() -> JParserProviders.create(JParser.Mode.BATCH, VERSION, List.of(), false, true)) + .isInstanceOf(IllegalStateException.class).hasMessage("alpha fails at create"); + } + + @Test + void a_provider_that_cannot_tell_whether_it_is_enabled_fails_instead_of_falling_back() { + JParserProviders.configure(settings(Map.of("alpha.fail", "enabled"))); + + assertThatThrownBy(() -> JParserProviders.create(JParser.Mode.BATCH, VERSION, List.of(), false, true)) + .hasMessage("alpha fails at enabled"); + } + + private static Configuration settings(Map properties) { + MapSettings settings = new MapSettings(); + properties.forEach(settings::setProperty); + return settings.asConfig(); + } +} diff --git a/java-frontend/src/test/java/org/sonar/java/model/RegisteredParserProviders.java b/java-frontend/src/test/java/org/sonar/java/model/RegisteredParserProviders.java new file mode 100644 index 00000000000..8e15aa5883b --- /dev/null +++ b/java-frontend/src/test/java/org/sonar/java/model/RegisteredParserProviders.java @@ -0,0 +1,92 @@ +/* + * 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 java.util.function.BiConsumer; +import java.util.function.BooleanSupplier; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.config.Configuration; +import org.sonar.java.AnalysisProgress; +import org.sonar.plugins.java.api.JavaVersion; + +/** + * Parser providers registered through {@code META-INF/services} for the tests of {@link JParserProviders}. A provider is + * driven by the configuration: {@code .enabled} turns it on and {@code .fail} set to {@code configure}, + * {@code enabled} or {@code create} makes that step throw. + */ +public final class RegisteredParserProviders { + + private RegisteredParserProviders() { + } + + public static final class Alpha extends Registered { + public Alpha() { + super("alpha"); + } + } + + public static final class Beta extends Registered { + public Beta() { + super("beta"); + } + } + + public record CreatedParser(String provider, JParser.Mode mode, JavaVersion javaVersion, List classpath, boolean ignoreUnnamedModule) implements JParser { + @Override + public void parse(Iterable inputFiles, BooleanSupplier isCanceled, AnalysisProgress analysisProgress, BiConsumer action) { + throw new UnsupportedOperationException(); + } + } + + abstract static class Registered implements JParserProvider { + private final String name; + private boolean enabled; + private String failure = ""; + + Registered(String name) { + this.name = name; + } + + @Override + public void configure(Configuration configuration) { + enabled = configuration.getBoolean(name + ".enabled").orElse(false); + failure = configuration.get(name + ".fail").orElse(""); + failAt("configure"); + } + + @Override + public boolean isEnabled() { + failAt("enabled"); + return enabled; + } + + @Override + public JParser create(JParser.Mode mode, JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage, + boolean shouldUseJdkReleaseOption) { + failAt("create"); + return new CreatedParser(name, mode, javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage); + } + + private void failAt(String step) { + if (step.equals(failure)) { + throw new IllegalStateException(name + " fails at " + step); + } + } + } +} diff --git a/java-frontend/src/test/resources/META-INF/services/org.sonar.java.model.JParserProvider b/java-frontend/src/test/resources/META-INF/services/org.sonar.java.model.JParserProvider new file mode 100644 index 00000000000..3bfd3327f48 --- /dev/null +++ b/java-frontend/src/test/resources/META-INF/services/org.sonar.java.model.JParserProvider @@ -0,0 +1,2 @@ +org.sonar.java.model.RegisteredParserProviders$Alpha +org.sonar.java.model.RegisteredParserProviders$Beta 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,