Search in sources :

Example 36 with ASTVisitor

use of org.eclipse.jdt.core.dom.ASTVisitor in project AutoRefactor by JnRouvignac.

the class AggregateASTVisitor method setRefactoringContext.

@Override
public void setRefactoringContext(final CompilationUnitRewrite cuRewrite) {
    this.cuRewrite = cuRewrite;
    for (ASTVisitor v : visitors) {
        ((RefactoringRule) v).setRefactoringContext(cuRewrite);
    }
    this.visitorsContributingRefactoring.clear();
}
Also used : RefactoringRule(org.autorefactor.jdt.internal.corext.dom.RefactoringRule) JavaRefactoringRule(org.autorefactor.jdt.internal.corext.dom.JavaRefactoringRule) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor)

Example 37 with ASTVisitor

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

the class ExtractMethodRefactoring method replaceBranches.

private void replaceBranches(final CompilationUnitChange result) {
    ASTNode[] selectedNodes = fAnalyzer.getSelectedNodes();
    for (int i = 0; i < selectedNodes.length; i++) {
        ASTNode astNode = selectedNodes[i];
        astNode.accept(new ASTVisitor() {

            private LinkedList<String> fOpenLoopLabels = new LinkedList<>();

            private void registerLoopLabel(Statement node) {
                String identifier;
                if (node.getParent() instanceof LabeledStatement) {
                    LabeledStatement labeledStatement = (LabeledStatement) node.getParent();
                    identifier = labeledStatement.getLabel().getIdentifier();
                } else {
                    identifier = null;
                }
                fOpenLoopLabels.add(identifier);
            }

            @Override
            public boolean visit(ForStatement node) {
                registerLoopLabel(node);
                return super.visit(node);
            }

            @Override
            public void endVisit(ForStatement node) {
                fOpenLoopLabels.removeLast();
            }

            @Override
            public boolean visit(WhileStatement node) {
                registerLoopLabel(node);
                return super.visit(node);
            }

            @Override
            public void endVisit(WhileStatement node) {
                fOpenLoopLabels.removeLast();
            }

            @Override
            public boolean visit(EnhancedForStatement node) {
                registerLoopLabel(node);
                return super.visit(node);
            }

            @Override
            public void endVisit(EnhancedForStatement node) {
                fOpenLoopLabels.removeLast();
            }

            @Override
            public boolean visit(DoStatement node) {
                registerLoopLabel(node);
                return super.visit(node);
            }

            @Override
            public void endVisit(DoStatement node) {
                fOpenLoopLabels.removeLast();
            }

            @Override
            public void endVisit(ContinueStatement node) {
                final SimpleName label = node.getLabel();
                if (fOpenLoopLabels.isEmpty() || (label != null && !fOpenLoopLabels.contains(label.getIdentifier()))) {
                    TextEditGroup description = new TextEditGroup(RefactoringCoreMessages.ExtractMethodRefactoring_replace_continue);
                    result.addTextEditGroup(description);
                    ReturnStatement rs = fAST.newReturnStatement();
                    IVariableBinding returnValue = fAnalyzer.getReturnValue();
                    if (returnValue != null) {
                        rs.setExpression(fAST.newSimpleName(getName(returnValue)));
                    }
                    fRewriter.replace(node, rs, description);
                }
            }
        });
    }
}
Also used : DoStatement(org.eclipse.jdt.core.dom.DoStatement) DoStatement(org.eclipse.jdt.core.dom.DoStatement) Statement(org.eclipse.jdt.core.dom.Statement) ContinueStatement(org.eclipse.jdt.core.dom.ContinueStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) LabeledStatement(org.eclipse.jdt.core.dom.LabeledStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) SimpleName(org.eclipse.jdt.core.dom.SimpleName) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) LinkedList(java.util.LinkedList) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) LabeledStatement(org.eclipse.jdt.core.dom.LabeledStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) TextEditGroup(org.eclipse.text.edits.TextEditGroup) ContinueStatement(org.eclipse.jdt.core.dom.ContinueStatement)

Example 38 with ASTVisitor

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

the class ExtractMethodAnalyzer method canHandleBranches.

