Search in sources :

Example 11 with ArrayCreation

use of org.eclipse.jdt.core.dom.ArrayCreation in project eclipse.jdt.ls by eclipse.

the class QuickAssistProcessor method convertMethodRefernceToLambda.

/**
 * Converts and replaces the given method reference with corresponding lambda
 * expression in the given ASTRewrite.
 *
 * @param methodReference
 *            the method reference to convert
 * @param functionalMethod
 *            the non-generic functional interface method to be implemented by
 *            the lambda expression
 * @param astRoot
 *            the AST root
 * @param rewrite
 *            the ASTRewrite
 * @param linkedProposalModel
 *            to create linked proposals for lambda's parameters or
 *            <code>null</code> if linked proposals are not required
 * @param createBlockBody
 *            <code>true</code> if lambda expression's body should be a block
 *
 * @return lambda expression used to replace the method reference in the given
 *         ASTRewrite
 * @throws JavaModelException
 *             if an exception occurs while accessing the Java element
 *             corresponding to the <code>functionalMethod</code>
 */
public static LambdaExpression convertMethodRefernceToLambda(MethodReference methodReference, IMethodBinding functionalMethod, CompilationUnit astRoot, ASTRewrite rewrite, LinkedProposalModel linkedProposalModel, boolean createBlockBody) throws JavaModelException {
    AST ast = astRoot.getAST();
    LambdaExpression lambda = ast.newLambdaExpression();
    String[] lambdaParamNames = getUniqueParameterNames(methodReference, functionalMethod);
    List<VariableDeclaration> lambdaParameters = lambda.parameters();
    for (int i = 0; i < lambdaParamNames.length; i++) {
        String paramName = lambdaParamNames[i];
        VariableDeclarationFragment lambdaParameter = ast.newVariableDeclarationFragment();
        SimpleName name = ast.newSimpleName(paramName);
        lambdaParameter.setName(name);
        lambdaParameters.add(lambdaParameter);
        if (linkedProposalModel != null) {
            linkedProposalModel.getPositionGroup(name.getIdentifier(), true).addPosition(rewrite.track(name), i == 0);
        }
    }
    int noOfLambdaParameters = lambdaParamNames.length;
    lambda.setParentheses(noOfLambdaParameters != 1);
    ITypeBinding returnTypeBinding = functionalMethod.getReturnType();
    // too often null, see bug 440000, bug 440344, bug 333665
    IMethodBinding referredMethodBinding = methodReference.resolveMethodBinding();
    if (methodReference instanceof CreationReference) {
        CreationReference creationRef = (CreationReference) methodReference;
        Type type = creationRef.getType();
        if (type instanceof ArrayType) {
            ArrayCreation arrayCreation = ast.newArrayCreation();
            if (createBlockBody) {
                Block blockBody = getBlockBodyForLambda(arrayCreation, returnTypeBinding, ast);
                lambda.setBody(blockBody);
            } else {
                lambda.setBody(arrayCreation);
            }
            ArrayType arrayType = (ArrayType) type;
            Type copiedElementType = (Type) rewrite.createCopyTarget(arrayType.getElementType());
            arrayCreation.setType(ast.newArrayType(copiedElementType, arrayType.getDimensions()));
            SimpleName name = ast.newSimpleName(lambdaParamNames[0]);
            arrayCreation.dimensions().add(name);
            if (linkedProposalModel != null) {
                linkedProposalModel.getPositionGroup(name.getIdentifier(), false).addPosition(rewrite.track(name), LinkedPositionGroup.NO_STOP);
            }
        } else {
            ClassInstanceCreation cic = ast.newClassInstanceCreation();
            if (createBlockBody) {
                Block blockBody = getBlockBodyForLambda(cic, returnTypeBinding, ast);
                lambda.setBody(blockBody);
            } else {
                lambda.setBody(cic);
            }
            ITypeBinding typeBinding = type.resolveBinding();
            if (!(type instanceof ParameterizedType) && typeBinding != null && typeBinding.getTypeDeclaration().isGenericType()) {
                cic.setType(ast.newParameterizedType((Type) rewrite.createCopyTarget(type)));
            } else {
                cic.setType((Type) rewrite.createCopyTarget(type));
            }
            List<SimpleName> invocationArgs = getInvocationArguments(ast, 0, noOfLambdaParameters, lambdaParamNames);
            cic.arguments().addAll(invocationArgs);
            if (linkedProposalModel != null) {
                for (SimpleName name : invocationArgs) {
                    linkedProposalModel.getPositionGroup(name.getIdentifier(), false).addPosition(rewrite.track(name), LinkedPositionGroup.NO_STOP);
                }
            }
            cic.typeArguments().addAll(getCopiedTypeArguments(rewrite, methodReference.typeArguments()));
        }
    } else if (referredMethodBinding != null && Modifier.isStatic(referredMethodBinding.getModifiers())) {
        MethodInvocation methodInvocation = ast.newMethodInvocation();
        if (createBlockBody) {
            Block blockBody = getBlockBodyForLambda(methodInvocation, returnTypeBinding, ast);
            lambda.setBody(blockBody);
        } else {
            lambda.setBody(methodInvocation);
        }
        Expression expr = null;
        boolean hasConflict = hasConflict(methodReference.getStartPosition(), referredMethodBinding, ScopeAnalyzer.METHODS | ScopeAnalyzer.CHECK_VISIBILITY, astRoot);
        if (hasConflict || !Bindings.isSuperType(referredMethodBinding.getDeclaringClass(), ASTNodes.getEnclosingType(methodReference)) || methodReference.typeArguments().size() != 0) {
            if (methodReference instanceof ExpressionMethodReference) {
                ExpressionMethodReference expressionMethodReference = (ExpressionMethodReference) methodReference;
                expr = (Expression) rewrite.createCopyTarget(expressionMethodReference.getExpression());
            } else if (methodReference instanceof TypeMethodReference) {
                Type type = ((TypeMethodReference) methodReference).getType();
                ITypeBinding typeBinding = type.resolveBinding();
                if (typeBinding != null) {
                    ImportRewrite importRewrite = CodeStyleConfiguration.createImportRewrite(astRoot, true);
                    expr = ast.newName(importRewrite.addImport(typeBinding));
                }
            }
        }
        methodInvocation.setExpression(expr);
        SimpleName methodName = getMethodInvocationName(methodReference);
        methodInvocation.setName((SimpleName) rewrite.createCopyTarget(methodName));
        List<SimpleName> invocationArgs = getInvocationArguments(ast, 0, noOfLambdaParameters, lambdaParamNames);
        methodInvocation.arguments().addAll(invocationArgs);
        if (linkedProposalModel != null) {
            for (SimpleName name : invocationArgs) {
                linkedProposalModel.getPositionGroup(name.getIdentifier(), false).addPosition(rewrite.track(name), LinkedPositionGroup.NO_STOP);
            }
        }
        methodInvocation.typeArguments().addAll(getCopiedTypeArguments(rewrite, methodReference.typeArguments()));
    } else if (methodReference instanceof SuperMethodReference) {
        SuperMethodInvocation superMethodInvocation = ast.newSuperMethodInvocation();
        if (createBlockBody) {
            Block blockBody = getBlockBodyForLambda(superMethodInvocation, returnTypeBinding, ast);
            lambda.setBody(blockBody);
        } else {
            lambda.setBody(superMethodInvocation);
        }
        Name superQualifier = ((SuperMethodReference) methodReference).getQualifier();
        if (superQualifier != null) {
            superMethodInvocation.setQualifier((Name) rewrite.createCopyTarget(superQualifier));
        }
        SimpleName methodName = getMethodInvocationName(methodReference);
        superMethodInvocation.setName((SimpleName) rewrite.createCopyTarget(methodName));
        List<SimpleName> invocationArgs = getInvocationArguments(ast, 0, noOfLambdaParameters, lambdaParamNames);
        superMethodInvocation.arguments().addAll(invocationArgs);
        if (linkedProposalModel != null) {
            for (SimpleName name : invocationArgs) {
                linkedProposalModel.getPositionGroup(name.getIdentifier(), false).addPosition(rewrite.track(name), LinkedPositionGroup.NO_STOP);
            }
        }
        superMethodInvocation.typeArguments().addAll(getCopiedTypeArguments(rewrite, methodReference.typeArguments()));
    } else {
        MethodInvocation methodInvocation = ast.newMethodInvocation();
        if (createBlockBody) {
            Block blockBody = getBlockBodyForLambda(methodInvocation, returnTypeBinding, ast);
            lambda.setBody(blockBody);
        } else {
            lambda.setBody(methodInvocation);
        }
        boolean isTypeReference = isTypeReferenceToInstanceMethod(methodReference);
        if (isTypeReference) {
            SimpleName name = ast.newSimpleName(lambdaParamNames[0]);
            methodInvocation.setExpression(name);
            if (linkedProposalModel != null) {
                linkedProposalModel.getPositionGroup(name.getIdentifier(), false).addPosition(rewrite.track(name), LinkedPositionGroup.NO_STOP);
            }
        } else {
            Expression expr = ((ExpressionMethodReference) methodReference).getExpression();
            if (!(expr instanceof ThisExpression && methodReference.typeArguments().size() == 0)) {
                methodInvocation.setExpression((Expression) rewrite.createCopyTarget(expr));
            }
        }
        SimpleName methodName = getMethodInvocationName(methodReference);
        methodInvocation.setName((SimpleName) rewrite.createCopyTarget(methodName));
        List<SimpleName> invocationArgs = getInvocationArguments(ast, isTypeReference ? 1 : 0, noOfLambdaParameters, lambdaParamNames);
        methodInvocation.arguments().addAll(invocationArgs);
        if (linkedProposalModel != null) {
            for (SimpleName name : invocationArgs) {
                linkedProposalModel.getPositionGroup(name.getIdentifier(), false).addPosition(rewrite.track(name), LinkedPositionGroup.NO_STOP);
            }
        }
        methodInvocation.typeArguments().addAll(getCopiedTypeArguments(rewrite, methodReference.typeArguments()));
    }
    rewrite.replace(methodReference, lambda, null);
    return lambda;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SimpleName(org.eclipse.jdt.core.dom.SimpleName) CreationReference(org.eclipse.jdt.core.dom.CreationReference) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) VariableDeclaration(org.eclipse.jdt.core.dom.VariableDeclaration) TypeMethodReference(org.eclipse.jdt.core.dom.TypeMethodReference) List(java.util.List) ArrayList(java.util.ArrayList) SuperMethodReference(org.eclipse.jdt.core.dom.SuperMethodReference) ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) AST(org.eclipse.jdt.core.dom.AST) ExpressionMethodReference(org.eclipse.jdt.core.dom.ExpressionMethodReference) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) IType(org.eclipse.jdt.core.IType) UnionType(org.eclipse.jdt.core.dom.UnionType) 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) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) Expression(org.eclipse.jdt.core.dom.Expression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) ArrayCreation(org.eclipse.jdt.core.dom.ArrayCreation) Block(org.eclipse.jdt.core.dom.Block) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression)

