Search in sources :

Example 16 with CastExpression

use of org.eclipse.jdt.core.dom.CastExpression in project che by eclipse.

the class StubUtility method getBaseNameFromExpression.

private static String getBaseNameFromExpression(IJavaProject project, Expression assignedExpression, int variableKind) {
    String name = null;
    if (assignedExpression instanceof CastExpression) {
        assignedExpression = ((CastExpression) assignedExpression).getExpression();
    }
    if (assignedExpression instanceof Name) {
        Name simpleNode = (Name) assignedExpression;
        IBinding binding = simpleNode.resolveBinding();
        if (binding instanceof IVariableBinding)
            return getBaseName((IVariableBinding) binding, project);
        return ASTNodes.getSimpleNameIdentifier(simpleNode);
    } else if (assignedExpression instanceof MethodInvocation) {
        name = ((MethodInvocation) assignedExpression).getName().getIdentifier();
    } else if (assignedExpression instanceof SuperMethodInvocation) {
        name = ((SuperMethodInvocation) assignedExpression).getName().getIdentifier();
    } else if (assignedExpression instanceof FieldAccess) {
        return ((FieldAccess) assignedExpression).getName().getIdentifier();
    } else if (variableKind == NamingConventions.VK_STATIC_FINAL_FIELD && (assignedExpression instanceof StringLiteral || assignedExpression instanceof NumberLiteral)) {
        String string = assignedExpression instanceof StringLiteral ? ((StringLiteral) assignedExpression).getLiteralValue() : ((NumberLiteral) assignedExpression).getToken();
        StringBuffer res = new StringBuffer();
        boolean needsUnderscore = false;
        for (int i = 0; i < string.length(); i++) {
            char ch = string.charAt(i);
            if (Character.isJavaIdentifierPart(ch)) {
                if (res.length() == 0 && !Character.isJavaIdentifierStart(ch) || needsUnderscore) {
                    res.append('_');
                }
                res.append(ch);
                needsUnderscore = false;
            } else {
                needsUnderscore = res.length() > 0;
            }
        }
        if (res.length() > 0) {
            return res.toString();
        }
    }
    if (name != null) {
        for (int i = 0; i < KNOWN_METHOD_NAME_PREFIXES.length; i++) {
            String curr = KNOWN_METHOD_NAME_PREFIXES[i];
            if (name.startsWith(curr)) {
                if (name.equals(curr)) {
                    // don't suggest 'get' as variable name
                    return null;
                } else if (Character.isUpperCase(name.charAt(curr.length()))) {
                    return name.substring(curr.length());
                }
            }
        }
    }
    return name;
}
Also used : IBinding(org.eclipse.jdt.core.dom.IBinding) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) Name(org.eclipse.jdt.core.dom.Name) StringLiteral(org.eclipse.jdt.core.dom.StringLiteral) CastExpression(org.eclipse.jdt.core.dom.CastExpression) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) NumberLiteral(org.eclipse.jdt.core.dom.NumberLiteral)

Example 17 with CastExpression

use of org.eclipse.jdt.core.dom.CastExpression in project che by eclipse.

the class TypeMismatchSubProcessor method addTypeMismatchProposals.

