Search in sources :

Example 1 with SearchMatch

use of org.eclipse.jdt.core.search.SearchMatch in project che by eclipse.

the class RenameMethodProcessor method batchFindNewOccurrences.

//Lower memory footprint than batchFindNewOccurrences. Not used because it is too slow.
//Final solution is maybe to do searches in chunks of ~ 50 CUs.
//	private SearchResultGroup[] findNewOccurrences(IMethod[] newMethods, ICompilationUnit[] newDeclarationWCs, IProgressMonitor pm) throws CoreException {
//		pm.beginTask("", fOccurrences.length * 2); //$NON-NLS-1$
//
//		SearchPattern refsPattern= RefactoringSearchEngine.createOrPattern(newMethods, IJavaSearchConstants.REFERENCES);
//		SearchParticipant[] searchParticipants= SearchUtils.getDefaultSearchParticipants();
//		IJavaSearchScope scope= RefactoringScopeFactory.create(newMethods);
//		MethodOccurenceCollector requestor= new MethodOccurenceCollector(getNewElementName());
//		SearchEngine searchEngine= new SearchEngine(fWorkingCopyOwner);
//
//		//TODO: should process only references
//		for (int j= 0; j < fOccurrences.length; j++) { //should be getReferences()
//			//cut memory peak by holding only one reference CU at a time in memory
//			ICompilationUnit originalCu= fOccurrences[j].getCompilationUnit();
//			ICompilationUnit newWc= null;
//			try {
//				ICompilationUnit wc= RenameAnalyzeUtil.findWorkingCopyForCu(newDeclarationWCs, originalCu);
//				if (wc == null) {
//					newWc= RenameAnalyzeUtil.createNewWorkingCopy(originalCu, fChangeManager, fWorkingCopyOwner,
//							new SubProgressMonitor(pm, 1));
//				}
//				searchEngine.search(refsPattern, searchParticipants, scope,	requestor, new SubProgressMonitor(pm, 1));
//			} finally {
//				if (newWc != null)
//					newWc.discardWorkingCopy();
//			}
//		}
//		SearchResultGroup[] newResults= RefactoringSearchEngine.groupByResource(requestor.getResults());
//		pm.done();
//		return newResults;
//	}
private SearchResultGroup[] batchFindNewOccurrences(IMethod[] wcNewMethods, final IMethod[] wcOldMethods, ICompilationUnit[] newDeclarationWCs, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
    //$NON-NLS-1$
    pm.beginTask("", 2);
    SearchPattern refsPattern = RefactoringSearchEngine.createOrPattern(wcNewMethods, IJavaSearchConstants.REFERENCES);
    SearchParticipant[] searchParticipants = SearchUtils.getDefaultSearchParticipants();
    IJavaSearchScope scope = RefactoringScopeFactory.create(wcNewMethods);
    MethodOccurenceCollector requestor;
    if (getDelegateUpdating()) {
        // There will be two new matches inside the delegate(s) (the invocation
        // and the javadoc) which are OK and must not be reported.
        // Note that except these ocurrences, the delegate bodies are empty
        // (as they were created this way).
        requestor = new MethodOccurenceCollector(getNewElementName()) {

            @Override
            public void acceptSearchMatch(ICompilationUnit unit, SearchMatch match) throws CoreException {
                for (int i = 0; i < wcOldMethods.length; i++) if (wcOldMethods[i].equals(match.getElement()))
                    return;
                super.acceptSearchMatch(unit, match);
            }
        };
    } else
        requestor = new MethodOccurenceCollector(getNewElementName());
    SearchEngine searchEngine = new SearchEngine(fWorkingCopyOwner);
    ArrayList<ICompilationUnit> needWCs = new ArrayList<ICompilationUnit>();
    HashSet<ICompilationUnit> declaringCUs = new HashSet<ICompilationUnit>(newDeclarationWCs.length);
    for (int i = 0; i < newDeclarationWCs.length; i++) declaringCUs.add(newDeclarationWCs[i].getPrimary());
    for (int i = 0; i < fOccurrences.length; i++) {
        ICompilationUnit cu = fOccurrences[i].getCompilationUnit();
        if (!declaringCUs.contains(cu))
            needWCs.add(cu);
    }
    ICompilationUnit[] otherWCs = null;
    try {
        otherWCs = RenameAnalyzeUtil.createNewWorkingCopies(needWCs.toArray(new ICompilationUnit[needWCs.size()]), fChangeManager, fWorkingCopyOwner, new SubProgressMonitor(pm, 1));
        searchEngine.search(refsPattern, searchParticipants, scope, requestor, new SubProgressMonitor(pm, 1));
    } finally {
        pm.done();
        if (otherWCs != null) {
            for (int i = 0; i < otherWCs.length; i++) {
                otherWCs[i].discardWorkingCopy();
            }
        }
    }
    SearchResultGroup[] newResults = RefactoringSearchEngine.groupByCu(requestor.getResults(), status);
    return newResults;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) ArrayList(java.util.ArrayList) SearchResultGroup(org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) SearchParticipant(org.eclipse.jdt.core.search.SearchParticipant) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) RefactoringSearchEngine(org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine) CoreException(org.eclipse.core.runtime.CoreException) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) HashSet(java.util.HashSet)

