com.sun.source.tree.TypeCastTree Java Examples

The following examples show how to use com.sun.source.tree.TypeCastTree. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
/**
 * strip out enclosing parentheses, type casts and Nullchk operators.
 *
 * @param expr a potentially parenthesised expression.
 * @return the same expression without parentheses.
 */
private static ExpressionTree stripParensAndCasts(ExpressionTree expr) {
  boolean someChange = true;
  while (someChange) {
    someChange = false;
    if (expr.getKind().equals(PARENTHESIZED)) {
      expr = ((ParenthesizedTree) expr).getExpression();
      someChange = true;
    }
    if (expr.getKind().equals(TYPE_CAST)) {
      expr = ((TypeCastTree) expr).getExpression();
      someChange = true;
    }

    // Strips Nullchk operator
    if (expr.getKind().equals(OTHER) && expr instanceof JCTree.JCUnary) {
      expr = ((JCTree.JCUnary) expr).getExpression();
      someChange = true;
    }
  }
  return expr;
}
 
Example #2
Source File: TooStrongCast.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(JavaFix.TransformationContext ctx) throws Exception {
    TreePath castPath = ctx.getPath();
    if (castPath.getLeaf().getKind() != Tree.Kind.TYPE_CAST) {
        return;
    }
    TypeCastTree tct = (TypeCastTree)castPath.getLeaf();
    Tree inside = tct.getExpression();
    Tree outside;
    TreePath upper = upto.resolve(ctx.getWorkingCopy());
    if (upper != null) {
        outside = upper.getLeaf();
    } else {
        outside = tct;
    }
    ctx.getWorkingCopy().rewrite(outside, inside);
}
 
Example #3
Source File: MathRandomCast.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    // path should be the typecast expression
    TreePath path = ctx.getPath();
    TreePath exprPath = exprHandle.resolve(ctx.getWorkingCopy());
    
    if (path.getLeaf().getKind() != Tree.Kind.TYPE_CAST || exprPath == null || !EXPRESSION_KINDS.contains(exprPath.getLeaf().getKind())) {
        // PENDING - some message ?
        return;
    }
    WorkingCopy copy = ctx.getWorkingCopy();
    TreeMaker make = ctx.getWorkingCopy().getTreeMaker();
    TypeCastTree cast = (TypeCastTree)path.getLeaf();
    // rewrite the type cast to the casted Math.random()
    copy.rewrite(path.getLeaf(), cast.getExpression());
    // rewrite the outermost expression to a typecast of it
    ExpressionTree expr = (ExpressionTree)exprPath.getLeaf();
    if (expr.getKind() != Tree.Kind.PARENTHESIZED) {
        expr = make.Parenthesized(expr);
    }
    copy.rewrite(exprPath.getLeaf(), make.TypeCast(cast.getType(), (ExpressionTree)expr));
}
 
Example #4
Source File: RemoveUselessCast.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    TreePath path = ctx.getPath();
    TypeCastTree tct = (TypeCastTree) path.getLeaf();
    ExpressionTree expression = tct.getExpression();

    while (expression.getKind() == Kind.PARENTHESIZED
           && !JavaFixUtilities.requiresParenthesis(((ParenthesizedTree) expression).getExpression(), tct, path.getParentPath().getLeaf())) {
        expression = ((ParenthesizedTree) expression).getExpression();
    }

    while (path.getParentPath().getLeaf().getKind() == Kind.PARENTHESIZED
           && !JavaFixUtilities.requiresParenthesis(expression, path.getLeaf(), path.getParentPath().getParentPath().getLeaf())) {
        path = path.getParentPath();
    }

    wc.rewrite(path.getLeaf(), expression);
}
 
Example #5
Source File: TooStrongCast.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static ErrorDescription reportUselessCast(HintContext ctx, TypeCastTree tct, 
        CharSequence currentTypeName, CompilationInfo info, ExpectedTypeResolver exp,
        TypeMirror castType) {
    
    if (!Utilities.isValidType(castType)) {
        return null;
    }
    if (castType.getKind().isPrimitive()) {
        TreePath binParent = findBinaryParent(ctx.getPath().getParentPath());
        if (binParent != null) {
            Map<Tree, TypeMirror> exclusions = (Map<Tree,TypeMirror>)ctx.getInfo().getCachedValue(RemoveCast.class);
            if (exclusions == null) {
                exclusions = new HashMap<>();
                ctx.getInfo().putCachedValue(RemoveCast.class, exclusions, CompilationInfo.CacheClearPolicy.ON_TASK_END);
            } else {
                TypeMirror x = exclusions.get(binParent.getLeaf());
                if (x != null && ctx.getInfo().getTypes().isSameType(x, castType)) {
                    return null;
                }
            }
            exclusions.put(binParent.getLeaf(), castType);
        }
    }
    
    return ErrorDescriptionFactory.forTree(ctx, tct.getType(), TEXT_UnnecessaryCast(
            currentTypeName), new RemoveCast(info, ctx.getPath(), exp.getTheExpression(), currentTypeName).
                    toEditorFix());
}
 
