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.NameOccurrence;
    13
    14  public class UnusedLocalVariableRule extends AbstractJavaRule {
    15
    16      public Object visit(ASTLocalVariableDeclaration decl, Object data) {
    17          for (int i = 0; i < decl.jjtGetNumChildren(); i++) {
    18              if (!(decl.jjtGetChild(i) instanceof ASTVariableDeclarator)) {
    19                  continue;
    20              }
    21              ASTVariableDeclaratorId node = (ASTVariableDeclaratorId) decl.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() && !actuallyUsed(node.getUsages())) {
    26                  addViolation(data, node, node.getNameDeclaration().getImage());
    27              }
    28          }
    29          return data;
    30      }
    31
    32      private boolean actuallyUsed(List<NameOccurrence> usages) {
    33          for (NameOccurrence occ: usages) {
    34              if (occ.isOnLeftHandSide()) {
    35                  continue;
    36              } else {
    37                  return true;
    38              }
    39          }
    40          return false;
    41      }
    42
    43  }