Example 2 with SearchMatch

use of org.eclipse.jdt.core.search.SearchMatch in project che by eclipse.

the class RenameMethodProcessor method searchForDeclarationsOfClashingMethods.

private IMethod[] searchForDeclarationsOfClashingMethods(IProgressMonitor pm) throws CoreException {
    final List<IMethod> results = new ArrayList<IMethod>();
    SearchPattern pattern = createNewMethodPattern();
    IJavaSearchScope scope = RefactoringScopeFactory.create(getMethod().getJavaProject());
    SearchRequestor requestor = new SearchRequestor() {

        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            Object method = match.getElement();
            if (// check for bug 90138: [refactoring] [rename] Renaming method throws internal exception
            method instanceof IMethod)
                results.add((IMethod) method);
            else
                //$NON-NLS-1$
                JavaPlugin.logErrorMessage("Unexpected element in search match: " + match.toString());
        }
    };
    new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm);
    return results.toArray(new IMethod[results.size()]);
}
Also used : SearchRequestor(org.eclipse.jdt.core.search.SearchRequestor) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) RefactoringSearchEngine(org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) ArrayList(java.util.ArrayList) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) IMethod(org.eclipse.jdt.core.IMethod)

Example 3 with SearchMatch

use of org.eclipse.jdt.core.search.SearchMatch in project che by eclipse.

the class RenameMethodProcessor method addOccurrences.

/**
	 * Add occurrences
	 *
	 * @param manager the text change manager
	 * @param pm the progress monitor
	 * @param status the status
	 * @throws CoreException if change creation failed
	 */
protected void addOccurrences(TextChangeManager manager, IProgressMonitor pm, RefactoringStatus status) throws CoreException /*thrown in subtype*/
{
    //$NON-NLS-1$
    pm.beginTask("", fOccurrences.length);
    for (int i = 0; i < fOccurrences.length; i++) {
        ICompilationUnit cu = fOccurrences[i].getCompilationUnit();
        if (cu == null)
            continue;
        SearchMatch[] results = fOccurrences[i].getSearchResults();
        // Split matches into declaration and non-declaration matches
        List<SearchMatch> declarationsInThisCu = new ArrayList<SearchMatch>();
        List<SearchMatch> referencesInThisCu = new ArrayList<SearchMatch>();
        for (int j = 0; j < results.length; j++) {
            if (results[j] instanceof MethodDeclarationMatch)
                declarationsInThisCu.add(results[j]);
            else
                referencesInThisCu.add(results[j]);
        }
        // First, handle the declarations
        if (declarationsInThisCu.size() > 0) {
            if (fDelegateUpdating) {
                // Update with delegates
                CompilationUnitRewrite rewrite = new CompilationUnitRewrite(cu);
                rewrite.setResolveBindings(true);
                for (Iterator<SearchMatch> iter = declarationsInThisCu.iterator(); iter.hasNext(); ) {
                    SearchMatch element = iter.next();
                    MethodDeclaration method = ASTNodeSearchUtil.getMethodDeclarationNode((IMethod) element.getElement(), rewrite.getRoot());
                    DelegateCreator creator = new DelegateMethodCreator();
                    creator.setDeclareDeprecated(fDelegateDeprecation);
                    creator.setDeclaration(method);
                    creator.setSourceRewrite(rewrite);
                    creator.setNewElementName(getNewElementName());
                    creator.prepareDelegate();
                    creator.createEdit();
                }
                // Need to handle all delegates first as this
                // creates a completely new change object.
                TextChange changeForThisCu = rewrite.createChange(true);
                changeForThisCu.setKeepPreviewEdits(true);
                manager.manage(cu, changeForThisCu);
            }
            // Update the normal methods
            for (Iterator<SearchMatch> iter = declarationsInThisCu.iterator(); iter.hasNext(); ) {
                SearchMatch element = iter.next();
                simpleUpdate(element, cu, manager.get(cu));
            }
        }
        // Second, handle references
        if (fUpdateReferences) {
            for (Iterator<SearchMatch> iter = referencesInThisCu.iterator(); iter.hasNext(); ) {
                SearchMatch element = iter.next();
                simpleUpdate(element, cu, manager.get(cu));
            }
        }
        pm.worked(1);
        if (pm.isCanceled())
            throw new OperationCanceledException();
    }
    pm.done();
}
Also used : CompilationUnitRewrite(org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) TextChange(org.eclipse.ltk.core.refactoring.TextChange) MethodDeclarationMatch(org.eclipse.jdt.core.search.MethodDeclarationMatch) DelegateMethodCreator(org.eclipse.jdt.internal.corext.refactoring.delegates.DelegateMethodCreator) DelegateCreator(org.eclipse.jdt.internal.corext.refactoring.delegates.DelegateCreator)

