diff --git a/its/ruling/src/test/resources/expected/guava/java-S1128.sarif b/its/ruling/src/test/resources/expected/guava/java-S1128.sarif index 30c6f30357e..e557af54128 100644 --- a/its/ruling/src/test/resources/expected/guava/java-S1128.sarif +++ b/its/ruling/src/test/resources/expected/guava/java-S1128.sarif @@ -12,78 +12,6 @@ }, "language" : "en-US", "results" : [ { - "ruleId" : "java:S1128", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this unused import 'java.util.Map.Entry'." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/cache/LocalCache.java", - "index" : -1 - }, - "region" : { - "startLine" : 67, - "startColumn" : 8, - "endLine" : 67, - "endColumn" : 27 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S1128", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this unused import 'java.util.Map.Entry'." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/collect/ArrayTable.java", - "index" : -1 - }, - "region" : { - "startLine" : 36, - "startColumn" : 8, - "endLine" : 36, - "endColumn" : 27 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S1128", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this unused import 'java.util.Map.Entry'." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/collect/DenseImmutableTable.java", - "index" : -1 - }, - "region" : { - "startLine" : 24, - "startColumn" : 8, - "endLine" : 24, - "endColumn" : 27 - } - } - } ], - "rank" : -1.0 - }, { "ruleId" : "java:S1128", "ruleIndex" : -1, "kind" : "fail", @@ -107,30 +35,6 @@ } } ], "rank" : -1.0 - }, { - "ruleId" : "java:S1128", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this unused import 'com.google.common.collect.Table.Cell'." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/collect/RegularImmutableTable.java", - "index" : -1 - }, - "region" : { - "startLine" : 20, - "startColumn" : 8, - "endLine" : 20, - "endColumn" : 44 - } - } - } ], - "rank" : -1.0 }, { "ruleId" : "java:S1128", "ruleIndex" : -1, diff --git a/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/HiddenMemberTypes.java b/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/HiddenMemberTypes.java new file mode 100644 index 00000000000..94d54d5b137 --- /dev/null +++ b/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/HiddenMemberTypes.java @@ -0,0 +1,42 @@ +package checks.UselessImportCheck; + +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; // Noncompliant {{Remove this unused import 'java.util.List'.}} +import java.util.Map.Entry; +import java.util.Properties; +import java.util.Set; // Noncompliant {{Remove this unused import 'java.util.Set'.}} +import java.util.TreeMap; +import java.util.WeakHashMap; + +class HiddenMemberTypes { + + static class Linked extends LinkedHashMap { + @Override + protected boolean removeEldestEntry(Entry eldest) { + return size() > 10; + } + } + + static class Sorted extends Properties { + private static final Comparator> BY_KEY = Entry.comparingByKey((a, b) -> a.toString().compareTo(b.toString())); + + Entry first() { + return null; + } + } + + static class Tree extends TreeMap { + Entry any() { + return firstEntry(); + } + } + + static class Weak extends WeakHashMap { + Entry none() { + return null; + } + } + + java.util.Set referencedWithItsQualifiedName; +} diff --git a/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/RedundantViaMemberScope.java b/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/RedundantViaMemberScope.java new file mode 100644 index 00000000000..5700651365e --- /dev/null +++ b/java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/RedundantViaMemberScope.java @@ -0,0 +1,22 @@ +package checks.UselessImportCheck; + +import checks.UselessImportCheck.RedundantViaMemberScope.Nested; // Noncompliant {{Remove this unused import 'checks.UselessImportCheck.RedundantViaMemberScope.Nested'.}} +import java.util.Map; +import java.util.Map.Entry; // Noncompliant {{Remove this unused import 'java.util.Map.Entry'.}} +import java.util.Set; + +abstract class RedundantViaMemberScope implements Map { + + Entry inherited() { + return null; + } + + Set> entries() { + return null; + } + + Nested nested; + + static class Nested { + } +} 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 33d0cfabd36..d7bc3f614a1 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 @@ -25,6 +25,8 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.annotation.CheckForNull; import org.sonar.check.Rule; import org.sonar.java.checks.helpers.ExpressionsHelper; import org.sonar.java.checks.helpers.QuickFixHelper; @@ -34,9 +36,15 @@ 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.Symbol; +import org.sonar.plugins.java.api.semantic.Type; +import org.sonar.plugins.java.api.tree.BaseTreeVisitor; +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.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; @@ -84,12 +92,23 @@ public void visitNode(Tree tree) { @Override public void leaveNode(Tree tree) { if (tree.is(Tree.Kind.COMPILATION_UNIT)) { - handleWarnings(((CompilationUnitTree) tree).warnings(ProblemKind.UNUSED_IMPORT)); + handleWarnings((CompilationUnitTree) tree); imports.clear(); } } - private void handleWarnings(List warnings) { + /** + * The compiler is the source of the unused imports, but its answer depends on the API of the JDK it sees. When that API is the one of an + * older release, member types which are not public (such as {@code LinkedHashMap.Entry}) do not exist anymore, and the compiler can + * consider an import as unused while its type is still referenced by simple name in the file. A warning is therefore only reported when + * no identifier of the file resolves to the imported type. + */ + private void handleWarnings(CompilationUnitTree compilationUnit) { + List warnings = compilationUnit.warnings(ProblemKind.UNUSED_IMPORT); + if (warnings.isEmpty()) { + return; + } + Set typesReferencedBySimpleName = typesReferencedBySimpleName(compilationUnit); for (Warning warning : warnings) { ImportTree reportTree = (ImportTree) warning.syntaxTree(); String importName = ExpressionsHelper.concatenate((ExpressionTree) reportTree.qualifiedIdentifier()); @@ -98,21 +117,87 @@ private void handleWarnings(List warnings) { 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 + "'."; + String message = message(reportTree, importName, onDemand, typesReferencedBySimpleName); + if (message != null) { + QuickFixHelper.newIssue(context) + .forRule(this) + .onTree(reportTree.qualifiedIdentifier()) + .withMessage(message) + .withQuickFix(() -> quickFix(reportTree, imports)) + .report(); + } + } + } + } + + @CheckForNull + private String message(ImportTree importTree, String importName, boolean onDemand, Set typesReferencedBySimpleName) { + if (duplicatedImports.contains(importName)) { + return "Remove this duplicated import."; + } + if (isImportFromSamePackage(importName, onDemand)) { + return "Remove this unnecessary import: same package classes are always implicitly imported."; + } + if (!onDemand && !importTree.isStatic() && typesReferencedBySimpleName.contains(importName)) { + return null; + } + return "Remove this unused import '" + importName + "'."; + } + + private static Set typesReferencedBySimpleName(CompilationUnitTree compilationUnit) { + ReferencedTypesCollector collector = new ReferencedTypesCollector(); + compilationUnit.types().forEach(type -> type.accept(collector)); + return collector.types; + } + + private static class ReferencedTypesCollector extends BaseTreeVisitor { + + private final Set types = new HashSet<>(); + + @Override + public void visitIdentifier(IdentifierTree identifier) { + Symbol symbol = identifier.symbol(); + if (symbol.isTypeSymbol() && !isQualifiedMember(identifier) && !isInMemberScope(identifier, symbol)) { + types.add(symbol.type().fullyQualifiedName().replace('$', '.')); + } + } + + /** + * A member type of an enclosing class, or inherited from a supertype of it, is in scope without any import. Supertypes are only + * followed through classes declared in the analyzed sources: the members of binary classes can be hidden by non-public member types + * which the API of the targeted release does not expose. + */ + private static boolean isInMemberScope(IdentifierTree identifier, Symbol type) { + Symbol owner = type.owner(); + if (owner == null || !owner.isTypeSymbol()) { + return false; + } + Tree current = identifier.parent(); + while (current != null) { + if (current instanceof ClassTree classTree && isOwnerReachableFrom(classTree.symbol(), owner, new HashSet<>())) { + return true; } - QuickFixHelper.newIssue(context) - .forRule(this) - .onTree(reportTree.qualifiedIdentifier()) - .withMessage(message) - .withQuickFix(() -> quickFix(reportTree, imports)) - .report(); + current = current.parent(); + } + return false; + } + + private static boolean isOwnerReachableFrom(Symbol.TypeSymbol candidate, Symbol owner, Set visited) { + if (candidate.type().fullyQualifiedName().equals(owner.type().fullyQualifiedName())) { + return true; } + if (candidate.declaration() == null || !visited.add(candidate)) { + return false; + } + return directSuperTypes(candidate).anyMatch(superType -> isOwnerReachableFrom(superType.symbol(), owner, visited)); + } + + private static Stream directSuperTypes(Symbol.TypeSymbol symbol) { + return Stream.concat(Stream.ofNullable(symbol.superClass()), symbol.interfaces().stream()); + } + + private static boolean isQualifiedMember(IdentifierTree identifier) { + return identifier.parent() instanceof MemberSelectExpressionTree memberSelect && memberSelect.identifier() == identifier; } } diff --git a/java-checks/src/test/java/org/sonar/java/checks/UselessImportCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/UselessImportCheckTest.java index 40c5a56adbd..b2544c8b65e 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/UselessImportCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/UselessImportCheckTest.java @@ -94,6 +94,20 @@ void with_compiling_module() { .verifyNoIssues(); } + @Test + void types_hidden_by_non_public_member_types_in_the_release_api() { + CheckVerifier.newVerifier() + .onFile(mainCodeSourcesPath("checks/UselessImportCheck/HiddenMemberTypes.java")) + .withCheck(new UselessImportCheck()) + .withJavaVersion(17) + .verifyIssues(); + + CheckVerifier.newVerifier() + .onFile(mainCodeSourcesPath("checks/UselessImportCheck/HiddenMemberTypes.java")) + .withCheck(new UselessImportCheck()) + .verifyIssues(); + } + @Test void intersection_type() { CheckVerifier.newVerifier() @@ -102,4 +116,12 @@ void intersection_type() { .verifyIssues(); } + @Test + void imports_redundant_because_of_inherited_member_types() { + CheckVerifier.newVerifier() + .onFile(mainCodeSourcesPath("checks/UselessImportCheck/RedundantViaMemberScope.java")) + .withCheck(new UselessImportCheck()) + .verifyIssues(); + } + }