From ee7618c5e3e896509c1150ec22dd73f7073d64ee Mon Sep 17 00:00:00 2001 From: lpilastri Date: Mon, 23 Nov 2026 13:53:17 +0100 Subject: [PATCH 1/5] Fix S1128 FPs when --release option shadows non-public members of JDK --- .../UselessImportCheck/HiddenMemberTypes.java | 42 ++++++++++ .../sonar/java/checks/UselessImportCheck.java | 78 +++++++++++++++---- .../java/checks/UselessImportCheckTest.java | 14 ++++ 3 files changed, 119 insertions(+), 15 deletions(-) create mode 100644 java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/HiddenMemberTypes.java 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/src/main/java/org/sonar/java/checks/UselessImportCheck.java b/java-checks/src/main/java/org/sonar/java/checks/UselessImportCheck.java index 33d0cfabd36..33351f6eb50 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,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; +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 +35,13 @@ 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.tree.BaseTreeVisitor; 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 +89,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,24 +114,56 @@ 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(); } - 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)) { + types.add(((Symbol.TypeSymbol) symbol).type().fullyQualifiedName().replace('$', '.')); + } + } + + private static boolean isQualifiedMember(IdentifierTree identifier) { + return identifier.parent() instanceof MemberSelectExpressionTree memberSelect && memberSelect.identifier() == identifier; + } + } + private boolean isImportFromSamePackage(String importName, boolean onDemand) { return onDemand ? importName.equals(currentPackage) : importName.substring(0, importName.lastIndexOf('.')).equals(currentPackage); } 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..bae87a71fab 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() From bf8d1761d9a0ab5affa48379dc68232680d1a5da Mon Sep 17 00:00:00 2001 From: lpilastri Date: Mon, 23 Nov 2026 14:19:04 +0100 Subject: [PATCH 2/5] Remove redundant cast --- .../src/main/java/org/sonar/java/checks/UselessImportCheck.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 33351f6eb50..5fa3ab265c2 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 @@ -155,7 +155,7 @@ private static class ReferencedTypesCollector extends BaseTreeVisitor { public void visitIdentifier(IdentifierTree identifier) { Symbol symbol = identifier.symbol(); if (symbol.isTypeSymbol() && !isQualifiedMember(identifier)) { - types.add(((Symbol.TypeSymbol) symbol).type().fullyQualifiedName().replace('$', '.')); + types.add((symbol).type().fullyQualifiedName().replace('$', '.')); } } From 993a08e6d85dda72d660531189df2924f53e908f Mon Sep 17 00:00:00 2001 From: lpilastri Date: Mon, 23 Nov 2026 16:24:34 +0100 Subject: [PATCH 3/5] Update ruling expectations --- .../resources/expected/guava/java-S1128.sarif | 120 ------------------ 1 file changed, 120 deletions(-) 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..9b05c1793bf 100644 --- a/its/ruling/src/test/resources/expected/guava/java-S1128.sarif +++ b/its/ruling/src/test/resources/expected/guava/java-S1128.sarif @@ -12,126 +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", - "level" : "warning", - "message" : { - "text" : "Remove this unused import 'com.google.common.collect.Multiset.Entry'." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/collect/ImmutableMultiset.java", - "index" : -1 - }, - "region" : { - "startLine" : 23, - "startColumn" : 8, - "endLine" : 23, - "endColumn" : 48 - } - } - } ], - "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, "kind" : "fail", From 26f1c1a891fdef7b6923c9b12c14b7e3a0d07bba Mon Sep 17 00:00:00 2001 From: lpilastri Date: Wed, 25 Nov 2026 09:20:07 +0100 Subject: [PATCH 4/5] Address gitar bot comment: report imports redundant through member scope Co-Authored-By: Claude Sonnet 5.5 --- .../RedundantViaMemberScope.java | 22 +++++++++++ .../sonar/java/checks/UselessImportCheck.java | 39 ++++++++++++++++++- .../java/checks/UselessImportCheckTest.java | 8 ++++ 3 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 java-checks-test-sources/default/src/main/java/checks/UselessImportCheck/RedundantViaMemberScope.java 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 5fa3ab265c2..0e6a0af3274 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,7 @@ 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; @@ -36,7 +37,9 @@ 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; @@ -154,11 +157,45 @@ private static class ReferencedTypesCollector extends BaseTreeVisitor { @Override public void visitIdentifier(IdentifierTree identifier) { Symbol symbol = identifier.symbol(); - if (symbol.isTypeSymbol() && !isQualifiedMember(identifier)) { + 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; + } + 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 bae87a71fab..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 @@ -116,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(); + } + } From c74b54fdd8c0f670a96e48057d19281ed0fa6ba0 Mon Sep 17 00:00:00 2001 From: lpilastri Date: Wed, 25 Nov 2026 11:51:12 +0100 Subject: [PATCH 5/5] Restore guava ruling expectation for ImmutableMultiset and remove redundant parentheses Co-Authored-By: Claude Sonnet 5.5 --- .../resources/expected/guava/java-S1128.sarif | 24 +++++++++++++++++++ .../sonar/java/checks/UselessImportCheck.java | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) 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 9b05c1793bf..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,6 +12,30 @@ }, "language" : "en-US", "results" : [ { + "ruleId" : "java:S1128", + "ruleIndex" : -1, + "kind" : "fail", + "level" : "warning", + "message" : { + "text" : "Remove this unused import 'com.google.common.collect.Multiset.Entry'." + }, + "locations" : [ { + "id" : -1, + "physicalLocation" : { + "artifactLocation" : { + "uri" : "guava:src/com/google/common/collect/ImmutableMultiset.java", + "index" : -1 + }, + "region" : { + "startLine" : 23, + "startColumn" : 8, + "endLine" : 23, + "endColumn" : 48 + } + } + } ], + "rank" : -1.0 + }, { "ruleId" : "java:S1128", "ruleIndex" : -1, "kind" : "fail", 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 0e6a0af3274..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 @@ -158,7 +158,7 @@ private static class ReferencedTypesCollector extends BaseTreeVisitor { public void visitIdentifier(IdentifierTree identifier) { Symbol symbol = identifier.symbol(); if (symbol.isTypeSymbol() && !isQualifiedMember(identifier) && !isInMemberScope(identifier, symbol)) { - types.add((symbol).type().fullyQualifiedName().replace('$', '.')); + types.add(symbol.type().fullyQualifiedName().replace('$', '.')); } }