Search in sources :

Example 1 with RefactoringASTParser

use of org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser in project che by eclipse.

the class RenameTypeProcessor method initializeSimilarElementsRenameProcessors.

// --------- Similar names
/**
	 * Creates and initializes the refactoring processors for similarly named elements
	 * @param progressMonitor progress monitor
	 * @param context context
	 * @return status
	 * @throws CoreException should not happen
	 */
private RefactoringStatus initializeSimilarElementsRenameProcessors(IProgressMonitor progressMonitor, CheckConditionsContext context) throws CoreException {
    Assert.isNotNull(fPreloadedElementToName);
    Assert.isNotNull(fPreloadedElementToSelection);
    final RefactoringStatus status = new RefactoringStatus();
    final Set<IMethod> handledTopLevelMethods = new HashSet<IMethod>();
    final Set<Warning> warnings = new HashSet<Warning>();
    final List<RefactoringProcessor> processors = new ArrayList<RefactoringProcessor>();
    fFinalSimilarElementToName = new HashMap<IJavaElement, String>();
    CompilationUnit currentResolvedCU = null;
    ICompilationUnit currentCU = null;
    int current = 0;
    final int max = fPreloadedElementToName.size();
    //$NON-NLS-1$
    progressMonitor.beginTask("", max * 3);
    progressMonitor.setTaskName(RefactoringCoreMessages.RenameTypeProcessor_checking_similarly_named_declarations_refactoring_conditions);
    for (Iterator<IJavaElement> iter = fPreloadedElementToName.keySet().iterator(); iter.hasNext(); ) {
        final IJavaElement element = iter.next();
        current++;
        progressMonitor.worked(3);
        // not selected? -> skip
        if (!(fPreloadedElementToSelection.get(element)).booleanValue())
            continue;
        // already registered? (may happen with overridden methods) -> skip
        if (fFinalSimilarElementToName.containsKey(element))
            continue;
        // CompilationUnit changed? (note: fPreloadedElementToName is sorted by CompilationUnit)
        ICompilationUnit newCU = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
        if (!newCU.equals(currentCU)) {
            checkCUCompleteConditions(status, currentResolvedCU, currentCU, processors);
            if (status.hasFatalError())
                return status;
            // reset values
            currentResolvedCU = null;
            currentCU = newCU;
            processors.clear();
        }
        final String newName = fPreloadedElementToName.get(element);
        RefactoringProcessor processor = null;
        if (element instanceof ILocalVariable) {
            final ILocalVariable currentLocal = (ILocalVariable) element;
            if (currentResolvedCU == null)
                currentResolvedCU = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(currentCU, true);
            processor = createLocalRenameProcessor(currentLocal, newName, currentResolvedCU);
            if (status.hasFatalError())
                return status;
            fFinalSimilarElementToName.put(currentLocal, newName);
        }
        if (element instanceof IField) {
            final IField currentField = (IField) element;
            processor = createFieldRenameProcessor(currentField, newName);
            status.merge(checkForConflictingRename(currentField, newName));
            if (status.hasFatalError())
                return status;
            fFinalSimilarElementToName.put(currentField, newName);
        }
        if (element instanceof IMethod) {
            IMethod currentMethod = (IMethod) element;
            if (MethodChecks.isVirtual(currentMethod)) {
                final IType declaringType = currentMethod.getDeclaringType();
                ITypeHierarchy hierarchy = null;
                if (!declaringType.isInterface())
                    hierarchy = declaringType.newTypeHierarchy(new NullProgressMonitor());
                final IMethod topmost = MethodChecks.getTopmostMethod(currentMethod, hierarchy, new NullProgressMonitor());
                if (topmost != null)
                    currentMethod = topmost;
                if (handledTopLevelMethods.contains(currentMethod))
                    continue;
                handledTopLevelMethods.add(currentMethod);
                final IMethod[] ripples = RippleMethodFinder2.getRelatedMethods(currentMethod, new NullProgressMonitor(), null);
                if (checkForWarnings(warnings, newName, ripples))
                    continue;
                status.merge(checkForConflictingRename(ripples, newName));
                if (status.hasFatalError())
                    return status;
                processor = createVirtualMethodRenameProcessor(currentMethod, newName, ripples, hierarchy);
                fFinalSimilarElementToName.put(currentMethod, newName);
                for (int i = 0; i < ripples.length; i++) {
                    fFinalSimilarElementToName.put(ripples[i], newName);
                }
            } else {
                status.merge(checkForConflictingRename(new IMethod[] { currentMethod }, newName));
                if (status.hasFatalError())
                    break;
                fFinalSimilarElementToName.put(currentMethod, newName);
                processor = createNonVirtualMethodRenameProcessor(currentMethod, newName);
            }
        }
        progressMonitor.subTask(Messages.format(RefactoringCoreMessages.RenameTypeProcessor_progress_current_total, new Object[] { String.valueOf(current), String.valueOf(max) }));
        status.merge(processor.checkInitialConditions(new NoOverrideProgressMonitor(progressMonitor, 1)));
        if (status.hasFatalError())
            return status;
        status.merge(processor.checkFinalConditions(new NoOverrideProgressMonitor(progressMonitor, 1), context));
        if (status.hasFatalError())
            return status;
        processors.add(processor);
        progressMonitor.worked(1);
        if (progressMonitor.isCanceled())
            throw new OperationCanceledException();
    }
    // check last CU
    checkCUCompleteConditions(status, currentResolvedCU, currentCU, processors);
    status.merge(addWarnings(warnings));
    progressMonitor.done();
    return status;
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IType(org.eclipse.jdt.core.IType) ILocalVariable(org.eclipse.jdt.core.ILocalVariable) ITypeHierarchy(org.eclipse.jdt.core.ITypeHierarchy) IMethod(org.eclipse.jdt.core.IMethod) HashSet(java.util.HashSet) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IField(org.eclipse.jdt.core.IField) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) RefactoringProcessor(org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor)

