Search in sources :

Example 16 with StatementTree

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

the class IncrementInForLoopAndHeader method matchForLoop.

@Override
public Description matchForLoop(ForLoopTree forLoopTree, VisitorState visitorState) {
    List<? extends ExpressionStatementTree> updates = forLoopTree.getUpdate();
    // keep track of all the symbols that are updated in the for loop header
    final Set<Symbol> incrementedSymbols = updates.stream().filter(expStateTree -> expStateTree.getExpression() instanceof UnaryTree).map(expStateTree -> ASTHelpers.getSymbol(((UnaryTree) expStateTree.getExpression()).getExpression())).collect(Collectors.toCollection(HashSet::new));
    // track if they are updated in the body without a conditional surrounding them
    StatementTree body = forLoopTree.getStatement();
    List<? extends StatementTree> statementTrees = body instanceof BlockTree ? ((BlockTree) body).getStatements() : ImmutableList.of(body);
    for (StatementTree s : statementTrees) {
        if (!CONDITIONALS.contains(s.getKind())) {
            Optional<Symbol> opSymbol = returnUnarySym(s);
            if (opSymbol.isPresent() && incrementedSymbols.contains(opSymbol.get())) {
                // both ++ and --
                return describeMatch(forLoopTree);
            }
        }
    }
    return Description.NO_MATCH;
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) UnaryTree(com.sun.source.tree.UnaryTree) Symbol(com.sun.tools.javac.code.Symbol) Set(java.util.Set) Collectors(java.util.stream.Collectors) ExpressionStatementTree(com.sun.source.tree.ExpressionStatementTree) HashSet(java.util.HashSet) VisitorState(com.google.errorprone.VisitorState) ForLoopTreeMatcher(com.google.errorprone.bugpatterns.BugChecker.ForLoopTreeMatcher) List(java.util.List) Kind(com.sun.source.tree.Tree.Kind) ImmutableList(com.google.common.collect.ImmutableList) Description(com.google.errorprone.matchers.Description) BlockTree(com.sun.source.tree.BlockTree) StatementTree(com.sun.source.tree.StatementTree) BugPattern(com.google.errorprone.BugPattern) Optional(java.util.Optional) WARNING(com.google.errorprone.BugPattern.SeverityLevel.WARNING) JDK(com.google.errorprone.BugPattern.Category.JDK) ForLoopTree(com.sun.source.tree.ForLoopTree) ASTHelpers(com.google.errorprone.util.ASTHelpers) ExpressionStatementTree(com.sun.source.tree.ExpressionStatementTree) StatementTree(com.sun.source.tree.StatementTree) Symbol(com.sun.tools.javac.code.Symbol) BlockTree(com.sun.source.tree.BlockTree) UnaryTree(com.sun.source.tree.UnaryTree)

Example 17 with StatementTree

use of com.sun.source.tree.StatementTree 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)

Example 18 with StatementTree

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

the class InputStreamSlowMultibyteRead method maybeMatchReadByte.

private Description maybeMatchReadByte(MethodTree readByteMethod, VisitorState state) {
    if (readByteMethod.getBody() != null) {
        // Null-check for native/abstract overrides of read()
        List<? extends StatementTree> statements = readByteMethod.getBody().getStatements();
        if (statements.size() == 1) {
            Tree tree = statements.get(0);
            if (tree.getKind() == Kind.RETURN && ASTHelpers.constValue(((ReturnTree) tree).getExpression()) != null) {
                return Description.NO_MATCH;
            }
        }
    }
    // Streams within JUnit test cases are likely to be OK as well.
    TreePath enclosingPath = ASTHelpers.findPathFromEnclosingNodeToTopLevel(state.getPath(), ClassTree.class);
    while (enclosingPath != null) {
        ClassTree klazz = (ClassTree) enclosingPath.getLeaf();
        if (JUnitMatchers.isTestCaseDescendant.matches(klazz, state) || hasAnnotation(JUnitMatchers.JUNIT4_RUN_WITH_ANNOTATION).matches(klazz, state)) {
            return Description.NO_MATCH;
        }
        enclosingPath = ASTHelpers.findPathFromEnclosingNodeToTopLevel(enclosingPath, ClassTree.class);
    }
    return describeMatch(readByteMethod);
}
Also used : TreePath(com.sun.source.util.TreePath) ClassTree(com.sun.source.tree.ClassTree) ReturnTree(com.sun.source.tree.ReturnTree) MethodTree(com.sun.source.tree.MethodTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) StatementTree(com.sun.source.tree.StatementTree)

