Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 0 additions & 96 deletions its/ruling/src/test/resources/expected/guava/java-S1128.sarif
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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<K, V> extends LinkedHashMap<K, V> {
@Override
protected boolean removeEldestEntry(Entry<K, V> eldest) {
return size() > 10;
}
}

static class Sorted extends Properties {
private static final Comparator<Entry<Object, Object>> BY_KEY = Entry.comparingByKey((a, b) -> a.toString().compareTo(b.toString()));

Entry<Object, Object> first() {
return null;
}
}

static class Tree<K, V> extends TreeMap<K, V> {
Entry<K, V> any() {
return firstEntry();
}
}

static class Weak<K, V> extends WeakHashMap<K, V> {
Entry<K, V> none() {
return null;
}
}

java.util.Set<String> referencedWithItsQualifiedName;
}
Original file line number Diff line number Diff line change
@@ -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<K, V> implements Map<K, V> {

Entry<K, V> inherited() {
return null;
}

Set<Entry<K, V>> entries() {
return null;
}

Nested nested;

static class Nested {
}
}
115 changes: 100 additions & 15 deletions java-checks/src/main/java/org/sonar/java/checks/UselessImportCheck.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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<Warning> 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<Warning> warnings = compilationUnit.warnings(ProblemKind.UNUSED_IMPORT);
if (warnings.isEmpty()) {
return;
}
Set<String> typesReferencedBySimpleName = typesReferencedBySimpleName(compilationUnit);
for (Warning warning : warnings) {
ImportTree reportTree = (ImportTree) warning.syntaxTree();
String importName = ExpressionsHelper.concatenate((ExpressionTree) reportTree.qualifiedIdentifier());
Expand All @@ -98,21 +117,87 @@ private void handleWarnings(List<Warning> 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<String> 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;
}
Comment thread
gitar-bot[bot] marked this conversation as resolved.
Resolved
return "Remove this unused import '" + importName + "'.";
}

private static Set<String> 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<String> 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<Symbol> 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<Type> 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;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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();
}

}
Loading