Search in sources :

Example 1 with EmptyStatementTree

use of com.sun.source.tree.EmptyStatementTree in project error-prone by google.

the class EmptyIfStatement method matchEmptyStatement.

/**
   * Match empty statement if:
   * - Parent statement is an if
   * - The then part of the parent if is an empty statement, and
   * - The else part of the parent if does not exist
   */
@Override
public Description matchEmptyStatement(EmptyStatementTree tree, VisitorState state) {
    boolean matches = false;
    Tree parent = state.getPath().getParentPath().getLeaf();
    if (parent.getKind() == IF) {
        IfTree parentAsIf = (IfTree) parent;
        matches = (parentAsIf.getThenStatement() instanceof EmptyStatementTree) && (parentAsIf.getElseStatement() == null);
    }
    if (!matches) {
        return Description.NO_MATCH;
    }
    /*
     * We suggest different fixes depending on what follows the parent if statement.
     * If there is no statement following the if, then suggest deleting the whole
     * if statement. If the next statement is a block, then suggest deleting the
     * empty then part of the if.  If the next statement is not a block, then also
     * suggest deleting the empty then part of the if.
     */
    boolean nextStmtIsNull = parentNode(nextStatement(Matchers.<StatementTree>isSame(null))).matches(tree, state);
    assert (state.getPath().getParentPath().getLeaf().getKind() == IF);
    IfTree ifParent = (IfTree) state.getPath().getParentPath().getLeaf();
    if (nextStmtIsNull) {
        // No following statements. Delete whole if.
        return describeMatch(parent, SuggestedFix.delete(parent));
    } else {
        // There are more statements. Delete the empty then part of the if.
        return describeMatch(ifParent.getThenStatement(), SuggestedFix.delete(ifParent.getThenStatement()));
    }
}
Also used : EmptyStatementTree(com.sun.source.tree.EmptyStatementTree) IfTree(com.sun.source.tree.IfTree) EmptyStatementTree(com.sun.source.tree.EmptyStatementTree) StatementTree(com.sun.source.tree.StatementTree) Tree(com.sun.source.tree.Tree) IfTree(com.sun.source.tree.IfTree)

Aggregations

EmptyStatementTree (com.sun.source.tree.EmptyStatementTree)1 IfTree (com.sun.source.tree.IfTree)1 StatementTree (com.sun.source.tree.StatementTree)1 Tree (com.sun.source.tree.Tree)1