Example 2 with RefactoringASTParser

use of org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser in project che 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(ASTProvider.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)

Example 3 with RefactoringASTParser

use of org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser in project che by eclipse.

the class RenameAnalyzeUtil method analyzeLocalRenames.

/**
	 * This method analyzes a set of local variable renames inside one cu. It checks whether
	 * any new compile errors have been introduced by the rename(s) and whether the correct
	 * node(s) has/have been renamed.
	 *
	 * @param analyzePackages the LocalAnalyzePackages containing the information about the local renames
	 * @param cuChange the TextChange containing all local variable changes to be applied.
	 * @param oldCUNode the fully (incl. bindings) resolved AST node of the original compilation unit
	 * @param recovery whether statements and bindings recovery should be performed when parsing the changed CU
	 * @return a RefactoringStatus containing errors if compile errors or wrongly renamed nodes are found
	 * @throws CoreException thrown if there was an error greating the preview content of the change
	 */
public static RefactoringStatus analyzeLocalRenames(LocalAnalyzePackage[] analyzePackages, TextChange cuChange, CompilationUnit oldCUNode, boolean recovery) throws CoreException {
    RefactoringStatus result = new RefactoringStatus();
    ICompilationUnit compilationUnit = (ICompilationUnit) oldCUNode.getJavaElement();
    String newCuSource = cuChange.getPreviewContent(new NullProgressMonitor());
    CompilationUnit newCUNode = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(newCuSource, compilationUnit, true, recovery, null);
    result.merge(analyzeCompileErrors(newCuSource, newCUNode, oldCUNode));
    if (result.hasError())
        return result;
    for (int i = 0; i < analyzePackages.length; i++) {
        ASTNode enclosing = getEnclosingBlockOrMethodOrLambda(analyzePackages[i].fDeclarationEdit, cuChange, newCUNode);
        // get new declaration
        IRegion newRegion = RefactoringAnalyzeUtil.getNewTextRange(analyzePackages[i].fDeclarationEdit, cuChange);
        ASTNode newDeclaration = NodeFinder.perform(newCUNode, newRegion.getOffset(), newRegion.getLength());
        Assert.isTrue(newDeclaration instanceof Name);
        VariableDeclaration declaration = getVariableDeclaration((Name) newDeclaration);
        Assert.isNotNull(declaration);
        SimpleName[] problemNodes = ProblemNodeFinder.getProblemNodes(enclosing, declaration, analyzePackages[i].fOccurenceEdits, cuChange);
        result.merge(RefactoringAnalyzeUtil.reportProblemNodes(newCuSource, problemNodes));
    }
    return result;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) SimpleName(org.eclipse.jdt.core.dom.SimpleName) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IRegion(org.eclipse.jface.text.IRegion) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) ASTNode(org.eclipse.jdt.core.dom.ASTNode) VariableDeclaration(org.eclipse.jdt.core.dom.VariableDeclaration)

