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(
21                  VariableNameDeclaration.class);
22          this.lookForViolation(params, data);
23          return super.visit(node, data);
24      }
25  
26      private void lookForViolation(Map<VariableNameDeclaration, List<NameOccurrence>> params, Object data) {
27          for (Map.Entry<VariableNameDeclaration, List<NameOccurrence>> entry : params.entrySet()) {
28              VariableNameDeclaration decl = entry.getKey();
29              List<NameOccurrence> usages = entry.getValue();
30              for (NameOccurrence occ : usages) {
31                  JavaNameOccurrence jocc = (JavaNameOccurrence) occ;
32                  if ((jocc.isOnLeftHandSide() || jocc.isSelfAssignment())
33                          && jocc.getNameForWhichThisIsAQualifier() == null
34                          && !jocc.useThisOrSuper()
35                          && !decl.isVarargs()
36                          && (!decl.isArray() || jocc.getLocation().jjtGetParent().jjtGetParent().jjtGetNumChildren() == 1)) {
37                      // not an array or no primary suffix to access the array
38                      // values
39                      addViolation(data, decl.getNode(), decl.getImage());
40                  }
41              }
42          }
43      }
44  
45      @Override
46      public Object visit(ASTConstructorDeclaration node, Object data) {
47          Map<VariableNameDeclaration, List<NameOccurrence>> params = node.getScope().getDeclarations(
48                  VariableNameDeclaration.class);
49          this.lookForViolation(params, data);
50          return super.visit(node, data);
51      }
52  }