View Javadoc

    1   package net.sourceforge.pmd.rules.strings;
    2
    3   import net.sourceforge.pmd.AbstractRule;
    4   import net.sourceforge.pmd.ast.ASTName;
    5   import net.sourceforge.pmd.ast.ASTPrimaryExpression;
    6   import net.sourceforge.pmd.ast.ASTPrimaryPrefix;
    7   import net.sourceforge.pmd.ast.ASTPrimarySuffix;
    8
    9   public class UnnecessaryCaseChange extends AbstractRule {
    10
    11      public Object visit(ASTPrimaryExpression exp, Object data) {
    12          if (exp.jjtGetNumChildren() < 4) {
    13              return data;
    14          }
    15
    16          String first = getBadPrefixOrNull(exp);
    17          if (first == null) {
    18              return data;
    19          }
    20
    21          String second = getBadSuffixOrNull(exp);
    22          if (second == null) {
    23              return data;
    24          }
    25
    26          if (!(exp.jjtGetChild(1) instanceof ASTPrimarySuffix)) {
    27              return data;
    28          }
    29          ASTPrimarySuffix methodCall = (ASTPrimarySuffix)exp.jjtGetChild(1);
    30          if (!methodCall.isArguments() || methodCall.getArgumentCount() > 0) {
    31              return data;
    32          }
    33
    34          addViolation(data, exp);
    35          return data;
    36      }
    37
    38      private String getBadPrefixOrNull(ASTPrimaryExpression exp) {
    39          // verify PrimaryPrefix/Name[ends-with(@Image, 'toUpperCase']
    40          if (!(exp.jjtGetChild(0) instanceof ASTPrimaryPrefix)) {
    41              return null;
    42          }
    43
    44          ASTPrimaryPrefix prefix = (ASTPrimaryPrefix) exp.jjtGetChild(0);
    45          if (prefix.jjtGetNumChildren() != 1 || !(prefix.jjtGetChild(0) instanceof ASTName)) {
    46              return null;
    47          }
    48
    49          ASTName name = (ASTName) prefix.jjtGetChild(0);
    50          if (name.getImage() == null || !(name.getImage().endsWith("toUpperCase") || name.getImage().endsWith("toLowerCase"))) {
    51              return null;
    52          }
    53          return name.getImage();
    54      }
    55
    56      private String getBadSuffixOrNull(ASTPrimaryExpression exp) {
    57          // verify PrimarySuffix[@Image='equals']
    58          if (!(exp.jjtGetChild(2) instanceof ASTPrimarySuffix)) {
    59              return null;
    60          }
    61
    62          ASTPrimarySuffix suffix = (ASTPrimarySuffix) exp.jjtGetChild(2);
    63          if (suffix.getImage() == null || !(suffix.getImage().equals("equals") || suffix.getImage().equals("equalsIgnoreCase"))) {
    64              return null;
    65          }
    66          return suffix.getImage();
    67      }
    68
    69  }