|
1 |
| package net.sourceforge.pmd.rules.design; |
|
2 |
| |
|
3 |
| import net.sourceforge.pmd.AbstractRule; |
|
4 |
| import net.sourceforge.pmd.ast.ASTEqualityExpression; |
|
5 |
| import net.sourceforge.pmd.ast.ASTInitializer; |
|
6 |
| import net.sourceforge.pmd.ast.ASTName; |
|
7 |
| import net.sourceforge.pmd.ast.Node; |
|
8 |
| import net.sourceforge.pmd.ast.SimpleNode; |
|
9 |
| import net.sourceforge.pmd.symboltable.NameOccurrence; |
|
10 |
| import net.sourceforge.pmd.symboltable.Scope; |
|
11 |
| import net.sourceforge.pmd.symboltable.VariableNameDeclaration; |
|
12 |
| |
|
13 |
| import java.util.Iterator; |
|
14 |
| import java.util.List; |
|
15 |
| import java.util.Map; |
|
16 |
| |
|
17 |
| public class CompareObjectsWithEquals extends AbstractRule { |
|
18 |
| |
|
19 |
12
| private boolean hasName(Node n) {
|
|
20 |
12
| return n.jjtGetNumChildren() > 0 && n.jjtGetChild(0) instanceof ASTName;
|
|
21 |
| } |
|
22 |
| |
|
23 |
7
| public Object visit(ASTEqualityExpression node, Object data) {
|
|
24 |
| |
|
25 |
7
| if (!hasName(((SimpleNode)node.jjtGetChild(0)).jjtGetChild(0)) || !hasName(((SimpleNode)node.jjtGetChild(1)).jjtGetChild(0))) {
|
|
26 |
3
| return data;
|
|
27 |
| } |
|
28 |
| |
|
29 |
| |
|
30 |
4
| if (((SimpleNode)node.jjtGetChild(0).jjtGetChild(0).jjtGetChild(0)).getImage().indexOf(".") != -1
|
|
31 |
| || ((SimpleNode)node.jjtGetChild(1).jjtGetChild(0).jjtGetChild(0)).getImage().indexOf(".") != -1) { |
|
32 |
1
| return data;
|
|
33 |
| } |
|
34 |
| |
|
35 |
| |
|
36 |
3
| if (!node.getParentsOfType(ASTInitializer.class).isEmpty()) {
|
|
37 |
0
| return data;
|
|
38 |
| } |
|
39 |
| |
|
40 |
3
| check((Scope)node.getScope(), node, data);
|
|
41 |
3
| check(node.getScope().getEnclosingMethodScope(), node, data);
|
|
42 |
3
| return data;
|
|
43 |
| } |
|
44 |
| |
|
45 |
6
| private void check(Scope scope, SimpleNode node, Object ctx) {
|
|
46 |
6
| Map vars = scope.getVariableDeclarations();
|
|
47 |
6
| for (Iterator i = vars.keySet().iterator(); i.hasNext();) {
|
|
48 |
4
| VariableNameDeclaration key = (VariableNameDeclaration)i.next();
|
|
49 |
4
| if (key.isPrimitiveType() || key.isArray()) {
|
|
50 |
2
| continue;
|
|
51 |
| } |
|
52 |
2
| List usages = (List)vars.get(key);
|
|
53 |
2
| if (usages.isEmpty()) {
|
|
54 |
0
| continue;
|
|
55 |
| } |
|
56 |
2
| for (Iterator j = usages.iterator(); j.hasNext();) {
|
|
57 |
2
| if (((NameOccurrence)j.next()).getLocation().jjtGetParent().jjtGetParent().jjtGetParent() == node) {
|
|
58 |
2
| addViolation(ctx, node);
|
|
59 |
2
| return;
|
|
60 |
| } |
|
61 |
| } |
|
62 |
| } |
|
63 |
| } |
|
64 |
| } |