Search in sources :

Example 31 with ASTNode

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

the class ChangeMethodSignatureProposal method modifyExceptions.

private void modifyExceptions(ASTRewrite rewrite, MethodDeclaration methodDecl) {
    AST ast = methodDecl.getAST();
    ImportRewrite imports = getImportRewrite();
    ImportRewriteContext context = new ContextSensitiveImportRewriteContext(methodDecl, imports);
    ListRewrite listRewrite = rewrite.getListRewrite(methodDecl, MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY);
    // old exceptions
    List<Type> exceptions = methodDecl.thrownExceptionTypes();
    // index over the old exceptions
    int k = 0;
    for (int i = 0; i < fExceptionChanges.length; i++) {
        ChangeDescription curr = fExceptionChanges[i];
        if (curr == null) {
            k++;
        } else if (curr instanceof InsertDescription) {
            InsertDescription desc = (InsertDescription) curr;
            String type = imports.addImport(desc.type, context);
            ASTNode newNode = imports.addImport(desc.type, ast, context);
            listRewrite.insertAt(newNode, i, null);
            String key = getExceptionTypeGroupId(i);
            addLinkedPosition(rewrite.track(newNode), false, key);
            Javadoc javadoc = methodDecl.getJavadoc();
            if (javadoc != null && JavadocTagsSubProcessor.findThrowsTag(javadoc, type) == null) {
                TagElement newTagElement = ast.newTagElement();
                newTagElement.setTagName(TagElement.TAG_THROWS);
                ASTNode newRef = ASTNodeFactory.newName(ast, type);
                newTagElement.fragments().add(newRef);
                //$NON-NLS-1$
                insertTabStop(rewrite, newTagElement.fragments(), "throws_tagcomment" + i);
                insertThrowsTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), exceptions, k, newTagElement);
                addLinkedPosition(rewrite.track(newRef), false, key);
            }
        } else if (curr instanceof RemoveDescription) {
            Type node = exceptions.get(k);
            listRewrite.remove(node, null);
            k++;
            TagElement tagNode = findThrowsTag(methodDecl, node);
            if (tagNode != null) {
                rewrite.remove(tagNode, null);
            }
        } else if (curr instanceof EditDescription) {
            EditDescription desc = (EditDescription) curr;
            Type oldNode = exceptions.get(k);
            String type = imports.addImport(desc.type, context);
            ASTNode newNode = imports.addImport(desc.type, ast, context);
            listRewrite.replace(oldNode, newNode, null);
            String key = getExceptionTypeGroupId(i);
            addLinkedPosition(rewrite.track(newNode), false, key);
            k++;
            TagElement tagNode = findThrowsTag(methodDecl, oldNode);
            if (tagNode != null) {
                ASTNode newRef = ASTNodeFactory.newType(ast, type);
                rewrite.replace((ASTNode) tagNode.fragments().get(0), newRef, null);
                addLinkedPosition(rewrite.track(newRef), false, key);
            }
        } else if (curr instanceof SwapDescription) {
            Type decl1 = exceptions.get(k);
            Type decl2 = exceptions.get(((SwapDescription) curr).index);
            rewrite.replace(decl1, rewrite.createCopyTarget(decl2), null);
            rewrite.replace(decl2, rewrite.createCopyTarget(decl1), null);
            k++;
            TagElement tagNode1 = findThrowsTag(methodDecl, decl1);
            TagElement tagNode2 = findThrowsTag(methodDecl, decl2);
            if (tagNode1 != null && tagNode2 != null) {
                rewrite.replace(tagNode1, rewrite.createCopyTarget(tagNode2), null);
                rewrite.replace(tagNode2, rewrite.createCopyTarget(tagNode1), null);
            }
        }
    }
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) Javadoc(org.eclipse.jdt.core.dom.Javadoc) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ASTNode(org.eclipse.jdt.core.dom.ASTNode) TagElement(org.eclipse.jdt.core.dom.TagElement)

Example 32 with ASTNode

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

the class ChangeMethodSignatureProposal method getRewrite.

