diff --git a/java-checks/src/main/java/org/sonar/java/checks/RedundantTypeCastCheck.java b/java-checks/src/main/java/org/sonar/java/checks/RedundantTypeCastCheck.java index ad2f59e5b9f..92b4508b0d9 100644 --- a/java-checks/src/main/java/org/sonar/java/checks/RedundantTypeCastCheck.java +++ b/java-checks/src/main/java/org/sonar/java/checks/RedundantTypeCastCheck.java @@ -21,14 +21,14 @@ import org.sonar.java.checks.helpers.NumericConversionUtils; import org.sonar.java.checks.helpers.QuickFixHelper; import org.sonar.java.model.ExpressionUtils; -import org.sonar.java.model.JProblem; -import org.sonar.java.model.JWarning; -import org.sonar.java.model.JavaTree; import org.sonar.java.reporting.AnalyzerMessage; import org.sonar.java.reporting.JavaQuickFix; import org.sonar.java.reporting.JavaTextEdit; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; +import org.sonar.plugins.java.api.diagnostics.Warning; import org.sonar.plugins.java.api.semantic.Type; +import org.sonar.plugins.java.api.tree.CompilationUnitTree; import org.sonar.plugins.java.api.tree.ExpressionTree; import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; import org.sonar.plugins.java.api.tree.MethodInvocationTree; @@ -40,7 +40,7 @@ @Rule(key = "S1905") public class RedundantTypeCastCheck extends IssuableSubscriptionVisitor { - private List warnings; + private List warnings; @Override public List nodesToVisit() { @@ -50,7 +50,7 @@ public List nodesToVisit() { @Override public void visitNode(Tree tree) { if (tree.is(Tree.Kind.COMPILATION_UNIT)) { - warnings = ((JavaTree.CompilationUnitTreeImpl) tree).warnings(JProblem.Type.REDUNDANT_CAST); + warnings = ((CompilationUnitTree) tree).warnings(ProblemKind.REDUNDANT_CAST); return; } @@ -95,7 +95,7 @@ private boolean isUnnecessaryCast(TypeCastTree typeCastTree) { // returns Class at compile time. To prevent false-positives, we ignore this case. return false; } - return warnings.stream().anyMatch(warning -> matchesWarning(warning, typeCastTree)); + return warnings.stream().anyMatch(warning -> typeCastTree.equals(warning.syntaxTree())); } private static boolean isMethodInvocationReceiverOfGetClass(TypeCastTree typeCastTree) { @@ -106,16 +106,6 @@ private static boolean isMethodInvocationReceiverOfGetClass(TypeCastTree typeCas methodInvocation.arguments().isEmpty(); } - private static boolean matchesWarning(JWarning warning, TypeCastTree tree) { - Tree warningTree = warning.syntaxTree(); - if (warningTree.is(Tree.Kind.PARENTHESIZED_EXPRESSION)) { - // When a cast expression is nested inside one or more parenthesized expression, Eclipse raises the warning on - // the outermost parenthesized expression rather than the cast expression, so we need to take that into account - return tree.equals(skipParentheses(warningTree)); - } - return tree.equals(warningTree); - } - @Override protected void clearState() { warnings = null; diff --git a/java-checks/src/main/java/org/sonar/java/checks/SelfAssignmentCheck.java b/java-checks/src/main/java/org/sonar/java/checks/SelfAssignmentCheck.java index 608514a5305..0a447962703 100644 --- a/java-checks/src/main/java/org/sonar/java/checks/SelfAssignmentCheck.java +++ b/java-checks/src/main/java/org/sonar/java/checks/SelfAssignmentCheck.java @@ -15,6 +15,7 @@ * along with this program; if not, see https://sonarsource.com/license/ssal/ */ package org.sonar.java.checks; + import java.util.Arrays; import java.util.HashSet; import java.util.List; @@ -22,15 +23,15 @@ import org.sonar.check.Rule; import org.sonar.java.checks.helpers.QuickFixHelper; import org.sonar.java.model.ExpressionUtils; -import org.sonar.java.model.JProblem; -import org.sonar.java.model.JWarning; -import org.sonar.java.model.JavaTree; import org.sonar.java.model.SyntacticEquivalence; import org.sonar.java.reporting.JavaQuickFix; import org.sonar.java.reporting.JavaTextEdit; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; +import org.sonar.plugins.java.api.diagnostics.Warning; import org.sonar.plugins.java.api.tree.AssignmentExpressionTree; import org.sonar.plugins.java.api.tree.ClassTree; +import org.sonar.plugins.java.api.tree.CompilationUnitTree; import org.sonar.plugins.java.api.tree.ExpressionTree; import org.sonar.plugins.java.api.tree.IdentifierTree; import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; @@ -45,7 +46,7 @@ public class SelfAssignmentCheck extends IssuableSubscriptionVisitor { private static final String ISSUE_MESSAGE = "Remove or correct this useless self-assignment."; - private final Set warnings = new HashSet<>(); + private final Set warnings = new HashSet<>(); @Override public List nodesToVisit() { @@ -56,7 +57,7 @@ public List nodesToVisit() { public void visitNode(Tree tree) { if (tree.is(Tree.Kind.COMPILATION_UNIT)) { warnings.clear(); - warnings.addAll(((JavaTree.CompilationUnitTreeImpl) tree).warnings(JProblem.Type.ASSIGNMENT_HAS_NO_EFFECT)); + warnings.addAll(((CompilationUnitTree) tree).warnings(ProblemKind.ASSIGNMENT_HAS_NO_EFFECT)); return; } AssignmentExpressionTree node = (AssignmentExpressionTree) tree; diff --git a/java-checks/src/main/java/org/sonar/java/checks/UnreachableCatchCheck.java b/java-checks/src/main/java/org/sonar/java/checks/UnreachableCatchCheck.java index dbe82afb9ab..953bd16ac3b 100644 --- a/java-checks/src/main/java/org/sonar/java/checks/UnreachableCatchCheck.java +++ b/java-checks/src/main/java/org/sonar/java/checks/UnreachableCatchCheck.java @@ -24,14 +24,14 @@ import java.util.List; import java.util.Map; import org.sonar.check.Rule; -import org.sonar.java.model.JProblem; -import org.sonar.java.model.JWarning; -import org.sonar.java.model.JavaTree.CompilationUnitTreeImpl; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.JavaFileScannerContext.Location; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; +import org.sonar.plugins.java.api.diagnostics.Warning; import org.sonar.plugins.java.api.location.Position; import org.sonar.plugins.java.api.semantic.Type; import org.sonar.plugins.java.api.tree.CatchTree; +import org.sonar.plugins.java.api.tree.CompilationUnitTree; import org.sonar.plugins.java.api.tree.SyntaxToken; import org.sonar.plugins.java.api.tree.Tree; import org.sonar.plugins.java.api.tree.TryStatementTree; @@ -41,7 +41,7 @@ @Rule(key = "S4970") public class UnreachableCatchCheck extends IssuableSubscriptionVisitor { - private final List warnings = new ArrayList<>(); + private final List warnings = new ArrayList<>(); private static final Comparator LOCATION_COMPARATOR = Comparator.comparing(loc -> Position.startOf(loc.syntaxNode)); @Override @@ -53,7 +53,7 @@ public List nodesToVisit() { public void visitNode(Tree tree) { if (tree.is(Tree.Kind.COMPILATION_UNIT)) { warnings.clear(); - warnings.addAll(((CompilationUnitTreeImpl) tree).warnings(JProblem.Type.MASKED_CATCH)); + warnings.addAll(((CompilationUnitTree) tree).warnings(ProblemKind.MASKED_CATCH)); return; } checkWarnings((TryStatementTree) tree); diff --git a/java-checks/src/main/java/org/sonar/java/checks/UselessImportCheck.java b/java-checks/src/main/java/org/sonar/java/checks/UselessImportCheck.java index 33187f485ff..33d0cfabd36 100644 --- a/java-checks/src/main/java/org/sonar/java/checks/UselessImportCheck.java +++ b/java-checks/src/main/java/org/sonar/java/checks/UselessImportCheck.java @@ -21,7 +21,6 @@ import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -29,17 +28,15 @@ import org.sonar.check.Rule; import org.sonar.java.checks.helpers.ExpressionsHelper; import org.sonar.java.checks.helpers.QuickFixHelper; -import org.sonar.java.model.JProblem; -import org.sonar.java.model.JWarning; -import org.sonar.java.model.JavaTree.CompilationUnitTreeImpl; import org.sonar.java.reporting.AnalyzerMessage; import org.sonar.java.reporting.JavaQuickFix; import org.sonar.java.reporting.JavaTextEdit; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; +import org.sonar.plugins.java.api.diagnostics.Warning; import org.sonar.plugins.java.api.tree.CompilationUnitTree; import org.sonar.plugins.java.api.tree.ExpressionTree; import org.sonar.plugins.java.api.tree.ImportTree; -import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; import org.sonar.plugins.java.api.tree.PackageDeclarationTree; import org.sonar.plugins.java.api.tree.SyntaxTrivia; import org.sonar.plugins.java.api.tree.SyntaxTrivia.CommentKind; @@ -50,7 +47,6 @@ @Rule(key = "S1128") public class UselessImportCheck extends IssuableSubscriptionVisitor { - private static final Pattern COMPILER_WARNING = Pattern.compile("The import ([$\\w]++(\\.[$\\w]++)*+) is never used"); private static final Pattern NON_WORDS_CHARACTERS = Pattern.compile("\\W+"); private static final Pattern JAVADOC_REFERENCE = Pattern.compile("\\{@link[^\\{\\}]++\\}|(@see|@throws)[^\r\n]++[\r\n]"); private static final Pattern MARKDOWN_REFERENCE = Pattern.compile("\\[[^\\[\\]\\r\\n]++\\]"); @@ -88,50 +84,40 @@ public void visitNode(Tree tree) { @Override public void leaveNode(Tree tree) { if (tree.is(Tree.Kind.COMPILATION_UNIT)) { - handleWarnings(((CompilationUnitTreeImpl) tree).warnings(JProblem.Type.UNUSED_IMPORT)); + handleWarnings(((CompilationUnitTree) tree).warnings(ProblemKind.UNUSED_IMPORT)); imports.clear(); } } - private void handleWarnings(List warnings) { - for (JWarning warning : warnings) { - Matcher matcher = COMPILER_WARNING.matcher(warning.message()); - Optional fqn = matcher.find() ? Optional.of(matcher.group(1)) : Optional.empty(); - fqn.ifPresent(importName -> { - if (!usedInJavaDoc.contains(importName) && !importName.startsWith("java.lang")) { - String message; - if (duplicatedImports.contains(importName)) { - message = "Remove this duplicated import."; - } else if (isImportFromSamePackage(importName, warning.syntaxTree())) { - message = "Remove this unnecessary import: same package classes are always implicitly imported."; - } else { - message = "Remove this unused import '" + importName + "'."; - } - ImportTree reportTree = (ImportTree) warning.syntaxTree(); - QuickFixHelper.newIssue(context) - .forRule(this) - .onTree(reportTree.qualifiedIdentifier()) - .withMessage(message) - .withQuickFix(() -> quickFix(reportTree, imports)) - .report(); + private void handleWarnings(List warnings) { + for (Warning warning : warnings) { + ImportTree reportTree = (ImportTree) warning.syntaxTree(); + String importName = ExpressionsHelper.concatenate((ExpressionTree) reportTree.qualifiedIdentifier()); + boolean onDemand = importName.endsWith(".*"); + if (onDemand) { + importName = importName.substring(0, importName.length() - 2); + } + if (!usedInJavaDoc.contains(importName) && !importName.startsWith("java.lang")) { + String message; + if (duplicatedImports.contains(importName)) { + message = "Remove this duplicated import."; + } else if (isImportFromSamePackage(importName, onDemand)) { + message = "Remove this unnecessary import: same package classes are always implicitly imported."; + } else { + message = "Remove this unused import '" + importName + "'."; } - }); - } - } - - private boolean isImportFromSamePackage(String importName, Tree tree) { - // ECJ warning message does not contain the ".*" in case of star import, we have to find out if we are in this case. - // Defensive programming, the syntax tree of the warning should always be an ImportTree. - if (tree.is(Tree.Kind.IMPORT)) { - Tree qualifiedIdentifier = ((ImportTree) tree).qualifiedIdentifier(); - // Defensive programming, the qualifiedIdentifier should always be a MemberSelectTree. - if (qualifiedIdentifier.is(Tree.Kind.MEMBER_SELECT) && - "*".equals(((MemberSelectExpressionTree) qualifiedIdentifier).identifier().name())) { - return importName.equals(currentPackage); + QuickFixHelper.newIssue(context) + .forRule(this) + .onTree(reportTree.qualifiedIdentifier()) + .withMessage(message) + .withQuickFix(() -> quickFix(reportTree, imports)) + .report(); } } + } - return importName.substring(0, importName.lastIndexOf(".")).equals(currentPackage); + private boolean isImportFromSamePackage(String importName, boolean onDemand) { + return onDemand ? importName.equals(currentPackage) : importName.substring(0, importName.lastIndexOf('.')).equals(currentPackage); } private void handleImportTree(ImportTree importTree) { diff --git a/java-frontend/src/main/java/org/sonar/java/SonarComponents.java b/java-frontend/src/main/java/org/sonar/java/SonarComponents.java index e57da7ea757..992dd4f39cb 100644 --- a/java-frontend/src/main/java/org/sonar/java/SonarComponents.java +++ b/java-frontend/src/main/java/org/sonar/java/SonarComponents.java @@ -64,7 +64,6 @@ import org.sonar.java.classpath.ClasspathForTest; import org.sonar.java.exceptions.ApiMismatchException; import org.sonar.java.model.GeneratedFile; -import org.sonar.java.model.JProblem; import org.sonar.java.model.LineUtils; import org.sonar.java.reporting.AnalyzerMessage; import org.sonar.java.reporting.JavaIssue; @@ -74,6 +73,8 @@ import org.sonar.plugins.java.api.JavaFileScanner; import org.sonar.plugins.java.api.JspCodeVisitor; import org.sonar.plugins.java.api.caching.SonarLintCache; +import org.sonar.plugins.java.api.diagnostics.Problem; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; import org.sonarsource.api.sonarlint.SonarLintSide; import org.sonarsource.sonarlint.plugin.api.SonarLintRuntime; @@ -120,7 +121,7 @@ public class SonarComponents extends CheckRegistrar.RegistrarContext { private final ClasspathForMain javaClasspath; private final ClasspathForTest javaTestClasspath; - private final Map> problemsToFilePaths = new HashMap<>(); + private final Map> problemsToFilePaths = new HashMap<>(); private final CheckFactory checkFactory; private final ActiveRules activeRules; @@ -613,9 +614,10 @@ public InputComponent project() { return context.project(); } - public void collectUndefinedTypes(String pathToFile, Set undefinedTypes) { - undefinedTypes.forEach(problem -> { - List filesAffectedByProblem = problemsToFilePaths.computeIfAbsent(problem, key -> new ArrayList<>()); + public void collectUndefinedTypes(String pathToFile, Set semanticProblems) { + semanticProblems.forEach(problem -> { + ProblemGroupKey problemGroupKey = new ProblemGroupKey(problem.type(), problem.message()); + List filesAffectedByProblem = problemsToFilePaths.computeIfAbsent(problemGroupKey, key -> new ArrayList<>()); filesAffectedByProblem.add(pathToFile); }); } @@ -639,31 +641,30 @@ public void logUndefinedTypes() { private void logUndefinedTypes(int maxLines) { logParserMessages( problemsToFilePaths.entrySet().stream() - .filter(entry -> entry.getKey().type() == JProblem.Type.UNDEFINED_TYPE), + .filter(entry -> entry.getKey().type() == ProblemKind.UNDEFINED_TYPE), maxLines, "Unresolved imports/types have been detected during analysis. Enable DEBUG mode to see them.", "Unresolved imports/types:" ); logParserMessages( problemsToFilePaths.entrySet().stream() - .filter(entry -> entry.getKey().type() == JProblem.Type.PREVIEW_FEATURE_USED), + .filter(entry -> entry.getKey().type() == ProblemKind.PREVIEW_FEATURE_USED), maxLines, "Use of preview features have been detected during analysis. Enable DEBUG mode to see them.", "Use of preview features:" ); } - private static void logParserMessages(Stream>> messages, int maxProblems, String warningMessage, - String debugMessage) { + private static void logParserMessages(Stream>> messages, int maxProblems, String warningMessage, String debugMessage) { String problemDelimiter = System.lineSeparator() + "- "; List> messagesList = messages - .sorted(Comparator.comparing(entry -> entry.getKey().toString())) + .sorted(Comparator.comparing(entry -> entry.getKey().message())) // We only consider the first `maxProblems` elements. We keep an extra one to know if we passed the threshold in later tests. .limit(maxProblems + 1L) .map(entry -> { List paths = entry.getValue(); List problemAndPaths = new ArrayList<>(paths.size() + 1); - problemAndPaths.add(problemDelimiter + entry.getKey().toString()); + problemAndPaths.add(problemDelimiter + entry.getKey().message()); paths.forEach(path -> problemAndPaths.add(" * " + path)); return problemAndPaths; }) @@ -700,4 +701,6 @@ public Configuration getConfiguration() { return context.config(); } + private record ProblemGroupKey(ProblemKind type, String message) {} + } diff --git a/java-frontend/src/main/java/org/sonar/java/ast/JavaAstScanner.java b/java-frontend/src/main/java/org/sonar/java/ast/JavaAstScanner.java index 5674d4f34ed..250505e02af 100644 --- a/java-frontend/src/main/java/org/sonar/java/ast/JavaAstScanner.java +++ b/java-frontend/src/main/java/org/sonar/java/ast/JavaAstScanner.java @@ -39,7 +39,6 @@ import org.sonar.java.annotations.VisibleForTesting; import org.sonar.java.model.InputFileUtils; import org.sonar.java.model.JParserConfig; -import org.sonar.java.model.JProblem; import org.sonar.java.model.JavaTree; import org.sonar.java.model.VisitorsBridge; import org.sonar.java.telemetry.NoOpTelemetry; @@ -47,6 +46,7 @@ import org.sonar.java.telemetry.TelemetryKey; import org.sonar.java.telemetry.TelemetryKey.JavaAnalysisKeys; import org.sonar.plugins.java.api.JavaVersion; +import org.sonar.plugins.java.api.diagnostics.Problem; import org.sonar.plugins.java.api.tree.CompilationUnitTree; import static java.lang.System.currentTimeMillis; @@ -165,7 +165,7 @@ public void simpleScan(InputFile inputFile, JParserConfig.Result result, Consume modifyCompilationUnit.accept(ast); visitor.visitFile(ast, sonarComponents != null && sonarComponents.fileCanBeSkipped(inputFile)); String path = inputFile.toString(); - Set undefinedTypes = ast.undefinedTypes(); + Set undefinedTypes = ast.semanticProblems(); collectUndefinedTypes(path, undefinedTypes); cleanUp.accept(ast); telemetryAnalysisKeys = javaAnalysisKeys.success(); @@ -198,7 +198,7 @@ private static void cleanUpAst(JavaTree.CompilationUnitTreeImpl ast) { ast.getEnvironmentCleaner().run(); } - private void collectUndefinedTypes(String path, Set undefinedTypes) { + private void collectUndefinedTypes(String path, Set undefinedTypes) { if (sonarComponents != null) { sonarComponents.collectUndefinedTypes(path, undefinedTypes); } 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 911c60bc7d6..a0d5af34a00 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 @@ -27,8 +27,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.Set; -import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; @@ -257,21 +255,6 @@ public class JParser { private static final Logger LOG = LoggerFactory.getLogger(JParser.class); - private static final Set WRONGLY_CATEGORIZED_AS_SYNTAX_ERROR = Set.of( - // Accept missing default clause, it may be due to missing semantic information of the switch expression, - // in this case, an enum fully covered with the switch cases will be seen as something that is not an enum - // when it is unknown, and the parser will wrongly consider the missing default clause as a syntax error. - IProblem.SwitchExpressionsYieldMissingDefaultCase, - // Accept missing default clause, it may be due the switch expression being an enum from a wrong dependency. - // In this case, the parser will wrongly consider the missing default clause as a syntax error. - IProblem.SwitchExpressionsYieldMissingEnumConstantCase - ); - - private static final Predicate IS_SYNTAX_ERROR = error -> ((error.getID() & IProblem.Syntax) != 0) && - !WRONGLY_CATEGORIZED_AS_SYNTAX_ERROR.contains(error.getID()); - - private static final Predicate IS_UNDEFINED_TYPE_ERROR = error -> (error.getID() & IProblem.UndefinedType) != 0; - /** * @param unitName see {@link ASTParser#setUnitName(String)} * @throws RecognitionException in case of syntax errors @@ -293,7 +276,7 @@ public static JavaTree.CompilationUnitTreeImpl parse(ASTParser astParser, String static JavaTree.CompilationUnitTreeImpl convert(String version, String unitName, String source, CompilationUnit astNode) { List errors = Stream.of(astNode.getProblems()).filter(IProblem::isError).toList(); - Optional possibleSyntaxError = errors.stream().filter(IS_SYNTAX_ERROR).findFirst(); + Optional possibleSyntaxError = errors.stream().filter(JProblem::isSyntaxError).findFirst(); LineColumnConverter lineColumnConverter = new LineColumnConverter(source); if (possibleSyntaxError.isPresent()) { IProblem syntaxError = possibleSyntaxError.get(); @@ -303,13 +286,6 @@ static JavaTree.CompilationUnitTreeImpl convert(String version, String unitName, throw new RecognitionException(pos.line(), message); } - Set undefinedTypes = errors.stream() - .filter(IS_UNDEFINED_TYPE_ERROR) - .map(i -> new JProblem( - i.getMessage(), - (i.getID() & IProblem.PreviewFeatureUsed) == 0 ? JProblem.Type.UNDEFINED_TYPE : JProblem.Type.PREVIEW_FEATURE_USED)) - .collect(Collectors.toSet()); - JParser converter = new JParser(); converter.sema = new JSema(astNode.getAST()); converter.compilationUnit = astNode; @@ -317,7 +293,7 @@ static JavaTree.CompilationUnitTreeImpl convert(String version, String unitName, converter.lineColumnConverter = lineColumnConverter; JavaTree.CompilationUnitTreeImpl tree = converter.convertCompilationUnit(astNode); - tree.setSemanticModel(converter.sema, undefinedTypes, converter.sema.getEnvironmentCleaner()); + tree.setSemanticModel(converter.sema, JProblem.semanticProblems(errors), converter.sema.getEnvironmentCleaner()); JWarning.Mapper.warningsFor(astNode, converter.lineColumnConverter).mappedInto(tree); ASTUtils.mayTolerateMissingType(astNode.getAST()); diff --git a/java-frontend/src/main/java/org/sonar/java/model/JParserConfig.java b/java-frontend/src/main/java/org/sonar/java/model/JParserConfig.java index 79cffd79a90..9a1c803dcd0 100644 --- a/java-frontend/src/main/java/org/sonar/java/model/JParserConfig.java +++ b/java-frontend/src/main/java/org/sonar/java/model/JParserConfig.java @@ -125,7 +125,7 @@ public ASTParser astParser() { options.put(JavaCore.COMPILER_PB_ENABLE_PREVIEW_FEATURES, "enabled"); } // enabling all supported compiler warnings - JProblem.Type.compilerOptions() + JProblem.compilerOptions() .forEach(option -> options.put(option, "warning")); astParser.setCompilerOptions(options); diff --git a/java-frontend/src/main/java/org/sonar/java/model/JProblem.java b/java-frontend/src/main/java/org/sonar/java/model/JProblem.java index 38abd459dad..2dc6186f0b9 100644 --- a/java-frontend/src/main/java/org/sonar/java/model/JProblem.java +++ b/java-frontend/src/main/java/org/sonar/java/model/JProblem.java @@ -16,50 +16,62 @@ */ package org.sonar.java.model; -import java.util.Collections; -import java.util.HashSet; +import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Set; -import java.util.stream.Stream; +import java.util.stream.Collectors; +import javax.annotation.CheckForNull; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.compiler.IProblem; -import org.sonar.plugins.java.api.tree.Tree; -import org.sonarsource.analyzer.commons.collections.SetUtils; +import org.sonar.plugins.java.api.diagnostics.Problem; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; -public class JProblem { +public class JProblem implements Problem { private static final String USE_ENABLE_PREVIEW = " Use --enable-preview to enable"; + private static final Map PROBLEM_KINDS = Map.of( + IProblem.UndefinedType, ProblemKind.UNDEFINED_TYPE, + IProblem.PreviewFeatureUsed, ProblemKind.PREVIEW_FEATURE_USED, + IProblem.UnusedImport, ProblemKind.UNUSED_IMPORT, + IProblem.UnnecessaryCast, ProblemKind.REDUNDANT_CAST, + IProblem.AssignmentHasNoEffect, ProblemKind.ASSIGNMENT_HAS_NO_EFFECT, + IProblem.MaskedCatch, ProblemKind.MASKED_CATCH); + + private static final Set COMPILER_OPTIONS = Set.of( + JavaCore.COMPILER_PB_UNUSED_IMPORT, + JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, + JavaCore.COMPILER_PB_NO_EFFECT_ASSIGNMENT, + JavaCore.COMPILER_PB_HIDDEN_CATCH_BLOCK); + + private static final Set WRONGLY_CATEGORIZED_AS_SYNTAX_ERROR = Set.of( + IProblem.SwitchExpressionsYieldMissingDefaultCase, + IProblem.SwitchExpressionsYieldMissingEnumConstantCase); + private final String message; - private final Type type; + private final ProblemKind type; - JProblem(String message, Type type) { - this.message = message; + JProblem(String message, ProblemKind type) { + this.message = type == ProblemKind.PREVIEW_FEATURE_USED && message.endsWith(USE_ENABLE_PREVIEW) + ? message.substring(0, message.length() - USE_ENABLE_PREVIEW.length()) + : message; this.type = type; } - public Type type() { + @Override + public ProblemKind type() { return type; } + @Override public String message() { return message; } @Override public String toString() { - if (type == JProblem.Type.PREVIEW_FEATURE_USED) { - return cleanMessage(message); - } - return message; - } - - private static String cleanMessage(String message) { - if (message.endsWith(USE_ENABLE_PREVIEW)) { - // Using --enable-preview is irrelevant in this context. - return message.substring(0, message.length() - USE_ENABLE_PREVIEW.length()); - } - return message; + return message(); } @Override @@ -67,10 +79,9 @@ public boolean equals(Object o) { if (this == o) { return true; } - if (!(o instanceof JProblem)) { + if (!(o instanceof JProblem that)) { return false; } - JProblem that = (JProblem) o; return type == that.type && message.equals(that.message); } @@ -79,48 +90,26 @@ public int hashCode() { return Objects.hash(type, message); } - public enum Type { - UNDEFINED_TYPE(IProblem.UndefinedType), - PREVIEW_FEATURE_USED(IProblem.PreviewFeatureUsed), - UNUSED_IMPORT(IProblem.UnusedImport, JavaCore.COMPILER_PB_UNUSED_IMPORT, Tree.Kind.IMPORT), - REDUNDANT_CAST(IProblem.UnnecessaryCast, JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, Tree.Kind.TYPE_CAST, Tree.Kind.PARENTHESIZED_EXPRESSION), - ASSIGNMENT_HAS_NO_EFFECT(IProblem.AssignmentHasNoEffect, JavaCore.COMPILER_PB_NO_EFFECT_ASSIGNMENT, Tree.Kind.ASSIGNMENT), - MASKED_CATCH(IProblem.MaskedCatch, JavaCore.COMPILER_PB_HIDDEN_CATCH_BLOCK, Tree.Kind.IDENTIFIER, Tree.Kind.MEMBER_SELECT); - - private final int warningID; - private final String compilerOptionKey; - private final Set kinds; - - private static final Set COMPILER_OPTIONS = new HashSet<>(); - - Type(int warningID) { - this.warningID = warningID; - this.compilerOptionKey = null; - this.kinds = Collections.emptySet(); - } - - Type(int warningID, String compilerOptionKey, Tree.Kind... kinds) { - this.warningID = warningID; - this.compilerOptionKey = compilerOptionKey; - this.kinds = SetUtils.immutableSetOf(kinds); - } - - boolean matches(IProblem warning) { - return warning.getID() == warningID; - } + public static Set compilerOptions() { + return COMPILER_OPTIONS; + } - public static Set compilerOptions() { - if (COMPILER_OPTIONS.isEmpty()) { - Stream.of(Type.values()) - .map(t -> t.compilerOptionKey) - .forEach(COMPILER_OPTIONS::add); - } - return Collections.unmodifiableSet(COMPILER_OPTIONS); - } + @CheckForNull + static ProblemKind kindOf(IProblem problem) { + return PROBLEM_KINDS.get(problem.getID()); + } - public Set getKinds() { - return kinds; - } + /** + * Missing switch defaults can be caused by incomplete enum type information rather than invalid syntax. + */ + static boolean isSyntaxError(IProblem problem) { + return (problem.getID() & IProblem.Syntax) != 0 && !WRONGLY_CATEGORIZED_AS_SYNTAX_ERROR.contains(problem.getID()); } + static Set semanticProblems(List errors) { + return errors.stream() + .filter(error -> (error.getID() & IProblem.UndefinedType) != 0) + .map(error -> new JProblem(error.getMessage(), (error.getID() & IProblem.PreviewFeatureUsed) == 0 ? ProblemKind.UNDEFINED_TYPE : ProblemKind.PREVIEW_FEATURE_USED)) + .collect(Collectors.toSet()); + } } diff --git a/java-frontend/src/main/java/org/sonar/java/model/JWarning.java b/java-frontend/src/main/java/org/sonar/java/model/JWarning.java index 8a95e692df6..6a9734c38cc 100644 --- a/java-frontend/src/main/java/org/sonar/java/model/JWarning.java +++ b/java-frontend/src/main/java/org/sonar/java/model/JWarning.java @@ -34,26 +34,30 @@ import org.sonar.java.annotations.VisibleForTesting; import org.sonar.java.ast.visitors.SubscriptionVisitor; import org.sonar.java.model.location.InternalPosition; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; +import org.sonar.plugins.java.api.diagnostics.Warning; import org.sonar.plugins.java.api.location.Position; +import org.sonar.plugins.java.api.tree.ExpressionTree; import org.sonar.plugins.java.api.tree.Tree; import static org.sonar.plugins.java.api.location.Position.endOf; import static org.sonar.plugins.java.api.location.Position.startOf; -public final class JWarning extends JProblem { +public final class JWarning extends JProblem implements Warning { private final Position start; private final Position end; private Tree syntaxTree; - JWarning(String message, Type type, int startLine, int startColumnOffset, int endLine, int endColumnOffset) { + JWarning(String message, ProblemKind type, int startLine, int startColumnOffset, int endLine, int endColumnOffset) { super(message, type); this.start = InternalPosition.atOffset(startLine, startColumnOffset); this.end = InternalPosition.atOffset(endLine, endColumnOffset); } + @Override public Tree syntaxTree() { - return syntaxTree; + return Objects.requireNonNull(syntaxTree, "Warning has not been associated with a syntax tree"); } Position start() { @@ -88,43 +92,58 @@ public int hashCode() { public static class Mapper extends SubscriptionVisitor { - private static final Set KINDS = Stream.of(Type.values()) - .map(Type::getKinds) + private static final Map> WARNING_KINDS = Map.of( + ProblemKind.UNUSED_IMPORT, Set.of(Tree.Kind.IMPORT), + ProblemKind.REDUNDANT_CAST, Set.of(Tree.Kind.TYPE_CAST, Tree.Kind.PARENTHESIZED_EXPRESSION), + ProblemKind.ASSIGNMENT_HAS_NO_EFFECT, Set.of(Tree.Kind.ASSIGNMENT), + ProblemKind.MASKED_CATCH, Set.of(Tree.Kind.IDENTIFIER, Tree.Kind.MEMBER_SELECT)); + + private static final Set KINDS = WARNING_KINDS.values().stream() .flatMap(Set::stream) .collect(Collectors.toSet()); - private final Map> warningsByType = new EnumMap<>(Type.class); + private final Map> warningsByType = new EnumMap<>(ProblemKind.class); private final PriorityQueue warnings = new PriorityQueue<>(Comparator.comparing(JWarning::start).thenComparing(JWarning::end)); private Mapper(CompilationUnit ast, LineColumnConverter lineColumnConverter) { + WARNING_KINDS.keySet().forEach(kind -> warningsByType.put(kind, new LinkedHashSet<>())); Stream.of(ast.getProblems()) - .map(problem -> convert(problem, ast, lineColumnConverter)) + .map(problem -> convert(problem, lineColumnConverter)) .filter(Objects::nonNull) .forEach(warnings::add); } @CheckForNull - private static JWarning convert(IProblem problem, CompilationUnit root, LineColumnConverter lineColumnConverter) { - for (Type type : Type.values()) { - if (type.matches(problem)) { - LineColumnConverter.Pos start = lineColumnConverter.toPos(problem.getSourceStart()); - LineColumnConverter.Pos end = lineColumnConverter.toPos(problem.getSourceStart()); - return new JWarning(problem.getMessage(), - type, - start.line(), start.columnOffset(), - end.line(), end.columnOffset()); - } + @VisibleForTesting + static JWarning convert(IProblem problem, LineColumnConverter lineColumnConverter) { + ProblemKind kind = JProblem.kindOf(problem); + if (kind == null || !WARNING_KINDS.containsKey(kind)) { + return null; } - return null; + LineColumnConverter.Pos start = lineColumnConverter.toPos(problem.getSourceStart()); + LineColumnConverter.Pos end = lineColumnConverter.toPos(problem.getSourceEnd()); + return new JWarning(problem.getMessage(), kind, start.line(), start.columnOffset(), end.line(), end.columnOffset()); } public static Mapper warningsFor(CompilationUnit ast, LineColumnConverter lineColumnConverter) { return new Mapper(ast, lineColumnConverter); } + /** + * Associates compiler warnings with the most precise matching syntax trees and stores them by kind in the compilation unit. + * Unmatched warnings are omitted. Redundant-cast warnings are unwrapped from parentheses and retained only when they identify a type cast. + * + * @param cut the compilation unit to scan and populate with mapped warnings + */ public void mappedInto(JavaTree.CompilationUnitTreeImpl cut) { scanTree(cut); + warningsByType.get(ProblemKind.REDUNDANT_CAST).removeIf(warning -> { + if (warning.syntaxTree instanceof ExpressionTree expression) { + warning.syntaxTree = ExpressionUtils.skipParentheses(expression); + } + return !warning.syntaxTree().is(Tree.Kind.TYPE_CAST); + }); cut.addWarnings(warningsByType); } @@ -160,7 +179,7 @@ static void setSyntaxTree(JWarning warning, Tree tree) { @VisibleForTesting static boolean isInsideTree(JWarning warning, Tree tree) { - if (warning.type().getKinds().stream().noneMatch(tree::is)) { + if (!WARNING_KINDS.getOrDefault(warning.type(), Set.of()).contains(tree.kind())) { // wrong kind return false; } diff --git a/java-frontend/src/main/java/org/sonar/java/model/JavaTree.java b/java-frontend/src/main/java/org/sonar/java/model/JavaTree.java index c59582e94a9..7f594d0437e 100644 --- a/java-frontend/src/main/java/org/sonar/java/model/JavaTree.java +++ b/java-frontend/src/main/java/org/sonar/java/model/JavaTree.java @@ -28,11 +28,13 @@ import java.util.Set; import javax.annotation.Nullable; import org.sonar.java.Preconditions; -import org.sonar.java.annotations.Beta; import org.sonar.java.ast.parser.QualifiedIdentifierListTreeImpl; import org.sonar.java.model.declaration.AnnotationTreeImpl; import org.sonar.java.model.expression.AssessableExpressionTree; import org.sonar.java.model.expression.TypeArgumentListTreeImpl; +import org.sonar.plugins.java.api.diagnostics.Problem; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; +import org.sonar.plugins.java.api.diagnostics.Warning; import org.sonar.plugins.java.api.semantic.Sema; import org.sonar.plugins.java.api.semantic.Symbol; import org.sonar.plugins.java.api.tree.AnnotationTree; @@ -162,10 +164,10 @@ public static class CompilationUnitTreeImpl extends JavaTree implements Compilat private final ModuleDeclarationTree moduleDeclaration; private final SyntaxToken eofToken; public Sema sema; - private Set undefinedTypes = Set.of(); + private Set semanticProblems = Set.of(); private Runnable environmentCleaner = () -> {}; - private final Map> warnings = new EnumMap<>(JProblem.Type.class); + private final Map> warnings = new EnumMap<>(ProblemKind.class); public CompilationUnitTreeImpl(@Nullable PackageDeclarationTree packageDeclaration, List imports, List types, @Nullable ModuleDeclarationTree moduleDeclaration, SyntaxToken eofToken) { @@ -177,14 +179,15 @@ public CompilationUnitTreeImpl(@Nullable PackageDeclarationTree packageDeclarati this.eofToken = eofToken; } - public void setSemanticModel(Sema sema, Set undefinedTypes, Runnable environmentCleaner) { + public void setSemanticModel(Sema sema, Set semanticProblems, Runnable environmentCleaner) { this.sema = Objects.requireNonNull(sema); - this.undefinedTypes = Set.copyOf(undefinedTypes); + this.semanticProblems = Set.copyOf(semanticProblems); this.environmentCleaner = Objects.requireNonNull(environmentCleaner); } - public Set undefinedTypes() { - return undefinedTypes; + @Override + public Set semanticProblems() { + return semanticProblems; } public Runnable getEnvironmentCleaner() { @@ -206,9 +209,14 @@ public List types() { return types; } - @Beta - public List warnings(JProblem.Type type) { - return Collections.unmodifiableList(new ArrayList<>(warnings.getOrDefault(type, Collections.emptySet()))); + @Override + public Set supportedWarningKinds() { + return Set.copyOf(warnings.keySet()); + } + + @Override + public List warnings(ProblemKind kind) { + return warnings.getOrDefault(kind, List.of()); } @Override @@ -245,8 +253,8 @@ public SyntaxToken eofToken() { return eofToken; } - public void addWarnings(Map> warnings) { - this.warnings.putAll(warnings); + public void addWarnings(Map> warnings) { + warnings.forEach((kind, values) -> this.warnings.put(kind, List.copyOf(values))); } } diff --git a/java-frontend/src/main/java/org/sonar/plugins/java/api/diagnostics/Problem.java b/java-frontend/src/main/java/org/sonar/plugins/java/api/diagnostics/Problem.java new file mode 100644 index 00000000000..76fb03dec87 --- /dev/null +++ b/java-frontend/src/main/java/org/sonar/plugins/java/api/diagnostics/Problem.java @@ -0,0 +1,27 @@ +/* + * 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.plugins.java.api.diagnostics; + +import org.sonar.java.annotations.Beta; + +@Beta +public interface Problem { + + ProblemKind type(); + + String message(); +} diff --git a/java-frontend/src/main/java/org/sonar/plugins/java/api/diagnostics/ProblemKind.java b/java-frontend/src/main/java/org/sonar/plugins/java/api/diagnostics/ProblemKind.java new file mode 100644 index 00000000000..5cf42612eef --- /dev/null +++ b/java-frontend/src/main/java/org/sonar/plugins/java/api/diagnostics/ProblemKind.java @@ -0,0 +1,29 @@ +/* + * 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.plugins.java.api.diagnostics; + +import org.sonar.java.annotations.Beta; + +@Beta +public enum ProblemKind { + UNDEFINED_TYPE, + PREVIEW_FEATURE_USED, + UNUSED_IMPORT, + REDUNDANT_CAST, + ASSIGNMENT_HAS_NO_EFFECT, + MASKED_CATCH +} diff --git a/java-frontend/src/main/java/org/sonar/plugins/java/api/diagnostics/Warning.java b/java-frontend/src/main/java/org/sonar/plugins/java/api/diagnostics/Warning.java new file mode 100644 index 00000000000..93f87eca97d --- /dev/null +++ b/java-frontend/src/main/java/org/sonar/plugins/java/api/diagnostics/Warning.java @@ -0,0 +1,31 @@ +/* + * 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.plugins.java.api.diagnostics; + +import org.sonar.java.annotations.Beta; +import org.sonar.plugins.java.api.tree.Tree; + +@Beta +public interface Warning extends Problem { + + /** + * The associated node in the compilation unit, never null for a published warning. + * Unused imports identify an {@code ImportTree}, redundant casts a {@code TypeCastTree}, assignments without effect an {@code AssignmentExpressionTree}, + * and masked catches the caught exception type. + */ + Tree syntaxTree(); +} diff --git a/java-frontend/src/main/java/org/sonar/plugins/java/api/diagnostics/package-info.java b/java-frontend/src/main/java/org/sonar/plugins/java/api/diagnostics/package-info.java new file mode 100644 index 00000000000..1805d2b510a --- /dev/null +++ b/java-frontend/src/main/java/org/sonar/plugins/java/api/diagnostics/package-info.java @@ -0,0 +1,21 @@ +/* + * 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/ + */ +@javax.annotation.ParametersAreNonnullByDefault +@MethodsAreNonnullByDefault +package org.sonar.plugins.java.api.diagnostics; + +import org.sonar.plugins.java.api.tree.MethodsAreNonnullByDefault; diff --git a/java-frontend/src/main/java/org/sonar/plugins/java/api/tree/CompilationUnitTree.java b/java-frontend/src/main/java/org/sonar/plugins/java/api/tree/CompilationUnitTree.java index 53f1f262ecd..71ac1a473c9 100644 --- a/java-frontend/src/main/java/org/sonar/plugins/java/api/tree/CompilationUnitTree.java +++ b/java-frontend/src/main/java/org/sonar/plugins/java/api/tree/CompilationUnitTree.java @@ -17,10 +17,14 @@ package org.sonar.plugins.java.api.tree; import org.sonar.java.annotations.Beta; +import org.sonar.plugins.java.api.diagnostics.Problem; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; +import org.sonar.plugins.java.api.diagnostics.Warning; import javax.annotation.Nullable; import java.util.List; +import java.util.Set; /** * Compilation unit. @@ -54,4 +58,27 @@ public interface CompilationUnitTree extends Tree { SyntaxToken eofToken(); + /** + * Immutable diagnostics for unresolved types and uses of preview features. + */ + default Set semanticProblems() { + return Set.of(); + } + + /** + * Warning kinds supported by this compilation unit's frontend, even when no warnings were produced. + * An empty set means that no compiler warnings are available. + */ + default Set supportedWarningKinds() { + return Set.of(); + } + + /** + * Immutable warnings in frontend encounter order. Unsupported kinds return an empty list; + * use supportedWarningKinds() to distinguish unsupported kinds from an absence of findings. + */ + default List warnings(ProblemKind kind) { + return List.of(); + } + } diff --git a/java-frontend/src/test/java/org/sonar/java/SonarComponentsTest.java b/java-frontend/src/test/java/org/sonar/java/SonarComponentsTest.java index dbd2713a525..ea268b97501 100644 --- a/java-frontend/src/test/java/org/sonar/java/SonarComponentsTest.java +++ b/java-frontend/src/test/java/org/sonar/java/SonarComponentsTest.java @@ -35,6 +35,7 @@ import java.util.HashMap; import java.util.List; import java.util.Optional; +import java.util.Set; import java.util.function.LongSupplier; import java.util.stream.Stream; import javax.annotation.CheckForNull; @@ -81,7 +82,6 @@ import org.sonar.java.exceptions.ApiMismatchException; import org.sonar.java.model.GeneratedFile; import org.sonar.java.model.JParserTestUtils; -import org.sonar.java.model.JavaTree; import org.sonar.java.reporting.AnalyzerMessage; import org.sonar.java.testing.ThreadLocalLogTester; import org.sonar.plugins.java.api.CheckRegistrar; @@ -90,6 +90,8 @@ import org.sonar.plugins.java.api.JavaFileScannerContext; import org.sonar.plugins.java.api.JspCodeVisitor; import org.sonar.plugins.java.api.caching.SonarLintCache; +import org.sonar.plugins.java.api.diagnostics.Problem; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; import org.sonar.scanner.plugin.api.impl.config.MapSettings; import org.sonar.scanner.plugin.api.impl.rule.ActiveRulesBuilder; import org.sonar.scanner.plugin.api.impl.rule.NewActiveRule; @@ -1177,6 +1179,39 @@ void beforeEach() { sonarComponents.setSensorContext(loggingContext); } + @Test + void groups_frontend_independent_problems_and_logs_their_messages() { + Problem first = independentProblem(); + Problem second = independentProblem(); + sonarComponents.collectUndefinedTypes("First.java", Set.of(first)); + sonarComponents.collectUndefinedTypes("Second.java", Set.of(second)); + sonarComponents.logUndefinedTypes(); + + assertThat(loggingLogTester.logs(Level.DEBUG)).containsExactly( + "Unresolved imports/types:" + System.lineSeparator() + + "- Unknown type" + System.lineSeparator() + + " * First.java" + System.lineSeparator() + + " * Second.java"); + loggingLogTester.clear(); + sonarComponents.logUndefinedTypes(); + assertThat(loggingLogTester.logs(Level.WARN)).isEmpty(); + assertThat(loggingLogTester.logs(Level.DEBUG)).isEmpty(); + } + + private Problem independentProblem() { + return new Problem() { + @Override + public ProblemKind type() { + return ProblemKind.UNDEFINED_TYPE; + } + + @Override + public String message() { + return "Unknown type"; + } + }; + } + @Test void log_only_50_undefined_types() { loggingLogTester.setLevel(Level.DEBUG); @@ -1184,7 +1219,7 @@ void log_only_50_undefined_types() { // artificially populated the semantic errors with 26 unknown types and 52 errors sonarComponents.collectUndefinedTypes(DEFAULT_PATH, - ((JavaTree.CompilationUnitTreeImpl) JParserTestUtils.parse(source)).undefinedTypes()); + JParserTestUtils.parse(source).semanticProblems()); // triggers log sonarComponents.logUndefinedTypes(); @@ -1215,7 +1250,7 @@ void remove_info_and_warning_from_log_related_to_undefined_types() { loggingLogTester.setLevel(Level.ERROR); String source = generateSource(26); sonarComponents.collectUndefinedTypes(DEFAULT_PATH, - ((JavaTree.CompilationUnitTreeImpl) JParserTestUtils.parse(source)).undefinedTypes()); + JParserTestUtils.parse(source).semanticProblems()); sonarComponents.logUndefinedTypes(); assertThat(loggingLogTester.logs(Level.WARN)).isEmpty(); @@ -1229,7 +1264,7 @@ void log_all_undefined_types_if_less_than_threshold() { // artificially populated the semantic errors with 1 unknown types and 2 errors sonarComponents.collectUndefinedTypes(DEFAULT_PATH, - ((JavaTree.CompilationUnitTreeImpl) JParserTestUtils.parse(source)).undefinedTypes()); + JParserTestUtils.parse(source).semanticProblems()); // triggers log sonarComponents.logUndefinedTypes(); @@ -1285,9 +1320,9 @@ void log_problems_with_list_of_paths_of_files_affected() { // artificially populated the semantic errors with 1 unknown types and 2 errors sonarComponents.collectUndefinedTypes(mainFile.toString(), - ((JavaTree.CompilationUnitTreeImpl) JParserTestUtils.parse(source)).undefinedTypes()); + JParserTestUtils.parse(source).semanticProblems()); sonarComponents.collectUndefinedTypes(testFile.toString(), - ((JavaTree.CompilationUnitTreeImpl) JParserTestUtils.parse(source)).undefinedTypes()); + JParserTestUtils.parse(source).semanticProblems()); sonarComponents.logUndefinedTypes(); List debugMessage = loggingLogTester.logs(Level.DEBUG); @@ -1320,7 +1355,7 @@ private void logUndefinedTypesWithOneMainAndOneTest() { // artificially populated the semantic errors with 1 unknown types and 2 errors sonarComponents.collectUndefinedTypes(DEFAULT_PATH, - ((JavaTree.CompilationUnitTreeImpl) JParserTestUtils.parse(source)).undefinedTypes()); + JParserTestUtils.parse(source).semanticProblems()); // Call these methods to initiate Main and Test ClassPath sonarComponents.getJavaClasspath(); diff --git a/java-frontend/src/test/java/org/sonar/java/model/JParserSemanticTest.java b/java-frontend/src/test/java/org/sonar/java/model/JParserSemanticTest.java index d8d11d8c2db..326ef83dcf2 100644 --- a/java-frontend/src/test/java/org/sonar/java/model/JParserSemanticTest.java +++ b/java-frontend/src/test/java/org/sonar/java/model/JParserSemanticTest.java @@ -26,7 +26,6 @@ import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.SwitchStatement; import org.eclipse.jdt.core.dom.TypeDeclaration; @@ -58,6 +57,8 @@ import org.sonar.java.model.statement.SwitchExpressionTreeImpl; import org.sonar.java.model.statement.YieldStatementTreeImpl; import org.sonar.plugins.java.api.JavaVersion; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; +import org.sonar.plugins.java.api.diagnostics.Warning; import org.sonar.plugins.java.api.location.Position; import org.sonar.plugins.java.api.semantic.Symbol; import org.sonar.plugins.java.api.semantic.Symbol.MethodSymbol; @@ -1840,30 +1841,33 @@ void warnings_are_detected() { + " }\n" + "}\n"; - JavaTree.CompilationUnitTreeImpl cu = test(source); - List importsWarnings = cu.warnings(JWarning.Type.UNUSED_IMPORT); + CompilationUnitTree cu = test(source); + assertThat(cu.supportedWarningKinds()).containsExactlyInAnyOrder( + ProblemKind.UNUSED_IMPORT, ProblemKind.REDUNDANT_CAST, ProblemKind.ASSIGNMENT_HAS_NO_EFFECT, ProblemKind.MASKED_CATCH); + assertThat(cu.warnings(ProblemKind.MASKED_CATCH)).isEmpty(); + List importsWarnings = cu.warnings(ProblemKind.UNUSED_IMPORT); assertThat(importsWarnings).hasSize(2); - JWarning listWarning = importsWarnings.get(0); + Warning listWarning = importsWarnings.get(0); assertThat(listWarning.message()).isEqualTo("The import java.util.List is never used"); assertThat(listWarning.syntaxTree()).isEqualTo(cu.imports().get(0)); - JWarning objectWarning = importsWarnings.get(1); + Warning objectWarning = importsWarnings.get(1); assertThat(objectWarning.message()).isEqualTo("The import java.lang.Object is never used"); assertThat(objectWarning.syntaxTree()).isEqualTo(cu.imports().get(2)); - List castWarnings = cu.warnings(JWarning.Type.REDUNDANT_CAST); + List castWarnings = cu.warnings(ProblemKind.REDUNDANT_CAST); assertThat(castWarnings).hasSize(2); TypeCastTree typeCast = (TypeCastTree) ((VariableTree) ((MethodTree) (((ClassTree) cu.types().get(0)).members().get(0))).block().body().get(0)).initializer(); - JWarning parentCastWarning = castWarnings.get(0); + Warning parentCastWarning = castWarnings.get(0); assertThat(parentCastWarning.message()).isEqualTo("Unnecessary cast from String to String"); assertThat(parentCastWarning.syntaxTree()).isEqualTo(typeCast); ParenthesizedTree parenthesizedTree = (ParenthesizedTree) typeCast.expression(); - JWarning nestedCastWarning = castWarnings.get(1); + Warning nestedCastWarning = castWarnings.get(1); assertThat(nestedCastWarning.message()).isEqualTo("Unnecessary cast from String to String"); - assertThat(nestedCastWarning.syntaxTree()).isEqualTo(parenthesizedTree); + assertThat(nestedCastWarning.syntaxTree()).isEqualTo(parenthesizedTree.expression()); } @Test 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 97b682df182..d6d8a3af6a1 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 @@ -57,10 +57,10 @@ import org.sonar.api.batch.fs.InputFile; import org.sonar.java.AnalysisProgress; import org.sonar.java.TestUtils; -import org.sonar.java.model.JavaTree.CompilationUnitTreeImpl; import org.sonar.java.model.declaration.ClassTreeImpl; import org.sonar.java.testing.ThreadLocalLogTester; import org.sonar.plugins.java.api.JavaVersion; +import org.sonar.plugins.java.api.diagnostics.Problem; import org.sonar.plugins.java.api.location.Range; import org.sonar.plugins.java.api.semantic.Symbol; import org.sonar.plugins.java.api.tree.ArrayTypeTree; @@ -150,7 +150,7 @@ void err() { void unknown_types_are_collected() { // import org.foo missing, type Bar unknown CompilationUnitTree cut = test("import org.foo.Bar;\n class Foo {\n void foo(Bar b) {}\n }\n"); - assertThat(((CompilationUnitTreeImpl) cut).undefinedTypes().stream().map(Object::toString)) + assertThat(cut.semanticProblems().stream().map(Problem::message)) .containsExactlyInAnyOrder("The import org.foo cannot be resolved", "Bar cannot be resolved to a type"); } @@ -158,7 +158,7 @@ void unknown_types_are_collected() { void warnings_are_collected() { // import org.foo missing, type Bar unknown CompilationUnitTree cut = test("import java.util.List;\n import java.util.ArrayList;\n class Foo {\n void foo(Bar b) {}\n }\n"); - assertThat(((CompilationUnitTreeImpl) cut).undefinedTypes().stream().map(Object::toString)) + assertThat(cut.semanticProblems().stream().map(Problem::message)) .containsExactlyInAnyOrder("Bar cannot be resolved to a type"); } diff --git a/java-frontend/src/test/java/org/sonar/java/model/JProblemTest.java b/java-frontend/src/test/java/org/sonar/java/model/JProblemTest.java index bc1e01ab9af..43a50ba5c47 100644 --- a/java-frontend/src/test/java/org/sonar/java/model/JProblemTest.java +++ b/java-frontend/src/test/java/org/sonar/java/model/JProblemTest.java @@ -16,39 +16,106 @@ */ package org.sonar.java.model; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.compiler.IProblem; import org.junit.jupiter.api.Test; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; class JProblemTest { + @Test + void normalizes_preview_messages_at_construction() { + String message = "Preview feature used Use --enable-preview to enable"; + JProblem preview = new JProblem(message, ProblemKind.PREVIEW_FEATURE_USED); + assertThat(preview.message()).isEqualTo("Preview feature used"); + assertThat(preview).hasToString(preview.message()); + assertThat(new JProblem("Preview feature used", ProblemKind.PREVIEW_FEATURE_USED).message()).isEqualTo("Preview feature used"); + assertThat(new JProblem(message + ".", ProblemKind.PREVIEW_FEATURE_USED).message()).isEqualTo(message + "."); + for (ProblemKind kind : ProblemKind.values()) { + if (kind != ProblemKind.PREVIEW_FEATURE_USED) { + assertThat(new JProblem(message, kind).message()).isEqualTo(message); + } + } + } + + @Test + void equivalent_normalized_messages_have_equal_values_and_hashes() { + JProblem withGuidance = new JProblem("Preview feature used Use --enable-preview to enable", ProblemKind.PREVIEW_FEATURE_USED); + JProblem withoutGuidance = new JProblem("Preview feature used", ProblemKind.PREVIEW_FEATURE_USED); + assertThat(withGuidance).isEqualTo(withoutGuidance); + assertThat(withoutGuidance).isEqualTo(withGuidance); + assertThat(withGuidance).hasSameHashCodeAs(withoutGuidance); + assertThat(new HashSet<>(List.of(withGuidance, withoutGuidance))).containsExactly(withoutGuidance); + } + + @Test + void compiler_options_enable_only_supported_warnings() { + assertThat(JProblem.compilerOptions()).containsExactlyInAnyOrder( + JavaCore.COMPILER_PB_UNUSED_IMPORT, + JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, + JavaCore.COMPILER_PB_NO_EFFECT_ASSIGNMENT, + JavaCore.COMPILER_PB_HIDDEN_CATCH_BLOCK); + Set options = JProblem.compilerOptions(); + assertThatThrownBy(options::clear).isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void classifies_ecj_syntax_errors_and_semantic_problems() { + IProblem syntax = problem(IProblem.ParsingError, "Syntax"); + IProblem toleratedSwitch = problem(IProblem.SwitchExpressionsYieldMissingDefaultCase, "Switch"); + IProblem undefined = problem(IProblem.UndefinedType, "Unknown type"); + IProblem preview = problem(IProblem.PreviewFeatureDisabled, "Preview"); + assertThat(JProblem.isSyntaxError(syntax)).isTrue(); + assertThat(JProblem.isSyntaxError(toleratedSwitch)).isFalse(); + assertThat(JProblem.isSyntaxError(undefined)).isFalse(); + assertThat(JProblem.semanticProblems(List.of(syntax, undefined, preview))) + .containsExactlyInAnyOrder(new JProblem("Unknown type", ProblemKind.UNDEFINED_TYPE), new JProblem("Preview", ProblemKind.PREVIEW_FEATURE_USED)); + assertThat(JProblem.kindOf(syntax)).isNull(); + } + @Test void test_equals() { - JProblem p1 = new JProblem("message1", JProblem.Type.UNDEFINED_TYPE); + JProblem p1 = new JProblem("message1", ProblemKind.UNDEFINED_TYPE); assertFalse(p1.equals(null)); assertTrue(p1.equals(p1)); - JProblem p2 = new JProblem("message1", JProblem.Type.UNDEFINED_TYPE); + JProblem p2 = new JProblem("message1", ProblemKind.UNDEFINED_TYPE); assertTrue(p1.equals(p2)); - p2 = new JProblem("message2", JProblem.Type.UNDEFINED_TYPE); + p2 = new JProblem("message2", ProblemKind.UNDEFINED_TYPE); assertFalse(p1.equals(p2)); - p2 = new JProblem("message1", JProblem.Type.PREVIEW_FEATURE_USED); + p2 = new JProblem("message1", ProblemKind.PREVIEW_FEATURE_USED); assertFalse(p1.equals(p2)); } @Test void test_hashcode() { assertEquals( - new JProblem("a", JProblem.Type.UNDEFINED_TYPE).hashCode(), - new JProblem("a", JProblem.Type.UNDEFINED_TYPE).hashCode()); + new JProblem("a", ProblemKind.UNDEFINED_TYPE).hashCode(), + new JProblem("a", ProblemKind.UNDEFINED_TYPE).hashCode()); assertNotEquals( - new JProblem("a", JProblem.Type.UNDEFINED_TYPE).hashCode(), - new JProblem("b", JProblem.Type.UNDEFINED_TYPE).hashCode()); + new JProblem("a", ProblemKind.UNDEFINED_TYPE).hashCode(), + new JProblem("b", ProblemKind.UNDEFINED_TYPE).hashCode()); assertNotEquals( - new JProblem("a", JProblem.Type.UNDEFINED_TYPE).hashCode(), - new JProblem("a", JProblem.Type.PREVIEW_FEATURE_USED).hashCode()); + new JProblem("a", ProblemKind.UNDEFINED_TYPE).hashCode(), + new JProblem("a", ProblemKind.PREVIEW_FEATURE_USED).hashCode()); + } + + private static IProblem problem(int id, String message) { + IProblem problem = mock(IProblem.class); + when(problem.getID()).thenReturn(id); + when(problem.getMessage()).thenReturn(message); + return problem; } } diff --git a/java-frontend/src/test/java/org/sonar/java/model/JWarningTest.java b/java-frontend/src/test/java/org/sonar/java/model/JWarningTest.java index 7f6929127d6..ab635cc19ac 100644 --- a/java-frontend/src/test/java/org/sonar/java/model/JWarningTest.java +++ b/java-frontend/src/test/java/org/sonar/java/model/JWarningTest.java @@ -17,10 +17,14 @@ package org.sonar.java.model; import java.util.Collections; +import org.eclipse.jdt.core.compiler.IProblem; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.sonar.java.model.declaration.VariableTreeImpl; import org.sonar.java.model.expression.IdentifierTreeImpl; +import org.sonar.plugins.java.api.diagnostics.ProblemKind; import org.sonar.plugins.java.api.tree.IdentifierTree; import org.sonar.plugins.java.api.tree.ImportTree; import org.sonar.plugins.java.api.tree.Tree; @@ -28,21 +32,51 @@ import org.sonar.plugins.java.api.tree.VariableTree; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNullPointerException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import static org.sonar.java.model.JWarning.Mapper.isInsideTree; -import static org.sonar.java.model.JWarning.Mapper.setSyntaxTree; -import static org.sonar.java.model.JWarning.Mapper.matchesTreeExactly; import static org.sonar.java.model.JWarning.Mapper.isMorePreciseTree; +import static org.sonar.java.model.JWarning.Mapper.matchesTreeExactly; +import static org.sonar.java.model.JWarning.Mapper.setSyntaxTree; class JWarningTest { + @ParameterizedTest + @CsvSource({"7, 2, 5", "13, 3, 4"}) + void ecj_conversion_preserves_source_range(int sourceEnd, int endLine, int endColumn) { + IProblem problem = mock(IProblem.class); + when(problem.getID()).thenReturn(IProblem.UnusedImport); + when(problem.getMessage()).thenReturn("Unused import"); + when(problem.getSourceStart()).thenReturn(2); + when(problem.getSourceEnd()).thenReturn(sourceEnd); + JWarning warning = JWarning.Mapper.convert(problem, new LineColumnConverter("x\nimport\njava.util.List;")); + assertThat(warning.type()).isEqualTo(ProblemKind.UNUSED_IMPORT); + assertThat(warning.message()).isEqualTo("Unused import"); + assertThat(warning.start().line()).isEqualTo(2); + assertThat(warning.start().columnOffset()).isZero(); + assertThat(warning.end().line()).isEqualTo(endLine); + assertThat(warning.end().columnOffset()).isEqualTo(endColumn); + } + + @Test + void ignores_diagnostics_that_cannot_be_associated_with_supported_warning_trees() { + LineColumnConverter converter = new LineColumnConverter(""); + for (int id : new int[]{IProblem.ParsingError, IProblem.UndefinedType}) { + IProblem problem = mock(IProblem.class); + when(problem.getID()).thenReturn(id); + assertThat(JWarning.Mapper.convert(problem, converter)).isNull(); + } + } + @Test void getters() { String message = "message"; - JWarning.Type type = JWarning.Type.UNUSED_IMPORT; + ProblemKind type = ProblemKind.UNUSED_IMPORT; int startLine = 0; int startColumn = 1; int endLine = 2; @@ -51,16 +85,16 @@ void getters() { assertThat(warning.message()).isEqualTo(message); assertThat(warning.type()).isEqualTo(type); - assertThat(warning.syntaxTree()).isNull(); + assertThatNullPointerException().isThrownBy(warning::syntaxTree); } @Test void test_equals() { - JWarning j1 = new JWarning("a", JProblem.Type.UNUSED_IMPORT, 0, 1, 2, 3); + JWarning j1 = new JWarning("a", ProblemKind.UNUSED_IMPORT, 0, 1, 2, 3); assertFalse(j1.equals(null)); assertTrue(j1.equals(j1)); - JWarning j2 = new JWarning("a", JProblem.Type.UNUSED_IMPORT, 0, 1, 2, 3); + JWarning j2 = new JWarning("a", ProblemKind.UNUSED_IMPORT, 0, 1, 2, 3); assertTrue(j1.equals(j2)); // syntaxTree is ignored in JWarning.equals() @@ -68,18 +102,18 @@ void test_equals() { setSyntaxTree(j2, beforeDifferentLine); assertTrue(j1.equals(j2)); - j2 = new JWarning("b", JProblem.Type.UNUSED_IMPORT, 0, 1, 2, 3); + j2 = new JWarning("b", ProblemKind.UNUSED_IMPORT, 0, 1, 2, 3); assertFalse(j1.equals(j2)); - j2 = new JWarning("a", JProblem.Type.UNUSED_IMPORT, 42, 1, 2, 3); + j2 = new JWarning("a", ProblemKind.UNUSED_IMPORT, 42, 1, 2, 3); assertFalse(j1.equals(j2)); - j2 = new JWarning("a", JProblem.Type.UNUSED_IMPORT, 0, 1, 42, 3); + j2 = new JWarning("a", ProblemKind.UNUSED_IMPORT, 0, 1, 42, 3); assertFalse(j1.equals(j2)); } @Test void test_hashcode() { - JWarning j1 = new JWarning("a", JProblem.Type.UNUSED_IMPORT, 0, 1, 2, 3); - JWarning j2 = new JWarning("a", JProblem.Type.UNUSED_IMPORT, 0, 1, 2, 3); + JWarning j1 = new JWarning("a", ProblemKind.UNUSED_IMPORT, 0, 1, 2, 3); + JWarning j2 = new JWarning("a", ProblemKind.UNUSED_IMPORT, 0, 1, 2, 3); assertEquals(j1.hashCode(), j2.hashCode()); // syntaxTree is ignored in JWarning.hashCode() @@ -88,11 +122,11 @@ void test_hashcode() { assertEquals(j1.hashCode(), j2.hashCode()); assertNotEquals( - new JWarning("a", JProblem.Type.UNUSED_IMPORT, 0, 1, 2, 3).hashCode(), - new JWarning("b", JProblem.Type.UNUSED_IMPORT, 0, 1, 2, 3).hashCode()); + new JWarning("a", ProblemKind.UNUSED_IMPORT, 0, 1, 2, 3).hashCode(), + new JWarning("b", ProblemKind.UNUSED_IMPORT, 0, 1, 2, 3).hashCode()); assertNotEquals( - new JWarning("a", JProblem.Type.UNUSED_IMPORT, 0, 1, 2, 3).hashCode(), - new JWarning("a", JProblem.Type.REDUNDANT_CAST, 0, 1, 2, 3).hashCode()); + new JWarning("a", ProblemKind.UNUSED_IMPORT, 0, 1, 2, 3).hashCode(), + new JWarning("a", ProblemKind.REDUNDANT_CAST, 0, 1, 2, 3).hashCode()); } @Nested @@ -103,7 +137,7 @@ class MapperTest { @Test void inside_multiline_warning() { - JWarning warning = new JWarning("message", JWarning.Type.UNUSED_IMPORT, 5, 20, 7, 50); + JWarning warning = new JWarning("message", ProblemKind.UNUSED_IMPORT, 5, 20, 7, 50); Tree beforeDifferentLine = importTree(4, 0, 5, 19); Tree beforeSameStartLine = importTree(5, 15, 6, 20); @@ -124,7 +158,7 @@ void inside_multiline_warning() { @Test void inside_single_line_warning() { - JWarning warning = new JWarning("message", JWarning.Type.UNUSED_IMPORT, 5, 20, 5, 50); + JWarning warning = new JWarning("message", ProblemKind.UNUSED_IMPORT, 5, 20, 5, 50); Tree beforeCompletely = importTree(3, 0, 3, 10); Tree beforeOverlapping = importTree(4, 0, 5, 30); @@ -145,7 +179,7 @@ void inside_single_line_warning() { @Test void inside_wrong_kind() { - JWarning warning = new JWarning("message", JWarning.Type.UNUSED_IMPORT, 5, 20, 7, 50); + JWarning warning = new JWarning("message", ProblemKind.UNUSED_IMPORT, 5, 20, 7, 50); VariableTree variableTree = variableTree(4, 55, 8, 15); ImportTree importTree = importTree(4, 55, 8, 15); @@ -168,8 +202,8 @@ void test_isMorePreciseTree() { @Test void test_setSyntaxTree() { - JWarning warningOnType = new JWarning("message", JWarning.Type.UNUSED_IMPORT, 1, 10, 1, 11); - assertThat(warningOnType.syntaxTree()).isNull(); + JWarning warningOnType = new JWarning("message", ProblemKind.UNUSED_IMPORT, 1, 10, 1, 11); + assertThatNullPointerException().isThrownBy(warningOnType::syntaxTree); setSyntaxTree(warningOnType, variable); assertThat(warningOnType.syntaxTree()).isEqualTo(variable); @@ -184,7 +218,7 @@ void test_setSyntaxTree() { @Test void test_matchesTreeExactly() { - JWarning warningOnType = new JWarning("message", JWarning.Type.UNUSED_IMPORT, 1, 10, 1, 11); + JWarning warningOnType = new JWarning("message", ProblemKind.UNUSED_IMPORT, 1, 10, 1, 11); setSyntaxTree(warningOnType, variable); assertThat(matchesTreeExactly(warningOnType)).isFalse(); @@ -192,7 +226,7 @@ void test_matchesTreeExactly() { setSyntaxTree(warningOnType, type); assertThat(matchesTreeExactly(warningOnType)).isTrue(); - JWarning warningOnTypeAgain = new JWarning("message", JWarning.Type.UNUSED_IMPORT, 1, 10, 1, 11); + JWarning warningOnTypeAgain = new JWarning("message", ProblemKind.UNUSED_IMPORT, 1, 10, 1, 11); setSyntaxTree(warningOnTypeAgain, name); assertThat(matchesTreeExactly(warningOnTypeAgain)).isFalse(); }