Search in sources :

Example 1 with ReferencesInBinaryContext

use of org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext in project che by eclipse.

the class RenameMethodProcessor method doCheckFinalConditions.

@Override
protected RefactoringStatus doCheckFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
    try {
        RefactoringStatus result = new RefactoringStatus();
        //$NON-NLS-1$
        pm.beginTask("", 9);
        // TODO workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=40367
        if (!Checks.isAvailable(fMethod)) {
            result.addFatalError(RefactoringCoreMessages.RenameMethodProcessor_is_binary, JavaStatusContext.create(fMethod));
            return result;
        }
        result.merge(Checks.checkIfCuBroken(fMethod));
        if (result.hasFatalError())
            return result;
        pm.setTaskName(RefactoringCoreMessages.RenameMethodRefactoring_taskName_checkingPreconditions);
        result.merge(checkNewElementName(getNewElementName()));
        if (result.hasFatalError())
            return result;
        boolean mustAnalyzeShadowing;
        IMethod[] newNameMethods = searchForDeclarationsOfClashingMethods(new SubProgressMonitor(pm, 1));
        if (newNameMethods.length == 0) {
            mustAnalyzeShadowing = false;
            pm.worked(1);
        } else {
            IType[] outerTypes = searchForOuterTypesOfReferences(newNameMethods, new SubProgressMonitor(pm, 1));
            if (outerTypes.length > 0) {
                //There exists a reference to a clashing method, where the reference is in a nested type.
                //That nested type could be a type in a ripple method's hierarchy, which could
                //cause the reference to bind to the new ripple method instead of to
                //its old binding (a method of an enclosing scope).
                //-> Getting *more* references than before -> Semantics not preserved.
                //Examples: RenameVirtualMethodInClassTests#testFail39() and #testFail41()
                //TODO: could pass declaringTypes to the RippleMethodFinder and check whether
                //a hierarchy contains one of outerTypes (or an outer type of an outerType, recursively).
                mustAnalyzeShadowing = true;
            } else {
                boolean hasOldRefsInInnerTypes = true;
                //(recursively), whether they declare a rippleMethod
                if (hasOldRefsInInnerTypes) {
                    //There exists a reference to a ripple method in a nested type
                    //of a type in the hierarchy of any ripple method.
                    //When that reference is renamed, and one of the supertypes of the
                    //nested type declared a method matching the new name, then
                    //the renamed reference will bind to the method in its supertype,
                    //since inherited methods bind stronger than methods from enclosing scopes.
                    //Getting *less* references than before -> Semantics not preserved.
                    //Examples: RenamePrivateMethodTests#testFail2(), RenamePrivateMethodTests#testFail5()
                    mustAnalyzeShadowing = true;
                } else {
                    mustAnalyzeShadowing = false;
                }
            }
        }
        String binaryRefsDescription = Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getJavaElementName(getCurrentElementName()));
        ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);
        initializeMethodsToRename(new SubProgressMonitor(pm, 1), binaryRefs);
        pm.setTaskName(RefactoringCoreMessages.RenameMethodRefactoring_taskName_searchingForReferences);
        fOccurrences = getOccurrences(new SubProgressMonitor(pm, 3), result, binaryRefs);
        binaryRefs.addErrorIfNecessary(result);
        pm.setTaskName(RefactoringCoreMessages.RenameMethodRefactoring_taskName_checkingPreconditions);
        if (fUpdateReferences)
            result.merge(checkRelatedMethods());
        //removes CUs with syntax errors
        result.merge(analyzeCompilationUnits());
        pm.worked(1);
        if (result.hasFatalError())
            return result;
        createChanges(new SubProgressMonitor(pm, 1), result);
        if (fUpdateReferences & mustAnalyzeShadowing)
            result.merge(analyzeRenameChanges(new SubProgressMonitor(pm, 1)));
        else
            pm.worked(1);
        return result;
    } finally {
        pm.done();
    }
}
Also used : ReferencesInBinaryContext(org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IMethod(org.eclipse.jdt.core.IMethod) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) IType(org.eclipse.jdt.core.IType)

Example 2 with ReferencesInBinaryContext

use of org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext in project che by eclipse.

the class RenameTypeProcessor method initializeReferences.

/**
	 * Initializes the references to the type and the similarly named elements. This
	 * method creates both the fReferences and the fPreloadedElementToName
	 * fields.
	 *
	 * May be called from the UI.
	 * @param monitor progress monitor
	 * @return initialization status
	 * @throws JavaModelException some fundamental error with the underlying model
	 * @throws OperationCanceledException if user canceled the task
	 *
	 */