Example 12 with ArrayCreation

use of org.eclipse.jdt.core.dom.ArrayCreation in project eclipse.jdt.ls by eclipse.

the class NecessaryParenthesesChecker method needsParentheses.

/**
 * Does the <code>expression</code> need parentheses when inserted into <code>parent</code> at
 * <code>locationInParent</code> ?
 *
 * @param expression the expression
 * @param parent the parent node
 * @param locationInParent location of expression in the parent
 * @param leftOperandType the type of the left operand in <code>parent</code> if
 *            <code>parent</code> is an infix expression with no bindings and
 *            <code>expression</code> is the right operand in it, <code>null</code> otherwise
 * @return <code>true</code> if <code>expression</code> needs parentheses, <code>false</code>
 *         otherwise.
 *
 * @since 3.9
 */
private static boolean needsParentheses(Expression expression, ASTNode parent, StructuralPropertyDescriptor locationInParent, ITypeBinding leftOperandType) {
    if (!expressionTypeNeedsParentheses(expression)) {
        return false;
    }
    if (!locationNeedsParentheses(locationInParent)) {
        return false;
    }
    if (parent instanceof Expression) {
        Expression parentExpression = (Expression) parent;
        if (expression instanceof PrefixExpression) {
            // see bug 405096
            return needsParenthesesForPrefixExpression(parentExpression, ((PrefixExpression) expression).getOperator());
        }
        if (expression instanceof ArrayCreation) {
            // see bug 394721
            return parentExpression instanceof ArrayAccess && ((ArrayCreation) expression).getInitializer() == null;
        }
        int expressionPrecedence = OperatorPrecedence.getExpressionPrecedence(expression);
        int parentPrecedence = OperatorPrecedence.getExpressionPrecedence(parentExpression);
        if (expressionPrecedence > parentPrecedence) {
            // (opEx) opParent and opEx binds more -> parentheses not needed
            return false;
        }
        if (expressionPrecedence < parentPrecedence) {
            // (opEx) opParent and opEx binds less -> parentheses needed
            return true;
        }
        if (parentExpression instanceof InfixExpression) {
            return needsParenthesesInInfixExpression(expression, (InfixExpression) parentExpression, locationInParent, leftOperandType);
        }
        if (parentExpression instanceof ConditionalExpression && locationInParent == ConditionalExpression.EXPRESSION_PROPERTY) {
            return true;
        }
        return false;
    }
    return true;
}
Also used : ArrayAccess(org.eclipse.jdt.core.dom.ArrayAccess) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) Expression(org.eclipse.jdt.core.dom.Expression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) ArrayCreation(org.eclipse.jdt.core.dom.ArrayCreation) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression)

