Search in sources :

Example 26 with BinaryTree

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

the class FloatCast method matchTypeCast.

@Override
public Description matchTypeCast(TypeCastTree tree, VisitorState state) {
    Tree parent = state.getPath().getParentPath().getLeaf();
    if (!(parent instanceof BinaryTree)) {
        return NO_MATCH;
    }
    BinaryTree binop = (BinaryTree) parent;
    if (!binop.getLeftOperand().equals(tree)) {
        // the precedence is unambiguous for e.g. `i + (int) f`
        return NO_MATCH;
    }
    if (binop.getKind() != Kind.MULTIPLY) {
        // there's a bound on the imprecision for +, -, /
        return NO_MATCH;
    }
    Type castType = ASTHelpers.getType(tree.getType());
    Type operandType = ASTHelpers.getType(tree.getExpression());
    if (castType == null || operandType == null) {
        return NO_MATCH;
    }
    Symtab symtab = state.getSymtab();
    if (isSameType(ASTHelpers.getType(parent), symtab.stringType, state)) {
        // string concatenation doesn't count
        return NO_MATCH;
    }
    switch(castType.getKind()) {
        case LONG:
        case INT:
        case SHORT:
        case CHAR:
        case BYTE:
            break;
        default:
            return NO_MATCH;
    }
    switch(operandType.getKind()) {
        case FLOAT:
        case DOUBLE:
            break;
        default:
            return NO_MATCH;
    }
    if (BLACKLIST.matches(tree.getExpression(), state)) {
        return NO_MATCH;
    }
    if (POW.matches(tree.getExpression(), state)) {
        MethodInvocationTree pow = (MethodInvocationTree) tree.getExpression();
        if (pow.getArguments().stream().map(ASTHelpers::getType).filter(x -> x != null).map(state.getTypes()::unboxedTypeOrType).map(Type::getKind).allMatch(INTEGRAL::contains)) {
            return NO_MATCH;
        }
    }
    // Find the outermost enclosing binop, to suggest e.g. `(long) (f * a * b)` instead of
    // `(long) (f * a) * b`.
    Tree enclosing = binop;
    TreePath path = state.getPath().getParentPath().getParentPath();
    while (path != null) {
        if (!(path.getLeaf() instanceof BinaryTree)) {
            break;
        }
        BinaryTree enclosingBinop = (BinaryTree) path.getLeaf();
        if (!enclosingBinop.getLeftOperand().equals(enclosing)) {
            break;
        }
        enclosing = enclosingBinop;
        path = path.getParentPath();
    }
    return buildDescription(tree).addFix(SuggestedFix.builder().prefixWith(tree.getExpression(), "(").postfixWith(enclosing, ")").build()).addFix(SuggestedFix.builder().prefixWith(tree, "(").postfixWith(tree, ")").build()).build();
}
Also used : Symtab(com.sun.tools.javac.code.Symtab) Symtab(com.sun.tools.javac.code.Symtab) TypeCastTreeMatcher(com.google.errorprone.bugpatterns.BugChecker.TypeCastTreeMatcher) BinaryTree(com.sun.source.tree.BinaryTree) VisitorState(com.google.errorprone.VisitorState) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) Kind(com.sun.source.tree.Tree.Kind) TypeCastTree(com.sun.source.tree.TypeCastTree) BugPattern(com.google.errorprone.BugPattern) Matcher(com.google.errorprone.matchers.Matcher) Tree(com.sun.source.tree.Tree) EnumSet(java.util.EnumSet) TreePath(com.sun.source.util.TreePath) ExpressionTree(com.sun.source.tree.ExpressionTree) Set(java.util.Set) NO_MATCH(com.google.errorprone.matchers.Description.NO_MATCH) TypeKind(javax.lang.model.type.TypeKind) MethodMatchers.staticMethod(com.google.errorprone.matchers.method.MethodMatchers.staticMethod) Description(com.google.errorprone.matchers.Description) WARNING(com.google.errorprone.BugPattern.SeverityLevel.WARNING) ProvidesFix(com.google.errorprone.BugPattern.ProvidesFix) SuggestedFix(com.google.errorprone.fixes.SuggestedFix) Pattern(java.util.regex.Pattern) ASTHelpers.isSameType(com.google.errorprone.util.ASTHelpers.isSameType) ASTHelpers(com.google.errorprone.util.ASTHelpers) Type(com.sun.tools.javac.code.Type) ASTHelpers.isSameType(com.google.errorprone.util.ASTHelpers.isSameType) Type(com.sun.tools.javac.code.Type) TreePath(com.sun.source.util.TreePath) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) BinaryTree(com.sun.source.tree.BinaryTree) BinaryTree(com.sun.source.tree.BinaryTree) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) TypeCastTree(com.sun.source.tree.TypeCastTree) Tree(com.sun.source.tree.Tree) ExpressionTree(com.sun.source.tree.ExpressionTree) ASTHelpers(com.google.errorprone.util.ASTHelpers)

