1 |
| |
2 |
| |
3 |
| |
4 |
| package net.sourceforge.pmd.rules; |
5 |
| |
6 |
| import net.sourceforge.pmd.AbstractRule; |
7 |
| import net.sourceforge.pmd.ast.ASTCompilationUnit; |
8 |
| import net.sourceforge.pmd.ast.ASTLocalVariableDeclaration; |
9 |
| import net.sourceforge.pmd.ast.ASTVariableDeclaratorId; |
10 |
| import net.sourceforge.pmd.symboltable.NameOccurrence; |
11 |
| import net.sourceforge.pmd.symboltable.Scope; |
12 |
| import net.sourceforge.pmd.symboltable.VariableNameDeclaration; |
13 |
| |
14 |
| import java.util.HashSet; |
15 |
| import java.util.Iterator; |
16 |
| import java.util.List; |
17 |
| import java.util.Map; |
18 |
| import java.util.Set; |
19 |
| |
20 |
| public class UnusedLocalVariableRule extends AbstractRule { |
21 |
| |
22 |
| private Set visited = new HashSet(); |
23 |
| |
24 |
22
| public Object visit(ASTCompilationUnit acu, Object data) {
|
25 |
22
| visited.clear();
|
26 |
22
| return super.visit(acu, data);
|
27 |
| } |
28 |
| |
29 |
31
| public Object visit(ASTVariableDeclaratorId node, Object data) {
|
30 |
31
| if (node.jjtGetParent().jjtGetParent() instanceof ASTLocalVariableDeclaration) {
|
31 |
30
| Scope scope = node.getScope();
|
32 |
30
| if (visited.contains(scope)) {
|
33 |
4
| return data;
|
34 |
| } else { |
35 |
26
| visited.add(scope);
|
36 |
| } |
37 |
26
| Map locals = scope.getVariableDeclarations();
|
38 |
26
| for (Iterator i = locals.keySet().iterator(); i.hasNext();) {
|
39 |
30
| VariableNameDeclaration decl = (VariableNameDeclaration) i.next();
|
40 |
| |
41 |
| |
42 |
| |
43 |
30
| if (decl.isArray()) {
|
44 |
1
| continue;
|
45 |
| } |
46 |
29
| List usages = (List) locals.get(decl);
|
47 |
29
| if (!actuallyUsed(usages)) {
|
48 |
16
| addViolation(data, decl.getNode(), decl.getImage());
|
49 |
| } |
50 |
| } |
51 |
| } |
52 |
27
| return data;
|
53 |
| } |
54 |
| |
55 |
29
| private boolean actuallyUsed(List usages) {
|
56 |
29
| for (Iterator j = usages.iterator(); j.hasNext();) {
|
57 |
15
| NameOccurrence occ = (NameOccurrence) j.next();
|
58 |
15
| if (occ.isOnLeftHandSide()) {
|
59 |
2
| continue;
|
60 |
| } else { |
61 |
13
| return true;
|
62 |
| } |
63 |
| } |
64 |
16
| return false;
|
65 |
| } |
66 |
| } |