View Javadoc

    1   /**
    2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
    3    */
    4   package net.sourceforge.pmd.rules;
    5
    6   import java.util.List;
    7   import java.util.Map;
    8
    9   import net.sourceforge.pmd.AbstractJavaRule;
    10  import net.sourceforge.pmd.ast.ASTConstructorDeclaration;
    11  import net.sourceforge.pmd.ast.ASTMethodDeclarator;
    12  import net.sourceforge.pmd.symboltable.NameOccurrence;
    13  import net.sourceforge.pmd.symboltable.VariableNameDeclaration;
    14
    15  public class AvoidReassigningParameters extends AbstractJavaRule {
    16
    17  	@Override
    18      public Object visit(ASTMethodDeclarator node, Object data) {
    19          Map<VariableNameDeclaration, List<NameOccurrence>> params = node.getScope().getVariableDeclarations();
    20          this.lookForViolation(params, data);
    21          return super.visit(node, data);
    22      }
    23
    24  	private void lookForViolation(Map<VariableNameDeclaration,List<NameOccurrence>> params,Object data) {
    25          for (Map.Entry<VariableNameDeclaration, List<NameOccurrence>> entry: params.entrySet()) {
    26              VariableNameDeclaration decl = entry.getKey();
    27              List<NameOccurrence> usages = entry.getValue();
    28              for (NameOccurrence occ: usages) {
    29                  if ((occ.isOnLeftHandSide() || occ.isSelfAssignment()) &&
    30                      occ.getNameForWhichThisIsAQualifier() == null &&
    31                      (! occ.useThisOrSuper()) &&
    32                      (!decl.isArray() || occ.getLocation().jjtGetParent().jjtGetParent().jjtGetNumChildren() == 1))
    33                  {
    34                      // not an array or no primary suffix to access the array values
    35                      addViolation(data, decl.getNode(), decl.getImage());
    36                  }
    37              }
    38          }
    39  	}
    40
    41      @Override
    42      public Object visit(ASTConstructorDeclaration node,Object data) {
    43      	Map<VariableNameDeclaration,List<NameOccurrence>> params = node.getScope().getVariableDeclarations();
    44      	this.lookForViolation(params, data);
    45      	return super.visit(node,data);
    46      }
    47  }