View Javadoc

1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.rules.optimization;
5   
6   import java.util.List;
7   import java.util.Map;
8   
9   import net.sourceforge.pmd.ast.ASTConstructorDeclaration;
10  import net.sourceforge.pmd.ast.ASTFormalParameter;
11  import net.sourceforge.pmd.ast.ASTMethodDeclaration;
12  import net.sourceforge.pmd.ast.AccessNode;
13  import net.sourceforge.pmd.symboltable.NameOccurrence;
14  import net.sourceforge.pmd.symboltable.Scope;
15  import net.sourceforge.pmd.symboltable.VariableNameDeclaration;
16  
17  public class MethodArgumentCouldBeFinal 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.getVariableDeclarations();
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  }