Example 4 with SearchMatch

use of org.eclipse.jdt.core.search.SearchMatch 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 5 with SearchMatch

use of org.eclipse.jdt.core.search.SearchMatch in project che by eclipse.

the class RenameFieldProcessor method getNewReferences.

private SearchResultGroup[] getNewReferences(IProgressMonitor pm, RefactoringStatus status, WorkingCopyOwner owner, ICompilationUnit[] newWorkingCopies) throws CoreException {
    //$NON-NLS-1$
    pm.beginTask("", 2);
    ICompilationUnit declaringCuWorkingCopy = RenameAnalyzeUtil.findWorkingCopyForCu(newWorkingCopies, fField.getCompilationUnit());
    if (declaringCuWorkingCopy == null)
        return new SearchResultGroup[0];
    IField field = getFieldInWorkingCopy(declaringCuWorkingCopy, getNewElementName());
    if (field == null || !field.exists())
        return new SearchResultGroup[0];
    CollectingSearchRequestor requestor = null;
    if (fDelegateUpdating && RefactoringAvailabilityTester.isDelegateCreationAvailable(getField())) {
        // There will be two new matches inside the delegate (the invocation
        // and the javadoc) which are OK and must not be reported.
        final IField oldField = getFieldInWorkingCopy(declaringCuWorkingCopy, getCurrentElementName());
        requestor = new CollectingSearchRequestor() {

            @Override
            public void acceptSearchMatch(SearchMatch match) throws CoreException {
                if (!oldField.equals(match.getElement()))
                    super.acceptSearchMatch(match);
            }
        };
    } else
        requestor = new CollectingSearchRequestor();
    SearchPattern newPattern = SearchPattern.createPattern(field, IJavaSearchConstants.REFERENCES);
    IJavaSearchScope scope = RefactoringScopeFactory.create(fField, true, true);
    return RefactoringSearchEngine.search(newPattern, owner, scope, requestor, new SubProgressMonitor(pm, 1), status);
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) CoreException(org.eclipse.core.runtime.CoreException) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) CuCollectingSearchRequestor(org.eclipse.jdt.internal.corext.refactoring.CuCollectingSearchRequestor) CollectingSearchRequestor(org.eclipse.jdt.internal.corext.refactoring.CollectingSearchRequestor) IField(org.eclipse.jdt.core.IField) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor)

Aggregations

SearchMatch (org.eclipse.jdt.core.search.SearchMatch)35 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)16 SearchPattern (org.eclipse.jdt.core.search.SearchPattern)13 SearchResultGroup (org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup)12 SearchEngine (org.eclipse.jdt.core.search.SearchEngine)10 ArrayList (java.util.ArrayList)8 CoreException (org.eclipse.core.runtime.CoreException)8 IJavaSearchScope (org.eclipse.jdt.core.search.IJavaSearchScope)8 SearchRequestor (org.eclipse.jdt.core.search.SearchRequestor)8 IJavaElement (org.eclipse.jdt.core.IJavaElement)7 SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)5 ReplaceEdit (org.eclipse.text.edits.ReplaceEdit)5 HashMap (java.util.HashMap)4 IResource (org.eclipse.core.resources.IResource)4 IMethod (org.eclipse.jdt.core.IMethod)4 RefactoringSearchEngine (org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine)4 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)4 HashSet (java.util.HashSet)3 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)3 IType (org.eclipse.jdt.core.IType)3