diff --git a/java-checks-common/src/test/java/org/sonar/java/checks/helpers/JParserTestUtils.java b/java-checks-common/src/test/java/org/sonar/java/checks/helpers/JParserTestUtils.java index 4b89c3a7115..b771d91e687 100644 --- a/java-checks-common/src/test/java/org/sonar/java/checks/helpers/JParserTestUtils.java +++ b/java-checks-common/src/test/java/org/sonar/java/checks/helpers/JParserTestUtils.java @@ -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.*; @@ -82,16 +79,7 @@ public static CompilationUnitTree parse(String source) { .setContents(source) .setCharset(StandardCharsets.UTF_8) .build(); - List 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); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/helpers/JParserTestUtils.java b/java-checks/src/test/java/org/sonar/java/checks/helpers/JParserTestUtils.java index e61ccd632be..e545c875079 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/helpers/JParserTestUtils.java +++ b/java-checks/src/test/java/org/sonar/java/checks/helpers/JParserTestUtils.java @@ -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; @@ -92,16 +89,7 @@ public static CompilationUnitTree parse(String source) { .setContents(source) .setCharset(StandardCharsets.UTF_8) .build(); - List 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); } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/helpers/SpringContextModelTestUtils.java b/java-checks/src/test/java/org/sonar/java/checks/helpers/SpringContextModelTestUtils.java index 435b442a216..5556ffe5bd3 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/helpers/SpringContextModelTestUtils.java +++ b/java-checks/src/test/java/org/sonar/java/checks/helpers/SpringContextModelTestUtils.java @@ -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; @@ -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; /** @@ -169,16 +165,6 @@ private static InputFile inputFile(File file) { } private static CompilationUnitTree parse(File file, List classpath) { - List 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); } } 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 88c0e1eed8c..41f697f0a4c 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 @@ -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; @@ -42,6 +43,18 @@ public JParser create(JavaVersion javaVersion, List classpath, boolean sho } } + static JavaTree.CompilationUnitTreeImpl parse(InputFile inputFile, List classpath, JavaVersion javaVersion) { + List 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 inputFiles, BooleanSupplier isCanceled, AnalysisProgress analysisProgress, BiConsumer action); } diff --git a/java-frontend/src/test/java/org/sonar/java/model/JParserTest.java b/java-frontend/src/test/java/org/sonar/java/model/JParserTest.java index cad4c86a4cf..a01d3904a9d 100644 --- a/java-frontend/src/test/java/org/sonar/java/model/JParserTest.java +++ b/java-frontend/src/test/java/org/sonar/java/model/JParserTest.java @@ -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 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 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(); diff --git a/java-frontend/src/test/java/org/sonar/java/model/JParserTestUtils.java b/java-frontend/src/test/java/org/sonar/java/model/JParserTestUtils.java index d80e7603da1..46a3564017c 100644 --- a/java-frontend/src/test/java/org/sonar/java/model/JParserTestUtils.java +++ b/java-frontend/src/test/java/org/sonar/java/model/JParserTestUtils.java @@ -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; @@ -125,16 +124,7 @@ public static CompilationUnitTree parse(String unitName, String source, List 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 checksTestClassPath() throws IOException { diff --git a/sonar-java-plugin/src/main/resources/static/documentation.md b/sonar-java-plugin/src/main/resources/static/documentation.md index cfbfe503d23..6c0816be05d 100644 --- a/sonar-java-plugin/src/main/resources/static/documentation.md +++ b/sonar-java-plugin/src/main/resources/static/documentation.md @@ -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)` or `JParser.Mode.FILE_BY_FILE.create(JavaVersion, List)`. 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, BooleanSupplier, AnalysisProgress, BiConsumer)` 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, BooleanSupplier, AnalysisProgress, BiConsumer)`. `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` instead of `Iterable`; callers must supply an `Iterable`, and implementations must update their override signatures. @@ -175,6 +175,7 @@ The tutorial [Writing Custom Java Rules 101](https://redirect.sonarsource.com/do **Added** +* New static method: `JParser.parse(InputFile, List, 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.