Search in sources :

Example 1 with MethodInvocation

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

the class AddImportsOperation method evaluateEdits.

private TextEdit evaluateEdits(CompilationUnit root, ImportRewrite importRewrite, int offset, int length, IProgressMonitor monitor) throws JavaModelException {
    SimpleName nameNode = null;
    if (root != null) {
        // got an AST
        ASTNode node = NodeFinder.perform(root, offset, length);
        if (node instanceof MarkerAnnotation) {
            node = ((Annotation) node).getTypeName();
        }
        if (node instanceof QualifiedName) {
            nameNode = ((QualifiedName) node).getName();
        } else if (node instanceof SimpleName) {
            nameNode = (SimpleName) node;
        }
    }
    String name, simpleName, containerName;
    int qualifierStart;
    int simpleNameStart;
    if (nameNode != null) {
        simpleName = nameNode.getIdentifier();
        simpleNameStart = nameNode.getStartPosition();
        if (nameNode.getLocationInParent() == QualifiedName.NAME_PROPERTY) {
            Name qualifier = ((QualifiedName) nameNode.getParent()).getQualifier();
            containerName = qualifier.getFullyQualifiedName();
            name = JavaModelUtil.concatenateName(containerName, simpleName);
            qualifierStart = qualifier.getStartPosition();
        } else if (nameNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY) {
            NameQualifiedType nameQualifiedType = (NameQualifiedType) nameNode.getParent();
            Name qualifier = nameQualifiedType.getQualifier();
            containerName = qualifier.getFullyQualifiedName();
            name = JavaModelUtil.concatenateName(containerName, simpleName);
            qualifierStart = qualifier.getStartPosition();
            List<Annotation> annotations = nameQualifiedType.annotations();
            if (!annotations.isEmpty()) {
                // don't remove annotations
                simpleNameStart = annotations.get(0).getStartPosition();
            }
        } else if (nameNode.getLocationInParent() == MethodInvocation.NAME_PROPERTY) {
            ASTNode qualifier = ((MethodInvocation) nameNode.getParent()).getExpression();
            if (qualifier instanceof Name) {
                containerName = ASTNodes.asString(qualifier);
                name = JavaModelUtil.concatenateName(containerName, simpleName);
                qualifierStart = qualifier.getStartPosition();
            } else {
                return null;
            }
        } else {
            //$NON-NLS-1$
            containerName = "";
            name = simpleName;
            qualifierStart = simpleNameStart;
        }
        IBinding binding = nameNode.resolveBinding();
        if (binding != null && !binding.isRecovered()) {
            if (binding instanceof ITypeBinding) {
                ITypeBinding typeBinding = ((ITypeBinding) binding).getTypeDeclaration();
                String qualifiedBindingName = typeBinding.getQualifiedName();
                if (containerName.length() > 0 && !qualifiedBindingName.equals(name)) {
                    return null;
                }
                ImportRewriteContext context = new ContextSensitiveImportRewriteContext(root, qualifierStart, importRewrite);
                String res = importRewrite.addImport(typeBinding, context);
                if (containerName.length() > 0 && !res.equals(simpleName)) {
                    // adding import failed
                    fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_importclash, null);
                    return null;
                }
                if (containerName.length() == 0 && res.equals(simpleName)) {
                    // no change necessary
                    return null;
                }
                return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, new String());
            } else if (JavaModelUtil.is50OrHigher(fCompilationUnit.getJavaProject()) && (binding instanceof IVariableBinding || binding instanceof IMethodBinding)) {
                boolean isField = binding instanceof IVariableBinding;
                ITypeBinding declaringClass = isField ? ((IVariableBinding) binding).getDeclaringClass() : ((IMethodBinding) binding).getDeclaringClass();
                if (declaringClass == null) {
                    // variableBinding.getDeclaringClass() is null for array.length
                    return null;
                }
                if (Modifier.isStatic(binding.getModifiers())) {
                    if (containerName.length() > 0) {
                        if (containerName.equals(declaringClass.getName()) || containerName.equals(declaringClass.getQualifiedName())) {
                            ASTNode node = nameNode.getParent();
                            boolean isDirectlyAccessible = false;
                            while (node != null) {
                                if (isTypeDeclarationSubTypeCompatible(node, declaringClass)) {
                                    isDirectlyAccessible = true;
                                    break;
                                }
                                node = node.getParent();
                            }
                            if (!isDirectlyAccessible) {
                                if (Modifier.isPrivate(declaringClass.getModifiers())) {
                                    fStatus = JavaUIStatus.createError(IStatus.ERROR, Messages.format(CodeGenerationMessages.AddImportsOperation_error_not_visible_class, BasicElementLabels.getJavaElementName(declaringClass.getName())), null);
                                    return null;
                                }
                                String res = importRewrite.addStaticImport(declaringClass.getQualifiedName(), binding.getName(), isField);
                                if (!res.equals(simpleName)) {
                                    // adding import failed
                                    return null;
                                }
                            }
                            //$NON-NLS-1$
                            return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
                        }
                    }
                }
                // no static imports for packages
                return null;
            } else {
                return null;
            }
        }
        if (binding != null && binding.getKind() != IBinding.TYPE) {
            // recovered binding
            return null;
        }
    } else {
        IBuffer buffer = fCompilationUnit.getBuffer();
        qualifierStart = getNameStart(buffer, offset);
        int nameEnd = getNameEnd(buffer, offset + length);
        int len = nameEnd - qualifierStart;
        name = buffer.getText(qualifierStart, len).trim();
        if (name.length() == 0) {
            return null;
        }
        simpleName = Signature.getSimpleName(name);
        containerName = Signature.getQualifier(name);
        IJavaProject javaProject = fCompilationUnit.getJavaProject();
        if (simpleName.length() == 0 || JavaConventionsUtil.validateJavaTypeName(simpleName, javaProject).matches(IStatus.ERROR) || (containerName.length() > 0 && JavaConventionsUtil.validateJavaTypeName(containerName, javaProject).matches(IStatus.ERROR))) {
            fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_invalid_selection, null);
            return null;
        }
        simpleNameStart = getSimpleNameStart(buffer, qualifierStart, containerName);
        int res = importRewrite.getDefaultImportRewriteContext().findInContext(containerName, simpleName, ImportRewriteContext.KIND_TYPE);
        if (res == ImportRewriteContext.RES_NAME_CONFLICT) {
            fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_importclash, null);
            return null;
        } else if (res == ImportRewriteContext.RES_NAME_FOUND) {
            //$NON-NLS-1$
            return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
        }
    }
    IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { fCompilationUnit.getJavaProject() });
    TypeNameMatch[] types = findAllTypes(simpleName, searchScope, nameNode, new SubProgressMonitor(monitor, 1));
    if (types.length == 0) {
        fStatus = JavaUIStatus.createError(IStatus.ERROR, Messages.format(CodeGenerationMessages.AddImportsOperation_error_notresolved_message, BasicElementLabels.getJavaElementName(simpleName)), null);
        return null;
    }
    if (monitor.isCanceled()) {
        throw new OperationCanceledException();
    }
    TypeNameMatch chosen;
    if (types.length > 1 && fQuery != null) {
        chosen = fQuery.chooseImport(types, containerName);
        if (chosen == null) {
            throw new OperationCanceledException();
        }
    } else {
        chosen = types[0];
    }
    ImportRewriteContext context = root == null ? null : new ContextSensitiveImportRewriteContext(root, simpleNameStart, importRewrite);
    importRewrite.addImport(chosen.getFullyQualifiedName(), context);
    //$NON-NLS-1$
    return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) IBinding(org.eclipse.jdt.core.dom.IBinding) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) IBuffer(org.eclipse.jdt.core.IBuffer) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name) MarkerAnnotation(org.eclipse.jdt.core.dom.MarkerAnnotation) IJavaProject(org.eclipse.jdt.core.IJavaProject) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) TypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) List(java.util.List) ArrayList(java.util.ArrayList) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType)