public RefactoringStatus initializeReferences(IProgressMonitor monitor) throws JavaModelException, OperationCanceledException {
    Assert.isNotNull(fType);
    Assert.isNotNull(getNewElementName());
    if (fReferences != null && (getNewElementName().equals(fCachedNewName)) && (fCachedRenameSimilarElements == getUpdateSimilarDeclarations()) && (fCachedRenamingStrategy == fRenamingStrategy))
        return fCachedRefactoringStatus;
    fCachedNewName = getNewElementName();
    fCachedRenameSimilarElements = fUpdateSimilarElements;
    fCachedRenamingStrategy = fRenamingStrategy;
    fCachedRefactoringStatus = new RefactoringStatus();
    try {
        SearchPattern pattern = SearchPattern.createPattern(fType, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
        String binaryRefsDescription = Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getJavaElementName(fType.getElementName()));
        ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);
        fReferences = RefactoringSearchEngine.search(pattern, RefactoringScopeFactory.create(fType, true, false), new TypeOccurrenceCollector(fType, binaryRefs), monitor, fCachedRefactoringStatus);
        binaryRefs.addErrorIfNecessary(fCachedRefactoringStatus);
        fReferences = Checks.excludeCompilationUnits(fReferences, fCachedRefactoringStatus);
        fPreloadedElementToName = new LinkedHashMap<IJavaElement, String>();
        fPreloadedElementToSelection = new HashMap<IJavaElement, Boolean>();
        final String unQualifiedTypeName = fType.getElementName();
        //$NON-NLS-1$
        monitor.beginTask("", fReferences.length);
        if (getUpdateSimilarDeclarations()) {
            RenamingNameSuggestor sugg = new RenamingNameSuggestor(fRenamingStrategy);
            for (int i = 0; i < fReferences.length; i++) {
                final ICompilationUnit cu = fReferences[i].getCompilationUnit();
                if (cu == null)
                    continue;
                final SearchMatch[] results = fReferences[i].getSearchResults();
                for (int j = 0; j < results.length; j++) {
                    if (!(results[j] instanceof TypeReferenceMatch))
                        continue;
                    final TypeReferenceMatch match = (TypeReferenceMatch) results[j];
                    final List<IJavaElement> matches = new ArrayList<IJavaElement>();
                    if (match.getLocalElement() != null) {
                        if (match.getLocalElement() instanceof ILocalVariable) {
                            matches.add(match.getLocalElement());
                        }
                    // else don't update (e.g. match in type parameter, annotation, ...)
                    } else {
                        matches.add((IJavaElement) match.getElement());
                    }
                    final IJavaElement[] others = match.getOtherElements();
                    if (others != null)
                        matches.addAll(Arrays.asList(others));
                    for (Iterator<IJavaElement> iter = matches.iterator(); iter.hasNext(); ) {
                        final IJavaElement element = iter.next();
                        if (!(element instanceof IMethod) && !(element instanceof IField) && !(element instanceof ILocalVariable))
                            continue;
                        if (!isInDeclaredType(match.getOffset(), element))
                            continue;
                        if (element instanceof IField) {
                            final IField currentField = (IField) element;
                            final String newFieldName = sugg.suggestNewFieldName(currentField.getJavaProject(), currentField.getElementName(), Flags.isStatic(currentField.getFlags()), unQualifiedTypeName, getNewElementName());
                            if (newFieldName != null)
                                fPreloadedElementToName.put(currentField, newFieldName);
                        } else if (element instanceof IMethod) {
                            final IMethod currentMethod = (IMethod) element;
                            addMethodRename(unQualifiedTypeName, sugg, currentMethod);
                        } else if (element instanceof ILocalVariable) {
                            final ILocalVariable currentLocal = (ILocalVariable) element;
                            final boolean isParameter;
                            if (currentLocal.isParameter()) {
                                addMethodRename(unQualifiedTypeName, sugg, (IMethod) currentLocal.getParent());
                                isParameter = true;
                            } else
                                isParameter = false;
                            final String newLocalName = sugg.suggestNewLocalName(currentLocal.getJavaProject(), currentLocal.getElementName(), isParameter, unQualifiedTypeName, getNewElementName());
                            if (newLocalName != null)
                                fPreloadedElementToName.put(currentLocal, newLocalName);
                        }
                    }
                }
                if (monitor.isCanceled())
                    throw new OperationCanceledException();
            }
        }
        for (Iterator<IJavaElement> iter = fPreloadedElementToName.keySet().iterator(); iter.hasNext(); ) {
            IJavaElement element = iter.next();
            fPreloadedElementToSelection.put(element, Boolean.TRUE);
        }
        fPreloadedElementToNameDefault = new LinkedHashMap<IJavaElement, String>(fPreloadedElementToName);
    } catch (OperationCanceledException e) {
        fReferences = null;
        fPreloadedElementToName = null;
        throw new OperationCanceledException();
    }
    return fCachedRefactoringStatus;
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IField(org.eclipse.jdt.core.IField) ILocalVariable(org.eclipse.jdt.core.ILocalVariable) ReferencesInBinaryContext(org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) IMethod(org.eclipse.jdt.core.IMethod) TypeReferenceMatch(org.eclipse.jdt.core.search.TypeReferenceMatch)

