View Javadoc

    1   package net.sourceforge.pmd.rules.design;
    2
    3   import net.sourceforge.pmd.AbstractRule;
    4   import net.sourceforge.pmd.ast.ASTExpression;
    5   import net.sourceforge.pmd.ast.ASTMethodDeclaration;
    6   import net.sourceforge.pmd.ast.ASTName;
    7   import net.sourceforge.pmd.ast.ASTPrimaryExpression;
    8   import net.sourceforge.pmd.ast.ASTReturnStatement;
    9   import net.sourceforge.pmd.symboltable.NameOccurrence;
    10  import net.sourceforge.pmd.symboltable.VariableNameDeclaration;
    11
    12  import java.util.Iterator;
    13  import java.util.List;
    14  import java.util.Map;
    15
    16  public class UnnecessaryLocalBeforeReturn extends AbstractRule {
    17
    18      public Object visit(ASTMethodDeclaration meth, Object data) {
    19          // skip void/abstract/native method
    20          if (meth.isVoid() || meth.isAbstract() || meth.isNative()) {
    21              return data;
    22          }
    23          return super.visit(meth, data);
    24      }
    25
    26      public Object visit(ASTReturnStatement rtn, Object data) {
    27          // skip returns of literals
    28          ASTName name = (ASTName) rtn.getFirstChildOfType(ASTName.class);
    29          if (name == null) {
    30              return data;
    31          }
    32
    33          // skip 'complicated' expressions
    34          if (rtn.findChildrenOfType(ASTExpression.class).size() > 1 || rtn.findChildrenOfType(ASTPrimaryExpression.class).size() > 1) {
    35              return data;
    36          }
    37
    38          Map vars = name.getScope().getVariableDeclarations();
    39          for (Iterator i = vars.keySet().iterator(); i.hasNext();) {
    40              VariableNameDeclaration key = (VariableNameDeclaration) i.next();
    41              List usages = (List) vars.get(key);
    42              for (Iterator j = usages.iterator(); j.hasNext();) {
    43                  NameOccurrence occ = (NameOccurrence) j.next();
    44                  if (occ.getLocation().equals(name)) {
    45                      // only check declarations that occur one line earlier
    46                      if (key.getNode().getBeginLine() == name.getBeginLine() - 1) {
    47                          String var = name.getImage();
    48                          if (var.indexOf('.') != -1) {
    49                              var = var.substring(0, var.indexOf('.'));
    50                          }
    51                          addViolation(data, rtn, var);
    52                      }
    53                  }
    54              }
    55          }
    56          return data;
    57      }
    58  }