01: /**
02: * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03: */package net.sourceforge.pmd.rules.imports;
04:
05: import net.sourceforge.pmd.AbstractRule;
06: import net.sourceforge.pmd.ast.ASTClassOrInterfaceType;
07: import net.sourceforge.pmd.ast.ASTCompilationUnit;
08: import net.sourceforge.pmd.ast.ASTImportDeclaration;
09: import net.sourceforge.pmd.ast.ASTName;
10: import net.sourceforge.pmd.ast.SimpleJavaNode;
11: import net.sourceforge.pmd.ast.SimpleNode;
12: import net.sourceforge.pmd.rules.ImportWrapper;
13:
14: import java.util.HashSet;
15: import java.util.Set;
16:
17: public class UnusedImportsRule extends AbstractRule {
18:
19: protected Set<ImportWrapper> imports = new HashSet<ImportWrapper>();
20:
21: public Object visit(ASTCompilationUnit node, Object data) {
22: imports.clear();
23: super .visit(node, data);
24: for (ImportWrapper wrapper : imports) {
25: addViolation(data, wrapper.getNode(), wrapper.getFullName());
26: }
27: return data;
28: }
29:
30: public Object visit(ASTImportDeclaration node, Object data) {
31: if (!node.isImportOnDemand()) {
32: ASTName importedType = (ASTName) node.jjtGetChild(0);
33: String className;
34: if (isQualifiedName(importedType)) {
35: int lastDot = importedType.getImage().lastIndexOf('.') + 1;
36: className = importedType.getImage().substring(lastDot);
37: } else {
38: className = importedType.getImage();
39: }
40: imports.add(new ImportWrapper(importedType.getImage(),
41: className, node));
42: }
43:
44: return data;
45: }
46:
47: public Object visit(ASTClassOrInterfaceType node, Object data) {
48: check(node);
49: return super .visit(node, data);
50: }
51:
52: public Object visit(ASTName node, Object data) {
53: check(node);
54: return data;
55: }
56:
57: protected void check(SimpleNode node) {
58: if (imports.isEmpty()) {
59: return;
60: }
61: ImportWrapper candidate = getImportWrapper(node);
62: if (imports.contains(candidate)) {
63: imports.remove(candidate);
64: }
65: }
66:
67: protected ImportWrapper getImportWrapper(SimpleNode node) {
68: String name;
69: if (!isQualifiedName(node)) {
70: name = node.getImage();
71: } else {
72: name = node.getImage().substring(0,
73: node.getImage().indexOf('.'));
74: }
75: ImportWrapper candidate = new ImportWrapper(node.getImage(),
76: name, new SimpleJavaNode(-1));
77: return candidate;
78: }
79: }
|