01: package net.sourceforge.pmd.rules.migration;
02:
03: import net.sourceforge.pmd.AbstractRule;
04: import net.sourceforge.pmd.ast.ASTCastExpression;
05: import net.sourceforge.pmd.ast.ASTClassOrInterfaceType;
06: import net.sourceforge.pmd.ast.ASTFieldDeclaration;
07: import net.sourceforge.pmd.ast.ASTLocalVariableDeclaration;
08: import net.sourceforge.pmd.ast.ASTName;
09: import net.sourceforge.pmd.ast.ASTVariableDeclaratorId;
10: import net.sourceforge.pmd.ast.SimpleNode;
11: import net.sourceforge.pmd.symboltable.NameOccurrence;
12:
13: import java.util.HashSet;
14: import java.util.List;
15: import java.util.Set;
16:
17: public class UnnecessaryCast extends AbstractRule {
18:
19: private static Set<String> implClassNames = new HashSet<String>();
20:
21: static {
22: implClassNames.add("List");
23: implClassNames.add("Set");
24: implClassNames.add("Map");
25: implClassNames.add("java.util.List");
26: implClassNames.add("java.util.Set");
27: implClassNames.add("java.util.Map");
28: implClassNames.add("ArrayList");
29: implClassNames.add("HashSet");
30: implClassNames.add("HashMap");
31: implClassNames.add("LinkedHashMap");
32: implClassNames.add("LinkedHashSet");
33: implClassNames.add("TreeSet");
34: implClassNames.add("TreeMap");
35: implClassNames.add("Vector");
36: implClassNames.add("java.util.ArrayList");
37: implClassNames.add("java.util.HashSet");
38: implClassNames.add("java.util.HashMap");
39: implClassNames.add("java.util.LinkedHashMap");
40: implClassNames.add("java.util.LinkedHashSet");
41: implClassNames.add("java.util.TreeSet");
42: implClassNames.add("java.util.TreeMap");
43: implClassNames.add("java.util.Vector");
44: }
45:
46: public Object visit(ASTLocalVariableDeclaration node, Object data) {
47: return process(node, data);
48: }
49:
50: public Object visit(ASTFieldDeclaration node, Object data) {
51: return process(node, data);
52: }
53:
54: private Object process(SimpleNode node, Object data) {
55: ASTClassOrInterfaceType cit = node
56: .getFirstChildOfType(ASTClassOrInterfaceType.class);
57: if (cit == null || !implClassNames.contains(cit.getImage())) {
58: return data;
59: }
60: cit = cit.getFirstChildOfType(ASTClassOrInterfaceType.class);
61: if (cit == null) {
62: return data;
63: }
64: ASTVariableDeclaratorId decl = node
65: .getFirstChildOfType(ASTVariableDeclaratorId.class);
66: List<NameOccurrence> usages = decl.getUsages();
67: for (NameOccurrence no : usages) {
68: ASTName name = (ASTName) no.getLocation();
69: SimpleNode n = (SimpleNode) name.jjtGetParent()
70: .jjtGetParent().jjtGetParent();
71: if (ASTCastExpression.class.equals(n.getClass())) {
72: addViolation(data, n);
73: }
74: }
75: return null;
76: }
77: }
|