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.ASTConstructorDeclaration;
10  import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter;
11  import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
12  import net.sourceforge.pmd.lang.java.ast.AccessNode;
13  import net.sourceforge.pmd.lang.java.symboltable.VariableNameDeclaration;
14  import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
15  import net.sourceforge.pmd.lang.symboltable.Scope;
16  
17  public class MethodArgumentCouldBeFinalRule extends AbstractOptimizationRule {
18  
19      @Override
20      public Object visit(ASTMethodDeclaration meth, Object data) {
21          if (meth.isNative() || meth.isAbstract()) {
22              return data;
23          }
24          this.lookForViolation(meth.getScope(), data);
25          return super.visit(meth, data);
26      }
27  
28      private void lookForViolation(Scope scope, Object data) {
29          Map<VariableNameDeclaration, List<NameOccurrence>> decls = scope.getDeclarations(VariableNameDeclaration.class);
30          for (Map.Entry<VariableNameDeclaration, List<NameOccurrence>> entry : decls.entrySet()) {
31              VariableNameDeclaration var = entry.getKey();
32              AccessNode node = var.getAccessNodeParent();
33              if (!node.isFinal() && node instanceof ASTFormalParameter && !assigned(entry.getValue())) {
34                  addViolation(data, node, var.getImage());
35              }
36          }
37      }
38  
39      @Override
40      public Object visit(ASTConstructorDeclaration constructor, Object data) {
41          this.lookForViolation(constructor.getScope(), data);
42          return super.visit(constructor, data);
43      }
44  
45  }