Example 27 with BinaryTree

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

the class BadComparable method matchTypeCast.

@Override
public Description matchTypeCast(TypeCastTree tree, VisitorState state) {
    // Check for a narrowing match first as its simplest match to test.
    if (!matches(tree, state)) {
        return Description.NO_MATCH;
    }
    // Test that the match is in a Comparable.compareTo or Comparator.compare method.
    ClassTree declaringClass = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class);
    if (!COMPARABLE_CLASS_MATCHER.matches(declaringClass, state) && !COMPARATOR_CLASS_MATCHER.matches(declaringClass, state)) {
        return Description.NO_MATCH;
    }
    MethodTree method = ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class);
    if (method == null) {
        return Description.NO_MATCH;
    }
    if (!COMPARABLE_METHOD_MATCHER.matches(method, state) && !COMPARATOR_METHOD_MATCHER.matches(method, state)) {
        return Description.NO_MATCH;
    }
    // Get the unparenthesized expression.
    BinaryTree subtract = (BinaryTree) ASTHelpers.stripParentheses(tree.getExpression());
    ExpressionTree lhs = subtract.getLeftOperand();
    ExpressionTree rhs = subtract.getRightOperand();
    Fix fix;
    if (ASTHelpers.getType(lhs).isPrimitive()) {
        fix = SuggestedFix.replace(tree, "Long.compare(" + lhs + ", " + rhs + ")");
    } else {
        fix = SuggestedFix.replace(tree, lhs + ".compareTo(" + rhs + ")");
    }
    return describeMatch(tree, fix);
}
Also used : Fix(com.google.errorprone.fixes.Fix) ProvidesFix(com.google.errorprone.BugPattern.ProvidesFix) SuggestedFix(com.google.errorprone.fixes.SuggestedFix) MethodTree(com.sun.source.tree.MethodTree) ClassTree(com.sun.source.tree.ClassTree) BinaryTree(com.sun.source.tree.BinaryTree) ExpressionTree(com.sun.source.tree.ExpressionTree)

Example 28 with BinaryTree

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

the class IntLongMath method check.

Description check(Type targetType, ExpressionTree init) {
    if (init == null) {
        return NO_MATCH;
    }
    if (ASTHelpers.constValue(init) != null) {
        return NO_MATCH;
    }
    if (targetType.getKind() != TypeKind.LONG) {
        return NO_MATCH;
    }
    // primtive widening conversions can't be combined with autoboxing.
    if (ASTHelpers.getType(init).getKind() != TypeKind.INT) {
        return NO_MATCH;
    }
    BinaryTree innerMost = null;
    ExpressionTree nested = init;
    while (true) {
        nested = ASTHelpers.stripParentheses(nested);
        if (!(nested instanceof BinaryTree)) {
            break;
        }
        switch(nested.getKind()) {
            case DIVIDE:
            case REMAINDER:
            case AND:
            case XOR:
            case OR:
            case RIGHT_SHIFT:
                // longs or ints.
                break;
            default:
                innerMost = (BinaryTree) nested;
        }
        nested = ((BinaryTree) nested).getLeftOperand();
    }
    if (innerMost == null) {
        return NO_MATCH;
    }
    if (innerMost.getLeftOperand().getKind() == Kind.INT_LITERAL) {
        return describeMatch(init, SuggestedFix.postfixWith(innerMost.getLeftOperand(), "L"));
    }
    if (innerMost.getRightOperand().getKind() == Kind.INT_LITERAL) {
        return describeMatch(init, SuggestedFix.postfixWith(innerMost.getRightOperand(), "L"));
    }
    return describeMatch(init, SuggestedFix.prefixWith(innerMost.getLeftOperand(), "(long) "));
}
Also used : BinaryTree(com.sun.source.tree.BinaryTree) ExpressionTree(com.sun.source.tree.ExpressionTree)

