Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
5265ad0
[PoC] Serve SonarJava from the SemSitter analyzer server instead of t…
antonioaversa Nov 12, 2026
5f2da23
[PoC] Start one analyzer per module root, rescan per classpath, tear …
antonioaversa Nov 13, 2026
905ed40
[PoC] Scan exactly the analyzed files once per run, start the module …
antonioaversa Nov 14, 2026
ce7fa0e
[PoC] Align member facts, numeric promotion, array and parameterized …
antonioaversa Nov 14, 2026
82aa334
[PoC] Align generic typing: subtyping and wildcard containment, invoc…
antonioaversa Nov 14, 2026
690d2d4
[PoC] Restart the analyzer when the classpath changes, scan a lone re…
antonioaversa Nov 14, 2026
2e17fcf
[PoC] Give anonymous classes a symbol from their creation node and bu…
antonioaversa Nov 15, 2026
a9341e0
[PoC] Trust the served variable-arity and synchronized flags, read ty…
antonioaversa Nov 15, 2026
6751aa0
[PoC] Align constants, conditionals, enums, raw receivers, varargs la…
antonioaversa Nov 15, 2026
4a83778
[PoC] Drop the diagnostic counters of the analyzer session and make t…
antonioaversa Nov 15, 2026
3d3a6da
[PoC] Skip the tests that need the analyzer when none is configured a…
antonioaversa Nov 15, 2026
a082d91
[PoC] Keep the Java compiler that Jasper needs on the classpath of th…
antonioaversa Nov 15, 2026
1192888
[PoC] Give each lambda a symbol of its own, read qualified this and s…
antonioaversa Nov 15, 2026
fa52fd2
[PoC] Own initializer variables by their block, type unnamed variable…
antonioaversa Nov 15, 2026
367bdb4
[PoC] Report syntax errors of a scanned file as parse errors, keep wi…
antonioaversa Nov 15, 2026
6d09ffa
[PoC] Keep unresolved interfaces among the supertypes, skip static me…
antonioaversa Nov 15, 2026
89187b3
[PoC] Type intersections declared with var, own record components by …
antonioaversa Nov 15, 2026
52964fa
[PoC] Align cancellation, boxed constants and unnamed record-pattern …
antonioaversa Nov 15, 2026
d21f317
[PoC] Type unnamed lambda and record-pattern variables, keep annotati…
antonioaversa Nov 16, 2026
b7c2949
[PoC] Keep raw-type behaviour of generic classes, leave the built-in …
antonioaversa Nov 16, 2026
28a1705
[PoC] Resolve constructors that override, view generic constructors w…
antonioaversa Nov 16, 2026
5491966
[PoC] List members of local types, keep recovered superclasses among …
antonioaversa Nov 16, 2026
6e0154c
[PoC] Keep matching by name for types the sources name but nothing de…
antonioaversa Nov 16, 2026
fd1abe4
[PoC] Align the finalize sample of non-compiling code with the analyz…
antonioaversa Nov 16, 2026
97c8c2c
[PoC] Treat types the analyzer left out as unresolved, keep unresolve…
antonioaversa Nov 16, 2026
99c81b1
[PoC] Read parameter annotations of class-file members and treat a pa…
antonioaversa Nov 16, 2026
a06862f
[PoC] Match imports of classes whose names contain a dollar sign
antonioaversa Nov 16, 2026
1bb4351
[PoC] Unbind lambda parameters that qualify a member only, and leave …
antonioaversa Nov 16, 2026
e16ed70
[PoC] Give a switch expression the type its assignment context expects
antonioaversa Nov 16, 2026
a5dd167
[PoC] Take an array of a primitive type as one element of a variable-…
antonioaversa Nov 16, 2026
f803c00
[PoC] Choose the most specific variable-arity overload and keep its r…
antonioaversa Nov 16, 2026
131c5e3
[PoC] Keep class literal types bound whatever their argument
antonioaversa Nov 16, 2026
a47b18e
[PoC] Skip private methods when looking for overridden ones and give …
antonioaversa Nov 16, 2026
4076d41
[PoC] Mark inferred parameterizations without a new field
antonioaversa Nov 16, 2026
ba41098
[PoC] Report a catch of a checked exception that the try body cannot …
antonioaversa Nov 16, 2026
d2b4ab0
[PoC] Do not expect a reassigned pattern variable to be tracked witho…
antonioaversa Nov 16, 2026
85f4540
[PoC] Infer call arguments, diamonds and captures from library generi…
antonioaversa Nov 16, 2026
fed7049
[PoC] Read default values of class-file annotation members
antonioaversa Nov 16, 2026
37dccd1
[PoC] Erase the return type variable of a raw call to its bound
antonioaversa Nov 16, 2026
9b87cb8
[PoC] Align two check samples with a typed lombok val and an array re…
antonioaversa Nov 16, 2026
4b017f2
[PoC] Package the Java analyzer for macOS aarch64
antonioaversa Nov 16, 2026
9a89a2d
[PoC] Refresh the packaged macOS aarch64 analyzer
antonioaversa Nov 16, 2026
910b4be
[PoC] Start the analyzer with the field reference edges its queries read
antonioaversa Nov 16, 2026
12fd693
[PoC] Package the Java analyzer for linux, macOS and windows
antonioaversa Nov 16, 2026
a13fb4b
[PoC] Infer the thrown type of a generic throws clause from the suppl…
antonioaversa Nov 16, 2026
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 @@ -9,8 +9,8 @@ void lambdas_not_resolved(UnknnownFunction lambda) {
int x = 1; // Compliant
return y + x;
});
lambdas_not_resolved(y -> ++y);
lambdas_not_resolved(y -> y += 2);
lambdas_not_resolved(y -> ++y); // Noncompliant
lambdas_not_resolved(y -> y += 2); // Noncompliant
}

