Search in sources :

Example 36 with IMethodBinding

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

the class UnresolvedElementsSubProcessor method addSimilarVariableProposals.

private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, IVariableBinding resolvedField, SimpleName node, boolean isWriteAccess, Collection<ICommandAccess> proposals) {
    int kind = ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY;
    if (!isWriteAccess) {
        // also try to find similar methods
        kind |= ScopeAnalyzer.METHODS;
    }
    IBinding[] varsAndMethodsInScope = (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(node, kind);
    if (varsAndMethodsInScope.length > 0) {
        // avoid corrections like int i= i;
        String otherNameInAssign = null;
        // help with x.getString() -> y.getString()
        String methodSenderName = null;
        String fieldSenderName = null;
        ASTNode parent = node.getParent();
        switch(parent.getNodeType()) {
            case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
                // node must be initializer
                otherNameInAssign = ((VariableDeclarationFragment) parent).getName().getIdentifier();
                break;
            case ASTNode.ASSIGNMENT:
                Assignment assignment = (Assignment) parent;
                if (isWriteAccess && assignment.getRightHandSide() instanceof SimpleName) {
                    otherNameInAssign = ((SimpleName) assignment.getRightHandSide()).getIdentifier();
                } else if (!isWriteAccess && assignment.getLeftHandSide() instanceof SimpleName) {
                    otherNameInAssign = ((SimpleName) assignment.getLeftHandSide()).getIdentifier();
                }
                break;
            case ASTNode.METHOD_INVOCATION:
                MethodInvocation inv = (MethodInvocation) parent;
                if (inv.getExpression() == node) {
                    methodSenderName = inv.getName().getIdentifier();
                }
                break;
            case ASTNode.QUALIFIED_NAME:
                QualifiedName qualName = (QualifiedName) parent;
                if (qualName.getQualifier() == node) {
                    fieldSenderName = qualName.getName().getIdentifier();
                }
                break;
        }
        ITypeBinding guessedType = ASTResolving.guessBindingForReference(node);
        //$NON-NLS-1$
        ITypeBinding objectBinding = astRoot.getAST().resolveWellKnownType("java.lang.Object");
        String identifier = node.getIdentifier();
        boolean isInStaticContext = ASTResolving.isInStaticContext(node);
        ArrayList<CUCorrectionProposal> newProposals = new ArrayList<CUCorrectionProposal>(51);
        loop: for (int i = 0; i < varsAndMethodsInScope.length && newProposals.size() <= 50; i++) {
            IBinding varOrMeth = varsAndMethodsInScope[i];
            if (varOrMeth instanceof IVariableBinding) {
                IVariableBinding curr = (IVariableBinding) varOrMeth;
                String currName = curr.getName();
                if (currName.equals(otherNameInAssign)) {
                    continue loop;
                }
                if (resolvedField != null && Bindings.equals(resolvedField, curr)) {
                    continue loop;
                }
                boolean isFinal = Modifier.isFinal(curr.getModifiers());
                if (isFinal && curr.isField() && isWriteAccess) {
                    continue loop;
                }
                if (isInStaticContext && !Modifier.isStatic(curr.getModifiers()) && curr.isField()) {
                    continue loop;
                }
                int relevance = IProposalRelevance.SIMILAR_VARIABLE_PROPOSAL;
                if (NameMatcher.isSimilarName(currName, identifier)) {
                    // variable with a similar name than the unresolved variable
                    relevance += 3;
                }
                if (currName.equalsIgnoreCase(identifier)) {
                    relevance += 5;
                }
                ITypeBinding varType = curr.getType();
                if (varType != null) {
                    if (guessedType != null && guessedType != objectBinding) {
                        // variable type is compatible with the guessed type
                        if (!isWriteAccess && canAssign(varType, guessedType) || isWriteAccess && canAssign(guessedType, varType)) {
                            // unresolved variable can be assign to this variable
                            relevance += 2;
                        }
                    }
                    if (methodSenderName != null && hasMethodWithName(varType, methodSenderName)) {
                        relevance += 2;
                    }
                    if (fieldSenderName != null && hasFieldWithName(varType, fieldSenderName)) {
                        relevance += 2;
                    }
                }
                if (relevance > 0) {
                    String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changevariable_description, BasicElementLabels.getJavaElementName(currName));
                    newProposals.add(new RenameNodeCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), currName, relevance));
                }
            } else if (varOrMeth instanceof IMethodBinding) {
                IMethodBinding curr = (IMethodBinding) varOrMeth;
                if (!curr.isConstructor() && guessedType != null && canAssign(curr.getReturnType(), guessedType)) {
                    if (NameMatcher.isSimilarName(curr.getName(), identifier)) {
                        AST ast = astRoot.getAST();
                        ASTRewrite rewrite = ASTRewrite.create(ast);
                        String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetomethod_description, ASTResolving.getMethodSignature(curr));
                        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
                        LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_TO_METHOD, image);
                        newProposals.add(proposal);
                        MethodInvocation newInv = ast.newMethodInvocation();
                        newInv.setName(ast.newSimpleName(curr.getName()));
                        ITypeBinding[] parameterTypes = curr.getParameterTypes();
                        for (int k = 0; k < parameterTypes.length; k++) {
                            ASTNode arg = ASTNodeFactory.newDefaultExpression(ast, parameterTypes[k]);
                            newInv.arguments().add(arg);
                            proposal.addLinkedPosition(rewrite.track(arg), false, null);
                        }
                        rewrite.replace(node, newInv, null);
                    }
                }
            }
        }
        if (newProposals.size() <= 50)
            proposals.addAll(newProposals);
    }
    if (binding != null && binding.isArray()) {
        //$NON-NLS-1$
        String idLength = "length";
        String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changevariable_description, idLength);
        proposals.add(new RenameNodeCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), idLength, IProposalRelevance.CHANGE_VARIABLE));
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) AST(org.eclipse.jdt.core.dom.AST) IBinding(org.eclipse.jdt.core.dom.IBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) ArrayList(java.util.ArrayList) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) Image(org.eclipse.swt.graphics.Image) Assignment(org.eclipse.jdt.core.dom.Assignment) RenameNodeCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.RenameNodeCorrectionProposal) CUCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ScopeAnalyzer(org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 37 with IMethodBinding

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

the class ASTNodes method getDimensions.

public static int getDimensions(VariableDeclaration declaration) {
    int dim = declaration.getExtraDimensions();
    if (declaration instanceof VariableDeclarationFragment && declaration.getParent() instanceof LambdaExpression) {
        LambdaExpression lambda = (LambdaExpression) declaration.getParent();
        IMethodBinding methodBinding = lambda.resolveMethodBinding();
        if (methodBinding != null) {
            ITypeBinding[] parameterTypes = methodBinding.getParameterTypes();
            int index = lambda.parameters().indexOf(declaration);
            ITypeBinding typeBinding = parameterTypes[index];
            return typeBinding.getDimensions();
        }
    } else {
        Type type = getType(declaration);
        if (type instanceof ArrayType) {
            dim += ((ArrayType) type).getDimensions();
        }
    }
    return dim;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ArrayType(org.eclipse.jdt.core.dom.ArrayType) 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) QualifiedType(org.eclipse.jdt.core.dom.QualifiedType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression)

Example 38 with IMethodBinding

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

the class ASTNodes method getTargetType.

/**
	 * Derives the target type defined at the location of the given expression if the target context
	 * supports poly expressions.
	 * 
	 * @param expression the expression at whose location the target type is required
	 * @return the type binding of the target type defined at the location of the given expression
	 *         if the target context supports poly expressions, or <code>null</code> if the target
	 *         type could not be derived
	 * 
	 * @since 3.10
	 */
public static ITypeBinding getTargetType(Expression expression) {
    ASTNode parent = expression.getParent();
    StructuralPropertyDescriptor locationInParent = expression.getLocationInParent();
    if (locationInParent == VariableDeclarationFragment.INITIALIZER_PROPERTY || locationInParent == SingleVariableDeclaration.INITIALIZER_PROPERTY) {
        return ((VariableDeclaration) parent).getName().resolveTypeBinding();
    } else if (locationInParent == Assignment.RIGHT_HAND_SIDE_PROPERTY) {
        return ((Assignment) parent).getLeftHandSide().resolveTypeBinding();
    } else if (locationInParent == ReturnStatement.EXPRESSION_PROPERTY) {
        return getTargetTypeForReturnStmt((ReturnStatement) parent);
    } else if (locationInParent == ArrayInitializer.EXPRESSIONS_PROPERTY) {
        return getTargetTypeForArrayInitializer((ArrayInitializer) parent);
    } else if (locationInParent == MethodInvocation.ARGUMENTS_PROPERTY) {
        MethodInvocation methodInvocation = (MethodInvocation) parent;
        IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
        if (methodBinding != null) {
            return getParameterTypeBinding(expression, methodInvocation.arguments(), methodBinding);
        }
    } else if (locationInParent == SuperMethodInvocation.ARGUMENTS_PROPERTY) {
        SuperMethodInvocation superMethodInvocation = (SuperMethodInvocation) parent;
        IMethodBinding superMethodBinding = superMethodInvocation.resolveMethodBinding();
        if (superMethodBinding != null) {
            return getParameterTypeBinding(expression, superMethodInvocation.arguments(), superMethodBinding);
        }
    } else if (locationInParent == ConstructorInvocation.ARGUMENTS_PROPERTY) {
        ConstructorInvocation constructorInvocation = (ConstructorInvocation) parent;
        IMethodBinding constructorBinding = constructorInvocation.resolveConstructorBinding();
        if (constructorBinding != null) {
            return getParameterTypeBinding(expression, constructorInvocation.arguments(), constructorBinding);
        }
    } else if (locationInParent == SuperConstructorInvocation.ARGUMENTS_PROPERTY) {
        SuperConstructorInvocation superConstructorInvocation = (SuperConstructorInvocation) parent;
        IMethodBinding superConstructorBinding = superConstructorInvocation.resolveConstructorBinding();
        if (superConstructorBinding != null) {
            return getParameterTypeBinding(expression, superConstructorInvocation.arguments(), superConstructorBinding);
        }
    } else if (locationInParent == ClassInstanceCreation.ARGUMENTS_PROPERTY) {
        ClassInstanceCreation creation = (ClassInstanceCreation) parent;
        IMethodBinding creationBinding = creation.resolveConstructorBinding();
        if (creationBinding != null) {
            return getParameterTypeBinding(expression, creation.arguments(), creationBinding);
        }
    } else if (locationInParent == EnumConstantDeclaration.ARGUMENTS_PROPERTY) {
        EnumConstantDeclaration enumConstantDecl = (EnumConstantDeclaration) parent;
        IMethodBinding enumConstructorBinding = enumConstantDecl.resolveConstructorBinding();
        if (enumConstructorBinding != null) {
            return getParameterTypeBinding(expression, enumConstantDecl.arguments(), enumConstructorBinding);
        }
    } else if (locationInParent == LambdaExpression.BODY_PROPERTY) {
        IMethodBinding methodBinding = ((LambdaExpression) parent).resolveMethodBinding();
        if (methodBinding != null) {
            return methodBinding.getReturnType();
        }
    } else if (locationInParent == ConditionalExpression.THEN_EXPRESSION_PROPERTY || locationInParent == ConditionalExpression.ELSE_EXPRESSION_PROPERTY) {
        return getTargetType((ConditionalExpression) parent);
    } else if (locationInParent == CastExpression.EXPRESSION_PROPERTY) {
        return ((CastExpression) parent).getType().resolveBinding();
    } else if (locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) {
        return getTargetType((ParenthesizedExpression) parent);
    }
    return null;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) 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) EnumConstantDeclaration(org.eclipse.jdt.core.dom.EnumConstantDeclaration) ConstructorInvocation(org.eclipse.jdt.core.dom.ConstructorInvocation) SuperConstructorInvocation(org.eclipse.jdt.core.dom.SuperConstructorInvocation) ASTNode(org.eclipse.jdt.core.dom.ASTNode) SuperConstructorInvocation(org.eclipse.jdt.core.dom.SuperConstructorInvocation) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor) ArrayInitializer(org.eclipse.jdt.core.dom.ArrayInitializer)

