01: /**
02: * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03: */package net.sourceforge.pmd.rules;
04:
05: import net.sourceforge.pmd.AbstractRule;
06: import net.sourceforge.pmd.ast.ASTLocalVariableDeclaration;
07: import net.sourceforge.pmd.ast.ASTVariableDeclarator;
08: import net.sourceforge.pmd.ast.ASTVariableDeclaratorId;
09: import net.sourceforge.pmd.symboltable.NameOccurrence;
10:
11: import java.util.List;
12:
13: public class UnusedLocalVariableRule extends AbstractRule {
14:
15: public Object visit(ASTLocalVariableDeclaration decl, Object data) {
16: for (int i = 0; i < decl.jjtGetNumChildren(); i++) {
17: if (!(decl.jjtGetChild(i) instanceof ASTVariableDeclarator)) {
18: continue;
19: }
20: ASTVariableDeclaratorId node = (ASTVariableDeclaratorId) decl
21: .jjtGetChild(i).jjtGetChild(0);
22: // TODO this isArray() check misses some cases
23: // need to add DFAish code to determine if an array
24: // is initialized locally or gotten from somewhere else
25: if (!node.getNameDeclaration().isArray()
26: && !actuallyUsed(node.getUsages())) {
27: addViolation(data, node, node.getNameDeclaration()
28: .getImage());
29: }
30: }
31: return data;
32: }
33:
34: private boolean actuallyUsed(List<NameOccurrence> usages) {
35: for (NameOccurrence occ : usages) {
36: if (occ.isOnLeftHandSide()) {
37: continue;
38: } else {
39: return true;
40: }
41: }
42: return false;
43: }
44:
45: }
|