private String canHandleBranches() {
    if (fReturnValue != null) {
        return RefactoringCoreMessages.ExtractMethodAnalyzer_branch_mismatch;
    }
    ASTNode[] selectedNodes = getSelectedNodes();
    final ASTNode lastSelectedNode = selectedNodes[selectedNodes.length - 1];
    Statement body = getParentLoopBody(lastSelectedNode.getParent());
    if (!(body instanceof Block)) {
        return RefactoringCoreMessages.ExtractMethodAnalyzer_branch_mismatch;
    }
    if (body != lastSelectedNode) {
        Block block = (Block) body;
        List<Statement> statements = block.statements();
        ASTNode lastStatementInLoop = statements.get(statements.size() - 1);
        if (lastSelectedNode != lastStatementInLoop) {
            return RefactoringCoreMessages.ExtractMethodAnalyzer_branch_mismatch;
        }
    }
    final String[] continueMatchesLoopProblem = { null };
    for (int i = 0; i < selectedNodes.length; i++) {
        final ASTNode astNode = selectedNodes[i];
        astNode.accept(new ASTVisitor() {

            ArrayList<String> fLocalLoopLabels = new ArrayList<>();

            @Override
            public boolean visit(BreakStatement node) {
                SimpleName label = node.getLabel();
                if (label != null && !fLocalLoopLabels.contains(label.getIdentifier())) {
                    // $NON-NLS-1$
                    continueMatchesLoopProblem[0] = Messages.format(RefactoringCoreMessages.ExtractMethodAnalyzer_branch_break_mismatch, new Object[] { ("break " + label.getIdentifier()) });
                }
                return false;
            }

            @Override
            public boolean visit(LabeledStatement node) {
                SimpleName label = node.getLabel();
                if (label != null) {
                    fLocalLoopLabels.add(label.getIdentifier());
                }
                return true;
            }

            @Override
            public void endVisit(ContinueStatement node) {
                SimpleName label = node.getLabel();
                if (label != null && !fLocalLoopLabels.contains(label.getIdentifier())) {
                    if (fEnclosingLoopLabel == null || !label.getIdentifier().equals(fEnclosingLoopLabel.getIdentifier())) {
                        // $NON-NLS-1$
                        continueMatchesLoopProblem[0] = Messages.format(RefactoringCoreMessages.ExtractMethodAnalyzer_branch_continue_mismatch, new Object[] { "continue " + label.getIdentifier() });
                    }
                }
            }
        });
    }
    return continueMatchesLoopProblem[0];
}
Also used : DoStatement(org.eclipse.jdt.core.dom.DoStatement) Statement(org.eclipse.jdt.core.dom.Statement) ContinueStatement(org.eclipse.jdt.core.dom.ContinueStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) BreakStatement(org.eclipse.jdt.core.dom.BreakStatement) LabeledStatement(org.eclipse.jdt.core.dom.LabeledStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayList(java.util.ArrayList) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) BreakStatement(org.eclipse.jdt.core.dom.BreakStatement) LabeledStatement(org.eclipse.jdt.core.dom.LabeledStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block) ContinueStatement(org.eclipse.jdt.core.dom.ContinueStatement)

Example 39 with ASTVisitor

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

the class RefactorProcessor method getAddStaticImportProposals.

/**
 * Create static import proposal, which converts invocations to static import.
 *
 * @param context
 *            the invocation context
 * @param node
 *            the node to work on
 * @param proposals
 *            the receiver of proposals, may be {@code null}
 * @return {@code true} if the operation could or has been performed,
 *         {@code false otherwise}
 */