@Override
protected ASTRewrite getRewrite() throws CoreException {
    CompilationUnit astRoot = (CompilationUnit) fInvocationNode.getRoot();
    ASTNode methodDecl = astRoot.findDeclaringNode(fSenderBinding);
    ASTNode newMethodDecl = null;
    if (methodDecl != null) {
        newMethodDecl = methodDecl;
    } else {
        astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
        newMethodDecl = astRoot.findDeclaringNode(fSenderBinding.getKey());
    }
    createImportRewrite(astRoot);
    if (newMethodDecl instanceof MethodDeclaration) {
        MethodDeclaration decl = (MethodDeclaration) newMethodDecl;
        ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
        if (fParameterChanges != null) {
            modifyParameters(rewrite, decl);
        }
        if (fExceptionChanges != null) {
            modifyExceptions(rewrite, decl);
        }
        return rewrite;
    }
    return null;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 33 with ASTNode

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

the class ConstructorFromSuperclassProposal method createNewMethodDeclaration.

private MethodDeclaration createNewMethodDeclaration(AST ast, IMethodBinding binding, ASTRewrite rewrite, ImportRewriteContext importRewriteContext, CodeGenerationSettings commentSettings) throws CoreException {
    String name = fTypeNode.getName().getIdentifier();
    MethodDeclaration decl = ast.newMethodDeclaration();
    decl.setConstructor(true);
    decl.setName(ast.newSimpleName(name));
    Block body = ast.newBlock();
    decl.setBody(body);
    SuperConstructorInvocation invocation = null;
    List<SingleVariableDeclaration> parameters = decl.parameters();
    String[] paramNames = getArgumentNames(binding);
    ITypeBinding enclosingInstance = getEnclosingInstance();
    if (enclosingInstance != null) {
        invocation = addEnclosingInstanceAccess(rewrite, importRewriteContext, parameters, paramNames, enclosingInstance);
    }
    if (binding == null) {
        decl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    } else {
        decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, binding.getModifiers()));
        ITypeBinding[] params = binding.getParameterTypes();
        for (int i = 0; i < params.length; i++) {
            SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
            var.setType(getImportRewrite().addImport(params[i], ast, importRewriteContext));
            var.setName(ast.newSimpleName(paramNames[i]));
            parameters.add(var);
        }
        List<Type> thrownExceptions = decl.thrownExceptionTypes();
        ITypeBinding[] excTypes = binding.getExceptionTypes();
        for (int i = 0; i < excTypes.length; i++) {
            Type excType = getImportRewrite().addImport(excTypes[i], ast, importRewriteContext);
            thrownExceptions.add(excType);
        }
        if (invocation == null) {
            invocation = ast.newSuperConstructorInvocation();
        }
        List<Expression> arguments = invocation.arguments();
        for (int i = 0; i < paramNames.length; i++) {
            Name argument = ast.newSimpleName(paramNames[i]);
            arguments.add(argument);
            //$NON-NLS-1$
            addLinkedPosition(rewrite.track(argument), false, "arg_name_" + paramNames[i]);
        }
    }
    String bodyStatement = (invocation == null) ? "" : ASTNodes.asFormattedString(invocation, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true));
    //$NON-NLS-1$
    String placeHolder = CodeGeneration.getMethodBodyContent(getCompilationUnit(), name, name, true, bodyStatement, String.valueOf('\n'));
    if (placeHolder != null) {
        ASTNode todoNode = rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
        body.statements().add(todoNode);
    }
    if (commentSettings != null) {
        String string = CodeGeneration.getMethodComment(getCompilationUnit(), name, decl, null, String.valueOf('\n'));
        if (string != null) {
            Javadoc javadoc = (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
            decl.setJavadoc(javadoc);
        }
    }
    return decl;
}
Also used : MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) Javadoc(org.eclipse.jdt.core.dom.Javadoc) Name(org.eclipse.jdt.core.dom.Name) Type(org.eclipse.jdt.core.dom.Type) Expression(org.eclipse.jdt.core.dom.Expression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block) SuperConstructorInvocation(org.eclipse.jdt.core.dom.SuperConstructorInvocation)

Example 34 with ASTNode

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

the class UnresolvedElementsSubProcessor method getAnnotationMemberProposals.

public static void getAnnotationMemberProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException {
    CompilationUnit astRoot = context.getASTRoot();
    ICompilationUnit cu = context.getCompilationUnit();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    Annotation annotation;
    String memberName;
    if (selectedNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) {
        if (selectedNode.getParent().getLocationInParent() != NormalAnnotation.VALUES_PROPERTY) {
            return;
        }
        annotation = (Annotation) selectedNode.getParent().getParent();
        memberName = ((SimpleName) selectedNode).getIdentifier();
    } else if (selectedNode.getLocationInParent() == SingleMemberAnnotation.VALUE_PROPERTY) {
        annotation = (Annotation) selectedNode.getParent();
        //$NON-NLS-1$
        memberName = "value";
    } else {
        return;
    }
    ITypeBinding annotBinding = annotation.resolveTypeBinding();
    if (annotBinding == null) {
        return;
    }
    if (annotation instanceof NormalAnnotation) {
        // similar names
        IMethodBinding[] otherMembers = annotBinding.getDeclaredMethods();
        for (int i = 0; i < otherMembers.length; i++) {
            IMethodBinding binding = otherMembers[i];
            String curr = binding.getName();
            int relevance = NameMatcher.isSimilarName(memberName, curr) ? IProposalRelevance.CHANGE_TO_ATTRIBUTE_SIMILAR_NAME : IProposalRelevance.CHANGE_TO_ATTRIBUTE;
            String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_UnresolvedElementsSubProcessor_changetoattribute_description, BasicElementLabels.getJavaElementName(curr));
            proposals.add(new RenameNodeCorrectionProposal(label, cu, problem.getOffset(), problem.getLength(), curr, relevance));
        }
    }
    if (annotBinding.isFromSource()) {
        ICompilationUnit targetCU = ASTResolving.findCompilationUnitForBinding(cu, astRoot, annotBinding);
        if (targetCU != null) {
            String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_UnresolvedElementsSubProcessor_createattribute_description, BasicElementLabels.getJavaElementName(memberName));
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
            proposals.add(new NewAnnotationMemberProposal(label, targetCU, selectedNode, annotBinding, IProposalRelevance.CREATE_ATTRIBUTE, image));
        }
    }
}
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) Image(org.eclipse.swt.graphics.Image) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation) SingleMemberAnnotation(org.eclipse.jdt.core.dom.SingleMemberAnnotation) Annotation(org.eclipse.jdt.core.dom.Annotation) RenameNodeCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.RenameNodeCorrectionProposal) NewAnnotationMemberProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.NewAnnotationMemberProposal) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation)

Example 35 with ASTNode

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

Aggregations

ASTNode (org.eclipse.jdt.core.dom.ASTNode)710 SimpleName (org.eclipse.jdt.core.dom.SimpleName)151 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)148 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)147 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)134 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)126 Expression (org.eclipse.jdt.core.dom.Expression)125 ArrayList (java.util.ArrayList)111 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)108 AST (org.eclipse.jdt.core.dom.AST)106 Type (org.eclipse.jdt.core.dom.Type)92 Block (org.eclipse.jdt.core.dom.Block)89 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)77 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)73 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)67 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)66 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)65 CastExpression (org.eclipse.jdt.core.dom.CastExpression)64 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)62 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)60