private boolean hasAssignmentOperator(Node node) {
   if (node instanceof ASTStatementExpression || node instanceof ASTExpression) {
     if (node.jjtGetNumChildren() >= 2 && node.jjtGetChild(1) instanceof ASTAssignmentOperator) {
       return true;
     }
   }
   return false;
 }
Пример #2
0
 protected void apply(Node node, RuleContext ctx) {
   for (int i = 0; i < node.jjtGetNumChildren(); i++) {
     apply(node.jjtGetChild(i), ctx);
   }
   if ("Foo".equals(node.getImage())) {
     addViolation(ctx, node);
   }
 }
Пример #3
0
 private boolean useInitCause(Node node, ASTCatchStatement catchStmt) {
   // In case of NPE...
   if (node != null && node.getImage() != null) {
     return catchStmt.hasDescendantMatchingXPath(
         "./Block/BlockStatement/Statement/StatementExpression/PrimaryExpression/PrimaryPrefix/Name[@Image = '"
             + node.getImage()
             + ".initCause']");
   }
   return false;
 }
  /**
   * Return whether a class of the specified type exists between the node argument and the topParent
   * argument.
   *
   * @param node Node
   * @param intermediateParentClass Class
   * @param topParent Node
   * @return boolean
   */
  public static boolean hasAsParentBetween(
      Node node, Class<?> intermediateParentClass, Node topParent) {

    Node currentParent = node.jjtGetParent();

    while (currentParent != topParent) {
      currentParent = currentParent.jjtGetParent();
      if (currentParent.getClass().equals(intermediateParentClass)) return true;
    }
    return false;
  }
  private boolean isStandAlonePostfix(Node primaryExpression) {
    if (!(primaryExpression instanceof ASTPostfixExpression)
        || !(primaryExpression.jjtGetParent() instanceof ASTStatementExpression)) {
      return false;
    }

    ASTPrimaryPrefix pf =
        (ASTPrimaryPrefix) ((ASTPrimaryExpression) primaryExpression.jjtGetChild(0)).jjtGetChild(0);
    if (pf.usesThisModifier()) {
      return true;
    }

    return thirdChildHasDottedName(primaryExpression);
  }
Пример #6
0
  private boolean initializedInConstructor(List<NameOccurrence> usages) {
    boolean initInConstructor = false;

    for (NameOccurrence occ : usages) {
      // specifically omitting prefix and postfix operators as there are
      // legitimate usages of these with static fields, e.g. typesafe enum pattern.
      if (((JavaNameOccurrence) occ).isOnLeftHandSide()) {
        Node node = occ.getLocation();
        Node constructor = node.getFirstParentOfType(ASTConstructorDeclaration.class);
        if (constructor != null) {
          initInConstructor = true;
        }
      }
    }

    return initInConstructor;
  }
Пример #7
0
 private String getExpressionVarName(Node e) {
   String assignedVar = getFirstNameImage(e);
   if (assignedVar == null) {
     ASTPrimarySuffix suffix = e.getFirstDescendantOfType(ASTPrimarySuffix.class);
     if (suffix != null) {
       assignedVar = suffix.getImage();
       ASTPrimaryPrefix prefix = e.getFirstDescendantOfType(ASTPrimaryPrefix.class);
       if (prefix != null) {
         if (prefix.usesThisModifier()) {
           assignedVar = "this." + assignedVar;
         } else if (prefix.usesSuperModifier()) {
           assignedVar = "super." + assignedVar;
         }
       }
     }
   }
   return assignedVar;
 }
Пример #8
0
 public ElementNode(
     DocumentNode document,
     IdGenerator idGenerator,
     ElementNode parent,
     Node node,
     int siblingPosition) {
   this.document = document;
   this.parent = parent;
   this.node = node;
   this.id = idGenerator.getNextId();
   this.siblingPosition = siblingPosition;
   if (node.jjtGetNumChildren() > 0) {
     this.children = new NodeInfo[node.jjtGetNumChildren()];
     for (int i = 0; i < children.length; i++) {
       children[i] = new ElementNode(document, idGenerator, this, node.jjtGetChild(i), i);
     }
   } else {
     this.children = null;
   }
   document.nodeToElementNode.put(node, this);
 }