public static void addTypeMismatchProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException {
    String[] args = problem.getProblemArguments();
    if (args.length != 2) {
        return;
    }
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    AST ast = astRoot.getAST();
    ASTNode selectedNode = problem.getCoveredNode(astRoot);
    if (!(selectedNode instanceof Expression)) {
        return;
    }
    Expression nodeToCast = (Expression) selectedNode;
    Name receiverNode = null;
    ITypeBinding castTypeBinding = null;
    int parentNodeType = selectedNode.getParent().getNodeType();
    if (parentNodeType == ASTNode.ASSIGNMENT) {
        Assignment assign = (Assignment) selectedNode.getParent();
        Expression leftHandSide = assign.getLeftHandSide();
        if (selectedNode.equals(leftHandSide)) {
            nodeToCast = assign.getRightHandSide();
        }
        castTypeBinding = assign.getLeftHandSide().resolveTypeBinding();
        if (leftHandSide instanceof Name) {
            receiverNode = (Name) leftHandSide;
        } else if (leftHandSide instanceof FieldAccess) {
            receiverNode = ((FieldAccess) leftHandSide).getName();
        }
    } else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
        VariableDeclarationFragment frag = (VariableDeclarationFragment) selectedNode.getParent();
        if (selectedNode.equals(frag.getName()) || selectedNode.equals(frag.getInitializer())) {
            nodeToCast = frag.getInitializer();
            castTypeBinding = ASTNodes.getType(frag).resolveBinding();
            receiverNode = frag.getName();
        }
    } else if (parentNodeType == ASTNode.MEMBER_VALUE_PAIR) {
        receiverNode = ((MemberValuePair) selectedNode.getParent()).getName();
        castTypeBinding = ASTResolving.guessBindingForReference(nodeToCast);
    } else if (parentNodeType == ASTNode.SINGLE_MEMBER_ANNOTATION) {
        // use the type name
        receiverNode = ((SingleMemberAnnotation) selectedNode.getParent()).getTypeName();
        castTypeBinding = ASTResolving.guessBindingForReference(nodeToCast);
    } else {
        // try to find the binding corresponding to 'castTypeName'
        castTypeBinding = ASTResolving.guessBindingForReference(nodeToCast);
    }
    if (castTypeBinding == null) {
        return;
    }
    ITypeBinding currBinding = nodeToCast.resolveTypeBinding();
    if (!(nodeToCast instanceof ArrayInitializer)) {
        ITypeBinding castFixType = null;
        if (currBinding == null || castTypeBinding.isCastCompatible(currBinding) || nodeToCast instanceof CastExpression) {
            castFixType = castTypeBinding;
        } else if (JavaModelUtil.is50OrHigher(cu.getJavaProject())) {
            ITypeBinding boxUnboxedTypeBinding = boxUnboxPrimitives(castTypeBinding, currBinding, ast);
            if (boxUnboxedTypeBinding != castTypeBinding && boxUnboxedTypeBinding.isCastCompatible(currBinding)) {
                castFixType = boxUnboxedTypeBinding;
            }
        }
        if (castFixType != null) {
            proposals.add(createCastProposal(context, castFixType, nodeToCast, IProposalRelevance.CREATE_CAST));
        }
    }
    //$NON-NLS-1$
    boolean nullOrVoid = currBinding == null || "void".equals(currBinding.getName());
    // change method return statement to actual type
    if (!nullOrVoid && parentNodeType == ASTNode.RETURN_STATEMENT) {
        BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
        if (decl instanceof MethodDeclaration) {
            MethodDeclaration methodDeclaration = (MethodDeclaration) decl;
            currBinding = Bindings.normalizeTypeBinding(currBinding);
            if (currBinding == null) {
                //$NON-NLS-1$
                currBinding = ast.resolveWellKnownType("java.lang.Object");
            }
            if (currBinding.isWildcardType()) {
                currBinding = ASTResolving.normalizeWildcardType(currBinding, true, ast);
            }
            ASTRewrite rewrite = ASTRewrite.create(ast);
            String label = Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturntype_description, BasicElementLabels.getJavaElementName(currBinding.getName()));
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
            LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_METHOD_RETURN_TYPE, image);
            ImportRewrite imports = proposal.createImportRewrite(astRoot);
            ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
            Type newReturnType = imports.addImport(currBinding, ast, importRewriteContext);
            rewrite.replace(methodDeclaration.getReturnType2(), newReturnType, null);
            //$NON-NLS-1$
            String returnKey = "return";
            proposal.addLinkedPosition(rewrite.track(newReturnType), true, returnKey);
            ITypeBinding[] typeSuggestions = ASTResolving.getRelaxingTypes(ast, currBinding);
            for (int i = 0; i < typeSuggestions.length; i++) {
                proposal.addLinkedPositionProposal(returnKey, typeSuggestions[i]);
            }
            proposals.add(proposal);
        }
    }
    if (!nullOrVoid && receiverNode != null) {
        currBinding = Bindings.normalizeTypeBinding(currBinding);
        if (currBinding == null) {
            //$NON-NLS-1$
            currBinding = ast.resolveWellKnownType("java.lang.Object");
        }
        if (currBinding.isWildcardType()) {
            currBinding = ASTResolving.normalizeWildcardType(currBinding, true, ast);
        }
        addChangeSenderTypeProposals(context, receiverNode, currBinding, true, IProposalRelevance.CHANGE_TYPE_OF_RECEIVER_NODE, proposals);
    }
    addChangeSenderTypeProposals(context, nodeToCast, castTypeBinding, false, IProposalRelevance.CHANGE_TYPE_OF_NODE_TO_CAST, proposals);
    if (castTypeBinding == ast.resolveWellKnownType("boolean") && currBinding != null && !currBinding.isPrimitive() && !Bindings.isVoidType(currBinding)) {
        //$NON-NLS-1$
        String label = CorrectionMessages.TypeMismatchSubProcessor_insertnullcheck_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
        InfixExpression expression = ast.newInfixExpression();
        expression.setLeftOperand((Expression) rewrite.createMoveTarget(nodeToCast));
        expression.setRightOperand(ast.newNullLiteral());
        expression.setOperator(InfixExpression.Operator.NOT_EQUALS);
        rewrite.replace(nodeToCast, expression, null);
        proposals.add(new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_NULL_CHECK, image));
    }
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) Image(org.eclipse.swt.graphics.Image) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) Assignment(org.eclipse.jdt.core.dom.Assignment) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) SingleMemberAnnotation(org.eclipse.jdt.core.dom.SingleMemberAnnotation) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) CastExpression(org.eclipse.jdt.core.dom.CastExpression) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) ArrayInitializer(org.eclipse.jdt.core.dom.ArrayInitializer)

