View Javadoc
1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.java.rule.unusedcode;
5   
6   import java.util.List;
7   
8   import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration;
9   import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator;
10  import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
11  import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
12  import net.sourceforge.pmd.lang.java.symboltable.JavaNameOccurrence;
13  import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
14  
15  public class UnusedLocalVariableRule extends AbstractJavaRule {
16  
17      public Object visit(ASTLocalVariableDeclaration decl, Object 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<NameOccurrence> usages) {
34          for (NameOccurrence occ: usages) {
35              JavaNameOccurrence jocc = (JavaNameOccurrence)occ;
36              if (jocc.isOnLeftHandSide()) {
37                  continue;
38              } else {
39                  return true;
40              }
41          }
42          return false;
43      }
44  
45  }