Skip to content
Merged
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 @@ -20,12 +20,9 @@
import com.sonarsource.scanner.engine.sensor.test.fixtures.TestInputFileBuilder;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.sonar.java.AnalysisProgress;
import org.sonar.java.model.JParseResult;
import org.sonar.java.model.JParser;
import org.sonar.plugins.java.api.JavaVersion;
import org.sonar.plugins.java.api.tree.*;
Expand Down Expand Up @@ -82,16 +79,7 @@ public static CompilationUnitTree parse(String source) {
.setContents(source)
.setCharset(StandardCharsets.UTF_8)
.build();
List<JParseResult> results = new ArrayList<>();
JParser.Mode.FILE_BY_FILE.create(version, classpath)
.parse(List.of(inputFile), () -> false, new AnalysisProgress(1), (input, result) -> results.add(result));
try {
return results.getFirst().get();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Unable to parse source", e);
}
return JParser.parse(inputFile, classpath, version);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,9 @@
import com.sonarsource.scanner.engine.sensor.test.fixtures.TestInputFileBuilder;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.sonar.java.AnalysisProgress;
import org.sonar.java.model.JParseResult;
import org.sonar.java.model.JParser;
import org.sonar.plugins.java.api.JavaVersion;
import org.sonar.plugins.java.api.tree.AssignmentExpressionTree;
Expand Down Expand Up @@ -92,16 +89,7 @@ public static CompilationUnitTree parse(String source) {
.setContents(source)
.setCharset(StandardCharsets.UTF_8)
.build();
List<JParseResult> results = new ArrayList<>();
JParser.Mode.FILE_BY_FILE.create(version, classpath)
.parse(List.of(inputFile), () -> false, new AnalysisProgress(1), (input, result) -> results.add(result));
try {
return results.getFirst().get();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Unable to parse source", e);
}
return JParser.parse(inputFile, classpath, version);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,12 @@
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.UnaryOperator;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.java.AnalysisProgress;
import org.sonar.java.SonarComponents;
import org.sonar.java.checks.verifier.TestUtils;
import org.sonar.java.model.JParseResult;
import org.sonar.java.model.JParser;
import org.sonar.java.model.VisitorsBridge;
import org.sonar.java.model.springcontext.BeanDefinitionGatherer;
Expand All @@ -45,7 +42,6 @@
import org.sonar.java.telemetry.NoOpTelemetry;
import org.sonar.java.test.classpath.TestClasspathUtils;
import org.sonar.plugins.java.api.JavaCheck;
import org.sonar.plugins.java.api.JavaVersion;
import org.sonar.plugins.java.api.tree.CompilationUnitTree;

/**
Expand Down Expand Up @@ -169,16 +165,6 @@ private static InputFile inputFile(File file) {
}

private static CompilationUnitTree parse(File file, List<File> classpath) {
List<JParseResult> results = new ArrayList<>();
JavaVersion version = JParser.MAXIMUM_SUPPORTED_JAVA_VERSION;
JParser.Mode.FILE_BY_FILE.create(version, classpath)
.parse(List.of(inputFile(file)), () -> false, new AnalysisProgress(1), (input, result) -> results.add(result));
try {
return results.getFirst().get();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Unable to parse file '" + file.getAbsolutePath() + "'", e);
}
return JParser.parse(inputFile(file), classpath, JParser.MAXIMUM_SUPPORTED_JAVA_VERSION);
}
}
13 changes: 13 additions & 0 deletions java-frontend/src/main/java/org/sonar/java/model/JParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package org.sonar.java.model;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.BooleanSupplier;
Expand All @@ -42,6 +43,18 @@ public JParser create(JavaVersion javaVersion, List<File> classpath, boolean sho
}
}

static JavaTree.CompilationUnitTreeImpl parse(InputFile inputFile, List<File> classpath, JavaVersion javaVersion) {
List<JParseResult> results = new ArrayList<>(1);
Mode.FILE_BY_FILE.create(javaVersion, classpath).parse(List.of(inputFile), () -> false, new AnalysisProgress(1), (input, result) -> results.add(result));
try {
return results.getFirst().get();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Unable to parse file '" + inputFile.absolutePath() + "'", e);
}
}

void parse(Iterable<InputFile> inputFiles, BooleanSupplier isCanceled, AnalysisProgress analysisProgress, BiConsumer<InputFile, JParseResult> action);

}
81 changes: 81 additions & 0 deletions java-frontend/src/test/java/org/sonar/java/model/JParserTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,87 @@ class Example {
@RegisterExtension
public ThreadLocalLogTester logTester = new ThreadLocalLogTester().setLevel(Level.DEBUG);

@Test
void should_parse_input_file_with_empty_classpath() throws IOException {
InputFile input = inputFile("SingleFile.java", "class SingleFile { String value; }");

CompilationUnitTree tree = JParser.parse(input, List.of(), MAXIMUM_SUPPORTED_JAVA_VERSION);

assertThat(tree.types()).hasSize(1);
ClassTree type = (ClassTree) tree.types().getFirst();
assertThat(type.simpleName().name()).isEqualTo("SingleFile");
VariableTree field = (VariableTree) type.members().getFirst();
assertThat(field.type().symbolType().fullyQualifiedName()).isEqualTo("java.lang.String");
assertThat(tree.semanticProblems()).isEmpty();
}

@Test
void should_parse_input_file_with_supplied_classpath() throws IOException {
InputFile input = inputFile("Dependency.java", "class Example { org.apache.commons.collections.Bag value; }");

CompilationUnitTree withoutClasspath = JParser.parse(input, List.of(), MAXIMUM_SUPPORTED_JAVA_VERSION);
assertThat(withoutClasspath.semanticProblems()).isNotEmpty();

List<File> classpath = List.of(new File("target/test-projects/commons-collections/bin"));
CompilationUnitTree tree = JParser.parse(input, classpath, MAXIMUM_SUPPORTED_JAVA_VERSION);

assertThat(tree.semanticProblems()).isEmpty();
ClassTree type = (ClassTree) tree.types().getFirst();
VariableTree field = (VariableTree) type.members().getFirst();
assertThat(field.type().symbolType().fullyQualifiedName()).isEqualTo("org.apache.commons.collections.Bag");
}

@Test
void should_parse_input_file_with_supplied_java_version() throws IOException {
assumeRunningJdkCanServeOlderReleases();
InputFile input = inputFile("Version.java", JDK_API_SOURCE);
List<File> classpath = List.of(runningJdkRuntimeImage());

CompilationUnitTree java11 = JParser.parse(input, classpath, new JavaVersionImpl(11));
CompilationUnitTree java17 = JParser.parse(input, classpath, new JavaVersionImpl(17));

assertThat(java11.semanticProblems()).extracting(Problem::message)
.containsExactly("java.lang.Record cannot be resolved to a type");
assertThat(java17.semanticProblems()).extracting(Problem::message)
.containsExactly("java.util.jar.Pack200 cannot be resolved to a type");
}

@Test
void should_throw_syntax_errors_when_parsing_input_file() throws IOException {
InputFile input = inputFile("Invalid.java", "class Example");

RecognitionException exception = assertThrows(RecognitionException.class, () -> JParser.parse(input, List.of(), MAXIMUM_SUPPORTED_JAVA_VERSION));

assertThat(exception.getLine()).isEqualTo(1);
}

@Test
void should_wrap_file_reading_exception_when_parsing_input_file() throws IOException {
InputFile input = mock(InputFile.class);
when(input.absolutePath()).thenReturn("/tmp/Example.java");
when(input.filename()).thenReturn("Example.java");
IOException expected = new IOException("Unable to read source");
when(input.contents()).thenThrow(expected);

IllegalStateException actual = assertThrows(IllegalStateException.class, () -> JParser.parse(input, List.of(), MAXIMUM_SUPPORTED_JAVA_VERSION));

assertThat(actual).hasMessage("Unable to parse file '/tmp/Example.java'");
assertSame(expected, actual.getCause());
}

@Test
void should_rethrow_runtime_exception_when_parsing_input_file() throws IOException {
InputFile input = mock(InputFile.class);
when(input.absolutePath()).thenReturn("/tmp/Example.java");
when(input.filename()).thenReturn("Example.java");
RuntimeException expected = new IllegalArgumentException("Unable to read source");
when(input.contents()).thenThrow(expected);

RuntimeException actual = assertThrows(RuntimeException.class, () -> JParser.parse(input, List.of(), MAXIMUM_SUPPORTED_JAVA_VERSION));

assertSame(expected, actual);
}

@Test
void should_only_see_the_jdk_api_of_the_requested_release() throws IOException {
assumeRunningJdkCanServeOlderReleases();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.sonar.java.AnalysisProgress;
import org.sonar.java.test.classpath.TestClasspathUtils;
import org.sonar.plugins.java.api.JavaVersion;
import org.sonar.plugins.java.api.semantic.Sema;
Expand Down Expand Up @@ -125,16 +124,7 @@ public static CompilationUnitTree parse(String unitName, String source, List<Fil
.setContents(source)
.setCharset(StandardCharsets.UTF_8)
.build();
List<JParseResult> results = new ArrayList<>();
JParser.Mode.FILE_BY_FILE.create(version, classpath)
.parse(List.of(inputFile), () -> false, new AnalysisProgress(1), (input, result) -> results.add(result));
try {
return results.getFirst().get();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Unable to parse source", e);
}
return JParser.parse(inputFile, classpath, version);
}

public static List<File> checksTestClassPath() throws IOException {
Expand Down
3 changes: 2 additions & 1 deletion sonar-java-plugin/src/main/resources/static/documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ The tutorial [Writing Custom Java Rules 101](https://redirect.sonarsource.com/do
* `org.sonar.java.model.JParser` is now an interface, independent of the underlying parser implementation, and replaces `JParserConfig`.
Create parsers with `JParser.Mode.BATCH.create(JavaVersion, List<File>)` or `JParser.Mode.FILE_BY_FILE.create(JavaVersion, List<File>)`. Both factories also accept an optional third `boolean` argument to ignore the unnamed module for split packages.
`JParserConfig` has been removed together with `JParserConfig#astParser()`, `JParserConfig#parse(String unitName, String source)`, and the `ParserConfigConstructor` interface. The string-based `parse(String version, String unitName, String source)` overload and the static `JParser.parse(JParser, String, String, String)` have also been removed.
Migrate consumers of these entry points to `JParser.Mode#create(...)` and `JParser#parse(Iterable<InputFile>, BooleanSupplier, AnalysisProgress, BiConsumer<InputFile, JParseResult>)` for all parsing, including a single file supplied as `List.of(inputFile)`.
Migrate single-file consumers to `JParser.parse(inputFile, classpath, javaVersion)`. For multiple files or custom parser options, use `JParser.Mode#create(...)` and `JParser#parse(Iterable<InputFile>, BooleanSupplier, AnalysisProgress, BiConsumer<InputFile, JParseResult>)`.
`MAXIMUM_SUPPORTED_JAVA_VERSION` has moved from `JParserConfig` to `JParser.MAXIMUM_SUPPORTED_JAVA_VERSION`.
The Java version and classpath are set when creating the parser; source contents, filename, and charset come from each `InputFile`.
The input parameter now takes `Iterable<InputFile>` instead of `Iterable<? extends InputFile>`; callers must supply an `Iterable<InputFile>`, and implementations must update their override signatures.
Expand All @@ -175,6 +175,7 @@ The tutorial [Writing Custom Java Rules 101](https://redirect.sonarsource.com/do

**Added**

* New static method: `JParser.parse(InputFile, List<File>, JavaVersion)`. Creates a file-by-file parser with the supplied classpath and Java version and returns the file's `JavaTree.CompilationUnitTreeImpl`. Checked exceptions are wrapped in an `IllegalStateException` with the input file's path in the message and the original exception as the cause. Runtime exceptions are rethrown unchanged, so callers do not need to handle or declare checked parsing exceptions.
* New method: `Symbol.MethodSymbol#annotationElementDefaultValue()`. Returns an annotation element's default value, or `null` if it has none.
Values use the same representation as `SymbolMetadata.AnnotationValue#value()`: constants, type symbols, variable symbols, annotation instances, or arrays of these values.
* New beta interfaces in `org.sonar.plugins.java.api.diagnostics`: `Problem` exposes `type()` and `message()`; `Warning` extends `Problem` and adds `syntaxTree()`, which returns the associated, non-null AST node.
Expand Down
Loading