Example 18 with CastExpression

use of org.eclipse.jdt.core.dom.CastExpression in project che by eclipse.

the class UnresolvedElementsSubProcessor method useExistingParentCastProposal.

private static boolean useExistingParentCastProposal(ICompilationUnit cu, CastExpression expression, Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes, Collection<ICommandAccess> proposals) {
    ITypeBinding castType = expression.getType().resolveBinding();
    if (castType == null) {
        return false;
    }
    if (paramTypes != null) {
        if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) {
            return false;
        }
    } else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) {
        return false;
    }
    ITypeBinding bindingToCast = accessExpression.resolveTypeBinding();
    if (bindingToCast != null && !bindingToCast.isCastCompatible(castType)) {
        return false;
    }
    IMethodBinding res = Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes);
    if (res != null) {
        AST ast = expression.getAST();
        ASTRewrite rewrite = ASTRewrite.create(ast);
        CastExpression newCast = ast.newCastExpression();
        newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType()));
        newCast.setExpression((Expression) rewrite.createCopyTarget(accessExpression));
        ParenthesizedExpression parents = ast.newParenthesizedExpression();
        parents.setExpression(newCast);
        ASTNode node = rewrite.createCopyTarget(expression.getExpression());
        rewrite.replace(expression, node, null);
        rewrite.replace(accessExpression, parents, null);
        String label = CorrectionMessages.UnresolvedElementsSubProcessor_missingcastbrackets_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
        ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_PARENTHESES_AROUND_CAST, image);
        proposals.add(proposal);
        return true;
    }
    return false;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) AST(org.eclipse.jdt.core.dom.AST) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) CastExpression(org.eclipse.jdt.core.dom.CastExpression) Image(org.eclipse.swt.graphics.Image)

Example 19 with CastExpression

use of org.eclipse.jdt.core.dom.CastExpression in project che by eclipse.

the class CastCorrectionProposal method getRewrite.

