View Javadoc

    1   package net.sourceforge.pmd.rules.design;
    2
    3   import net.sourceforge.pmd.AbstractRule;
    4   import net.sourceforge.pmd.ast.ASTEqualityExpression;
    5   import net.sourceforge.pmd.ast.ASTInitializer;
    6   import net.sourceforge.pmd.ast.ASTName;
    7   import net.sourceforge.pmd.ast.Node;
    8   import net.sourceforge.pmd.ast.SimpleNode;
    9   import net.sourceforge.pmd.symboltable.VariableNameDeclaration;
    10
    11  public class CompareObjectsWithEquals extends AbstractRule {
    12
    13      private boolean hasName(Node n) {
    14          return n.jjtGetNumChildren() > 0 && n.jjtGetChild(0) instanceof ASTName;
    15      }
    16
    17      public Object visit(ASTEqualityExpression node, Object data) {
    18          // skip if either child is not a simple name
    19          if (!hasName(((SimpleNode) node.jjtGetChild(0)).jjtGetChild(0)) || !hasName(((SimpleNode) node.jjtGetChild(1)).jjtGetChild(0))) {
    20              return data;
    21          }
    22
    23          // skip if either is a qualified name
    24          if (isQualifiedName((SimpleNode) node.jjtGetChild(0).jjtGetChild(0).jjtGetChild(0))
    25              || isQualifiedName((SimpleNode) node.jjtGetChild(1).jjtGetChild(0).jjtGetChild(0))) {
    26              return data;
    27          }
    28
    29          // skip static initializers... missing some cases here
    30          if (!node.getParentsOfType(ASTInitializer.class).isEmpty()) {
    31              return data;
    32          }
    33
    34          ASTName n0 = (ASTName) node.jjtGetChild(0).jjtGetChild(0).jjtGetChild(0);
    35          ASTName n1 = (ASTName) node.jjtGetChild(1).jjtGetChild(0).jjtGetChild(0);
    36
    37          if (n0.getNameDeclaration() instanceof VariableNameDeclaration && n1.getNameDeclaration() instanceof VariableNameDeclaration) {
    38              VariableNameDeclaration nd0 = (VariableNameDeclaration) n0.getNameDeclaration();
    39              VariableNameDeclaration nd1 = (VariableNameDeclaration) n1.getNameDeclaration();
    40
    41              // skip array dereferences... this misses some cases
    42              // FIXME catch comparisons btwn array elements of reference types
    43              if (nd0.isArray() || nd1.isArray()) {
    44                  return data;
    45              }
    46
    47              if (nd0.isReferenceType() && nd1.isReferenceType()) {
    48                  addViolation(data, node);
    49              }
    50          }
    51
    52          return data;
    53      }
    54  }