Search in sources :

Example 1 with QualifiedName

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

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

the class SimilarElementsRequestor method findSimilarElement.

public static SimilarElement[] findSimilarElement(ICompilationUnit cu, Name name, int kind) throws JavaModelException {
    int pos = name.getStartPosition();
    int nArguments = -1;
    String identifier = ASTNodes.getSimpleNameIdentifier(name);
    String returnType = null;
    ICompilationUnit preparedCU = null;
    try {
        if (name.isQualifiedName()) {
            pos = ((QualifiedName) name).getName().getStartPosition();
        } else {
            // first letter must be included, other
            pos = name.getStartPosition() + 1;
        }
        Javadoc javadoc = (Javadoc) ASTNodes.getParent(name, ASTNode.JAVADOC);
        if (javadoc != null) {
            preparedCU = createPreparedCU(cu, javadoc, name.getStartPosition());
            cu = preparedCU;
        }
        SimilarElementsRequestor requestor = new SimilarElementsRequestor(identifier, kind, nArguments, returnType);
        requestor.setIgnored(CompletionProposal.ANONYMOUS_CLASS_DECLARATION, true);
        requestor.setIgnored(CompletionProposal.ANONYMOUS_CLASS_CONSTRUCTOR_INVOCATION, true);
        requestor.setIgnored(CompletionProposal.KEYWORD, true);
        requestor.setIgnored(CompletionProposal.LABEL_REF, true);
        requestor.setIgnored(CompletionProposal.METHOD_DECLARATION, true);
        requestor.setIgnored(CompletionProposal.PACKAGE_REF, true);
        requestor.setIgnored(CompletionProposal.VARIABLE_DECLARATION, true);
        requestor.setIgnored(CompletionProposal.METHOD_REF, true);
        requestor.setIgnored(CompletionProposal.CONSTRUCTOR_INVOCATION, true);
        requestor.setIgnored(CompletionProposal.METHOD_REF_WITH_CASTED_RECEIVER, true);
        requestor.setIgnored(CompletionProposal.FIELD_REF, true);
        requestor.setIgnored(CompletionProposal.FIELD_REF_WITH_CASTED_RECEIVER, true);
        requestor.setIgnored(CompletionProposal.LOCAL_VARIABLE_REF, true);
        requestor.setIgnored(CompletionProposal.VARIABLE_DECLARATION, true);
        requestor.setIgnored(CompletionProposal.VARIABLE_DECLARATION, true);
        requestor.setIgnored(CompletionProposal.POTENTIAL_METHOD_DECLARATION, true);
        requestor.setIgnored(CompletionProposal.METHOD_NAME_REFERENCE, true);
        return requestor.process(cu, pos);
    } finally {
        if (preparedCU != null) {
            preparedCU.discardWorkingCopy();
        }
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Javadoc(org.eclipse.jdt.core.dom.Javadoc)

Example 3 with QualifiedName

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

the class ExtractToNullCheckedLocalProposal method getRewrite.

@Override
protected ASTRewrite getRewrite() throws CoreException {
    // infrastructure:
    AST ast = this.compilationUnit.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    ImportRewrite imports = ImportRewrite.create(this.compilationUnit, true);
    TextEditGroup group = new TextEditGroup(FixMessages.ExtractToNullCheckedLocalProposal_extractCheckedLocal_editName);
    LinkedProposalPositionGroup localNameGroup = new LinkedProposalPositionGroup(LOCAL_NAME_POSITION_GROUP);
    getLinkedProposalModel().addPositionGroup(localNameGroup);
    // AST context:
    Statement origStmt = (Statement) ASTNodes.getParent(this.fieldReference, Statement.class);
    // determine suitable strategy for rearranging elements towards a new code structure:
    RearrangeStrategy rearrangeStrategy = RearrangeStrategy.create(origStmt, rewrite, group);
    Expression toReplace;
    ASTNode directParent = this.fieldReference.getParent();
    if (directParent instanceof FieldAccess) {
        toReplace = (Expression) directParent;
    } else if (directParent instanceof QualifiedName && this.fieldReference.getLocationInParent() == QualifiedName.NAME_PROPERTY) {
        toReplace = (Expression) directParent;
    } else {
        toReplace = this.fieldReference;
    }
    // new local declaration initialized from the field reference
    VariableDeclarationFragment localFrag = ast.newVariableDeclarationFragment();
    VariableDeclarationStatement localDecl = ast.newVariableDeclarationStatement(localFrag);
    // ... type
    localDecl.setType(newType(toReplace.resolveTypeBinding(), ast, imports));
    localDecl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD));
    // ... name
    String localName = proposeLocalName(this.fieldReference, this.compilationUnit, getCompilationUnit().getJavaProject());
    localFrag.setName(ast.newSimpleName(localName));
    // ... initialization
    localFrag.setInitializer((Expression) ASTNode.copySubtree(ast, toReplace));
    rearrangeStrategy.insertLocalDecl(localDecl);
    // if statement:
    IfStatement ifStmt = ast.newIfStatement();
    // condition:
    InfixExpression nullCheck = ast.newInfixExpression();
    nullCheck.setLeftOperand(ast.newSimpleName(localName));
    nullCheck.setRightOperand(ast.newNullLiteral());
    nullCheck.setOperator(InfixExpression.Operator.NOT_EQUALS);
    ifStmt.setExpression(nullCheck);
    // then block: the original statement
    Block thenBlock = ast.newBlock();
    thenBlock.statements().add(rearrangeStrategy.createMoveTargetForOrigStmt());
    ifStmt.setThenStatement(thenBlock);
    // ... but with the field reference replaced by the new local:
    SimpleName dereferencedName = ast.newSimpleName(localName);
    rewrite.replace(toReplace, dereferencedName, group);
    // else block: a Todo comment
    Block elseBlock = ast.newBlock();
    //$NON-NLS-1$
    String elseStatement = "// TODO " + FixMessages.ExtractToNullCheckedLocalProposal_todoHandleNullDescription;
    if (origStmt instanceof ReturnStatement) {
        Type returnType = newType(((ReturnStatement) origStmt).getExpression().resolveTypeBinding(), ast, imports);
        ReturnStatement returnStatement = ast.newReturnStatement();
        returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, returnType, 0));
        elseStatement += '\n' + ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true));
    }
    EmptyStatement todoNode = (EmptyStatement) rewrite.createStringPlaceholder(elseStatement, ASTNode.EMPTY_STATEMENT);
    elseBlock.statements().add(todoNode);
    ifStmt.setElseStatement(elseBlock);
    // link all three occurrences of the new local variable:
    addLinkedPosition(rewrite.track(localFrag.getName()), true, /*first*/
    LOCAL_NAME_POSITION_GROUP);
    addLinkedPosition(rewrite.track(nullCheck.getLeftOperand()), false, LOCAL_NAME_POSITION_GROUP);
    addLinkedPosition(rewrite.track(dereferencedName), false, LOCAL_NAME_POSITION_GROUP);
    rearrangeStrategy.insertIfStatement(ifStmt, thenBlock);
    return rewrite;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) Statement(org.eclipse.jdt.core.dom.Statement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) EmptyStatement(org.eclipse.jdt.core.dom.EmptyStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) SimpleName(org.eclipse.jdt.core.dom.SimpleName) EmptyStatement(org.eclipse.jdt.core.dom.EmptyStatement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ASTNode(org.eclipse.jdt.core.dom.ASTNode) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) Block(org.eclipse.jdt.core.dom.Block) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) TextEditGroup(org.eclipse.text.edits.TextEditGroup) LinkedProposalPositionGroup(org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroup)

