Search in sources :

Example 21 with CastExpression

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

the class UnusedCodeFix method replaceCast.

private static void replaceCast(CastExpression castExpression, Expression replacement, ASTRewrite rewrite, TextEditGroup group) {
    boolean castEnclosedInNecessaryParentheses = castExpression.getParent() instanceof ParenthesizedExpression && NecessaryParenthesesChecker.needsParentheses(castExpression, castExpression.getParent().getParent(), castExpression.getParent().getLocationInParent());
    ASTNode toReplace = castEnclosedInNecessaryParentheses ? castExpression.getParent() : castExpression;
    ASTNode move;
    if (NecessaryParenthesesChecker.needsParentheses(replacement, toReplace.getParent(), toReplace.getLocationInParent())) {
        if (replacement.getParent() instanceof ParenthesizedExpression) {
            move = rewrite.createMoveTarget(replacement.getParent());
        } else if (castEnclosedInNecessaryParentheses) {
            toReplace = castExpression;
            move = rewrite.createMoveTarget(replacement);
        } else {
            ParenthesizedExpression parentheses = replacement.getAST().newParenthesizedExpression();
            parentheses.setExpression((Expression) rewrite.createMoveTarget(replacement));
            move = parentheses;
        }
    } else {
        move = rewrite.createMoveTarget(replacement);
    }
    rewrite.replace(toReplace, move, group);
}
Also used : ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) Expression(org.eclipse.jdt.core.dom.Expression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) PostfixExpression(org.eclipse.jdt.core.dom.PostfixExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) ASTNode(org.eclipse.jdt.core.dom.ASTNode)

Example 22 with CastExpression

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

the class ASTResolving method getPossibleReferenceBinding.

