1
2
3
4 package net.sourceforge.pmd.lang.java.rule;
5
6 import java.util.HashMap;
7 import java.util.Iterator;
8 import java.util.Map;
9
10 import net.sourceforge.pmd.RuleContext;
11 import net.sourceforge.pmd.lang.dfa.DataFlowNode;
12 import net.sourceforge.pmd.lang.dfa.VariableAccess;
13 import net.sourceforge.pmd.lang.dfa.pathfinder.CurrentPath;
14 import net.sourceforge.pmd.lang.dfa.pathfinder.DAAPathFinder;
15 import net.sourceforge.pmd.lang.dfa.pathfinder.Executable;
16 import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
17
18
19 public class UselessAssignment extends AbstractJavaRule implements Executable {
20
21 private RuleContext rc;
22
23 public Object visit(ASTMethodDeclaration node, Object data) {
24 this.rc = (RuleContext) data;
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40 DAAPathFinder a = new DAAPathFinder(node.getDataFlowNode().getFlow().get(0), this);
41 a.run();
42
43 return data;
44 }
45
46 private static class Usage {
47 public int accessType;
48 public DataFlowNode node;
49
50 public Usage(int accessType, DataFlowNode node) {
51 this.accessType = accessType;
52 this.node = node;
53 }
54
55 public String toString() {
56 return "accessType = " + accessType + ", line = " + node.getLine();
57 }
58 }
59
60 public void execute(CurrentPath path) {
61 Map<String, Usage> hash = new HashMap<String, Usage>();
62
63 for (Iterator<DataFlowNode> i = path.iterator(); i.hasNext();) {
64
65 DataFlowNode inode = i.next();
66 if (inode.getVariableAccess() == null) {
67 continue;
68 }
69 for (int j = 0; j < inode.getVariableAccess().size(); j++) {
70 VariableAccess va = inode.getVariableAccess().get(j);
71
72 Usage u = hash.get(va.getVariableName());
73 if (u != null) {
74
75
76
77
78
79 if (va.isDefinition() && va.accessTypeMatches(u.accessType)) {
80
81 addViolation(rc, u.node.getNode(), va.getVariableName());
82 }
83
84
85
86
87
88
89
90
91
92
93
94
95 }
96 u = new Usage(va.getAccessType(), inode);
97 hash.put(va.getVariableName(), u);
98 }
99 }
100 }
101 }