View Javadoc

    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.List;
    13
    14  public class UnusedLocalVariableRule extends AbstractRule {
    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  }