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