View Javadoc

    1   package net.sourceforge.pmd.rules.strings;
    2
    3   import net.sourceforge.pmd.AbstractRule;
    4   import net.sourceforge.pmd.ast.ASTAdditiveExpression;
    5   import net.sourceforge.pmd.ast.ASTLiteral;
    6   import net.sourceforge.pmd.ast.ASTPrimaryExpression;
    7   import net.sourceforge.pmd.ast.ASTVariableDeclaratorId;
    8   import net.sourceforge.pmd.ast.SimpleNode;
    9   import net.sourceforge.pmd.symboltable.NameOccurrence;
    10
    11  import java.util.Iterator;
    12  import java.util.List;
    13
    14  public class UseIndexOfChar extends AbstractRule {
    15      public Object visit(ASTVariableDeclaratorId node, Object data) {
    16          if (!node.getNameDeclaration().getTypeImage().equals("String")) {
    17              return data;
    18          }
    19          for (Iterator i = node.getUsages().iterator(); i.hasNext();) {
    20              NameOccurrence occ = (NameOccurrence) i.next();
    21              if (occ.getNameForWhichThisIsAQualifier() != null &&
    22                  (occ.getNameForWhichThisIsAQualifier().getImage().indexOf("indexOf") != -1 ||
    23                  occ.getNameForWhichThisIsAQualifier().getImage().indexOf("lastIndexOf") != -1)) {
    24                  SimpleNode parent = (SimpleNode)occ.getLocation().jjtGetParent().jjtGetParent();
    25                  if (parent instanceof ASTPrimaryExpression) {
    26                      // bail out if it's something like indexOf("a" + "b")
    27                      List additives = parent.findChildrenOfType(ASTAdditiveExpression.class);
    28                      if (!additives.isEmpty()) {
    29                          return data;
    30                      }
    31                      List literals = parent.findChildrenOfType(ASTLiteral.class);
    32                      for (Iterator j = literals.iterator(); j.hasNext();) {
    33                          ASTLiteral literal = (ASTLiteral)j.next();
    34                          if (literal.getImage().length() == 3 && literal.getImage().charAt(0) == '\"') {
    35                              addViolation(data, occ.getLocation());
    36                          }
    37                      }
    38                  }
    39              }
    40          }
    41          return data;
    42      }
    43  }
    44