Example #6
Source File: TreeDiffer.java    From compile-testing with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitTypeCast(TypeCastTree expected, Tree actual) {
  Optional<TypeCastTree> other = checkTypeAndCast(expected, actual);
  if (!other.isPresent()) {
    addTypeMismatch(expected, actual);
    return null;
  }

  scan(expected.getType(), other.get().getType());
  scan(expected.getExpression(), other.get().getExpression());
  return null;
}
 
Example #7
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitTypeCast(TypeCastTree node, Void unused) {
  sync(node);
  builder.open(plusFour);
  token("(");
  scan(node.getType(), null);
  token(")");
  builder.breakOp(" ");
  scan(node.getExpression(), null);
  builder.close();
  return null;
}
 
Example #8
Source File: CastScanner.java    From annotation-tools with MIT License 5 votes vote down vote up
@Override
public Void visitTypeCast(TypeCastTree node, Void p) {
  if (!done) {
    index++;
  }
  if (tree == node) {
    done = true;
    return p;
  }
  return super.visitTypeCast(node, p);
}
 
Example #9
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Void visitTypeCast(TypeCastTree node, Void unused) {
    sync(node);
    builder.open(plusFour);
    token("(");
    scan(node.getType(), null);
    token(")");
    builder.breakOp(" ");
    scan(node.getExpression(), null);
    builder.close();
    return null;
}
 
Example #10
Source File: JDIWrappersTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Element getElement(Tree tree) {
    TreePath expPath = TreePath.getPath(cut, tree);
    Element e = trees.getElement(expPath);
    if (e == null) {
        if (tree instanceof ParenthesizedTree) {
            e = getElement(((ParenthesizedTree) tree).getExpression());
            //if (e == null) {
            //    System.err.println("Have null element for "+tree);
            //}
            //System.err.println("\nHAVE "+e.asType().toString()+" for ParenthesizedTree "+tree);
        }
        else if (tree instanceof TypeCastTree) {
            e = getElement(((TypeCastTree) tree).getType());
            //if (e == null) {
            //    System.err.println("Have null element for "+tree);
            //}
            //System.err.println("\nHAVE "+e.asType().toString()+" for TypeCastTree "+tree);
        }
        else if (tree instanceof AssignmentTree) {
            e = getElement(((AssignmentTree) tree).getVariable());
        }
        else if (tree instanceof ArrayAccessTree) {
            e = getElement(((ArrayAccessTree) tree).getExpression());
            if (e != null) {
                TypeMirror tm = e.asType();
                if (tm.getKind() == TypeKind.ARRAY) {
                    tm = ((ArrayType) tm).getComponentType();
                    e = types.asElement(tm);
                }
            }
            //System.err.println("ArrayAccessTree = "+((ArrayAccessTree) tree).getExpression()+", element = "+getElement(((ArrayAccessTree) tree).getExpression())+", type = "+getElement(((ArrayAccessTree) tree).getExpression()).asType());
        }
    }
    return e;
}
 
Example #11
Source File: TooStrongCast.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    TreePath castPath = ctx.getPath();
    if (castPath.getLeaf().getKind() != Tree.Kind.TYPE_CAST) {
        return;
    }
    TypeCastTree tct = (TypeCastTree)castPath.getLeaf();
    
    TypeMirror targetType = handle.resolve(ctx.getWorkingCopy());
    Tree tt = ctx.getWorkingCopy().getTreeMaker().Type(targetType);
    ctx.getWorkingCopy().rewrite(tct.getType(), tt);
}
 
Example #12
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitTypeCast(TypeCastTree node, Void unused) {
    sync(node);
    builder.open(plusFour);
    token("(");
    scan(node.getType(), null);
    token(")");
    builder.breakOp(" ");
    scan(node.getExpression(), null);
    builder.close();
    return null;
}
 