Example 29 with BinaryTree

use of com.sun.source.tree.BinaryTree in project ceylon by eclipse.

the class T6654037 method main.

public static void main(String[] args) throws Exception {
    // NOI18N
    final String bootPath = System.getProperty("sun.boot.class.path");
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    assert tool != null;
    String code = "package test; public class Test {private void test() {Object o = null; boolean b = o != null && o instanceof String;} private Test() {}}";
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, Arrays.asList("-bootclasspath", bootPath, "-Xjcov"), null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    MethodTree method = (MethodTree) clazz.getMembers().get(0);
    VariableTree condSt = (VariableTree) method.getBody().getStatements().get(1);
    BinaryTree cond = (BinaryTree) condSt.getInitializer();
    JCTree condJC = (JCTree) cond;
    if (condJC.pos != 93)
        throw new IllegalStateException("Unexpected position=" + condJC.pos);
}
Also used : JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) MethodTree(com.sun.source.tree.MethodTree) ClassTree(com.sun.source.tree.ClassTree) VariableTree(com.sun.source.tree.VariableTree) BinaryTree(com.sun.source.tree.BinaryTree) JavaCompiler(javax.tools.JavaCompiler) JCTree(com.sun.tools.javac.tree.JCTree)

Example 30 with BinaryTree

use of com.sun.source.tree.BinaryTree in project ceylon-compiler by ceylon.

the class T6654037 method main.

public static void main(String[] args) throws Exception {
    // NOI18N
    final String bootPath = System.getProperty("sun.boot.class.path");
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    assert tool != null;
    String code = "package test; public class Test {private void test() {Object o = null; boolean b = o != null && o instanceof String;} private Test() {}}";
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, Arrays.asList("-bootclasspath", bootPath, "-Xjcov"), null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    MethodTree method = (MethodTree) clazz.getMembers().get(0);
    VariableTree condSt = (VariableTree) method.getBody().getStatements().get(1);
    BinaryTree cond = (BinaryTree) condSt.getInitializer();
    JCTree condJC = (JCTree) cond;
    if (condJC.pos != 93)
        throw new IllegalStateException("Unexpected position=" + condJC.pos);
}
Also used : JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) MethodTree(com.sun.source.tree.MethodTree) ClassTree(com.sun.source.tree.ClassTree) VariableTree(com.sun.source.tree.VariableTree) BinaryTree(com.sun.source.tree.BinaryTree) JavaCompiler(javax.tools.JavaCompiler) JCTree(com.sun.tools.javac.tree.JCTree)

Aggregations

BinaryTree (com.sun.source.tree.BinaryTree)30 ExpressionTree (com.sun.source.tree.ExpressionTree)26 Tree (com.sun.source.tree.Tree)17 LiteralTree (com.sun.source.tree.LiteralTree)15 ConditionalExpressionTree (com.sun.source.tree.ConditionalExpressionTree)13 IdentifierTree (com.sun.source.tree.IdentifierTree)11 MethodInvocationTree (com.sun.source.tree.MethodInvocationTree)11 MemberSelectTree (com.sun.source.tree.MemberSelectTree)10 ClassTree (com.sun.source.tree.ClassTree)9 CompoundAssignmentTree (com.sun.source.tree.CompoundAssignmentTree)9 TypeCastTree (com.sun.source.tree.TypeCastTree)9 MethodTree (com.sun.source.tree.MethodTree)8 PrimitiveTypeTree (com.sun.source.tree.PrimitiveTypeTree)8 VariableTree (com.sun.source.tree.VariableTree)8 AnnotatedTypeTree (com.sun.source.tree.AnnotatedTypeTree)6 BlockTree (com.sun.source.tree.BlockTree)6 ReturnTree (com.sun.source.tree.ReturnTree)6 StatementTree (com.sun.source.tree.StatementTree)6 TypeMirror (javax.lang.model.type.TypeMirror)6 SuggestedFix (com.google.errorprone.fixes.SuggestedFix)5