1 |
| package net.sourceforge.pmd.rules; |
2 |
| |
3 |
| import net.sourceforge.pmd.AbstractRule; |
4 |
| import net.sourceforge.pmd.ast.ASTEqualityExpression; |
5 |
| import net.sourceforge.pmd.ast.ASTLiteral; |
6 |
| import net.sourceforge.pmd.ast.ASTPrimitiveType; |
7 |
| import net.sourceforge.pmd.ast.ASTRelationalExpression; |
8 |
| import net.sourceforge.pmd.ast.ASTVariableDeclaratorId; |
9 |
| import net.sourceforge.pmd.ast.SimpleNode; |
10 |
| import net.sourceforge.pmd.symboltable.NameOccurrence; |
11 |
| |
12 |
| import java.util.Iterator; |
13 |
| import java.util.List; |
14 |
| |
15 |
| |
16 |
| |
17 |
| |
18 |
| |
19 |
| |
20 |
| |
21 |
| |
22 |
| public abstract class AbstractInefficientZeroCheck extends AbstractRule { |
23 |
| |
24 |
| public abstract boolean appliesToClassName(String name); |
25 |
| |
26 |
| public abstract boolean isTargetMethod(NameOccurrence occ); |
27 |
| |
28 |
28
| public Object visit(ASTVariableDeclaratorId node, Object data) {
|
29 |
28
| SimpleNode nameNode = node.getTypeNameNode();
|
30 |
28
| if (nameNode instanceof ASTPrimitiveType) {
|
31 |
8
| return data;
|
32 |
| } |
33 |
20
| if (!appliesToClassName(node.getNameDeclaration().getTypeImage())) {
|
34 |
1
| return data;
|
35 |
| } |
36 |
| |
37 |
19
| List declars = node.getUsages();
|
38 |
19
| for (Iterator i = declars.iterator(); i.hasNext();) {
|
39 |
20
| NameOccurrence occ = (NameOccurrence) i.next();
|
40 |
20
| if (!isTargetMethod(occ)) {
|
41 |
6
| continue;
|
42 |
| } |
43 |
14
| SimpleNode expr = (SimpleNode) occ.getLocation().jjtGetParent().jjtGetParent().jjtGetParent();
|
44 |
14
| if ((expr instanceof ASTEqualityExpression ||
|
45 |
| (expr instanceof ASTRelationalExpression && ">".equals(expr.getImage()))) |
46 |
| && isCompareZero(expr)) { |
47 |
8
| addViolation(data, occ.getLocation());
|
48 |
| } |
49 |
| } |
50 |
19
| return data;
|
51 |
| } |
52 |
| |
53 |
| |
54 |
| |
55 |
| |
56 |
| |
57 |
| |
58 |
| |
59 |
11
| private boolean isCompareZero(SimpleNode equality) {
|
60 |
11
| return (checkComparison(equality, 0) || checkComparison(equality, 1));
|
61 |
| |
62 |
| } |
63 |
| |
64 |
| |
65 |
| |
66 |
| |
67 |
| |
68 |
| |
69 |
| |
70 |
| |
71 |
| |
72 |
| |
73 |
21
| private boolean checkComparison(SimpleNode equality, int i) {
|
74 |
21
| SimpleNode target = (SimpleNode) equality.jjtGetChild(i).jjtGetChild(0);
|
75 |
21
| if (target.jjtGetNumChildren() == 0) {
|
76 |
1
| return false;
|
77 |
| } |
78 |
20
| target = (SimpleNode) target.jjtGetChild(0);
|
79 |
20
| return (target instanceof ASTLiteral && "0".equals(target.getImage()));
|
80 |
| } |
81 |
| |
82 |
| } |