Example 4 with QualifiedName

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

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

the class NullAnnotationsCorrectionProcessor method findProblemFieldName.

private static SimpleName findProblemFieldName(ASTNode selectedNode, int problemID) {
    // with expected type declared @NonNull we first need to find the SimpleName inside:
    if (selectedNode instanceof FieldAccess)
        selectedNode = ((FieldAccess) selectedNode).getName();
    else if (selectedNode instanceof QualifiedName)
        selectedNode = ((QualifiedName) selectedNode).getName();
    if (selectedNode instanceof SimpleName) {
        SimpleName name = (SimpleName) selectedNode;
        if (problemID == IProblem.NullableFieldReference)
            return name;
        // not field dereference, but compatibility issue - is value a field reference?
        IBinding binding = name.resolveBinding();
        if ((binding instanceof IVariableBinding) && ((IVariableBinding) binding).isField())
            return name;
    }
    return null;
}
Also used : QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IBinding(org.eclipse.jdt.core.dom.IBinding) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding)

Aggregations

QualifiedName (org.eclipse.jdt.core.dom.QualifiedName)59 SimpleName (org.eclipse.jdt.core.dom.SimpleName)38 ASTNode (org.eclipse.jdt.core.dom.ASTNode)32 FieldAccess (org.eclipse.jdt.core.dom.FieldAccess)21 Name (org.eclipse.jdt.core.dom.Name)20 Expression (org.eclipse.jdt.core.dom.Expression)18 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)15 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)14 IBinding (org.eclipse.jdt.core.dom.IBinding)13 SimpleType (org.eclipse.jdt.core.dom.SimpleType)13 ArrayList (java.util.ArrayList)11 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)10 NameQualifiedType (org.eclipse.jdt.core.dom.NameQualifiedType)9 CastExpression (org.eclipse.jdt.core.dom.CastExpression)8 IVariableBinding (org.eclipse.jdt.core.dom.IVariableBinding)8 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)8 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)8 Type (org.eclipse.jdt.core.dom.Type)8 Assignment (org.eclipse.jdt.core.dom.Assignment)7 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)7