Example 13 with ArrayCreation

use of org.eclipse.jdt.core.dom.ArrayCreation in project whole by wholeplatform.

the class CompilationUnitBuilder method newArrayCreation.

public ArrayCreation newArrayCreation(String type, ArrayInitializer initializer) {
    ArrayCreation stm = newArrayCreation(type);
    stm.setInitializer(initializer);
    return stm;
}
Also used : ArrayCreation(org.eclipse.jdt.core.dom.ArrayCreation)

Example 14 with ArrayCreation

use of org.eclipse.jdt.core.dom.ArrayCreation 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 15 with ArrayCreation

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

the class QuickAssistProcessor method getSplitVariableProposals.

private static boolean getSplitVariableProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
    VariableDeclarationFragment fragment;
    if (node instanceof VariableDeclarationFragment) {
        fragment = (VariableDeclarationFragment) node;
    } else if (node.getLocationInParent() == VariableDeclarationFragment.NAME_PROPERTY) {
        fragment = (VariableDeclarationFragment) node.getParent();
    } else {
        return false;
    }
    if (fragment.getInitializer() == null) {
        return false;
    }
    Statement statement;
    ASTNode fragParent = fragment.getParent();
    if (fragParent instanceof VariableDeclarationStatement) {
        statement = (VariableDeclarationStatement) fragParent;
    } else if (fragParent instanceof VariableDeclarationExpression) {
        if (fragParent.getLocationInParent() == TryStatement.RESOURCES_PROPERTY) {
            return false;
        }
        statement = (Statement) fragParent.getParent();
    } else {
        return false;
    }
    // statement is ForStatement or VariableDeclarationStatement
    ASTNode statementParent = statement.getParent();
    StructuralPropertyDescriptor property = statement.getLocationInParent();
    if (!property.isChildListProperty()) {
        return false;
    }
    List<? extends ASTNode> list = ASTNodes.getChildListProperty(statementParent, (ChildListPropertyDescriptor) property);
    if (resultingCollections == null) {
        return true;
    }
    AST ast = statement.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    String label = CorrectionMessages.QuickAssistProcessor_splitdeclaration_description;
    // Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.SPLIT_VARIABLE_DECLARATION);
    boolean commandConflict = false;
    for (Iterator<ICommandAccess> iterator = resultingCollections.iterator(); iterator.hasNext(); ) {
        Object completionProposal = iterator.next();
        if (completionProposal instanceof ChangeCorrectionProposal) {
            if (SPLIT_JOIN_VARIABLE_DECLARATION_ID.equals(((ChangeCorrectionProposal) completionProposal).getCommandId())) {
                commandConflict = true;
            }
        }
    }
    if (!commandConflict) {
        proposal.setCommandId(SPLIT_JOIN_VARIABLE_DECLARATION_ID);
    }
    Statement newStatement;
    int insertIndex = list.indexOf(statement);
    Expression placeholder = (Expression) rewrite.createMoveTarget(fragment.getInitializer());
    ITypeBinding binding = fragment.getInitializer().resolveTypeBinding();
    if (placeholder instanceof ArrayInitializer && binding != null && binding.isArray()) {
        ArrayCreation creation = ast.newArrayCreation();
        creation.setInitializer((ArrayInitializer) placeholder);
        final ITypeBinding componentType = binding.getElementType();
        Type type = null;
        if (componentType.isPrimitive())
            type = ast.newPrimitiveType(PrimitiveType.toCode(componentType.getName()));
        else
            type = ast.newSimpleType(ast.newSimpleName(componentType.getName()));
        creation.setType(ast.newArrayType(type, binding.getDimensions()));
        placeholder = creation;
    }
    Assignment assignment = ast.newAssignment();
    assignment.setRightHandSide(placeholder);
    assignment.setLeftHandSide(ast.newSimpleName(fragment.getName().getIdentifier()));
    if (statement instanceof VariableDeclarationStatement) {
        newStatement = ast.newExpressionStatement(assignment);
        // add after declaration
        insertIndex += 1;
    } else {
        rewrite.replace(fragment.getParent(), assignment, null);
        VariableDeclarationFragment newFrag = ast.newVariableDeclarationFragment();
        newFrag.setName(ast.newSimpleName(fragment.getName().getIdentifier()));
        newFrag.extraDimensions().addAll(DimensionRewrite.copyDimensions(fragment.extraDimensions(), rewrite));
        VariableDeclarationExpression oldVarDecl = (VariableDeclarationExpression) fragParent;
        VariableDeclarationStatement newVarDec = ast.newVariableDeclarationStatement(newFrag);
        newVarDec.setType((Type) rewrite.createCopyTarget(oldVarDecl.getType()));
        newVarDec.modifiers().addAll(ASTNodeFactory.newModifiers(ast, oldVarDecl.getModifiers()));
        newStatement = newVarDec;
    }
    ListRewrite listRewriter = rewrite.getListRewrite(statementParent, (ChildListPropertyDescriptor) property);
    listRewriter.insertAt(newStatement, insertIndex, null);
    resultingCollections.add(proposal);
    return true;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) DoStatement(org.eclipse.jdt.core.dom.DoStatement) Statement(org.eclipse.jdt.core.dom.Statement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ICommandAccess(org.eclipse.jdt.ui.text.java.correction.ICommandAccess) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) ChangeCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) Assignment(org.eclipse.jdt.core.dom.Assignment) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) IType(org.eclipse.jdt.core.IType) UnionType(org.eclipse.jdt.core.dom.UnionType) 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) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) 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) PostfixExpression(org.eclipse.jdt.core.dom.PostfixExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayCreation(org.eclipse.jdt.core.dom.ArrayCreation) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor) ArrayInitializer(org.eclipse.jdt.core.dom.ArrayInitializer)

Aggregations

ArrayCreation (org.eclipse.jdt.core.dom.ArrayCreation)21 Expression (org.eclipse.jdt.core.dom.Expression)11 ArrayInitializer (org.eclipse.jdt.core.dom.ArrayInitializer)10 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)10 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)8 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)8 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)8 AST (org.eclipse.jdt.core.dom.AST)7 ArrayType (org.eclipse.jdt.core.dom.ArrayType)7 VariableDeclaration (org.eclipse.jdt.core.dom.VariableDeclaration)7 Assignment (org.eclipse.jdt.core.dom.Assignment)6 CastExpression (org.eclipse.jdt.core.dom.CastExpression)6 ClassInstanceCreation (org.eclipse.jdt.core.dom.ClassInstanceCreation)6 ConditionalExpression (org.eclipse.jdt.core.dom.ConditionalExpression)6 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)6 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)6 SimpleName (org.eclipse.jdt.core.dom.SimpleName)6 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)6 SuperMethodInvocation (org.eclipse.jdt.core.dom.SuperMethodInvocation)6 ASTNode (org.eclipse.jdt.core.dom.ASTNode)5