private static boolean getAddStaticImportProposals(IInvocationContext context, ASTNode node, Collection<ChangeCorrectionProposal> proposals) {
    if (!(node instanceof SimpleName)) {
        return false;
    }
    final SimpleName name = (SimpleName) node;
    final IBinding binding;
    final ITypeBinding declaringClass;
    if (name.getParent() instanceof MethodInvocation) {
        MethodInvocation mi = (MethodInvocation) name.getParent();
        Expression expression = mi.getExpression();
        if (expression == null || expression.equals(name)) {
            return false;
        }
        binding = mi.resolveMethodBinding();
        if (binding == null) {
            return false;
        }
        declaringClass = ((IMethodBinding) binding).getDeclaringClass();
    } else if (name.getParent() instanceof QualifiedName) {
        QualifiedName qn = (QualifiedName) name.getParent();
        if (name.equals(qn.getQualifier()) || qn.getParent() instanceof ImportDeclaration) {
            return false;
        }
        binding = qn.resolveBinding();
        if (!(binding instanceof IVariableBinding)) {
            return false;
        }
        declaringClass = ((IVariableBinding) binding).getDeclaringClass();
    } else {
        return false;
    }
    if (!Modifier.isStatic(binding.getModifiers())) {
        // only work with static bindings
        return false;
    }
    boolean needImport = false;
    if (!isDirectlyAccessible(name, declaringClass)) {
        if (Modifier.isPrivate(declaringClass.getModifiers())) {
            return false;
        }
        needImport = true;
    }
    if (proposals == null) {
        // return early, just testing if we could do it
        return true;
    }
    try {
        ImportRewrite importRewrite = StubUtility.createImportRewrite(context.getCompilationUnit(), true);
        ASTRewrite astRewrite = ASTRewrite.create(node.getAST());
        ASTRewrite astRewriteReplaceAllOccurrences = ASTRewrite.create(node.getAST());
        ImportRemover remover = new ImportRemover(context.getCompilationUnit().getJavaProject(), context.getASTRoot());
        ImportRemover removerAllOccurences = new ImportRemover(context.getCompilationUnit().getJavaProject(), context.getASTRoot());
        MethodInvocation mi = null;
        QualifiedName qn = null;
        if (name.getParent() instanceof MethodInvocation) {
            mi = (MethodInvocation) name.getParent();
            // convert the method invocation
            astRewrite.remove(mi.getExpression(), null);
            remover.registerRemovedNode(mi.getExpression());
            removerAllOccurences.registerRemovedNode(mi.getExpression());
            mi.typeArguments().forEach(typeObject -> {
                Type type = (Type) typeObject;
                astRewrite.remove(type, null);
                remover.registerRemovedNode(type);
                removerAllOccurences.registerRemovedNode(type);
            });
        } else if (name.getParent() instanceof QualifiedName) {
            qn = (QualifiedName) name.getParent();
            // convert the field access
            astRewrite.replace(qn, ASTNodeFactory.newName(node.getAST(), name.getFullyQualifiedName()), null);
            remover.registerRemovedNode(qn);
            removerAllOccurences.registerRemovedNode(qn);
        } else {
            return false;
        }
        MethodInvocation miFinal = mi;
        name.getRoot().accept(new ASTVisitor() {

            @Override
            public boolean visit(MethodInvocation methodInvocation) {
                Expression methodInvocationExpression = methodInvocation.getExpression();
                if (methodInvocationExpression == null) {
                    return super.visit(methodInvocation);
                }
                if (methodInvocationExpression instanceof Name) {
                    String fullyQualifiedName = ((Name) methodInvocationExpression).getFullyQualifiedName();
                    if (miFinal != null && miFinal.getExpression() instanceof Name && ((Name) miFinal.getExpression()).getFullyQualifiedName().equals(fullyQualifiedName) && miFinal.getName().getIdentifier().equals(methodInvocation.getName().getIdentifier())) {
                        methodInvocation.typeArguments().forEach(type -> {
                            astRewriteReplaceAllOccurrences.remove((Type) type, null);
                            removerAllOccurences.registerRemovedNode((Type) type);
                        });
                        astRewriteReplaceAllOccurrences.remove(methodInvocationExpression, null);
                        removerAllOccurences.registerRemovedNode(methodInvocationExpression);
                    }
                }
                return super.visit(methodInvocation);
            }
        });
        QualifiedName qnFinal = qn;
        name.getRoot().accept(new ASTVisitor() {

            @Override
            public boolean visit(QualifiedName qualifiedName) {
                if (qnFinal != null && qualifiedName.getFullyQualifiedName().equals(qnFinal.getFullyQualifiedName())) {
                    astRewriteReplaceAllOccurrences.replace(qualifiedName, ASTNodeFactory.newName(node.getAST(), name.getFullyQualifiedName()), null);
                    removerAllOccurences.registerRemovedNode(qualifiedName);
                }
                return super.visit(qualifiedName);
            }
        });
        if (needImport) {
            importRewrite.addStaticImport(binding);
        }
        ASTRewriteRemoveImportsCorrectionProposal proposal = new ASTRewriteRemoveImportsCorrectionProposal(CorrectionMessages.QuickAssistProcessor_convert_to_static_import, CodeActionKind.Refactor, context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_STATIC_IMPORT);
        proposal.setImportRewrite(importRewrite);
        proposal.setImportRemover(remover);
        proposals.add(proposal);
        ASTRewriteRemoveImportsCorrectionProposal proposalReplaceAllOccurrences = new ASTRewriteRemoveImportsCorrectionProposal(CorrectionMessages.QuickAssistProcessor_convert_to_static_import_replace_all, CodeActionKind.Refactor, context.getCompilationUnit(), astRewriteReplaceAllOccurrences, IProposalRelevance.ADD_STATIC_IMPORT);
        proposalReplaceAllOccurrences.setImportRewrite(importRewrite);
        proposalReplaceAllOccurrences.setImportRemover(removerAllOccurences);
        proposals.add(proposalReplaceAllOccurrences);
    } catch (IllegalArgumentException e) {
        // Wrong use of ASTRewrite or ImportRewrite API, see bug 541586
        JavaLanguageServerPlugin.logException("Failed to get static import proposal", e);
        return false;
    } catch (JavaModelException e) {
        return false;
    }
    return true;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) Dimension(org.eclipse.jdt.core.dom.Dimension) RefactoringAvailabilityTesterCore(org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTesterCore) Arrays(java.util.Arrays) CleanUpRequirementsCore(org.eclipse.jdt.core.manipulation.CleanUpRequirementsCore) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor) CreateChangeOperation(org.eclipse.ltk.core.refactoring.CreateChangeOperation) ArrayInitializer(org.eclipse.jdt.core.dom.ArrayInitializer) CoreException(org.eclipse.core.runtime.CoreException) MultiFixMessages(org.eclipse.jdt.internal.ui.fix.MultiFixMessages) InlineConstantRefactoring(org.eclipse.jdt.internal.corext.refactoring.code.InlineConstantRefactoring) StubUtility(org.eclipse.jdt.internal.core.manipulation.StubUtility) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) AnonymousClassDeclaration(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) InlineTempRefactoring(org.eclipse.jdt.internal.corext.refactoring.code.InlineTempRefactoring) Expression(org.eclipse.jdt.core.dom.Expression) TypeChangeCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.TypeChangeCorrectionProposal) Map(java.util.Map) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Bindings(org.eclipse.jdt.internal.corext.dom.Bindings) RefactoringCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.RefactoringCorrectionProposal) ASTNodes(org.eclipse.jdt.internal.corext.dom.ASTNodes) ASTNode(org.eclipse.jdt.core.dom.ASTNode) IProposalRelevance(org.eclipse.jdt.ls.core.internal.corrections.proposals.IProposalRelevance) ConvertLoopFixCore(org.eclipse.jdt.internal.corext.fix.ConvertLoopFixCore) IJavaProject(org.eclipse.jdt.core.IJavaProject) ASTRewriteRemoveImportsCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteRemoveImportsCorrectionProposal) Messages(org.eclipse.jdt.internal.corext.util.Messages) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) Collection(java.util.Collection) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) FixCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.FixCorrectionProposal) IBinding(org.eclipse.jdt.core.dom.IBinding) VariableDeclaration(org.eclipse.jdt.core.dom.VariableDeclaration) JavaModelUtil(org.eclipse.jdt.internal.corext.util.JavaModelUtil) AbstractCleanUpCore(org.eclipse.jdt.internal.ui.fix.AbstractCleanUpCore) IJavaModelMarker(org.eclipse.jdt.core.IJavaModelMarker) IType(org.eclipse.jdt.core.IType) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) CleanUpOptionsCore(org.eclipse.jdt.core.manipulation.CleanUpOptionsCore) IProposableFix(org.eclipse.jdt.internal.corext.fix.IProposableFix) IProblemLocationCore(org.eclipse.jdt.internal.ui.text.correction.IProblemLocationCore) List(java.util.List) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) CleanUpConstants(org.eclipse.jdt.internal.corext.fix.CleanUpConstants) ImportRemover(org.eclipse.jdt.internal.corext.refactoring.structure.ImportRemover) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ICleanUpFixCore(org.eclipse.jdt.core.manipulation.ICleanUpFixCore) RefactoringCorrectionCommandProposal(org.eclipse.jdt.ls.core.internal.text.correction.RefactoringCorrectionCommandProposal) IField(org.eclipse.jdt.core.IField) LinkedProposalModelCore(org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore) JavaModelException(org.eclipse.jdt.core.JavaModelException) ConvertAnonymousToNestedRefactoring(org.eclipse.jdt.internal.corext.refactoring.code.ConvertAnonymousToNestedRefactoring) MethodReference(org.eclipse.jdt.core.dom.MethodReference) HashMap(java.util.HashMap) CheckConditionsOperation(org.eclipse.ltk.core.refactoring.CheckConditionsOperation) InlineMethodRefactoring(org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring) ArrayList(java.util.ArrayList) Type(org.eclipse.jdt.core.dom.Type) RefactorProposalUtility(org.eclipse.jdt.ls.core.internal.text.correction.RefactorProposalUtility) CodeActionParams(org.eclipse.lsp4j.CodeActionParams) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) Name(org.eclipse.jdt.core.dom.Name) LambdaExpressionsCleanUpCore(org.eclipse.jdt.internal.ui.fix.LambdaExpressionsCleanUpCore) ChangeCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.ChangeCorrectionProposal) ASTNodeFactory(org.eclipse.jdt.internal.corext.dom.ASTNodeFactory) Modifier(org.eclipse.jdt.core.dom.Modifier) JavaCore(org.eclipse.jdt.core.JavaCore) ILocalVariable(org.eclipse.jdt.core.ILocalVariable) ForStatement(org.eclipse.jdt.core.dom.ForStatement) JavaLanguageServerPlugin(org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) PreferenceManager(org.eclipse.jdt.ls.core.internal.preferences.PreferenceManager) CleanUpContextCore(org.eclipse.jdt.core.manipulation.CleanUpContextCore) ActionMessages(org.eclipse.jdt.ls.core.internal.text.correction.ActionMessages) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) CUCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.CUCorrectionProposal) IJavaElement(org.eclipse.jdt.core.IJavaElement) ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) ICleanUpCore(org.eclipse.jdt.internal.corext.fix.ICleanUpCore) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) IMethod(org.eclipse.jdt.core.IMethod) LambdaExpressionsFixCore(org.eclipse.jdt.internal.corext.fix.LambdaExpressionsFixCore) CodeActionKind(org.eclipse.lsp4j.CodeActionKind) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) Collections(java.util.Collections) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) JavaModelException(org.eclipse.jdt.core.JavaModelException) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IBinding(org.eclipse.jdt.core.dom.IBinding) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name) IType(org.eclipse.jdt.core.IType) Type(org.eclipse.jdt.core.dom.Type) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ASTRewriteRemoveImportsCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteRemoveImportsCorrectionProposal) ImportRemover(org.eclipse.jdt.internal.corext.refactoring.structure.ImportRemover)