Example 2 with MethodInvocation

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

the class UnresolvedElementsSubProcessor method doEqualNumberOfParameters.

private static void doEqualNumberOfParameters(IInvocationContext context, ASTNode invocationNode, IProblemLocation problem, List<Expression> arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection<ICommandAccess> proposals) throws CoreException {
    ITypeBinding[] paramTypes = methodBinding.getParameterTypes();
    int[] indexOfDiff = new int[paramTypes.length];
    int nDiffs = 0;
    for (int n = 0; n < argTypes.length; n++) {
        if (!canAssign(argTypes[n], paramTypes[n])) {
            indexOfDiff[nDiffs++] = n;
        }
    }
    ITypeBinding declaringTypeDecl = methodBinding.getDeclaringClass().getTypeDeclaration();
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode nameNode = problem.getCoveringNode(astRoot);
    if (nameNode == null) {
        return;
    }
    if (nDiffs == 0) {
        if (nameNode.getParent() instanceof MethodInvocation) {
            MethodInvocation inv = (MethodInvocation) nameNode.getParent();
            if (inv.getExpression() == null) {
                addQualifierToOuterProposal(context, inv, methodBinding, proposals);
            }
        }
        return;
    }
    if (nDiffs == 1) {
        // one argument mismatching: try to fix
        int idx = indexOfDiff[0];
        Expression nodeToCast = arguments.get(idx);
        ITypeBinding castType = paramTypes[idx];
        castType = Bindings.normalizeTypeBinding(castType);
        if (castType.isWildcardType()) {
            castType = ASTResolving.normalizeWildcardType(castType, false, nodeToCast.getAST());
        }
        if (castType != null) {
            ITypeBinding binding = nodeToCast.resolveTypeBinding();
            ITypeBinding castFixType = null;
            if (binding == null || castType.isCastCompatible(binding)) {
                castFixType = castType;
            } else if (JavaModelUtil.is50OrHigher(cu.getJavaProject())) {
                ITypeBinding boxUnboxedTypeBinding = TypeMismatchSubProcessor.boxUnboxPrimitives(castType, binding, nodeToCast.getAST());
                if (boxUnboxedTypeBinding != castType && boxUnboxedTypeBinding.isCastCompatible(binding)) {
                    castFixType = boxUnboxedTypeBinding;
                }
            }
            if (castFixType != null) {
                ASTRewriteCorrectionProposal proposal = TypeMismatchSubProcessor.createCastProposal(context, castFixType, nodeToCast, IProposalRelevance.CAST_ARGUMENT_1);
                String castTypeName = BindingLabelProvider.getBindingLabel(castFixType, JavaElementLabels.ALL_DEFAULT);
                String[] arg = new String[] { getArgumentName(arguments, idx), castTypeName };
                proposal.setDisplayName(Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_addargumentcast_description, arg));
                proposals.add(proposal);
            }
            TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, nodeToCast, castType, false, IProposalRelevance.CAST_ARGUMENT_2, proposals);
        }
    }
    if (nDiffs == 2) {
        // try to swap
        int idx1 = indexOfDiff[0];
        int idx2 = indexOfDiff[1];
        boolean canSwap = canAssign(argTypes[idx1], paramTypes[idx2]) && canAssign(argTypes[idx2], paramTypes[idx1]);
        if (canSwap) {
            Expression arg1 = arguments.get(idx1);
            Expression arg2 = arguments.get(idx2);
            ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
            rewrite.replace(arg1, rewrite.createCopyTarget(arg2), null);
            rewrite.replace(arg2, rewrite.createCopyTarget(arg1), null);
            {
                String[] arg = new String[] { getArgumentName(arguments, idx1), getArgumentName(arguments, idx2) };
                String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_swaparguments_description, arg);
                Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
                ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.SWAP_ARGUMENTS, image);
                proposals.add(proposal);
            }
            if (declaringTypeDecl.isFromSource()) {
                ICompilationUnit targetCU = ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringTypeDecl);
                if (targetCU != null) {
                    ChangeDescription[] changeDesc = new ChangeDescription[paramTypes.length];
                    for (int i = 0; i < nDiffs; i++) {
                        changeDesc[idx1] = new SwapDescription(idx2);
                    }
                    IMethodBinding methodDecl = methodBinding.getMethodDeclaration();
                    ITypeBinding[] declParamTypes = methodDecl.getParameterTypes();
                    ITypeBinding[] swappedTypes = new ITypeBinding[] { declParamTypes[idx1], declParamTypes[idx2] };
                    String[] args = new String[] { ASTResolving.getMethodSignature(methodDecl), getTypeNames(swappedTypes) };
                    String label;
                    if (methodDecl.isConstructor()) {
                        label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_swapparams_constr_description, args);
                    } else {
                        label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_swapparams_description, args);
                    }
                    Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
                    ChangeMethodSignatureProposal proposal = new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodDecl, changeDesc, null, IProposalRelevance.CHANGE_METHOD_SWAP_PARAMETERS, image);
                    proposals.add(proposal);
                }
            }
            return;
        }
    }
    if (declaringTypeDecl.isFromSource()) {
        ICompilationUnit targetCU = ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringTypeDecl);
        if (targetCU != null) {
            ChangeDescription[] changeDesc = createSignatureChangeDescription(indexOfDiff, nDiffs, paramTypes, arguments, argTypes);
            if (changeDesc != null) {
                IMethodBinding methodDecl = methodBinding.getMethodDeclaration();
                ITypeBinding[] declParamTypes = methodDecl.getParameterTypes();
                ITypeBinding[] newParamTypes = new ITypeBinding[changeDesc.length];
                for (int i = 0; i < newParamTypes.length; i++) {
                    newParamTypes[i] = changeDesc[i] == null ? declParamTypes[i] : ((EditDescription) changeDesc[i]).type;
                }
                boolean isVarArgs = methodDecl.isVarargs() && newParamTypes.length > 0 && newParamTypes[newParamTypes.length - 1].isArray();
                String[] args = new String[] { ASTResolving.getMethodSignature(methodDecl), ASTResolving.getMethodSignature(methodDecl.getName(), newParamTypes, isVarArgs) };
                String label;
                if (methodDecl.isConstructor()) {
                    label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changeparamsignature_constr_description, args);
                } else {
                    label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changeparamsignature_description, args);
                }
                Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
                ChangeMethodSignatureProposal proposal = new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodDecl, changeDesc, null, IProposalRelevance.CHANGE_METHOD_SIGNATURE, image);
                proposals.add(proposal);
            }
        }
    }
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ChangeMethodSignatureProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposal) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) Image(org.eclipse.swt.graphics.Image) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) SwapDescription(org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposal.SwapDescription) EditDescription(org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposal.EditDescription) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) Expression(org.eclipse.jdt.core.dom.Expression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ChangeDescription(org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposal.ChangeDescription) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 3 with MethodInvocation

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

the class UnresolvedElementsSubProcessor method getArrayAccessProposals.

public static void getArrayAccessProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    CompilationUnit root = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(root);
    if (!(selectedNode instanceof MethodInvocation)) {
        return;
    }
    MethodInvocation decl = (MethodInvocation) selectedNode;
    SimpleName nameNode = decl.getName();
    String methodName = nameNode.getIdentifier();
    IBinding[] bindings = (new ScopeAnalyzer(root)).getDeclarationsInScope(nameNode, ScopeAnalyzer.METHODS);
    for (int i = 0; i < bindings.length; i++) {
        String currName = bindings[i].getName();
        if (NameMatcher.isSimilarName(methodName, currName)) {
            String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_arraychangetomethod_description, BasicElementLabels.getJavaElementName(currName));
            proposals.add(new RenameNodeCorrectionProposal(label, context.getCompilationUnit(), nameNode.getStartPosition(), nameNode.getLength(), currName, IProposalRelevance.ARRAY_CHANGE_TO_METHOD));
        }
    }
    // always suggest 'length'
    //$NON-NLS-1$
    String lengthId = "length";
    String label = CorrectionMessages.UnresolvedElementsSubProcessor_arraychangetolength_description;
    int offset = nameNode.getStartPosition();
    int length = decl.getStartPosition() + decl.getLength() - offset;
    proposals.add(new RenameNodeCorrectionProposal(label, context.getCompilationUnit(), offset, length, lengthId, IProposalRelevance.ARRAY_CHANGE_TO_LENGTH));
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) RenameNodeCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.RenameNodeCorrectionProposal) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IBinding(org.eclipse.jdt.core.dom.IBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ScopeAnalyzer(org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation)

Example 4 with MethodInvocation

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

the class GenerateForLoopAssistProposal method getIndexBasedForBodyAssignment.

/**
	 * Creates an {@link Assignment} as first expression appearing in an index based
	 * <code>for</code> loop's body. This Assignment declares a local variable and initializes it
	 * using the {@link List}'s current element identified by the loop index.
	 * 
	 * @param rewrite the current {@link ASTRewrite} instance
	 * @param loopVariableName the name of the index variable in String representation
	 * @return a completed {@link Assignment} containing the mentioned declaration and
	 *         initialization
	 */
private Expression getIndexBasedForBodyAssignment(ASTRewrite rewrite, SimpleName loopVariableName) {
    AST ast = rewrite.getAST();
    ITypeBinding loopOverType = extractElementType(ast);
    Assignment assignResolvedVariable = ast.newAssignment();
    // left hand side
    SimpleName resolvedVariableName = resolveLinkedVariableNameWithProposals(rewrite, loopOverType.getName(), loopVariableName.getIdentifier(), false);
    VariableDeclarationFragment resolvedVariableDeclarationFragment = ast.newVariableDeclarationFragment();
    resolvedVariableDeclarationFragment.setName(resolvedVariableName);
    VariableDeclarationExpression resolvedVariableDeclaration = ast.newVariableDeclarationExpression(resolvedVariableDeclarationFragment);
    resolvedVariableDeclaration.setType(getImportRewrite().addImport(loopOverType, ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite())));
    assignResolvedVariable.setLeftHandSide(resolvedVariableDeclaration);
    // right hand side
    MethodInvocation invokeGetExpression = ast.newMethodInvocation();
    //$NON-NLS-1$
    invokeGetExpression.setName(ast.newSimpleName("get"));
    SimpleName indexVariableName = ast.newSimpleName(loopVariableName.getIdentifier());
    addLinkedPosition(rewrite.track(indexVariableName), LinkedPositionGroup.NO_STOP, indexVariableName.getIdentifier());
    invokeGetExpression.arguments().add(indexVariableName);
    invokeGetExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));
    assignResolvedVariable.setRightHandSide(invokeGetExpression);
    assignResolvedVariable.setOperator(Assignment.Operator.ASSIGN);
    return assignResolvedVariable;
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) AST(org.eclipse.jdt.core.dom.AST) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation)

