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.optimizations;
    5
    6   import java.util.List;
    7   import java.util.Map;
    8
    9   import net.sourceforge.pmd.lang.ast.Node;
    10  import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration;
    11  import net.sourceforge.pmd.lang.java.symboltable.NameOccurrence;
    12  import net.sourceforge.pmd.lang.java.symboltable.Scope;
    13  import net.sourceforge.pmd.lang.java.symboltable.VariableNameDeclaration;
    14
    15  public class LocalVariableCouldBeFinalRule extends AbstractOptimizationRule {
    16
    17      public Object visit(ASTLocalVariableDeclaration node, Object data) {
    18          if (node.isFinal()) {
    19              return data;
    20          }
    21          Scope s = node.getScope();
    22          Map<VariableNameDeclaration, List<NameOccurrence>> decls = s.getVariableDeclarations();
    23          for (Map.Entry<VariableNameDeclaration, List<NameOccurrence>> entry: decls.entrySet()) {
    24              VariableNameDeclaration var = entry.getKey();
    25              if (var.getAccessNodeParent() != node) {
    26                  continue;
    27              }
    28              if (!assigned(entry.getValue())) {
    29                  addViolation(data, (Node)var.getAccessNodeParent(), var.getImage());
    30              }
    31          }
    32          return data;
    33      }
    34
    35  }