Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -39,7 +38,7 @@ public JParser create(JavaVersion javaVersion, List<File> classpath) {
}

public JParser create(JavaVersion javaVersion, List<File> classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage, boolean shouldUseJdkReleaseOption) {
return JDTParser.create(this, javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption);
return JParserProviders.create(this, javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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<File> classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage,
boolean shouldUseJdkReleaseOption);
}
Original file line number Diff line number Diff line change
@@ -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.
Comment thread
rombirli marked this conversation as resolved.
Resolved
*/
public final class JParserProviders {

private static List<JParserProvider> 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<JParserProvider> discovered = ServiceLoader.load(JParserProvider.class, JParserProviders.class.getClassLoader())
Comment thread
david-schroeter marked this conversation as resolved.
Resolved
.stream().map(ServiceLoader.Provider::get).toList();
configured = configure(discovered, configuration);
}

private static List<JParserProvider> configure(List<JParserProvider> providers, Configuration configuration) {
providers.forEach(provider -> provider.configure(configuration));
return providers;
}

static JParser create(JParser.Mode mode, JavaVersion javaVersion, List<File> classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage,
boolean shouldUseJdkReleaseOption) {
return create(configured, mode, javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption);
}

private static JParser create(List<JParserProvider> providers, JParser.Mode mode, JavaVersion javaVersion, List<File> classpath,
boolean shouldIgnoreUnnamedModuleForSplitPackage, boolean shouldUseJdkReleaseOption) {
List<JParserProvider> 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);
}
}
Original file line number Diff line number Diff line change
@@ -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<File> 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<String, String> properties) {
MapSettings settings = new MapSettings();
properties.forEach(settings::setProperty);
return settings.asConfig();
}
}
Original file line number Diff line number Diff line change
@@ -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 <name>.enabled} turns it on and {@code <name>.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<File> classpath, boolean ignoreUnnamedModule) implements JParser {
@Override
public void parse(Iterable<InputFile> inputFiles, BooleanSupplier isCanceled, AnalysisProgress analysisProgress, BiConsumer<InputFile, JParseResult> 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<File> 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);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
org.sonar.java.model.RegisteredParserProviders$Alpha
org.sonar.java.model.RegisteredParserProviders$Beta
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down