Search in sources :

Example 1 with IRestrictedAccessTypeRequestor

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

the class JavaModelManager method secondaryTypesSearching.

/*
     * Perform search request to get all secondary types of a given project.
     * If not waiting for indexes and indexing is running, will return types found in current built indexes...
     */
private Map secondaryTypesSearching(IJavaProject project, boolean waitForIndexes, IProgressMonitor monitor, final PerProjectInfo projectInfo) throws JavaModelException {
    if (VERBOSE || BasicSearchEngine.VERBOSE) {
        //$NON-NLS-1$
        StringBuffer buffer = new StringBuffer("JavaModelManager.secondaryTypesSearch(");
        buffer.append(project.getElementName());
        buffer.append(',');
        buffer.append(waitForIndexes);
        buffer.append(')');
        Util.verbose(buffer.toString());
    }
    final Hashtable secondaryTypes = new Hashtable(3);
    IRestrictedAccessTypeRequestor nameRequestor = new IRestrictedAccessTypeRequestor() {

        public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) {
            //$NON-NLS-1$
            String key = packageName == null ? "" : new String(packageName);
            HashMap types = (HashMap) secondaryTypes.get(key);
            if (types == null)
                types = new HashMap(3);
            types.put(new String(simpleTypeName), path);
            secondaryTypes.put(key, types);
        }
    };
    // Build scope using prereq projects but only source folders
    IPackageFragmentRoot[] allRoots = project.getAllPackageFragmentRoots();
    int length = allRoots.length, size = 0;
    IPackageFragmentRoot[] allSourceFolders = new IPackageFragmentRoot[length];
    for (int i = 0; i < length; i++) {
        if (allRoots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
            allSourceFolders[size++] = allRoots[i];
        }
    }
    if (size < length) {
        System.arraycopy(allSourceFolders, 0, allSourceFolders = new IPackageFragmentRoot[size], 0, size);
    }
    // Search all secondary types on scope
    new BasicSearchEngine().searchAllSecondaryTypeNames(allSourceFolders, nameRequestor, waitForIndexes, monitor);
    // Build types from paths
    Iterator packages = secondaryTypes.values().iterator();
    while (packages.hasNext()) {
        HashMap types = (HashMap) packages.next();
        HashMap tempTypes = new HashMap(types.size());
        Iterator names = types.entrySet().iterator();
        while (names.hasNext()) {
            Map.Entry entry = (Map.Entry) names.next();
            String typeName = (String) entry.getKey();
            String path = (String) entry.getValue();
            names.remove();
            if (Util.isJavaLikeFileName(path)) {
                IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(path));
                ICompilationUnit unit = org.eclipse.jdt.internal.core.JavaModelManager.createCompilationUnitFrom(file, null);
                IType type = unit.getType(typeName);
                tempTypes.put(typeName, type);
            }
        }
        types.putAll(tempTypes);
    }
    // Store result in per project info cache if still null or there's still an indexing cache (may have been set by another thread...)
    if (projectInfo.secondaryTypes == null || projectInfo.secondaryTypes.get(INDEXED_SECONDARY_TYPES) != null) {
        projectInfo.secondaryTypes = secondaryTypes;
        if (VERBOSE || BasicSearchEngine.VERBOSE) {
            //$NON-NLS-1$
            System.out.print(Thread.currentThread() + "	-> secondary paths stored in cache: ");
            System.out.println();
            Iterator entries = secondaryTypes.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry entry = (Map.Entry) entries.next();
                String qualifiedName = (String) entry.getKey();
                //$NON-NLS-1$
                Util.verbose("		- " + qualifiedName + '-' + entry.getValue());
            }
        }
    }
    return projectInfo.secondaryTypes;
}
Also used : IPath(org.eclipse.core.runtime.IPath) Path(org.eclipse.core.runtime.Path) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AccessRestriction(org.eclipse.jdt.internal.compiler.env.AccessRestriction) IFile(org.eclipse.core.resources.IFile) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) Hashtable(java.util.Hashtable) IRestrictedAccessTypeRequestor(org.eclipse.jdt.internal.core.search.IRestrictedAccessTypeRequestor) BasicSearchEngine(org.eclipse.jdt.internal.core.search.BasicSearchEngine) IPackageFragmentRoot(org.eclipse.jdt.core.IPackageFragmentRoot) IType(org.eclipse.jdt.core.IType) IClasspathEntry(org.eclipse.jdt.core.IClasspathEntry) Iterator(java.util.Iterator) Map(java.util.Map) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap)