Пример #9
0
 /**
  * Checks whether the given target is in the argument list. If this is the case, then the target
  * (root exception) is used as the cause.
  *
  * @param target
  * @param baseNode
  */
 private boolean checkForTargetUsage(String target, Node baseNode) {
   boolean match = false;
   if (target != null && baseNode != null) {
     List<ASTName> nameNodes = baseNode.findDescendantsOfType(ASTName.class);
     for (ASTName nameNode : nameNodes) {
       if (target.equals(nameNode.getImage())) {
         match = true;
         break;
       }
     }
   }
   return match;
 }
  public boolean isOnLeftHandSide() {
    // I detest this method with every atom of my being
    Node primaryExpression;
    if (location.jjtGetParent() instanceof ASTPrimaryExpression) {
      primaryExpression = location.jjtGetParent().jjtGetParent();
    } else if (location.jjtGetParent().jjtGetParent() instanceof ASTPrimaryExpression) {
      primaryExpression = location.jjtGetParent().jjtGetParent().jjtGetParent();
    } else {
      throw new RuntimeException(
          "Found a NameOccurrence that didn't have an ASTPrimary Expression as parent or grandparent.  Parent = "
              + location.jjtGetParent()
              + " and grandparent = "
              + location.jjtGetParent().jjtGetParent());
    }

    if (isStandAlonePostfix(primaryExpression)) {
      return true;
    }

    if (primaryExpression.jjtGetNumChildren() <= 1) {
      return false;
    }

    if (!(primaryExpression.jjtGetChild(1) instanceof ASTAssignmentOperator)) {
      return false;
    }

    if (isPartOfQualifiedName() /* or is an array type */) {
      return false;
    }

    if (isCompoundAssignment(primaryExpression)) {
      return false;
    }

    return true;
  }
Пример #11
0
 /** {@inheritDoc} */
 @Override
 @SuppressWarnings("unchecked")
 public List<Node> evaluate(Node node, RuleContext data) {
   List<Node> results = new ArrayList<Node>();
   try {
     initializeXPathExpression(
         data.getLanguageVersion().getLanguageVersionHandler().getXPathHandler().getNavigator());
     List<XPath> xpaths = nodeNameToXPaths.get(node.toString());
     if (xpaths == null) {
       xpaths = nodeNameToXPaths.get(AST_ROOT);
     }
     for (XPath xpath : xpaths) {
       List<Node> nodes = xpath.selectNodes(node);
       results.addAll(nodes);
     }
   } catch (JaxenException ex) {
     throw new RuntimeException(ex);
   }
   return results;
 }