Example #13
Source File: TreeNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitTypeCast(TypeCastTree tree, List<Node> d) {
    List<Node> below = new ArrayList<Node>();
    
    addCorrespondingType(below);
    addCorrespondingComments(below);
    super.visitTypeCast(tree, below);
    
    d.add(new TreeNode(info, getCurrentPath(), below));
    return null;
}
 
Example #14
Source File: CopyFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Boolean visitTypeCast(TypeCastTree node, TreePath p) {
    if (p == null)
        return super.visitTypeCast(node, p);

    TypeCastTree t = (TypeCastTree) p.getLeaf();

    if (!scan(node.getType(), t.getType(), p))
        return false;

    return scan(node.getExpression(), t.getExpression(), p);
}
 
Example #15
Source File: TreeDuplicator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Tree visitTypeCast(TypeCastTree tree, Void p) {
    TypeCastTree n = make.TypeCast(tree.getType(), tree.getExpression());
    model.setType(n, model.getType(tree));
    comments.copyComments(tree, n);
    model.setPos(n, model.getPos(tree));
    return n;
}
 
Example #16
Source File: Utilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private String simpleName(Tree t) {
    if (t == null) {
        return Bundle.DisplayName_Unknown();
    }
    if (t.getKind() == Kind.IDENTIFIER) {
        return ((IdentifierTree) t).getName().toString();
    }

    if (t.getKind() == Kind.MEMBER_SELECT) {
        return ((MemberSelectTree) t).getIdentifier().toString();
    }

    if (t.getKind() == Kind.METHOD_INVOCATION) {
        return scan(t, null);
    }

    if (t.getKind() == Kind.PARAMETERIZED_TYPE) {
        return simpleName(((ParameterizedTypeTree) t).getType()) + "<...>"; // NOI18N
    }

    if (t.getKind() == Kind.ARRAY_ACCESS) {
        return simpleName(((ArrayAccessTree) t).getExpression()) + "[]"; //NOI18N
    }

    if (t.getKind() == Kind.PARENTHESIZED) {
        return "(" + simpleName(((ParenthesizedTree)t).getExpression()) + ")"; //NOI18N
    }

    if (t.getKind() == Kind.TYPE_CAST) {
        return simpleName(((TypeCastTree)t).getType());
    }

    if (t.getKind() == Kind.ARRAY_TYPE) {
        return simpleName(((ArrayTypeTree)t).getType());
    }

    if (t.getKind() == Kind.PRIMITIVE_TYPE) {
        return ((PrimitiveTypeTree) t).getPrimitiveTypeKind().name().toLowerCase();
    }
    
    throw new IllegalStateException("Currently unsupported kind of tree: " + t.getKind()); // NOI18N
}
 
Example #17
Source File: Flow.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public Boolean visitTypeCast(TypeCastTree node, ConstructorData p) {
    super.visitTypeCast(node, p);
    return null;
}
 
Example #18
Source File: ArithmeticUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Object visitTypeCast(TypeCastTree node, Void p) {
    Object op = scan(node.getExpression(), p);
    if (op == null) {
        return null;
    }
    Object result = null;
    TypeMirror tm = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), node.getType()));
    if (!Utilities.isValidType(tm)) {
        return null;
    }
    // casting to some non-char primitive type, perform unary numeric promotion JLS 5.6.1
    if (tm.getKind() != TypeKind.CHAR && op instanceof Character) {
        op = Integer.valueOf(((Character)op).charValue());
    }
    // accept unboxing conversion, primitive conversion
    switch (tm.getKind()) {
        case BOOLEAN:
            if (op instanceof Boolean) result = op;
            break;
        case BYTE:
            if (op instanceof Number)  result = ((Number)op).byteValue();
            break;
        case CHAR:
            if (op instanceof Character) result = op;
            if (op instanceof Number)  result = Character.valueOf((char)((Number)op).intValue());
            break;
        case DOUBLE:
            if (op instanceof Number)  result = ((Number)op).doubleValue();
            break;
        case FLOAT:
            if (op instanceof Number)  result = ((Number)op).floatValue();
            break;
        case INT:
            if (op instanceof Number)  result = ((Number)op).intValue();
            break;
        case LONG:
            if (op instanceof Number)  result = ((Number)op).longValue();
            break;
        case SHORT:
            if (op instanceof Number)  result = ((Number)op).shortValue();
            break;
        default:
            return resolveTypeCast(node, tm, op, p);
            
    }
    return result;
}
 
