Search in sources :

Example 1 with ICompilationUnit

use of org.eclipse.jdt.core.ICompilationUnit in project che by eclipse.

the class Util method getCompilationUnit.

private static ICompilationUnit getCompilationUnit(char[] fileName, WorkingCopyOwner workingCopyOwner) {
    char[] slashSeparatedFileName = CharOperation.replaceOnCopy(fileName, File.separatorChar, '/');
    // pkgEnd is exclusive
    int pkgEnd = CharOperation.lastIndexOf('/', slashSeparatedFileName);
    if (pkgEnd == -1)
        return null;
    IPackageFragment pkg = getPackageFragment(slashSeparatedFileName, pkgEnd, -1);
    if (pkg == null)
        return null;
    int start;
    ICompilationUnit cu = pkg.getCompilationUnit(new String(slashSeparatedFileName, start = pkgEnd + 1, slashSeparatedFileName.length - start));
    if (workingCopyOwner != null) {
        ICompilationUnit workingCopy = cu.findWorkingCopy(workingCopyOwner);
        if (workingCopy != null)
            return workingCopy;
    }
    return cu;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IPackageFragment(org.eclipse.jdt.core.IPackageFragment)

Example 2 with ICompilationUnit

use of org.eclipse.jdt.core.ICompilationUnit in project che by eclipse.

the class ContextSensitiveImportRewriteContext method findInContext.

@Override
public int findInContext(String qualifier, String name, int kind) {
    IBinding[] declarationsInScope = getDeclarationsInScope();
    for (int i = 0; i < declarationsInScope.length; i++) {
        if (declarationsInScope[i] instanceof ITypeBinding) {
            ITypeBinding typeBinding = (ITypeBinding) declarationsInScope[i];
            if (isSameType(typeBinding, qualifier, name)) {
                return RES_NAME_FOUND;
            } else if (isConflicting(typeBinding, name)) {
                return RES_NAME_CONFLICT;
            }
        } else if (declarationsInScope[i] != null) {
            if (isConflicting(declarationsInScope[i], name)) {
                return RES_NAME_CONFLICT;
            }
        }
    }
    Name[] names = getImportedNames();
    for (int i = 0; i < names.length; i++) {
        IBinding binding = names[i].resolveBinding();
        if (binding instanceof ITypeBinding && !binding.isRecovered()) {
            ITypeBinding typeBinding = (ITypeBinding) binding;
            if (isConflictingType(typeBinding, qualifier, name)) {
                return RES_NAME_CONFLICT;
            }
        }
    }
    List<AbstractTypeDeclaration> list = fCompilationUnit.types();
    for (Iterator<AbstractTypeDeclaration> iter = list.iterator(); iter.hasNext(); ) {
        AbstractTypeDeclaration type = iter.next();
        ITypeBinding binding = type.resolveBinding();
        if (binding != null) {
            if (isSameType(binding, qualifier, name)) {
                return RES_NAME_FOUND;
            } else {
                ITypeBinding decl = containingDeclaration(binding, qualifier, name);
                while (decl != null && !decl.equals(binding)) {
                    int modifiers = decl.getModifiers();
                    if (Modifier.isPrivate(modifiers))
                        return RES_NAME_CONFLICT;
                    decl = decl.getDeclaringClass();
                }
            }
        }
    }
    String[] addedImports = fImportRewrite.getAddedImports();
    String qualifiedName = JavaModelUtil.concatenateName(qualifier, name);
    for (int i = 0; i < addedImports.length; i++) {
        String addedImport = addedImports[i];
        if (qualifiedName.equals(addedImport)) {
            return RES_NAME_FOUND;
        } else {
            if (isConflicting(name, addedImport))
                return RES_NAME_CONFLICT;
        }
    }
    if (qualifier.equals("java.lang")) {
        //$NON-NLS-1$
        //No explicit import statement required
        ITypeRoot typeRoot = fCompilationUnit.getTypeRoot();
        if (typeRoot != null) {
            IPackageFragment packageFragment = (IPackageFragment) typeRoot.getParent();
            try {
                ICompilationUnit[] compilationUnits = packageFragment.getCompilationUnits();
                for (int i = 0; i < compilationUnits.length; i++) {
                    ICompilationUnit cu = compilationUnits[i];
                    IType[] allTypes = cu.getAllTypes();
                    for (int j = 0; j < allTypes.length; j++) {
                        IType type = allTypes[j];
                        String packageTypeName = type.getFullyQualifiedName();
                        if (isConflicting(name, packageTypeName))
                            return RES_NAME_CONFLICT;
                    }
                }
            } catch (JavaModelException e) {
            }
        }
    }
    return fImportRewrite.getDefaultImportRewriteContext().findInContext(qualifier, name, kind);
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) JavaModelException(org.eclipse.jdt.core.JavaModelException) IBinding(org.eclipse.jdt.core.dom.IBinding) ITypeRoot(org.eclipse.jdt.core.ITypeRoot) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) IType(org.eclipse.jdt.core.IType) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 3 with ICompilationUnit

use of org.eclipse.jdt.core.ICompilationUnit 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 4 with ICompilationUnit

use of org.eclipse.jdt.core.ICompilationUnit in project che by eclipse.

the class RenameMethodProcessor method getDeclarationCUs.

private ICompilationUnit[] getDeclarationCUs() {
    Set<ICompilationUnit> cus = new HashSet<ICompilationUnit>();
    for (Iterator<IMethod> iter = fMethodsToRename.iterator(); iter.hasNext(); ) {
        IMethod method = iter.next();
        cus.add(method.getCompilationUnit());
    }
    return cus.toArray(new ICompilationUnit[cus.size()]);
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IMethod(org.eclipse.jdt.core.IMethod) HashSet(java.util.HashSet)

Example 5 with ICompilationUnit

use of org.eclipse.jdt.core.ICompilationUnit 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)

Aggregations

ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)1974 Test (org.junit.Test)1481 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)1455 ArrayList (java.util.ArrayList)836 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)548 List (java.util.List)476 AssistContext (org.eclipse.jdt.internal.ui.text.correction.AssistContext)385 CUCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal)284 Hashtable (java.util.Hashtable)143 IType (org.eclipse.jdt.core.IType)136 IPackageFragmentRoot (org.eclipse.jdt.core.IPackageFragmentRoot)103 ASTNode (org.eclipse.jdt.core.dom.ASTNode)97 JavaModelException (org.eclipse.jdt.core.JavaModelException)82 IJavaElement (org.eclipse.jdt.core.IJavaElement)81 OrganizeImportsOperation (org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation)70 IChooseImportQuery (org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery)70 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)65 IJavaProject (org.eclipse.jdt.core.IJavaProject)63 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)62 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)56