Example 2 with IRestrictedAccessTypeRequestor

use of org.eclipse.jdt.internal.core.search.IRestrictedAccessTypeRequestor in project xtext-eclipse by eclipse.

the class InteractiveUnresolvedTypeResolver method findCandidateTypes.

protected void findCandidateTypes(final JvmDeclaredType contextType, final String typeSimpleName, IJavaSearchScope searchScope, final IAcceptor<JvmDeclaredType> acceptor) throws JavaModelException {
    BasicSearchEngine searchEngine = new BasicSearchEngine();
    final IVisibilityHelper contextualVisibilityHelper = new ContextualVisibilityHelper(visibilityHelper, contextType);
    searchEngine.searchAllTypeNames(null, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, typeSimpleName.toCharArray(), SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, IJavaSearchConstants.TYPE, searchScope, new IRestrictedAccessTypeRequestor() {

        @Override
        public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) {
            final String qualifiedTypeName = getQualifiedTypeName(packageName, enclosingTypeNames, simpleTypeName);
            if ((access == null || (access.getProblemId() != IProblem.ForbiddenReference && !access.ignoreIfBetter())) && !TypeFilter.isFiltered(packageName, simpleTypeName)) {
                JvmType importType = typeRefs.findDeclaredType(qualifiedTypeName, contextType.eResource());
                if (importType instanceof JvmDeclaredType && contextualVisibilityHelper.isVisible((JvmDeclaredType) importType)) {
                    acceptor.accept((JvmDeclaredType) importType);
                }
            }
        }
    }, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, new NullProgressMonitor());
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) AccessRestriction(org.eclipse.jdt.internal.compiler.env.AccessRestriction) BasicSearchEngine(org.eclipse.jdt.internal.core.search.BasicSearchEngine) IRestrictedAccessTypeRequestor(org.eclipse.jdt.internal.core.search.IRestrictedAccessTypeRequestor) JvmDeclaredType(org.eclipse.xtext.common.types.JvmDeclaredType) IVisibilityHelper(org.eclipse.xtext.xbase.typesystem.util.IVisibilityHelper) JvmType(org.eclipse.xtext.common.types.JvmType) ContextualVisibilityHelper(org.eclipse.xtext.xbase.typesystem.util.ContextualVisibilityHelper)

Example 3 with IRestrictedAccessTypeRequestor

use of org.eclipse.jdt.internal.core.search.IRestrictedAccessTypeRequestor in project xtext-eclipse by eclipse.

the class JdtTypesProposalProvider method searchAndCreateProposals.