Example 3 with ReferencesInBinaryContext

use of org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext in project che by eclipse.

the class RenameFieldProcessor method getReferences.

private SearchResultGroup[] getReferences(IProgressMonitor pm, RefactoringStatus status) throws CoreException {
    String binaryRefsDescription = Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getJavaElementName(getCurrentElementName()));
    ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);
    SearchResultGroup[] result = RefactoringSearchEngine.search(createSearchPattern(), createRefactoringScope(), new CuCollectingSearchRequestor(binaryRefs), pm, status);
    binaryRefs.addErrorIfNecessary(status);
    return result;
}
Also used : ReferencesInBinaryContext(org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext) CuCollectingSearchRequestor(org.eclipse.jdt.internal.corext.refactoring.CuCollectingSearchRequestor) SearchResultGroup(org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup)

Example 4 with ReferencesInBinaryContext

use of org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext in project che by eclipse.

the class ReplaceInvocationsRefactoring method checkFinalConditions.

@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
    //$NON-NLS-1$
    pm.beginTask("", 20);
    fChangeManager = new TextChangeManager();
    RefactoringStatus result = new RefactoringStatus();
    fSourceProvider = resolveSourceProvider(fMethodBinding, result);
    if (result.hasFatalError())
        return result;
    result.merge(fSourceProvider.checkActivation());
    if (result.hasFatalError())
        return result;
    fSourceProvider.initialize();
    fTargetProvider.initialize();
    pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_searching);
    RefactoringStatus searchStatus = new RefactoringStatus();
    String binaryRefsDescription = Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getJavaElementName(fSourceProvider.getMethodName()));
    ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);
    ICompilationUnit[] units = fTargetProvider.getAffectedCompilationUnits(searchStatus, binaryRefs, new SubProgressMonitor(pm, 1));
    binaryRefs.addErrorIfNecessary(searchStatus);
    if (searchStatus.hasFatalError()) {
        result.merge(searchStatus);
        return result;
    }
    IFile[] filesToBeModified = getFilesToBeModified(units);
    result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
    if (result.hasFatalError())
        return result;
    result.merge(ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1)));
    checkOverridden(result, new SubProgressMonitor(pm, 4));
    IProgressMonitor sub = new SubProgressMonitor(pm, 15);
    //$NON-NLS-1$
    sub.beginTask("", units.length * 3);
    for (int c = 0; c < units.length; c++) {
        ICompilationUnit unit = units[c];
        sub.subTask(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_processing, BasicElementLabels.getFileName(unit)));
        CallInliner inliner = null;
        try {
            boolean added = false;
            MultiTextEdit root = new MultiTextEdit();
            CompilationUnitChange change = (CompilationUnitChange) fChangeManager.get(unit);
            change.setEdit(root);
            BodyDeclaration[] bodies = fTargetProvider.getAffectedBodyDeclarations(unit, new SubProgressMonitor(pm, 1));
            if (bodies.length == 0)
                continue;
            inliner = new CallInliner(unit, (CompilationUnit) bodies[0].getRoot(), fSourceProvider);
            for (int b = 0; b < bodies.length; b++) {
                BodyDeclaration body = bodies[b];
                inliner.initialize(body);
                RefactoringStatus nestedInvocations = new RefactoringStatus();
                ASTNode[] invocations = removeNestedCalls(nestedInvocations, unit, fTargetProvider.getInvocations(body, new SubProgressMonitor(sub, 2)));
                for (int i = 0; i < invocations.length; i++) {
                    ASTNode invocation = invocations[i];
                    result.merge(inliner.initialize(invocation, fTargetProvider.getStatusSeverity()));
                    if (result.hasFatalError())
                        break;
                    if (result.getSeverity() < fTargetProvider.getStatusSeverity()) {
                        added = true;
                        TextEditGroup group = new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_inline);
                        change.addTextEditGroup(group);
                        result.merge(inliner.perform(group));
                    }
                }
                // do this after we have inlined the method calls. We still want
                // to generate the modifications.
                result.merge(nestedInvocations);
            }
            if (!added) {
                fChangeManager.remove(unit);
            } else {
                root.addChild(inliner.getModifications());
                ImportRewrite rewrite = inliner.getImportEdit();
                if (rewrite.hasRecordedChanges()) {
                    TextEdit edit = rewrite.rewriteImports(null);
                    if (edit instanceof MultiTextEdit ? ((MultiTextEdit) edit).getChildrenSize() > 0 : true) {
                        root.addChild(edit);
                        change.addTextEditGroup(new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_import, new TextEdit[] { edit }));
                    }
                }
            }
        } finally {
            if (inliner != null)
                inliner.dispose();
        }
        sub.worked(1);
        if (sub.isCanceled())
            throw new OperationCanceledException();
    }
    result.merge(searchStatus);
    sub.done();
    pm.done();
    return result;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IFile(org.eclipse.core.resources.IFile) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) ReferencesInBinaryContext(org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ASTNode(org.eclipse.jdt.core.dom.ASTNode) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) TextEditGroup(org.eclipse.text.edits.TextEditGroup) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextChangeManager(org.eclipse.jdt.internal.corext.refactoring.util.TextChangeManager) CompilationUnitChange(org.eclipse.jdt.core.refactoring.CompilationUnitChange)