Example 19 with StatementTree

use of com.sun.source.tree.StatementTree in project bazel by bazelbuild.

the class TreeUtils method containsThisConstructorInvocation.

/**
     * @return true if the first statement in the body is a self constructor
     *  invocation within a constructor
     */
public static final boolean containsThisConstructorInvocation(MethodTree node) {
    if (!TreeUtils.isConstructor(node) || node.getBody().getStatements().isEmpty())
        return false;
    StatementTree st = node.getBody().getStatements().get(0);
    if (!(st instanceof ExpressionStatementTree) || !(((ExpressionStatementTree) st).getExpression() instanceof MethodInvocationTree))
        return false;
    MethodInvocationTree invocation = (MethodInvocationTree) ((ExpressionStatementTree) st).getExpression();
    return "this".contentEquals(TreeUtils.methodName(invocation));
}
Also used : ExpressionStatementTree(com.sun.source.tree.ExpressionStatementTree) StatementTree(com.sun.source.tree.StatementTree) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) ExpressionStatementTree(com.sun.source.tree.ExpressionStatementTree)

Example 20 with StatementTree

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

the class MissingFail method matchTry.

@Override
public Description matchTry(TryTree tree, VisitorState state) {
    if (tryTreeMatches(tree, state)) {
        List<? extends StatementTree> tryStatements = tree.getBlock().getStatements();
        StatementTree lastTryStatement = tryStatements.get(tryStatements.size() - 1);
        String failCall = String.format("\nfail(\"Expected %s\");", exceptionToString(tree));
        SuggestedFix.Builder fixBuilder = SuggestedFix.builder().postfixWith(lastTryStatement, failCall);
        // Make sure that when the fail import is added it doesn't conflict with existing ones.
        fixBuilder.removeStaticImport("junit.framework.Assert.fail");
        fixBuilder.removeStaticImport("junit.framework.TestCase.fail");
        fixBuilder.addStaticImport("org.junit.Assert.fail");
        return describeMatch(lastTryStatement, fixBuilder.build());
    } else {
        return Description.NO_MATCH;
    }
}
Also used : StatementTree(com.sun.source.tree.StatementTree) SuggestedFix(com.google.errorprone.fixes.SuggestedFix)

Aggregations

StatementTree (com.sun.source.tree.StatementTree)37 MethodInvocationTree (com.sun.source.tree.MethodInvocationTree)19 ExpressionStatementTree (com.sun.source.tree.ExpressionStatementTree)18 BlockTree (com.sun.source.tree.BlockTree)16 Tree (com.sun.source.tree.Tree)16 ExpressionTree (com.sun.source.tree.ExpressionTree)12 TreePath (com.sun.source.util.TreePath)9 SuggestedFix (com.google.errorprone.fixes.SuggestedFix)8 MethodTree (com.sun.source.tree.MethodTree)8 MemberSelectTree (com.sun.source.tree.MemberSelectTree)7 TryTree (com.sun.source.tree.TryTree)7 VariableTree (com.sun.source.tree.VariableTree)7 CatchTree (com.sun.source.tree.CatchTree)6 JCTree (com.sun.tools.javac.tree.JCTree)6 ClassTree (com.sun.source.tree.ClassTree)5 IdentifierTree (com.sun.source.tree.IdentifierTree)5 MethodSymbol (com.sun.tools.javac.code.Symbol.MethodSymbol)5 VisitorState (com.google.errorprone.VisitorState)4 Description (com.google.errorprone.matchers.Description)4 EnhancedForLoopTree (com.sun.source.tree.EnhancedForLoopTree)4