Example 40 with ASTVisitor

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

the class RenameTypeProcessor method analyseEnclosedTypes.

private RefactoringStatus analyseEnclosedTypes() throws CoreException {
    final ISourceRange typeRange = fType.getSourceRange();
    final RefactoringStatus result = new RefactoringStatus();
    CompilationUnit cuNode = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(fType.getCompilationUnit(), false);
    cuNode.accept(new ASTVisitor() {

        @Override
        public boolean visit(TypeDeclaration node) {
            // enums and annotations can't be local
            if (node.getStartPosition() <= typeRange.getOffset()) {
                return true;
            }
            if (node.getStartPosition() > typeRange.getOffset() + typeRange.getLength()) {
                return true;
            }
            if (getNewElementName().equals(node.getName().getIdentifier())) {
                RefactoringStatusContext context = JavaStatusContext.create(fType.getCompilationUnit(), node);
                String msg = null;
                if (node.isLocalTypeDeclaration()) {
                    msg = Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_local_type, new String[] { JavaElementUtil.createSignature(fType), getNewElementLabel() });
                } else if (node.isMemberTypeDeclaration()) {
                    msg = Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_member_type, new String[] { JavaElementUtil.createSignature(fType), getNewElementLabel() });
                }
                if (msg != null) {
                    result.addError(msg, context);
                }
            }
            MethodDeclaration[] methods = node.getMethods();
            for (int i = 0; i < methods.length; i++) {
                if (Modifier.isNative(methods[i].getModifiers())) {
                    RefactoringStatusContext context = JavaStatusContext.create(fType.getCompilationUnit(), methods[i]);
                    String msg = Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_enclosed_type_native, BasicElementLabels.getJavaElementName(node.getName().getIdentifier()));
                    result.addWarning(msg, context);
                }
            }
            return true;
        }
    });
    return result;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) RefactoringStatusContext(org.eclipse.ltk.core.refactoring.RefactoringStatusContext) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) ISourceRange(org.eclipse.jdt.core.ISourceRange) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor)

Aggregations

ASTVisitor (org.eclipse.jdt.core.dom.ASTVisitor)66 ArrayList (java.util.ArrayList)27 ASTNode (org.eclipse.jdt.core.dom.ASTNode)20 SimpleName (org.eclipse.jdt.core.dom.SimpleName)20 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)18 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)15 List (java.util.List)14 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)14 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)12 TypeDeclaration (org.eclipse.jdt.core.dom.TypeDeclaration)12 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)12 ASTParser (org.eclipse.jdt.core.dom.ASTParser)11 Block (org.eclipse.jdt.core.dom.Block)10 Expression (org.eclipse.jdt.core.dom.Expression)10 ImportDeclaration (org.eclipse.jdt.core.dom.ImportDeclaration)10 Name (org.eclipse.jdt.core.dom.Name)10 Statement (org.eclipse.jdt.core.dom.Statement)10 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)9 SearchResult (com.liferay.blade.api.SearchResult)8 FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)8