protected void searchAndCreateProposals(IJavaSearchScope scope, final ICompletionProposalFactory proposalFactory, ContentAssistContext context, EReference typeReference, final Filter filter, final IValueConverter<String> valueConverter, final ICompletionProposalAcceptor acceptor) throws JavaModelException {
    String prefix = context.getPrefix();
    List<String> split = Strings.split(prefix, '.');
    char[] typeName = null;
    char[] packageName = null;
    if (prefix.length() > 0 && !split.isEmpty()) {
        CharMatcher dotMatcher = CharMatcher.is('.');
        if (Character.isUpperCase(split.get(split.size() - 1).charAt(0))) {
            typeName = split.get(split.size() - 1).toCharArray();
            if (split.size() > 1)
                packageName = ("*" + dotMatcher.replaceFrom(prefix.substring(0, prefix.length() - (typeName.length + 1)), "*.") + "*").toCharArray();
        } else {
            if (prefix.endsWith("."))
                prefix = prefix.substring(0, prefix.length() - 1);
            packageName = ("*" + dotMatcher.replaceFrom(prefix, "*.") + "*").toCharArray();
        }
    }
    IScope typeScope = null;
    if (context.getCurrentModel() != null) {
        typeScope = scopeProvider.getScope(context.getCurrentModel(), typeReference);
    }
    final IReplacementTextApplier textApplier = createTextApplier(context, typeScope, qualifiedNameConverter, valueConverter);
    final ICompletionProposalAcceptor scopeAware = textApplier != null ? new ICompletionProposalAcceptor.Delegate(acceptor) {

        @Override
        public void accept(ICompletionProposal proposal) {
            if (proposal instanceof ConfigurableCompletionProposal) {
                ((ConfigurableCompletionProposal) proposal).setTextApplier(textApplier);
            }
            super.accept(proposal);
        }
    } : acceptor;
    Builder contextBuilder = context.copy();
    final PrefixMatcher original = context.getMatcher();
    contextBuilder.setMatcher(new PrefixMatcher() {

        @Override
        public boolean isCandidateMatchingPrefix(String name, String prefix) {
            if (original.isCandidateMatchingPrefix(name, prefix))
                return true;
            String nameWithoutDollars = name.replace('$', '.');
            String prefixWithoutDollars = prefix.replace('$', '.');
            final boolean nameOrPrefixHasDollars = (nameWithoutDollars != name) || (prefixWithoutDollars != prefix);
            if (nameOrPrefixHasDollars && original.isCandidateMatchingPrefix(nameWithoutDollars, prefixWithoutDollars))
                return true;
            String sub = nameWithoutDollars;
            int delimiter = sub.indexOf('.');
            while (delimiter != -1) {
                sub = sub.substring(delimiter + 1);
                delimiter = sub.indexOf('.');
                if (delimiter == -1 || prefixWithoutDollars.length() > 0 && Character.isLowerCase(prefixWithoutDollars.charAt(0))) {
                    if (original.isCandidateMatchingPrefix(sub, prefixWithoutDollars))
                        return true;
                }
            }
            return false;
        }
    });
    final ContentAssistContext myContext = contextBuilder.toContext();
    final IJvmTypeProvider jvmTypeProvider = jdtTypeProviderFactory.findOrCreateTypeProvider(context.getResource().getResourceSet());
    final Set<String> filteredTypeNames = getDirtyTypeNames();
    final Filter dirtyTypenameFilter = new ITypesProposalProvider.Filter() {

        @Override
        public boolean accept(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) {
            if (path == null || path.endsWith(".class") || path.endsWith(".java")) {
                // Java index match
                String identifier = getIdentifier(packageName, simpleTypeName, enclosingTypeNames);
                if (filteredTypeNames.contains(identifier)) {
                    return false;
                }
            }
            return true;
        }

        @Override
        public int getSearchFor() {
            return filter.getSearchFor();
        }
    };
    BasicSearchEngine searchEngine = new BasicSearchEngine();
    searchEngine.searchAllTypeNames(packageName, SearchPattern.R_PATTERN_MATCH, typeName, SearchPattern.R_PREFIX_MATCH | SearchPattern.R_CAMELCASE_MATCH, filter.getSearchFor(), scope, new IRestrictedAccessTypeRequestor() {

        @Override
        public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) {
            if (dirtyTypenameFilter.accept(modifiers, packageName, simpleTypeName, enclosingTypeNames, path) && filter.accept(modifiers, packageName, simpleTypeName, enclosingTypeNames, path) && (!checkAccessRestriction() || (access == null || access.getProblemId() != IProblem.ForbiddenReference && !access.ignoreIfBetter()))) {
                StringBuilder fqName = new StringBuilder(packageName.length + simpleTypeName.length + 1);
                if (packageName.length != 0) {
                    fqName.append(packageName);
                    fqName.append('.');
                }
                for (char[] enclosingType : enclosingTypeNames) {
                    /*
								 * the JDT index sometimes yields enclosingTypeNames in the form
								 * char[][] { { Outer$Middle } }
								 * rather than
								 * char[][] { { Outer }, { Middle } }
								 * thus we create the fqName as the binary name and post process the proposal later on
								 */
                    fqName.append(enclosingType);
                    fqName.append('$');
                }
                fqName.append(simpleTypeName);
                String fqNameAsString = fqName.toString();
                createTypeProposal(fqNameAsString, modifiers, enclosingTypeNames.length > 0, proposalFactory, myContext, scopeAware, jvmTypeProvider, valueConverter);
            }
        }
    }, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, new NullProgressMonitor() {

        @Override
        public boolean isCanceled() {
            return !acceptor.canAcceptMoreProposals();
        }
    });
    if (acceptor.canAcceptMoreProposals()) {
        Iterable<IEObjectDescription> allDirtyTypes = dirtyStateManager.getExportedObjectsByType(TypesPackage.Literals.JVM_TYPE);
        for (IEObjectDescription description : allDirtyTypes) {
            QualifiedName qualifiedName = description.getQualifiedName();
            final int modifiers = getDirtyStateModifiers(context, description);
            if (filter.accept(modifiers, qualifiedName.skipLast(1).toString().toCharArray(), qualifiedName.getLastSegment().toCharArray(), new char[0][0], description.getEObjectURI().toPlatformString(true))) {
                String fqName = description.getQualifiedName().toString();
                createTypeProposal(fqName, modifiers, fqName.indexOf('$') > 0, proposalFactory, myContext, scopeAware, jvmTypeProvider, valueConverter);
            }
        }
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) AccessRestriction(org.eclipse.jdt.internal.compiler.env.AccessRestriction) IReplacementTextApplier(org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal.IReplacementTextApplier) BasicSearchEngine(org.eclipse.jdt.internal.core.search.BasicSearchEngine) Builder(org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext.Builder) StyledString(org.eclipse.jface.viewers.StyledString) ICompletionProposalAcceptor(org.eclipse.xtext.ui.editor.contentassist.ICompletionProposalAcceptor) IJvmTypeProvider(org.eclipse.xtext.common.types.access.IJvmTypeProvider) IEObjectDescription(org.eclipse.xtext.resource.IEObjectDescription) ConfigurableCompletionProposal(org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) IScope(org.eclipse.xtext.scoping.IScope) PrefixMatcher(org.eclipse.xtext.ui.editor.contentassist.PrefixMatcher) IRestrictedAccessTypeRequestor(org.eclipse.jdt.internal.core.search.IRestrictedAccessTypeRequestor) CharMatcher(com.google.common.base.CharMatcher) QualifiedName(org.eclipse.xtext.naming.QualifiedName) ContentAssistContext(org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext)