Example 5 with MethodInvocation

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

the class NewMethodCorrectionProposal method evaluateModifiers.

private int evaluateModifiers(ASTNode targetTypeDecl) {
    if (getSenderBinding().isAnnotation()) {
        return 0;
    }
    if (getSenderBinding().isInterface()) {
        // for interface and annotation members copy the modifiers from an existing field
        MethodDeclaration[] methodDecls = ((TypeDeclaration) targetTypeDecl).getMethods();
        if (methodDecls.length > 0) {
            return methodDecls[0].getModifiers();
        }
        return 0;
    }
    ASTNode invocationNode = getInvocationNode();
    if (invocationNode instanceof MethodInvocation) {
        int modifiers = 0;
        Expression expression = ((MethodInvocation) invocationNode).getExpression();
        if (expression != null) {
            if (expression instanceof Name && ((Name) expression).resolveBinding().getKind() == IBinding.TYPE) {
                modifiers |= Modifier.STATIC;
            }
        } else if (ASTResolving.isInStaticContext(invocationNode)) {
            modifiers |= Modifier.STATIC;
        }
        ASTNode node = ASTResolving.findParentType(invocationNode);
        if (targetTypeDecl.equals(node)) {
            modifiers |= Modifier.PRIVATE;
        } else if (node instanceof AnonymousClassDeclaration && ASTNodes.isParent(node, targetTypeDecl)) {
            modifiers |= Modifier.PROTECTED;
            if (ASTResolving.isInStaticContext(node) && expression == null) {
                modifiers |= Modifier.STATIC;
            }
        } else {
            modifiers |= Modifier.PUBLIC;
        }
        return modifiers;
    }
    return Modifier.PUBLIC;
}
Also used : Expression(org.eclipse.jdt.core.dom.Expression) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) AnonymousClassDeclaration(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name)

Aggregations

MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)266 Expression (org.eclipse.jdt.core.dom.Expression)112 SuperMethodInvocation (org.eclipse.jdt.core.dom.SuperMethodInvocation)59 ASTNode (org.eclipse.jdt.core.dom.ASTNode)53 SimpleName (org.eclipse.jdt.core.dom.SimpleName)53 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)51 ASTRewrite (org.autorefactor.jdt.core.dom.ASTRewrite)48 ASTNodeFactory (org.autorefactor.jdt.internal.corext.dom.ASTNodeFactory)47 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)43 ArrayList (java.util.ArrayList)41 CastExpression (org.eclipse.jdt.core.dom.CastExpression)40 TextEditGroup (org.eclipse.text.edits.TextEditGroup)37 Block (org.eclipse.jdt.core.dom.Block)34 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)34 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)33 ClassInstanceCreation (org.eclipse.jdt.core.dom.ClassInstanceCreation)32 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)31 AST (org.eclipse.jdt.core.dom.AST)30 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)29 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)28