Example #19
Source File: ArithmeticUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Object resolveTypeCast(TypeCastTree node, TypeMirror target, Object result, Void p) {
    if (target.getKind() != TypeKind.DECLARED) {
        return null;
    }
    DeclaredType dt = (DeclaredType)target;
    TypeElement e = (TypeElement)dt.asElement();
    if (enhanceProcessing) {
        // accept null constant typecasted to anything as null
        if (result == NULL) {
            return NULL;
        } else if (result == NOT_NULL) {
            // some unspecified reference type...
            return result;
        }
    }
    String qn = e.getQualifiedName().toString();
    // type casts to String are permitted by JLS 15.28
    if ("java.lang.String".equals(qn)) { // NOI18N
        return result instanceof String ? result : null;
    } else if (!enhanceProcessing) {
        // other typecasts are not lised in JLS 15.28
        return null;
    }
    TypeMirror castee = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
    if (!Utilities.isValidType(castee)) {
        return null;
    }
    if (info.getTypes().isAssignable(castee, target)) {
        return result;
    }
    // a constant of primitive type may be casted / wrapped to the wrapper type
    switch (qn) {
        case "java.lang.Boolean": // NOI18N
            if (result instanceof Boolean) return result;
            break;
        case "java.lang.Byte": // NOI18N
            // the casted expression may be typed as Byte or byte; 
            if (result instanceof Number && castee != null && castee.getKind() == TypeKind.BYTE) 
                return ((Number)result).byteValue();
            break;
        case "java.lang.Character": // NOI18N
            if (result instanceof Number && castee != null && castee.getKind() == TypeKind.CHAR) 
                return Character.valueOf((char)((Number)result).intValue());
            break;
        case "java.lang.Double": // NOI18N
            if (result instanceof Number && castee != null && castee.getKind() == TypeKind.DOUBLE) 
                return ((Number)result).doubleValue();
            break;
        case "java.lang.Float": // NOI18N
            if (result instanceof Number && castee != null && castee.getKind() == TypeKind.FLOAT) 
                return ((Number)result).floatValue();
            break;
        case "java.lang.Integer": // NOI18N
            if (result instanceof Number && castee != null && castee.getKind() == TypeKind.INT) 
                return ((Number)result).intValue();
            break;
        case "java.lang.Long": // NOI18N
            if (result instanceof Number && castee != null && castee.getKind() == TypeKind.LONG) 
                return ((Number)result).longValue();
            break;
        case "java.lang.Short": // NOI18N
            if (result instanceof Number && castee != null && castee.getKind() == TypeKind.SHORT) 
                return ((Number)result).shortValue();
            break;
    }
    return null;
}
 
Example #20
Source File: ExpressionScanner.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public List<Tree> visitTypeCast(TypeCastTree node, ExpressionScanner.ExpressionsInfo p) {
    return scan(node.getExpression(), p);
}
 
Example #21
Source File: RemoveUnnecessary.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Object visitTypeCast(TypeCastTree node, Object p) {
    return scan(node.getExpression(), p);
}
 
Example #22
Source File: DependencyCollector.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * type cast adds dependency on the casted-to type
 */
@Override
public Object visitTypeCast(TypeCastTree node, Object p) {
    addDependency(node.getType());
    return super.visitTypeCast(node, p);
}
 
Example #23
Source File: GeneratorUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override public Object visitTypeCast(TypeCastTree node, Object p) {
    return scan(node.getExpression(), p);
}
 
Example #24
Source File: TreeConverter.java    From j2objc with Apache License 2.0 4 votes vote down vote up
private TreeNode convertTypeCast(TypeCastTree node, TreePath parent) {
  TreePath path = getTreePath(parent, node);
  return new CastExpression(
      getTypeMirror(path), (Expression) convert(node.getExpression(), path));
}
 
Example #25
Source File: UTemplater.java    From Refaster with Apache License 2.0 4 votes vote down vote up
@Override
public UTypeCast visitTypeCast(TypeCastTree tree, Void v) {
  return UTypeCast.create(template(tree.getType()), template(tree.getExpression()));
}
 
Example #26
Source File: UTypeCast.java    From Refaster with Apache License 2.0 4 votes vote down vote up
@Override
@Nullable
public Unifier visitTypeCast(TypeCastTree cast, @Nullable Unifier unifier) {
  unifier = getType().unify(cast.getType(), unifier);
  return getExpression().unify(cast.getExpression(), unifier);
}
 
Example #27
Source File: TreePruner.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public Boolean visitTypeCast(TypeCastTree node, Void p) {
  return reduce(
      constantType((JCTree) node.getType()), node.getExpression().accept(this, null));
}