private static ITypeBinding getPossibleReferenceBinding(ASTNode node) {
    ASTNode parent = node.getParent();
    switch(parent.getNodeType()) {
        case ASTNode.ASSIGNMENT:
            Assignment assignment = (Assignment) parent;
            if (node.equals(assignment.getLeftHandSide())) {
                // field write access: xx= expression
                return assignment.getRightHandSide().resolveTypeBinding();
            }
            // read access
            return assignment.getLeftHandSide().resolveTypeBinding();
        case ASTNode.INFIX_EXPRESSION:
            InfixExpression infix = (InfixExpression) parent;
            InfixExpression.Operator op = infix.getOperator();
            if (op == InfixExpression.Operator.CONDITIONAL_AND || op == InfixExpression.Operator.CONDITIONAL_OR) {
                //$NON-NLS-1$
                return infix.getAST().resolveWellKnownType("boolean");
            } else if (op == InfixExpression.Operator.LEFT_SHIFT || op == InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED || op == InfixExpression.Operator.RIGHT_SHIFT_SIGNED) {
                //$NON-NLS-1$
                return infix.getAST().resolveWellKnownType("int");
            }
            if (node.equals(infix.getLeftOperand())) {
                //	xx operation expression
                ITypeBinding rigthHandBinding = infix.getRightOperand().resolveTypeBinding();
                if (rigthHandBinding != null) {
                    return rigthHandBinding;
                }
            } else {
                // expression operation xx
                ITypeBinding leftHandBinding = infix.getLeftOperand().resolveTypeBinding();
                if (leftHandBinding != null) {
                    return leftHandBinding;
                }
            }
            if (op != InfixExpression.Operator.EQUALS && op != InfixExpression.Operator.NOT_EQUALS) {
                //$NON-NLS-1$
                return infix.getAST().resolveWellKnownType("int");
            }
            break;
        case ASTNode.INSTANCEOF_EXPRESSION:
            InstanceofExpression instanceofExpression = (InstanceofExpression) parent;
            return instanceofExpression.getRightOperand().resolveBinding();
        case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
            VariableDeclarationFragment frag = (VariableDeclarationFragment) parent;
            if (frag.getInitializer().equals(node)) {
                return frag.getName().resolveTypeBinding();
            }
            break;
        case ASTNode.SUPER_METHOD_INVOCATION:
            SuperMethodInvocation superMethodInvocation = (SuperMethodInvocation) parent;
            IMethodBinding superMethodBinding = ASTNodes.getMethodBinding(superMethodInvocation.getName());
            if (superMethodBinding != null) {
                return getParameterTypeBinding(node, superMethodInvocation.arguments(), superMethodBinding);
            }
            break;
        case ASTNode.METHOD_INVOCATION:
            MethodInvocation methodInvocation = (MethodInvocation) parent;
            IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
            if (methodBinding != null) {
                return getParameterTypeBinding(node, methodInvocation.arguments(), methodBinding);
            }
            break;
        case ASTNode.SUPER_CONSTRUCTOR_INVOCATION:
            {
                SuperConstructorInvocation superInvocation = (SuperConstructorInvocation) parent;
                IMethodBinding superBinding = superInvocation.resolveConstructorBinding();
                if (superBinding != null) {
                    return getParameterTypeBinding(node, superInvocation.arguments(), superBinding);
                }
                break;
            }
        case ASTNode.CONSTRUCTOR_INVOCATION:
            {
                ConstructorInvocation constrInvocation = (ConstructorInvocation) parent;
                IMethodBinding constrBinding = constrInvocation.resolveConstructorBinding();
                if (constrBinding != null) {
                    return getParameterTypeBinding(node, constrInvocation.arguments(), constrBinding);
                }
                break;
            }
        case ASTNode.CLASS_INSTANCE_CREATION:
            {
                ClassInstanceCreation creation = (ClassInstanceCreation) parent;
                IMethodBinding creationBinding = creation.resolveConstructorBinding();
                if (creationBinding != null) {
                    return getParameterTypeBinding(node, creation.arguments(), creationBinding);
                }
                break;
            }
        case ASTNode.PARENTHESIZED_EXPRESSION:
            return guessBindingForReference(parent);
        case ASTNode.ARRAY_ACCESS:
            if (((ArrayAccess) parent).getIndex().equals(node)) {
                //$NON-NLS-1$
                return parent.getAST().resolveWellKnownType("int");
            } else {
                ITypeBinding parentBinding = getPossibleReferenceBinding(parent);
                if (parentBinding == null) {
                    //$NON-NLS-1$
                    parentBinding = parent.getAST().resolveWellKnownType("java.lang.Object");
                }
                return parentBinding.createArrayType(1);
            }
        case ASTNode.ARRAY_CREATION:
            if (((ArrayCreation) parent).dimensions().contains(node)) {
                //$NON-NLS-1$
                return parent.getAST().resolveWellKnownType("int");
            }
            break;
        case ASTNode.ARRAY_INITIALIZER:
            ASTNode initializerParent = parent.getParent();
            int dim = 1;
            while (initializerParent instanceof ArrayInitializer) {
                initializerParent = initializerParent.getParent();
                dim++;
            }
            Type creationType = null;
            if (initializerParent instanceof ArrayCreation) {
                creationType = ((ArrayCreation) initializerParent).getType();
            } else if (initializerParent instanceof VariableDeclaration) {
                VariableDeclaration varDecl = (VariableDeclaration) initializerParent;
                creationType = ASTNodes.getType(varDecl);
                dim -= varDecl.getExtraDimensions();
            } else if (initializerParent instanceof MemberValuePair) {
                String name = ((MemberValuePair) initializerParent).getName().getIdentifier();
                IMethodBinding annotMember = findAnnotationMember((Annotation) initializerParent.getParent(), name);
                if (annotMember != null) {
                    return getReducedDimensionBinding(annotMember.getReturnType(), dim);
                }
            }
            if (creationType instanceof ArrayType) {
                ITypeBinding creationTypeBinding = ((ArrayType) creationType).resolveBinding();
                if (creationTypeBinding != null) {
                    return Bindings.getComponentType(creationTypeBinding, dim);
                }
            }
            break;
        case ASTNode.CONDITIONAL_EXPRESSION:
            ConditionalExpression expression = (ConditionalExpression) parent;
            if (node.equals(expression.getExpression())) {
                //$NON-NLS-1$
                return parent.getAST().resolveWellKnownType("boolean");
            }
            if (node.equals(expression.getElseExpression())) {
                return expression.getThenExpression().resolveTypeBinding();
            }
            return expression.getElseExpression().resolveTypeBinding();
        case ASTNode.POSTFIX_EXPRESSION:
            //$NON-NLS-1$
            return parent.getAST().resolveWellKnownType("int");
        case ASTNode.PREFIX_EXPRESSION:
            if (((PrefixExpression) parent).getOperator() == PrefixExpression.Operator.NOT) {
                //$NON-NLS-1$
                return parent.getAST().resolveWellKnownType("boolean");
            }
            //$NON-NLS-1$
            return parent.getAST().resolveWellKnownType("int");
        case ASTNode.IF_STATEMENT:
        case ASTNode.WHILE_STATEMENT:
        case ASTNode.DO_STATEMENT:
            if (node instanceof Expression) {
                //$NON-NLS-1$
                return parent.getAST().resolveWellKnownType("boolean");
            }
            break;
        case ASTNode.SWITCH_STATEMENT:
            if (((SwitchStatement) parent).getExpression().equals(node)) {
                //$NON-NLS-1$
                return parent.getAST().resolveWellKnownType("int");
            }
            break;
        case ASTNode.RETURN_STATEMENT:
            MethodDeclaration decl = ASTResolving.findParentMethodDeclaration(parent);
            if (decl != null && !decl.isConstructor()) {
                return decl.getReturnType2().resolveBinding();
            }
            LambdaExpression lambdaExpr = ASTResolving.findEnclosingLambdaExpression(parent);
            if (lambdaExpr != null) {
                IMethodBinding lambdaMethodBinding = lambdaExpr.resolveMethodBinding();
                if (lambdaMethodBinding != null && lambdaMethodBinding.getReturnType() != null) {
                    return lambdaMethodBinding.getReturnType();
                }
            }
            break;
        case ASTNode.CAST_EXPRESSION:
            return ((CastExpression) parent).getType().resolveBinding();
        case ASTNode.THROW_STATEMENT:
        case ASTNode.CATCH_CLAUSE:
            //$NON-NLS-1$
            return parent.getAST().resolveWellKnownType("java.lang.Exception");
        case ASTNode.FIELD_ACCESS:
            if (node.equals(((FieldAccess) parent).getName())) {
                return getPossibleReferenceBinding(parent);
            }
            break;
        case ASTNode.SUPER_FIELD_ACCESS:
            return getPossibleReferenceBinding(parent);
        case ASTNode.QUALIFIED_NAME:
            if (node.equals(((QualifiedName) parent).getName())) {
                return getPossibleReferenceBinding(parent);
            }
            break;
        case ASTNode.SWITCH_CASE:
            if (node.equals(((SwitchCase) parent).getExpression()) && parent.getParent() instanceof SwitchStatement) {
                return ((SwitchStatement) parent.getParent()).getExpression().resolveTypeBinding();
            }
            break;
        case ASTNode.ASSERT_STATEMENT:
            if (node.getLocationInParent() == AssertStatement.EXPRESSION_PROPERTY) {
                //$NON-NLS-1$
                return parent.getAST().resolveWellKnownType("boolean");
            }
            //$NON-NLS-1$
            return parent.getAST().resolveWellKnownType("java.lang.String");
        case ASTNode.SINGLE_MEMBER_ANNOTATION:
            {
                //$NON-NLS-1$
                IMethodBinding annotMember = findAnnotationMember((Annotation) parent, "value");
                if (annotMember != null) {
                    return annotMember.getReturnType();
                }
                break;
            }
        case ASTNode.MEMBER_VALUE_PAIR:
            {
                String name = ((MemberValuePair) parent).getName().getIdentifier();
                IMethodBinding annotMember = findAnnotationMember((Annotation) parent.getParent(), name);
                if (annotMember != null) {
                    return annotMember.getReturnType();
                }
                break;
            }
        default:
    }
    return null;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) Assignment(org.eclipse.jdt.core.dom.Assignment) ArrayType(org.eclipse.jdt.core.dom.ArrayType) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) ConstructorInvocation(org.eclipse.jdt.core.dom.ConstructorInvocation) SuperConstructorInvocation(org.eclipse.jdt.core.dom.SuperConstructorInvocation) MemberValuePair(org.eclipse.jdt.core.dom.MemberValuePair) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) InstanceofExpression(org.eclipse.jdt.core.dom.InstanceofExpression) ASTNode(org.eclipse.jdt.core.dom.ASTNode) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) VariableDeclaration(org.eclipse.jdt.core.dom.VariableDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) Annotation(org.eclipse.jdt.core.dom.Annotation) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) WildcardType(org.eclipse.jdt.core.dom.WildcardType) QualifiedType(org.eclipse.jdt.core.dom.QualifiedType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) SwitchCase(org.eclipse.jdt.core.dom.SwitchCase) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) InstanceofExpression(org.eclipse.jdt.core.dom.InstanceofExpression) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) ArrayCreation(org.eclipse.jdt.core.dom.ArrayCreation) SuperConstructorInvocation(org.eclipse.jdt.core.dom.SuperConstructorInvocation) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) ArrayInitializer(org.eclipse.jdt.core.dom.ArrayInitializer)

