Search in sources :

Example 31 with BodyDeclaration

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

the class AbstractMethodCorrectionProposal method getRewrite.

@Override
protected ASTRewrite getRewrite() throws CoreException {
    CompilationUnit astRoot = ASTResolving.findParentCompilationUnit(fNode);
    ASTNode typeDecl = astRoot.findDeclaringNode(fSenderBinding);
    ASTNode newTypeDecl = null;
    boolean isInDifferentCU;
    if (typeDecl != null) {
        isInDifferentCU = false;
        newTypeDecl = typeDecl;
    } else {
        isInDifferentCU = true;
        astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
        newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey());
    }
    createImportRewrite(astRoot);
    if (newTypeDecl != null) {
        ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
        MethodDeclaration newStub = getStub(rewrite, newTypeDecl);
        ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
        List<BodyDeclaration> members = ASTNodes.getBodyDeclarations(newTypeDecl);
        int insertIndex;
        if (isConstructor()) {
            insertIndex = findConstructorInsertIndex(members);
        } else if (!isInDifferentCU) {
            insertIndex = findMethodInsertIndex(members, fNode.getStartPosition());
        } else {
            insertIndex = members.size();
        }
        ListRewrite listRewriter = rewrite.getListRewrite(newTypeDecl, property);
        listRewriter.insertAt(newStub, insertIndex, null);
        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) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor)

Example 32 with BodyDeclaration

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

the class QuickAssistProcessor method getCatchClauseToThrowsProposals.

public static boolean getCatchClauseToThrowsProposals(IInvocationContext context, ASTNode node, Collection<CUCorrectionProposal> resultingCollections) {
    if (resultingCollections == null) {
        return true;
    }
    CatchClause catchClause = (CatchClause) ASTResolving.findAncestor(node, ASTNode.CATCH_CLAUSE);
    if (catchClause == null) {
        return false;
    }
    Statement statement = ASTResolving.findParentStatement(node);
    if (statement != catchClause.getParent() && statement != catchClause.getBody()) {
        // selection is in a statement inside the body
        return false;
    }
    Type type = catchClause.getException().getType();
    if (!type.isSimpleType() && !type.isUnionType() && !type.isNameQualifiedType()) {
        return false;
    }
    BodyDeclaration bodyDeclaration = ASTResolving.findParentBodyDeclaration(catchClause);
    if (!(bodyDeclaration instanceof MethodDeclaration) && !(bodyDeclaration instanceof Initializer)) {
        return false;
    }
    AST ast = bodyDeclaration.getAST();
    Type selectedMultiCatchType = null;
    if (type.isUnionType() && node instanceof Name) {
        Name topMostName = ASTNodes.getTopMostName((Name) node);
        ASTNode parent = topMostName.getParent();
        if (parent instanceof SimpleType) {
            selectedMultiCatchType = (SimpleType) parent;
        } else if (parent instanceof NameQualifiedType) {
            selectedMultiCatchType = (NameQualifiedType) parent;
        }
    }
    if (bodyDeclaration instanceof MethodDeclaration) {
        MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration;
        ASTRewrite rewrite = ASTRewrite.create(ast);
        if (selectedMultiCatchType != null) {
            removeException(rewrite, (UnionType) type, selectedMultiCatchType);
            addExceptionToThrows(ast, methodDeclaration, rewrite, selectedMultiCatchType);
            String label = CorrectionMessages.QuickAssistProcessor_exceptiontothrows_description;
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_EXCEPTION_WITH_THROWS);
            resultingCollections.add(proposal);
        } else {
            removeCatchBlock(rewrite, catchClause);
            if (type.isUnionType()) {
                UnionType unionType = (UnionType) type;
                List<Type> types = unionType.types();
                for (Type elementType : types) {
                    if (!(elementType instanceof SimpleType || elementType instanceof NameQualifiedType)) {
                        return false;
                    }
                    addExceptionToThrows(ast, methodDeclaration, rewrite, elementType);
                }
            } else {
                addExceptionToThrows(ast, methodDeclaration, rewrite, type);
            }
            String label = CorrectionMessages.QuickAssistProcessor_catchclausetothrows_description;
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_CATCH_CLAUSE_WITH_THROWS);
            resultingCollections.add(proposal);
        }
    }
    {
        // for initializers or method declarations
        ASTRewrite rewrite = ASTRewrite.create(ast);
        if (selectedMultiCatchType != null) {
            removeException(rewrite, (UnionType) type, selectedMultiCatchType);
            String label = CorrectionMessages.QuickAssistProcessor_removeexception_description;
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_EXCEPTION);
            resultingCollections.add(proposal);
        } else {
            removeCatchBlock(rewrite, catchClause);
            String label = CorrectionMessages.QuickAssistProcessor_removecatchclause_description;
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_CATCH_CLAUSE);
            resultingCollections.add(proposal);
        }
    }
    return true;
}
Also used : UnionType(org.eclipse.jdt.core.dom.UnionType) AST(org.eclipse.jdt.core.dom.AST) Statement(org.eclipse.jdt.core.dom.Statement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) CatchClause(org.eclipse.jdt.core.dom.CatchClause) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) ASTRewriteCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteCorrectionProposal) SimpleType(org.eclipse.jdt.core.dom.SimpleType) 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) Initializer(org.eclipse.jdt.core.dom.Initializer) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType)