Example 39 with IMethodBinding

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

the class ScopeAnalyzer method addInherited.

/**
	 * Collects all elements available in a type and its hierarchy
	 * @param binding The type binding
	 * @param flags Flags defining the elements to report
	 * @param requestor the requestor to which all results are reported
	 * @return return <code>true</code> if the requestor has reported the binding as found and no further results are required
	 */
private boolean addInherited(ITypeBinding binding, int flags, IBindingRequestor requestor) {
    if (!fTypesVisited.add(binding)) {
        return false;
    }
    if (hasFlag(VARIABLES, flags)) {
        IVariableBinding[] variableBindings = binding.getDeclaredFields();
        for (int i = 0; i < variableBindings.length; i++) {
            if (requestor.acceptBinding(variableBindings[i]))
                return true;
        }
    }
    if (hasFlag(METHODS, flags)) {
        IMethodBinding[] methodBindings = binding.getDeclaredMethods();
        for (int i = 0; i < methodBindings.length; i++) {
            IMethodBinding curr = methodBindings[i];
            if (!curr.isSynthetic() && !curr.isConstructor()) {
                if (requestor.acceptBinding(curr))
                    return true;
            }
        }
    }
    if (hasFlag(TYPES, flags)) {
        ITypeBinding[] typeBindings = binding.getDeclaredTypes();
        for (int i = 0; i < typeBindings.length; i++) {
            ITypeBinding curr = typeBindings[i];
            if (requestor.acceptBinding(curr))
                return true;
        }
    }
    ITypeBinding superClass = binding.getSuperclass();
    if (superClass != null) {
        if (// recursive
        addInherited(superClass, flags, requestor))
            return true;
    } else if (binding.isArray()) {
        if (//$NON-NLS-1$
        addInherited(fRoot.getAST().resolveWellKnownType("java.lang.Object"), flags, requestor))
            return true;
    }
    // includes looking for methods: abstract, unimplemented methods
    ITypeBinding[] interfaces = binding.getInterfaces();
    for (int i = 0; i < interfaces.length; i++) {
        if (// recursive
        addInherited(interfaces[i], flags, requestor))
            return true;
    }
    return false;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding)

