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