Example 5 with ReferencesInBinaryContext

use of org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext in project che by eclipse.

the class ChangeSignatureProcessor method checkFinalConditions.

/* (non-Javadoc)
	 * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkFinalConditions(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext)
	 */
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException, OperationCanceledException {
    try {
        pm.beginTask(RefactoringCoreMessages.ChangeSignatureRefactoring_checking_preconditions, 8);
        RefactoringStatus result = new RefactoringStatus();
        clearManagers();
        fBaseCuRewrite.clearASTAndImportRewrites();
        fBaseCuRewrite.getASTRewrite().setTargetSourceRangeComputer(new TightSourceRangeComputer());
        if (isSignatureSameAsInitial())
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeSignatureRefactoring_unchanged);
        result.merge(checkSignature(true));
        if (result.hasFatalError())
            return result;
        if (fDelegateUpdating && isSignatureClashWithInitial())
            result.merge(RefactoringStatus.createErrorStatus(RefactoringCoreMessages.ChangeSignatureRefactoring_old_and_new_signatures_not_sufficiently_different));
        String binaryRefsDescription = Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getJavaElementName(getMethodName()));
        ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);
        fRippleMethods = RippleMethodFinder2.getRelatedMethods(fMethod, binaryRefs, new SubProgressMonitor(pm, 1), null);
        result.merge(checkVarargs());
        if (result.hasFatalError())
            return result;
        fOccurrences = findOccurrences(new SubProgressMonitor(pm, 1), binaryRefs, result);
        binaryRefs.addErrorIfNecessary(result);
        result.merge(checkVisibilityChanges());
        result.merge(checkTypeVariables());
        if (!isOrderSameAsInitial())
            result.merge(checkReorderings(new SubProgressMonitor(pm, 1)));
        else
            pm.worked(1);
        if (!areNamesSameAsInitial())
            result.merge(checkRenamings(new SubProgressMonitor(pm, 1)));
        else
            pm.worked(1);
        if (result.hasFatalError())
            return result;
        //			resolveTypesWithoutBindings(new SubProgressMonitor(pm, 1)); // already done in checkSignature(true)
        createChangeManager(new SubProgressMonitor(pm, 1), result);
        fCachedTypeHierarchy = null;
        if (mustAnalyzeAstOfDeclaringCu())
            //TODO: should also check in ripple methods (move into createChangeManager)
            result.merge(checkCompilationofDeclaringCu());
        if (result.hasFatalError())
            return result;
        Checks.addModifiedFilesToChecker(getAllFilesToModify(), context);
        return result;
    } finally {
        pm.done();
    }
}
Also used : TightSourceRangeComputer(org.eclipse.jdt.internal.corext.refactoring.util.TightSourceRangeComputer) ReferencesInBinaryContext(org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor)

Aggregations

ReferencesInBinaryContext (org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext)7 SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)5 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)5 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)3 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)3 IFile (org.eclipse.core.resources.IFile)2 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)2 IMethod (org.eclipse.jdt.core.IMethod)2 ASTNode (org.eclipse.jdt.core.dom.ASTNode)2 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)2 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)2 ImportRewrite (org.eclipse.jdt.core.dom.rewrite.ImportRewrite)2 CompilationUnitChange (org.eclipse.jdt.core.refactoring.CompilationUnitChange)2 SearchPattern (org.eclipse.jdt.core.search.SearchPattern)2 SearchResultGroup (org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup)2 TextChangeManager (org.eclipse.jdt.internal.corext.refactoring.util.TextChangeManager)2 MultiTextEdit (org.eclipse.text.edits.MultiTextEdit)2 TextEdit (org.eclipse.text.edits.TextEdit)2 TextEditGroup (org.eclipse.text.edits.TextEditGroup)2 ArrayList (java.util.ArrayList)1