Example 40 with IMethodBinding

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

the class ASTResolving method isVariableDefinedInContext.

private static boolean isVariableDefinedInContext(IBinding binding, ITypeBinding typeVariable) {
    if (binding.getKind() == IBinding.VARIABLE) {
        IVariableBinding var = (IVariableBinding) binding;
        binding = var.getDeclaringMethod();
        if (binding == null) {
            binding = var.getDeclaringClass();
        }
    }
    if (binding instanceof IMethodBinding) {
        if (binding == typeVariable.getDeclaringMethod()) {
            return true;
        }
        binding = ((IMethodBinding) binding).getDeclaringClass();
    }
    while (binding instanceof ITypeBinding) {
        if (binding == typeVariable.getDeclaringClass()) {
            return true;
        }
        if (Modifier.isStatic(binding.getModifiers())) {
            break;
        }
        binding = ((ITypeBinding) binding).getDeclaringClass();
    }
    return false;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding)

Aggregations

IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)173 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)110 ASTNode (org.eclipse.jdt.core.dom.ASTNode)46 Expression (org.eclipse.jdt.core.dom.Expression)36 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)33 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)32 IVariableBinding (org.eclipse.jdt.core.dom.IVariableBinding)29 ArrayList (java.util.ArrayList)27 IBinding (org.eclipse.jdt.core.dom.IBinding)25 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)21 CastExpression (org.eclipse.jdt.core.dom.CastExpression)20 SimpleName (org.eclipse.jdt.core.dom.SimpleName)20 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)20 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)19 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)19 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)19 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)17 Image (org.eclipse.swt.graphics.Image)16 AST (org.eclipse.jdt.core.dom.AST)15 Type (org.eclipse.jdt.core.dom.Type)15