KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > pmd > rules > UnusedLocalVariableRule


1 /**
2  * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3  */

4 package net.sourceforge.pmd.rules;
5
6 import net.sourceforge.pmd.AbstractRule;
7 import net.sourceforge.pmd.ast.ASTLocalVariableDeclaration;
8 import net.sourceforge.pmd.ast.ASTVariableDeclarator;
9 import net.sourceforge.pmd.ast.ASTVariableDeclaratorId;
10 import net.sourceforge.pmd.symboltable.NameOccurrence;
11
12 import java.util.Iterator JavaDoc;
13 import java.util.List JavaDoc;
14
15 public class UnusedLocalVariableRule extends AbstractRule {
16
17     public Object JavaDoc visit(ASTLocalVariableDeclaration decl, Object JavaDoc data) {
18         for (int i = 0; i < decl.jjtGetNumChildren(); i++) {
19             if (!(decl.jjtGetChild(i) instanceof ASTVariableDeclarator)) {
20                 continue;
21             }
22             ASTVariableDeclaratorId node = (ASTVariableDeclaratorId) decl.jjtGetChild(i).jjtGetChild(0);
23             // TODO this isArray() check misses some cases
24
// need to add DFAish code to determine if an array
25
// is initialized locally or gotten from somewhere else
26
if (!node.getNameDeclaration().isArray() && !actuallyUsed(node.getUsages())) {
27                 addViolation(data, node, node.getNameDeclaration().getImage());
28             }
29         }
30         return data;
31     }
32
33     private boolean actuallyUsed(List JavaDoc usages) {
34         for (Iterator JavaDoc j = usages.iterator(); j.hasNext();) {
35             NameOccurrence occ = (NameOccurrence) j.next();
36             if (occ.isOnLeftHandSide()) {
37                 continue;
38             } else {
39                 return true;
40             }
41         }
42         return false;
43     }
44
45 }
46
Popular Tags