void fpLambdaWithAssignment(boolean cond) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public void foo() { // Compliant
}

@Override
protected boolean finalize() { // Compliant
protected boolean finalize() { // Noncompliant {{Do not override the Object.finalize() method.}}
}

}
Expand All @@ -41,7 +41,7 @@ public void bar() { // Compliant
}

@Override
protected boolean finalize() { // Compliant
protected boolean finalize() { // Noncompliant {{Do not override the Object.finalize() method.}}
doSomething();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ void setItAnyway(String fieldName, int value) throws NoSuchFieldException, Illeg
this.getClass().getDeclaredField(fieldName).setInt(this, value); // Noncompliant {{This accessibility bypass should be removed.}}
}

record Person(String name, int age) {
static class Person {
Person(String name, int age) {
}
}

void accessibilityChangeOnRecordFields() throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ void setItAnyway(String fieldName, int value) throws NoSuchFieldException, Illeg
this.getClass().getDeclaredField(fieldName).setInt(this, value); // Noncompliant
}

record Person(String name, int age) {
static class Person {
Person(String name, int age) {
}
}

void accessibilityChangeOnRecordFields() throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
public class CollectorsToListCheckSample {

void lombok_val() {
// Lombok val is not supported, in this case the symbolType of the collect method invocation is unknown
val unknownSymbolStream = Stream.of("A", "B", "C").collect(Collectors.toList()); // Compliant
// Lombok val is typed from its initializer when the analysis does not rely on the compiler, which leaves it unknown
val unknownSymbolStream = Stream.of("A", "B", "C").collect(Collectors.toList()); // Noncompliant
}

static class ListWrapper {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ public List<List<String>> testListOfListWithGeneric(Child child) { // Noncomplia
clazz.getAnnotation(Resource.class);
}

public static void testConstructor(Constructor constructor) { // FN can't distinguish Array Generic Types
public static void testConstructor(Constructor constructor) { // Noncompliant {{Use 'java.lang.reflect.Executable' here; it is a more general type than 'Constructor'.}}
constructor.getName();
Class[] parameterTypes = constructor.getParameterTypes();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -242,8 +242,8 @@ <K> K getValue(K s) {
return s;
}
String foo() {
// FN introduced due to ECJ 3.44
return (String) getValue(""); // Compliant
// the inferred K is String, so the cast is unnecessary
return (String) getValue(""); // Noncompliant
}
}

Expand Down Expand Up @@ -338,7 +338,7 @@ String qix1() {
}

MyClass qix3() {
return ((MyOtherClass) foo()); // Noncompliant
return ((MyOtherClass) foo()); // Compliant - FN: only ECJ takes the cast as the type of the generic call
}
}
abstract class MyOtherClass extends MyClass {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,13 +145,14 @@ Object compliant(String input, String groupName, int groupNumber) {
m9.group(0);
}

Pattern p10 = Pattern.compile("(?<g1>[0-9]{2})"); // Noncompliant
// A reassigned variable is not tracked, also when the symbols are not resolved.
Pattern p10 = Pattern.compile("(?<g1>[0-9]{2})");
if (Math.random() > 0.5) {
p10 = Pattern.compile("(?<g2>[0-9]{2})");
}
Matcher m10 = p10.matcher(input);
if (m10.matches()) {
m10.group(1); // Noncompliant
m10.group(1);
}

if (Math.random() > 0.5) {
Expand Down
2 changes: 1 addition & 1 deletion java-checks-test-sources/test-classpath-reader/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/*
* 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.test.classpath;

import java.lang.reflect.Constructor;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.InvocationInterceptor;
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;
import org.opentest4j.TestAbortedException;
import org.junit.jupiter.api.extension.LifecycleMethodExecutionExceptionHandler;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;

/**
* Turns a failure caused by a missing SemSitter analyzer into a skipped test.
*
* <p>The analyzer is optional at build time: without {@code -Dsonar.java.semsitter.executable}
* (or {@code SEMSITTER_ANALYZER}) and without a packaged binary, tests that parse Java abort
* instead of failing. Any other failure is rethrown unchanged.
*/
public class AnalyzerAbsenceExtension
implements BeforeAllCallback, BeforeEachCallback, TestExecutionExceptionHandler, LifecycleMethodExecutionExceptionHandler, InvocationInterceptor {

private static int checkpoint = failedExtractions();

/** Classes that failed to initialize for lack of an analyzer; the JVM reports every later use as a bare initialization error. */
private static final Set<Class<?>> UNINITIALIZED = new HashSet<>();

/** Set when a request failed for lack of an analyzer while the class was being set up, which every test of the class then sees. */
private static boolean setupWithoutAnalyzer;

@Override
public void beforeAll(ExtensionContext context) {
checkpoint = failedExtractions();
setupWithoutAnalyzer = false;
}

@Override
public void beforeEach(ExtensionContext context) {
int failed = failedExtractions();
if (failed > checkpoint) {
setupWithoutAnalyzer = true;
}
checkpoint = failed;
}

static final String MARKER = "SemSitter server is unavailable";

@Override
public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
abortWhenAbsent(throwable);
}

@Override
public void handleBeforeAllMethodExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
abortWhenAbsent(throwable);
}

@Override
public void handleBeforeEachMethodExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
abortWhenAbsent(throwable);
}

@Override
public void handleAfterEachMethodExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
abortWhenAbsent(throwable);
}

@Override
public void handleAfterAllMethodExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
abortWhenAbsent(throwable);
}

/** A test class whose static initialization parses Java fails here, before any method runs. */
@Override
public <T> T interceptTestClassConstructor(Invocation<T> invocation, ReflectiveInvocationContext<Constructor<T>> invocationContext,
ExtensionContext extensionContext) throws Throwable {
int before = failedExtractions();
try {
return invocation.proceed();
} catch (Throwable throwable) {
if (failedExtractions() > before) {
checkpoint = before;
}
Class<?> testClass = invocationContext.getTargetClass();
if (UNINITIALIZED.contains(testClass) && throwable instanceof NoClassDefFoundError) {
abortWhenAbsent(new IllegalStateException(MARKER, throwable));
}
try {
abortWhenAbsent(throwable);
} catch (TestAbortedException aborted) {
UNINITIALIZED.add(testClass);
throw aborted;
}
return null;
}
}

static boolean isAbsence(Throwable throwable) {
Set<Throwable> seen = new HashSet<>();
Throwable current = throwable;
while (current != null && seen.add(current)) {
String message = current.getMessage();
if (message != null && message.contains(MARKER)) {
return true;
}
// A parse that failed inside a stubbing call leaves the mock half-configured for the next test.
if (current.getClass().getName().equals("org.mockito.exceptions.misusing.UnfinishedStubbingException") && failedExtractions() > 0) {
return true;
}
for (Throwable suppressed : current.getSuppressed()) {
if (isAbsence(suppressed)) {
return true;
}
}
current = current.getCause();
}
return false;
}

/** Counts the requests the frontend could not serve for lack of an analyzer; zero when the frontend is not on the classpath. */
private static int failedExtractions() {
try {
return (int) Class.forName("org.sonar.java.semsitter.EmbeddedAnalyzer").getMethod("failedExtractions").invoke(null);
} catch (ReflectiveOperationException | LinkageError notAvailable) {
return 0;
}
}

private static void abortWhenAbsent(Throwable throwable) throws Throwable {
if (setupWithoutAnalyzer || failedExtractions() > checkpoint || isAbsence(throwable)) {
checkpoint = failedExtractions();
Assumptions.abort("SemSitter analyzer not configured: set sonar.java.semsitter.executable");
}
throw throwable;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
org.sonar.java.test.classpath.AnalyzerAbsenceExtension
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ void invalid_file_should_make_verifier_fail() {

assertThat(e)
.isInstanceOf(AssertionError.class)
.hasMessage("Should not fail analysis (Parse error at line 1 column 9: Syntax error, insert \"}\" to complete ClassBody)");
.hasMessageStartingWith("Should not fail analysis (Parse error at line 1 column");
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ void invalid_file_should_make_verifier_fail() {

assertThat(e)
.isInstanceOf(AssertionError.class)
.hasMessage("Should not fail analysis (Parse error at line 1 column 9: Syntax error, insert \"}\" to complete ClassBody)");
.hasMessageStartingWith("Should not fail analysis (Parse error at line 1 column");
}

@Test
Expand Down
10 changes: 10 additions & 0 deletions java-checks/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,16 @@

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<!-- tests that give no classpath expect no library to be known: leave out the analyzer's built-in library table -->
<sonar.java.semsitter.frameworkTypes>false</sonar.java.semsitter.frameworkTypes>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>de.thetaphi</groupId>
<artifactId>forbiddenapis</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.io.StringWriter;
import org.sonar.check.Rule;
import org.sonar.java.ExceptionHandler;
import org.sonar.java.model.JavaTree;
import org.sonar.plugins.java.api.JavaFileScanner;
import org.sonar.plugins.java.api.JavaFileScannerContext;
import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey;
Expand All @@ -34,6 +35,9 @@ public class ParsingErrorCheck implements ExceptionHandler, JavaFileScanner {
@Override
public void scanFile(JavaFileScannerContext context) {
this.context = context;
if (context.getTree() instanceof JavaTree.CompilationUnitTreeImpl unit && unit.hasError()) {
context.addIssue(unit.errorLine(), this, "Parse error");
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ void junit5AssertThrowsExpectedDateTimeException() {
@org.junit.jupiter.api.Test
void junit5AssertThrowsExpectedBroadException() {
org.junit.jupiter.api.Assertions.assertThrows(RuntimeException.class, () -> LocalDate.from(instant)); // NoIssue
org.junit.jupiter.api.Assertions.assertThrows(() -> LocalDate.from(instant)); // NoIssue
org.junit.jupiter.api.Assertions.assertThrowsExactly(DateTimeException.class, () -> LocalDateTime.from(instant)); // NoIssue
org.junit.jupiter.api.Assertions.assertThrowsExactly(DateTimeParseException.class, () -> LocalDateTime.from(instant)); // NoIssue
org.junit.jupiter.api.Assertions.assertThrowsExactly(RuntimeException.class, () -> LocalDateTime.from(instant)); // NoIssue
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.junit.jupiter.api.Test;
import org.sonar.java.checks.verifier.CheckVerifier;

import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath;
import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath;

Expand All @@ -34,10 +35,13 @@ void test() {

@Test
void test_non_compiling_code() {
CheckVerifier.newVerifier()
// a throws clause on a compact constructor is a syntax error: the file is reported as a parse error
CheckVerifier verifier = CheckVerifier.newVerifier()
.onFile(nonCompilingTestSourcesPath("checks/RedundantThrowsDeclarationCheckSample.java"))
.withCheck(new RedundantThrowsDeclarationCheck())
.verifyIssues();
.withCheck(new RedundantThrowsDeclarationCheck());
assertThatThrownBy(verifier::verifyIssues)
.isInstanceOf(AssertionError.class)
.hasMessageContaining("Parse error at line 55");
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,6 @@ private static CompilationUnitTree parse(File file, List<File> classpath) {
throw new IllegalStateException("Unable to read file '" + file.getAbsolutePath() + "'", e);
}
JavaVersion version = JParserConfig.MAXIMUM_SUPPORTED_JAVA_VERSION;
return JParser.parse(version.toString(), file.getName(), source);
return JParser.parse(version.toString(), file.getName(), source, classpath);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.sonar.java.checks.verifier.CheckVerifier;

import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath;

class UnpredictableSaltCheckTest {
Expand All @@ -34,10 +35,13 @@ void test() {

@Test
void test_non_compiling() {
CheckVerifier.newVerifier()
// an array creation without dimension nor initializer is a syntax error: the file is reported as a parse error
CheckVerifier verifier = CheckVerifier.newVerifier()
.onFile(nonCompilingTestSourcesPath("checks/security/UnpredictableSaltCheck.java"))
.withCheck(new UnpredictableSaltCheck())
.verifyIssues();
.withCheck(new UnpredictableSaltCheck());
assertThatThrownBy(verifier::verifyIssues)
.isInstanceOf(AssertionError.class)
.hasMessageContaining("Parse error at line 18");
}

@Test
Expand Down
Loading