Example 23 with CastExpression

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

the class AdvancedQuickAssistProcessor method getReplaceIfElseWithConditionalProposals.

private static boolean getReplaceIfElseWithConditionalProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
    if (!(node instanceof IfStatement)) {
        return false;
    }
    IfStatement ifStatement = (IfStatement) node;
    Statement thenStatement = getSingleStatement(ifStatement.getThenStatement());
    Statement elseStatement = getSingleStatement(ifStatement.getElseStatement());
    if (thenStatement == null || elseStatement == null) {
        return false;
    }
    Expression assigned = null;
    Expression thenExpression = null;
    Expression elseExpression = null;
    ITypeBinding exprBinding = null;
    if (thenStatement instanceof ReturnStatement && elseStatement instanceof ReturnStatement) {
        thenExpression = ((ReturnStatement) thenStatement).getExpression();
        elseExpression = ((ReturnStatement) elseStatement).getExpression();
        MethodDeclaration declaration = ASTResolving.findParentMethodDeclaration(node);
        if (declaration == null || declaration.isConstructor()) {
            return false;
        }
        exprBinding = declaration.getReturnType2().resolveBinding();
    } else if (thenStatement instanceof ExpressionStatement && elseStatement instanceof ExpressionStatement) {
        Expression inner1 = ((ExpressionStatement) thenStatement).getExpression();
        Expression inner2 = ((ExpressionStatement) elseStatement).getExpression();
        if (inner1 instanceof Assignment && inner2 instanceof Assignment) {
            Assignment assign1 = (Assignment) inner1;
            Assignment assign2 = (Assignment) inner2;
            Expression left1 = assign1.getLeftHandSide();
            Expression left2 = assign2.getLeftHandSide();
            if (left1 instanceof Name && left2 instanceof Name && assign1.getOperator() == assign2.getOperator()) {
                IBinding bind1 = ((Name) left1).resolveBinding();
                IBinding bind2 = ((Name) left2).resolveBinding();
                if (bind1 == bind2 && bind1 instanceof IVariableBinding) {
                    assigned = left1;
                    exprBinding = ((IVariableBinding) bind1).getType();
                    thenExpression = assign1.getRightHandSide();
                    elseExpression = assign2.getRightHandSide();
                }
            }
        }
    }
    if (thenExpression == null || elseExpression == null) {
        return false;
    }
    //  we could produce quick assist
    if (resultingCollections == null) {
        return true;
    }
    //
    AST ast = node.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    //		TightSourceRangeComputer sourceRangeComputer= new TightSourceRangeComputer();
    //		sourceRangeComputer.addTightSourceNode(ifStatement);
    //		rewrite.setTargetSourceRangeComputer(sourceRangeComputer);
    String label = CorrectionMessages.AdvancedQuickAssistProcessor_replaceIfWithConditional;
    //		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_IF_ELSE_WITH_CONDITIONAL);
    // prepare conditional expression
    ConditionalExpression conditionalExpression = ast.newConditionalExpression();
    Expression conditionCopy = (Expression) rewrite.createCopyTarget(ifStatement.getExpression());
    conditionalExpression.setExpression(conditionCopy);
    Expression thenCopy = (Expression) rewrite.createCopyTarget(thenExpression);
    Expression elseCopy = (Expression) rewrite.createCopyTarget(elseExpression);
    IJavaProject project = context.getCompilationUnit().getJavaProject();
    if (!JavaModelUtil.is50OrHigher(project)) {
        ITypeBinding thenBinding = thenExpression.resolveTypeBinding();
        ITypeBinding elseBinding = elseExpression.resolveTypeBinding();
        if (thenBinding != null && elseBinding != null && exprBinding != null && !elseBinding.isAssignmentCompatible(thenBinding)) {
            CastExpression castException = ast.newCastExpression();
            ImportRewrite importRewrite = proposal.createImportRewrite(context.getASTRoot());
            ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, importRewrite);
            castException.setType(importRewrite.addImport(exprBinding, ast, importRewriteContext));
            castException.setExpression(elseCopy);
            elseCopy = castException;
        }
    } else if (JavaModelUtil.is17OrHigher(project)) {
        addExplicitTypeArgumentsIfNecessary(rewrite, proposal, thenExpression);
        addExplicitTypeArgumentsIfNecessary(rewrite, proposal, elseExpression);
    }
    conditionalExpression.setThenExpression(thenCopy);
    conditionalExpression.setElseExpression(elseCopy);
    // replace 'if' statement with conditional expression
    if (assigned == null) {
        ReturnStatement returnStatement = ast.newReturnStatement();
        returnStatement.setExpression(conditionalExpression);
        rewrite.replace(ifStatement, returnStatement, null);
    } else {
        Assignment assignment = ast.newAssignment();
        assignment.setLeftHandSide((Expression) rewrite.createCopyTarget(assigned));
        assignment.setRightHandSide(conditionalExpression);
        assignment.setOperator(((Assignment) assigned.getParent()).getOperator());
        ExpressionStatement expressionStatement = ast.newExpressionStatement(assignment);
        rewrite.replace(ifStatement, expressionStatement, null);
    }
    // add correction proposal
    resultingCollections.add(proposal);
    return true;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) DoStatement(org.eclipse.jdt.core.dom.DoStatement) Statement(org.eclipse.jdt.core.dom.Statement) ContinueStatement(org.eclipse.jdt.core.dom.ContinueStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) AssertStatement(org.eclipse.jdt.core.dom.AssertStatement) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) BreakStatement(org.eclipse.jdt.core.dom.BreakStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) IBinding(org.eclipse.jdt.core.dom.IBinding) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name) Assignment(org.eclipse.jdt.core.dom.Assignment) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) IfStatement(org.eclipse.jdt.core.dom.IfStatement) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) IJavaProject(org.eclipse.jdt.core.IJavaProject) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) InstanceofExpression(org.eclipse.jdt.core.dom.InstanceofExpression) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) CastExpression(org.eclipse.jdt.core.dom.CastExpression)

Example 24 with CastExpression

use of org.eclipse.jdt.core.dom.CastExpression in project flux 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)

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