Aggregations

AccessRestriction (org.eclipse.jdt.internal.compiler.env.AccessRestriction)3 BasicSearchEngine (org.eclipse.jdt.internal.core.search.BasicSearchEngine)3 IRestrictedAccessTypeRequestor (org.eclipse.jdt.internal.core.search.IRestrictedAccessTypeRequestor)3 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)2 CharMatcher (com.google.common.base.CharMatcher)1 HashMap (java.util.HashMap)1 Hashtable (java.util.Hashtable)1 Iterator (java.util.Iterator)1 Map (java.util.Map)1 WeakHashMap (java.util.WeakHashMap)1 IFile (org.eclipse.core.resources.IFile)1 IPath (org.eclipse.core.runtime.IPath)1 Path (org.eclipse.core.runtime.Path)1 IClasspathEntry (org.eclipse.jdt.core.IClasspathEntry)1 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)1 IPackageFragmentRoot (org.eclipse.jdt.core.IPackageFragmentRoot)1 IType (org.eclipse.jdt.core.IType)1 ICompletionProposal (org.eclipse.jface.text.contentassist.ICompletionProposal)1 StyledString (org.eclipse.jface.viewers.StyledString)1 JvmDeclaredType (org.eclipse.xtext.common.types.JvmDeclaredType)1