Пример #12
0
 @Override
 public Object visit(ASTCatchStatement catchStmt, Object data) {
   String target =
       catchStmt
           .jjtGetChild(0)
           .findChildrenOfType(ASTVariableDeclaratorId.class)
           .get(0)
           .getImage();
   // Inspect all the throw stmt inside the catch stmt
   List<ASTThrowStatement> lstThrowStatements =
       catchStmt.findDescendantsOfType(ASTThrowStatement.class);
   for (ASTThrowStatement throwStatement : lstThrowStatements) {
     Node n = throwStatement.jjtGetChild(0).jjtGetChild(0);
     if (n instanceof ASTCastExpression) {
       ASTPrimaryExpression expr = (ASTPrimaryExpression) n.jjtGetChild(1);
       if (expr.jjtGetNumChildren() > 1 && expr.jjtGetChild(1) instanceof ASTPrimaryPrefix) {
         RuleContext ctx = (RuleContext) data;
         addViolation(ctx, throwStatement);
       }
       continue;
     }
     // Retrieve all argument for the throw exception (to see if the
     // original exception is preserved)
     ASTArgumentList args = throwStatement.getFirstDescendantOfType(ASTArgumentList.class);
     if (args != null) {
       Node parent = args.jjtGetParent().jjtGetParent();
       if (parent instanceof ASTAllocationExpression) {
         // maybe it is used inside a anonymous class
         ck(data, target, throwStatement, parent);
       } else {
         ck(data, target, throwStatement, args);
       }
     } else {
       Node child = throwStatement.jjtGetChild(0);
       while (child != null && child.jjtGetNumChildren() > 0 && !(child instanceof ASTName)) {
         child = child.jjtGetChild(0);
       }
       if (child != null) {
         if (child instanceof ASTName
             && !target.equals(child.getImage())
             && !child.hasImageEqualTo(target + FILL_IN_STACKTRACE)) {
           Map<VariableNameDeclaration, List<NameOccurrence>> vars =
               ((ASTName) child).getScope().getDeclarations(VariableNameDeclaration.class);
           for (Map.Entry<VariableNameDeclaration, List<NameOccurrence>> entry : vars.entrySet()) {
             VariableNameDeclaration decl = entry.getKey();
             List<NameOccurrence> occurrences = entry.getValue();
             if (decl.getImage().equals(child.getImage())) {
               if (!isInitCauseCalled(target, occurrences)) {
                 args =
                     decl.getNode().jjtGetParent().getFirstDescendantOfType(ASTArgumentList.class);
                 if (args != null) {
                   ck(data, target, throwStatement, args);
                 }
               }
             }
           }
         } else if (child instanceof ASTClassOrInterfaceType) {
           addViolation(data, throwStatement);
         }
       }
     }
   }
   return super.visit(catchStmt, data);
 }
 private boolean isCompoundAssignment(Node primaryExpression) {
   return ((ASTAssignmentOperator) primaryExpression.jjtGetChild(1)).isCompound();
 }
 private boolean thirdChildHasDottedName(Node primaryExpression) {
   Node thirdChild = primaryExpression.jjtGetChild(0).jjtGetChild(0).jjtGetChild(0);
   return thirdChild instanceof ASTName && ((ASTName) thirdChild).getImage().indexOf('.') == -1;
 }
  /**
   * Assert it the occurrence is a self assignment such as: <code>
   * 		i += 3;
   * </code>
   *
   * @return true, if the occurrence is self-assignment, false, otherwise.
   */
  @SuppressWarnings("PMD.AvoidBranchingStatementAsLastInLoop")
  public boolean isSelfAssignment() {
    Node l = location;
    while (true) {
      Node p = l.jjtGetParent();
      Node gp = p.jjtGetParent();
      Node node = gp.jjtGetParent();
      if (node instanceof ASTPreDecrementExpression
          || node instanceof ASTPreIncrementExpression
          || node instanceof ASTPostfixExpression) {
        return true;
      }

      if (hasAssignmentOperator(gp)) {
        return isCompoundAssignment(gp);
      }

      if (hasAssignmentOperator(node)) {
        return isCompoundAssignment(node);
      }

      // deal with extra parenthesis: "(i)++"
      if (p instanceof ASTPrimaryPrefix
          && p.jjtGetNumChildren() == 1
          && gp instanceof ASTPrimaryExpression
          && gp.jjtGetNumChildren() == 1
          && node instanceof ASTExpression
          && node.jjtGetNumChildren() == 1
          && node.jjtGetParent() instanceof ASTPrimaryPrefix
          && node.jjtGetParent().jjtGetNumChildren() == 1) {
        l = node;
        continue;
      }

      // catch this.i++ or ++this.i
      return gp instanceof ASTPreDecrementExpression
          || gp instanceof ASTPreIncrementExpression
          || gp instanceof ASTPostfixExpression;
    }
  }
Пример #16
0
 @Override
 public String getLocalPart() {
   return node.toString();
 }
Пример #17
0
 @Override
 public int getLineNumber() {
   return node.getBeginLine();
 }
Пример #18
0
 @Override
 public int getColumnNumber() {
   return node.getBeginColumn();
 }
 public boolean isOnRightHandSide() {
   Node node = location.jjtGetParent().jjtGetParent().jjtGetParent();
   return node instanceof ASTExpression && node.jjtGetNumChildren() == 3;
 }