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.design;
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.ASTMethodDeclarator;
11  import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
12  import net.sourceforge.pmd.lang.java.symboltable.JavaNameOccurrence;
13  import net.sourceforge.pmd.lang.java.symboltable.VariableNameDeclaration;
14  import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
15  
16  public class AvoidReassigningParametersRule extends AbstractJavaRule {
17  
18  	@Override
19      public Object visit(ASTMethodDeclarator node, Object data) {
20          Map<VariableNameDeclaration, List<NameOccurrence>> params = node.getScope().getDeclarations(VariableNameDeclaration.class);
21          this.lookForViolation(params, data);
22          return super.visit(node, data);
23      }
24  
25  	private void lookForViolation(Map<VariableNameDeclaration,List<NameOccurrence>> params,Object data) {
26          for (Map.Entry<VariableNameDeclaration, List<NameOccurrence>> entry: params.entrySet()) {
27              VariableNameDeclaration decl = entry.getKey();
28              List<NameOccurrence> usages = entry.getValue();
29              for (NameOccurrence occ: usages) {
30                  JavaNameOccurrence jocc = (JavaNameOccurrence)occ;
31                  if ((jocc.isOnLeftHandSide() || jocc.isSelfAssignment()) &&
32                          jocc.getNameForWhichThisIsAQualifier() == null &&
33                      (! jocc.useThisOrSuper()) &&
34                      (!decl.isArray() || jocc.getLocation().jjtGetParent().jjtGetParent().jjtGetNumChildren() == 1))
35                  {
36                      // not an array or no primary suffix to access the array values
37                      addViolation(data, decl.getNode(), decl.getImage());
38                  }
39              }
40          }
41  	}
42  
43      @Override
44      public Object visit(ASTConstructorDeclaration node,Object data) {
45      	Map<VariableNameDeclaration,List<NameOccurrence>> params = node.getScope().getDeclarations(VariableNameDeclaration.class);
46      	this.lookForViolation(params, data);
47      	return super.visit(node,data);
48      }
49  }