@Override
protected ASTRewrite getRewrite() throws CoreException {
    AST ast = fNodeToCast.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    ImportRewrite importRewrite = createImportRewrite((CompilationUnit) fNodeToCast.getRoot());
    Type newTypeNode = getNewCastTypeNode(rewrite, importRewrite);
    if (fNodeToCast.getNodeType() == ASTNode.CAST_EXPRESSION) {
        CastExpression expression = (CastExpression) fNodeToCast;
        rewrite.replace(expression.getType(), newTypeNode, null);
    } else {
        Expression expressionCopy = (Expression) rewrite.createCopyTarget(fNodeToCast);
        if (needsInnerParantheses(fNodeToCast)) {
            ParenthesizedExpression parenthesizedExpression = ast.newParenthesizedExpression();
            parenthesizedExpression.setExpression(expressionCopy);
            expressionCopy = parenthesizedExpression;
        }
        CastExpression castExpression = ast.newCastExpression();
        castExpression.setExpression(expressionCopy);
        castExpression.setType(newTypeNode);
        ASTNode replacingNode = castExpression;
        if (needsOuterParantheses(fNodeToCast)) {
            ParenthesizedExpression parenthesizedExpression = ast.newParenthesizedExpression();
            parenthesizedExpression.setExpression(castExpression);
            replacingNode = parenthesizedExpression;
        }
        rewrite.replace(fNodeToCast, replacingNode, null);
    }
    return rewrite;
}
Also used : ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) AST(org.eclipse.jdt.core.dom.AST) Type(org.eclipse.jdt.core.dom.Type) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) CastExpression(org.eclipse.jdt.core.dom.CastExpression) Expression(org.eclipse.jdt.core.dom.Expression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) CastExpression(org.eclipse.jdt.core.dom.CastExpression)

Example 20 with CastExpression

use of org.eclipse.jdt.core.dom.CastExpression in project che by eclipse.

the class CastCorrectionProposal method getNewCastTypeNode.

private Type getNewCastTypeNode(ASTRewrite rewrite, ImportRewrite importRewrite) {
    AST ast = rewrite.getAST();
    ImportRewriteContext context = new ContextSensitiveImportRewriteContext((CompilationUnit) fNodeToCast.getRoot(), fNodeToCast.getStartPosition(), importRewrite);
    if (fCastType != null) {
        return importRewrite.addImport(fCastType, ast, context);
    }
    ASTNode node = fNodeToCast;
    ASTNode parent = node.getParent();
    if (parent instanceof CastExpression) {
        node = parent;
        parent = parent.getParent();
    }
    while (parent instanceof ParenthesizedExpression) {
        node = parent;
        parent = parent.getParent();
    }
    if (parent instanceof MethodInvocation) {
        MethodInvocation invocation = (MethodInvocation) node.getParent();
        if (invocation.getExpression() == node) {
            IBinding targetContext = ASTResolving.getParentMethodOrTypeBinding(node);
            ITypeBinding[] bindings = ASTResolving.getQualifierGuess(node.getRoot(), invocation.getName().getIdentifier(), invocation.arguments(), targetContext);
            if (bindings.length > 0) {
                ITypeBinding first = getCastFavorite(bindings, fNodeToCast.resolveTypeBinding());
                Type newTypeNode = importRewrite.addImport(first, ast, context);
                //$NON-NLS-1$
                addLinkedPosition(rewrite.track(newTypeNode), true, "casttype");
                for (int i = 0; i < bindings.length; i++) {
                    //$NON-NLS-1$
                    addLinkedPositionProposal("casttype", bindings[i]);
                }
                return newTypeNode;
            }
        }
    }
    //$NON-NLS-1$
    Type newCastType = ast.newSimpleType(ast.newSimpleName("Object"));
    //$NON-NLS-1$
    addLinkedPosition(rewrite.track(newCastType), true, "casttype");
    return newCastType;
}
Also used : ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) AST(org.eclipse.jdt.core.dom.AST) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) IBinding(org.eclipse.jdt.core.dom.IBinding) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) CastExpression(org.eclipse.jdt.core.dom.CastExpression)

Aggregations

CastExpression (org.eclipse.jdt.core.dom.CastExpression)24 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)18 ASTNode (org.eclipse.jdt.core.dom.ASTNode)16 Expression (org.eclipse.jdt.core.dom.Expression)16 AST (org.eclipse.jdt.core.dom.AST)11 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)11 Type (org.eclipse.jdt.core.dom.Type)10 ConditionalExpression (org.eclipse.jdt.core.dom.ConditionalExpression)7 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)7 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)7 Assignment (org.eclipse.jdt.core.dom.Assignment)6 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)6 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)6 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)6 SimpleName (org.eclipse.jdt.core.dom.SimpleName)6 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)6 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)6 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)6 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)6 IBinding (org.eclipse.jdt.core.dom.IBinding)4