Example 33 with BodyDeclaration

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

the class ExtractConstantRefactoring method getReplacementScope.

/*
	 * Elements returned by next() are BodyDeclaration or Annotation instances.
	 */
private Iterator<ASTNode> getReplacementScope() throws JavaModelException {
    boolean declPredecessorReached = false;
    Collection<ASTNode> scope = new ArrayList<>();
    AbstractTypeDeclaration containingType = getContainingTypeDeclarationNode();
    if (containingType instanceof EnumDeclaration) {
        // replace in all enum constants bodies
        EnumDeclaration enumDeclaration = (EnumDeclaration) containingType;
        scope.addAll(enumDeclaration.enumConstants());
    }
    for (Iterator<IExtendedModifier> iter = containingType.modifiers().iterator(); iter.hasNext(); ) {
        IExtendedModifier modifier = iter.next();
        if (modifier instanceof Annotation) {
            scope.add((ASTNode) modifier);
        }
    }
    for (Iterator<BodyDeclaration> bodyDeclarations = containingType.bodyDeclarations().iterator(); bodyDeclarations.hasNext(); ) {
        BodyDeclaration bodyDeclaration = bodyDeclarations.next();
        if (bodyDeclaration == getNodeToInsertConstantDeclarationAfter()) {
            declPredecessorReached = true;
        }
        if (insertFirst() || declPredecessorReached || !isStaticFieldOrStaticInitializer(bodyDeclaration)) {
            scope.add(bodyDeclaration);
        }
    }
    return scope.iterator();
}
Also used : ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayList(java.util.ArrayList) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) Annotation(org.eclipse.jdt.core.dom.Annotation) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) EnumDeclaration(org.eclipse.jdt.core.dom.EnumDeclaration) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier)

Example 34 with BodyDeclaration

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

the class ExtractMethodRefactoring method initializeDestinations.

private void initializeDestinations() {
    List<ASTNode> result = new ArrayList<>();
    BodyDeclaration decl = fAnalyzer.getEnclosingBodyDeclaration();
    ASTNode current = ASTResolving.findParentType(decl.getParent());
    if (fAnalyzer.isValidDestination(current)) {
        result.add(current);
    }
    if (current != null && (decl instanceof MethodDeclaration || decl instanceof Initializer || decl instanceof FieldDeclaration)) {
        ITypeBinding binding = ASTNodes.getEnclosingType(current);
        ASTNode next = ASTResolving.findParentType(current.getParent());
        while (next != null && binding != null && binding.isNested()) {
            if (fAnalyzer.isValidDestination(next)) {
                result.add(next);
            }
            current = next;
            binding = ASTNodes.getEnclosingType(current);
            next = ASTResolving.findParentType(next.getParent());
        }
    }
    fDestinations = result.toArray(new ASTNode[result.size()]);
    fDestination = fDestinations[fDestinationIndex];
}
Also used : Initializer(org.eclipse.jdt.core.dom.Initializer) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayList(java.util.ArrayList) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration)

Example 35 with BodyDeclaration

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

the class ExtractMethodRefactoring method createChange.