Example 4 with RefactoringASTParser

use of org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser in project che by eclipse.

the class ReplaceInvocationsRefactoring method checkInitialConditions.

@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
    // TargetProvider must get an untampered AST with original invocation node
    // SourceProvider must get a tweaked AST with method body / parameter names replaced
    RefactoringStatus result = new RefactoringStatus();
    if (fMethod == null) {
        if (!(fSelectionTypeRoot instanceof ICompilationUnit))
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReplaceInvocationsRefactoring_cannot_replace_in_binary);
        ICompilationUnit cu = (ICompilationUnit) fSelectionTypeRoot;
        CompilationUnit root = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(cu, true);
        fSelectionNode = getTargetNode(cu, root, fSelectionStart, fSelectionLength);
        if (fSelectionNode == null)
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReplaceInvocationsRefactoring_select_method_to_apply);
        if (fSelectionNode.getNodeType() == ASTNode.METHOD_DECLARATION) {
            MethodDeclaration methodDeclaration = (MethodDeclaration) fSelectionNode;
            fTargetProvider = TargetProvider.create(methodDeclaration);
            fMethodBinding = methodDeclaration.resolveBinding();
        } else {
            MethodInvocation methodInvocation = (MethodInvocation) fSelectionNode;
            fTargetProvider = TargetProvider.create(cu, methodInvocation);
            fMethodBinding = methodInvocation.resolveMethodBinding();
        }
        if (fMethodBinding == null)
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration);
        fMethod = (IMethod) fMethodBinding.getJavaElement();
    } else {
        ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
        parser.setProject(fMethod.getJavaProject());
        IBinding[] bindings = parser.createBindings(new IJavaElement[] { fMethod }, null);
        fMethodBinding = (IMethodBinding) bindings[0];
        if (fMethodBinding == null)
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration);
        fTargetProvider = TargetProvider.create(fMethodBinding);
    }
    result.merge(fTargetProvider.checkActivation());
    return result;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) IBinding(org.eclipse.jdt.core.dom.IBinding) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) ASTParser(org.eclipse.jdt.core.dom.ASTParser)

Example 5 with RefactoringASTParser

use of org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser in project che by eclipse.

the class ChangeSignatureProcessor method checkCompilationofDeclaringCu.

private RefactoringStatus checkCompilationofDeclaringCu() throws CoreException {
    ICompilationUnit cu = getCu();
    TextChange change = fChangeManager.get(cu);
    String newCuSource = change.getPreviewContent(new NullProgressMonitor());
    CompilationUnit newCUNode = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(newCuSource, cu, true, false, null);
    IProblem[] problems = RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fBaseCuRewrite.getRoot());
    RefactoringStatus result = new RefactoringStatus();
    for (int i = 0; i < problems.length; i++) {
        IProblem problem = problems[i];
        if (shouldReport(problem, newCUNode))
            result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem))));
    }
    return result;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) RefactoringStatusEntry(org.eclipse.ltk.core.refactoring.RefactoringStatusEntry) TextChange(org.eclipse.ltk.core.refactoring.TextChange) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) JavaStringStatusContext(org.eclipse.jdt.internal.corext.refactoring.base.JavaStringStatusContext) IProblem(org.eclipse.jdt.core.compiler.IProblem)

Aggregations

RefactoringASTParser (org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser)15 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)12 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)12 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)7 ASTNode (org.eclipse.jdt.core.dom.ASTNode)6 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)6 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)4 ArrayList (java.util.ArrayList)3 IMethod (org.eclipse.jdt.core.IMethod)3 IType (org.eclipse.jdt.core.IType)3 IProblem (org.eclipse.jdt.core.compiler.IProblem)3 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)3 Name (org.eclipse.jdt.core.dom.Name)3 SimpleName (org.eclipse.jdt.core.dom.SimpleName)3 JavaStringStatusContext (org.eclipse.jdt.internal.corext.refactoring.base.JavaStringStatusContext)3 IDocument (org.eclipse.jface.text.IDocument)3 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)2 IClassFile (org.eclipse.jdt.core.IClassFile)2 ISourceRange (org.eclipse.jdt.core.ISourceRange)2 JavaModelException (org.eclipse.jdt.core.JavaModelException)2