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