@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
    if (fMethodName == null) {
        return null;
    }
    // $NON-NLS-1$
    pm.beginTask("", 2);
    try {
        fAnalyzer.aboutToCreateChange();
        BodyDeclaration declaration = fAnalyzer.getEnclosingBodyDeclaration();
        fRewriter = ASTRewrite.create(declaration.getAST());
        final CompilationUnitChange result = new CompilationUnitChange(RefactoringCoreMessages.ExtractMethodRefactoring_change_name, fCUnit);
        result.setSaveMode(TextFileChange.KEEP_SAVE_STATE);
        result.setDescriptor(new RefactoringChangeDescriptor(getRefactoringDescriptor()));
        MultiTextEdit root = new MultiTextEdit();
        result.setEdit(root);
        ASTNode[] selectedNodes = fAnalyzer.getSelectedNodes();
        fRewriter.setTargetSourceRangeComputer(new SelectionAwareSourceRangeComputer(selectedNodes, fCUnit.getBuffer(), fSelectionStart, fSelectionLength));
        TextEditGroup substituteDesc = new TextEditGroup(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_substitute_with_call, BasicElementLabels.getJavaElementName(fMethodName)));
        result.addTextEditGroup(substituteDesc);
        MethodDeclaration mm = createNewMethod(selectedNodes, fCUnit.findRecommendedLineSeparator(), substituteDesc);
        if (fLinkedProposalModel != null) {
            LinkedProposalPositionGroup typeGroup = fLinkedProposalModel.getPositionGroup(KEY_TYPE, true);
            typeGroup.addPosition(fRewriter.track(mm.getReturnType2()), false);
            ITypeBinding typeBinding = fAnalyzer.getReturnTypeBinding();
            if (typeBinding != null) {
                ITypeBinding[] relaxingTypes = ASTResolving.getNarrowingTypes(fAST, typeBinding);
                for (int i = 0; i < relaxingTypes.length; i++) {
                    typeGroup.addProposal(relaxingTypes[i], fCUnit, relaxingTypes.length - i);
                }
            }
            LinkedProposalPositionGroup nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
            nameGroup.addPosition(fRewriter.track(mm.getName()), false);
            ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(fLinkedProposalModel, fRewriter, mm.modifiers(), false);
        }
        TextEditGroup insertDesc = new TextEditGroup(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_add_method, BasicElementLabels.getJavaElementName(fMethodName)));
        result.addTextEditGroup(insertDesc);
        if (fDestination == ASTResolving.findParentType(declaration.getParent())) {
            ChildListPropertyDescriptor desc = (ChildListPropertyDescriptor) declaration.getLocationInParent();
            ListRewrite container = fRewriter.getListRewrite(declaration.getParent(), desc);
            container.insertAfter(mm, declaration, insertDesc);
        } else {
            BodyDeclarationRewrite container = BodyDeclarationRewrite.create(fRewriter, fDestination);
            container.insert(mm, insertDesc);
        }
        replaceDuplicates(result, mm.getModifiers());
        replaceBranches(result);
        if (fImportRewriter.hasRecordedChanges()) {
            TextEdit edit = fImportRewriter.rewriteImports(null);
            root.addChild(edit);
            result.addTextEditGroup(new TextEditGroup(RefactoringCoreMessages.ExtractMethodRefactoring_organize_imports, new TextEdit[] { edit }));
        }
        root.addChild(fRewriter.rewriteAST());
        return result;
    } finally {
        pm.done();
    }
}
Also used : SelectionAwareSourceRangeComputer(org.eclipse.jdt.ls.core.internal.corext.refactoring.util.SelectionAwareSourceRangeComputer) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) RefactoringChangeDescriptor(org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) BodyDeclarationRewrite(org.eclipse.jdt.ls.core.internal.corext.dom.BodyDeclarationRewrite) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) TextEditGroup(org.eclipse.text.edits.TextEditGroup) LinkedProposalPositionGroup(org.eclipse.jdt.ls.core.internal.corext.fix.LinkedProposalPositionGroup) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) CompilationUnitChange(org.eclipse.jdt.core.refactoring.CompilationUnitChange)

Aggregations

BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)98 ASTNode (org.eclipse.jdt.core.dom.ASTNode)61 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)53 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)28 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)27 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)26 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)26 Type (org.eclipse.jdt.core.dom.Type)25 AST (org.eclipse.jdt.core.dom.AST)23 FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)18 ImportRewrite (org.eclipse.jdt.core.dom.rewrite.ImportRewrite)17 Expression (org.eclipse.jdt.core.dom.Expression)16 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)15 Initializer (org.eclipse.jdt.core.dom.Initializer)15 SimpleName (org.eclipse.jdt.core.dom.SimpleName)15 TypeDeclaration (org.eclipse.jdt.core.dom.TypeDeclaration)15 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)14 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)14 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)13 ArrayList (java.util.ArrayList)12