下面列出了com.intellij.psi.search.LocalSearchScope#com.intellij.util.Query 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Return an instance of search pattern.
*/
public Query<PsiModifierListOwner> createSearchPattern(SearchContext context) {
Query<PsiModifierListOwner> query = null;
String[] patterns = getPatterns();
if (patterns == null) {
return null;
}
for (String pattern : patterns) {
if (query == null) {
query = createSearchPattern(context, pattern);
} else {
Query<PsiModifierListOwner> rightQuery = createSearchPattern(context, pattern);
if (rightQuery != null) {
query = new MergeQuery<>(query, rightQuery);
}
}
}
return query;
}
public MicroProfileProjectInfo getMicroProfileProjectInfo(Module module,
List<MicroProfilePropertiesScope> scopes, ClasspathKind classpathKind, IPsiUtils utils,
DocumentFormat documentFormat) {
MicroProfileProjectInfo info = createInfo(module, classpathKind);
long startTime = System.currentTimeMillis();
boolean excludeTestCode = classpathKind == ClasspathKind.SRC;
PropertiesCollector collector = new PropertiesCollector(info, scopes);
SearchScope scope = createSearchScope(module, scopes, classpathKind == ClasspathKind.TEST);
SearchContext context = new SearchContext(module, scope, collector, utils, documentFormat);
DumbService.getInstance(module.getProject()).runReadActionInSmartMode(() -> {
Query<PsiModifierListOwner> query = createSearchQuery(context);
beginSearch(context);
query.forEach((Consumer<? super PsiModifierListOwner>) psiMember -> collectProperties(psiMember, context));
endSearch(context);
});
LOGGER.info("End computing MicroProfile properties for '" + info.getProjectURI() + "' in "
+ (System.currentTimeMillis() - startTime) + "ms.");
return info;
}
@Nullable
@Override
public List<UsageInfo> findUsages(final PsiFile psiFile, final PsiDirectory newParent, final boolean searchInComments, final boolean searchInNonJavaFiles) {
Query<PsiReference> search = ReferencesSearch.search(psiFile);
final List<PsiExtraFileReference> extraFileRefs = new ArrayList<PsiExtraFileReference>();
search.forEach(new Processor<PsiReference>() {
@Override
public boolean process(PsiReference psiReference) {
if (psiReference instanceof PsiExtraFileReference) {
extraFileRefs.add((PsiExtraFileReference) psiReference);
}
return true;
}
});
if (extraFileRefs.isEmpty()) {
return null;
} else {
final List<UsageInfo> result = new ArrayList<UsageInfo>(extraFileRefs.size());
for (final PsiExtraFileReference e : extraFileRefs) {
result.add(new FileUsageInfo(e));
}
return result;
}
}
public QuerySearchRequest(@Nonnull Query<PsiReference> query,
@Nonnull final SearchRequestCollector collector,
boolean inReadAction,
@Nonnull final PairProcessor<? super PsiReference, ? super SearchRequestCollector> processor) {
this.query = query;
this.collector = collector;
if (inReadAction) {
this.processor = new ReadActionProcessor<PsiReference>() {
@Override
public boolean processInReadAction(PsiReference psiReference) {
return processor.process(psiReference, collector);
}
};
}
else {
this.processor = psiReference -> processor.process(psiReference, collector);
}
}
@Nullable
private PsiPackage createPackage(@Nonnull String qualifiedName, @Nonnull Class<? extends ModuleExtension> extensionClass) {
Query<VirtualFile> dirs = myDirectoryIndex.getDirectoriesByPackageName(qualifiedName, true);
if (dirs.findFirst() == null) {
return null;
}
for (VirtualFile directory : dirs) {
PsiPackage packageFromProviders = createPackageFromProviders(directory, extensionClass, qualifiedName);
if (packageFromProviders != null) {
return packageFromProviders;
}
PsiPackage packageFromLibrary = createPackageFromLibrary(directory, extensionClass, qualifiedName);
if (packageFromLibrary != null) {
return packageFromLibrary;
}
}
return null;
}
@RequiredReadAction
@Override
public PsiPackage findAnyPackage(@Nonnull String packageName) {
Query<VirtualFile> dirs = myDirectoryIndex.getDirectoriesByPackageName(packageName, true);
if (dirs.findFirst() == null) {
return null;
}
PsiPackage packageFromCache = findAnyPackageFromCache(packageName);
if (packageFromCache != null) {
return packageFromCache;
}
for (VirtualFile dir : dirs) {
PsiPackage psiPackage = findAnyPackage(dir);
if (psiPackage != null) {
return psiPackage;
}
}
return null;
}
@Nullable
public static VirtualFile findResourceFileInScope(final String resourceName,
final Project project,
final GlobalSearchScope scope) {
int index = resourceName.lastIndexOf('/');
String packageName = index >= 0 ? resourceName.substring(0, index).replace('/', '.') : "";
final String fileName = index >= 0 ? resourceName.substring(index+1) : resourceName;
Query<VirtualFile> directoriesByPackageName = DirectoryIndex.getInstance(project).getDirectoriesByPackageName(packageName, true);
for (VirtualFile virtualFile : directoriesByPackageName) {
final VirtualFile child = virtualFile.findChild(fileName);
if(child != null && scope.contains(child)) {
return child;
}
}
return null;
}
static Collection<PsiFileSystemItem> getContextsForModule(@Nonnull Module module, @Nonnull String packageName, @Nullable GlobalSearchScope scope) {
List<PsiFileSystemItem> result = null;
Query<VirtualFile> query = DirectoryIndex.getInstance(module.getProject()).getDirectoriesByPackageName(packageName, false);
PsiManager manager = null;
for (VirtualFile file : query) {
if (scope != null && !scope.contains(file)) continue;
if (result == null) {
result = new ArrayList<>();
manager = PsiManager.getInstance(module.getProject());
}
PsiDirectory psiDirectory = manager.findDirectory(file);
if (psiDirectory != null) result.add(psiDirectory);
}
return result != null ? result : Collections.emptyList();
}
/**
* Create a search pattern for the given <code>annotationName</code> annotation
* name.
*
* @param annotationName the annotation name to search.
* @return a search pattern for the given <code>annotationName</code> annotation
* name.
*/
protected static Query<PsiModifierListOwner> createAnnotationTypeReferenceSearchPattern(SearchContext context, String annotationName) {
PsiClass annotationClass = context.getUtils().findClass(context.getModule(), annotationName);
if (annotationClass != null) {
return AnnotatedElementsSearch.searchElements(annotationClass, context.getScope(), PsiModifierListOwner.class);
} else {
return new EmptyQuery<>();
}
}
/**
* Create a search pattern for the given <code>className</code> class name.
*
* @param annotationName the class name to search.
* @return a search pattern for the given <code>className</code> class name.
*/
protected static Query<PsiModifierListOwner> createAnnotationTypeDeclarationSearchPattern(SearchContext context, String annotationName) {
JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(context.getModule().getProject());
PsiClass annotationClass = javaPsiFacade.findClass(annotationName, GlobalSearchScope.allScope(context.getModule().getProject()));
if (annotationClass != null) {
return new ArrayQuery<>(annotationClass);
} else {
return new EmptyQuery<>();
}
}
private Query<PsiModifierListOwner> createSearchQuery(SearchContext context) {
Query<PsiModifierListOwner> query = null;
for(IPropertiesProvider provider : IPropertiesProvider.EP_NAME.getExtensions()) {
Query<PsiModifierListOwner> providerQuery = provider.createSearchPattern(context);
if (providerQuery != null) {
if (query == null) {
query = providerQuery;
} else {
query = new MergeQuery<>(query, providerQuery);
}
}
}
return query;
}
private static void validateInterfaceType(PsiClass interfaceType, List<Diagnostic> diagnostics,
JavaDiagnosticsContext context) {
boolean hasRegisterRestClient = AnnotationUtils.hasAnnotation(interfaceType, REGISTER_REST_CLIENT_ANNOTATION);
if (hasRegisterRestClient) {
return;
}
final AtomicInteger nbReferences = new AtomicInteger(0);
Query<PsiReference> query = ReferencesSearch.search(interfaceType, createSearchScope(context.getJavaProject()));
query.forEach(match -> {
PsiElement o = PsiTreeUtil.getParentOfType(match.getElement(), PsiField.class);
if (o instanceof PsiField) {
PsiField field = (PsiField) o;
boolean hasInjectAnnotation = AnnotationUtils.hasAnnotation(field, INJECT_ANNOTATION);
boolean hasRestClientAnnotation = AnnotationUtils.hasAnnotation(field, REST_CLIENT_ANNOTATION);
if (hasInjectAnnotation && hasRestClientAnnotation) {
nbReferences.incrementAndGet();
}
}
});
if (nbReferences.get() > 0) {
String uri = context.getUri();
Range restInterfaceRange = PositionUtils.toNameRange(interfaceType, context.getUtils());
Diagnostic d = context.createDiagnostic(uri,
"The interface `" + interfaceType.getName()
+ "` does not have the @RegisterRestClient annotation. The " + nbReferences.get()
+ " fields references will not be injected as CDI beans.",
restInterfaceRange, MicroProfileRestClientConstants.DIAGNOSTIC_SOURCE,
MicroProfileRestClientErrorCode.RegisterRestClientAnnotationMissing);
diagnostics.add(d);
}
}
/**
* Return a list of {@link PsiClass}s annotated with the specified annotation
* @param project - Project reference to narrow the search inside.
* @param annotation - the full qualify annotation name to search for
* @return a list of classes annotated with the specified annotation.
*/
@NotNull
private Collection<PsiClass> getClassesAnnotatedWith(Project project, String annotation) {
PsiClass stepClass = JavaPsiFacade.getInstance(project).findClass(annotation, ProjectScope.getLibrariesScope(project));
if (stepClass != null) {
final Query<PsiClass> psiMethods = AnnotatedElementsSearch.searchPsiClasses(stepClass, GlobalSearchScope.allScope(project));
return psiMethods.findAll();
}
return Collections.emptyList();
}
public static void method(Project project, PsiJavaFile psiJavaFile, int type, MethodEntity methodEntity, boolean isDel) {
for (PsiElement psiInterface :
getClasses(psiJavaFile)) {
if (psiInterface instanceof PsiClass) {
switch (type) {
case ChangeMVPDialog.VIEW:
if (!ClassHelper.VIEW.equals(((PsiClass) psiInterface).getName())) continue;
break;
case ChangeMVPDialog.PRESENTER:
if (!ClassHelper.PRESENTER.equals(((PsiClass) psiInterface).getName())) continue;
break;
case ChangeMVPDialog.MODEL:
if (!ClassHelper.MODEL.equals(((PsiClass) psiInterface).getName())) continue;
break;
}
if (isDel) {
delMethod(project, psiInterface, methodEntity);
} else {
ClassHelper.addMethodToClass(project, (PsiClass) psiInterface, createList(methodEntity), false);
}
if (((PsiClass) psiInterface).getExtendsList() == null) return;
// ClassInheritorsSearch query = ClassInheritorsSearch.search((PsiClass) psiInterface, true);
Query<PsiClass> query = ClassInheritorsSearch.search((PsiClass) psiInterface);
for (Iterator<PsiClass> it = query.iterator(); it.hasNext(); ) {
PsiClass p = it.next();
if (isDel) {
delMethod(project, p, methodEntity);
} else {
ClassHelper.addMethodToClass(project, p, createList(methodEntity), true);
}
}
}
}
}
private static List<PsiClass> findConcernsCandidates( final @NotNull PsiClass classToCheck )
{
GlobalSearchScope searchScope = determineSearchScope( classToCheck );
PsiClass concernOfClass = getConcernOfClass( classToCheck.getProject(), searchScope );
if( concernOfClass == null )
{
return emptyList();
}
Query<PsiClass> psiClassQuery = search( concernOfClass, searchScope, true, false );
final List<PsiClass> concernCandidates = new ArrayList<PsiClass>();
psiClassQuery.forEach( new Processor<PsiClass>()
{
public boolean process( PsiClass psiClass )
{
// TODO: Ideally search for all "extends" as well
boolean isInheritor = psiClass.isInheritor( classToCheck, true );
if( isInheritor )
{
concernCandidates.add( psiClass );
}
return true;
}
} );
return concernCandidates;
}
@Test
public void testComment() {
PsiFile file = myFixture.configureByText(BashFileType.BASH_FILE_TYPE, "# fixme: a\n# b");
Query<IndexPatternOccurrence> result = IndexPatternSearch.search(file, TodoIndexPatternProvider.getInstance(), true);
Collection<IndexPatternOccurrence> matches = result.findAll();
Assert.assertEquals(1, matches.size());
IndexPatternOccurrence first = matches.iterator().next();
Assert.assertEquals("A multiline comment must be detected as a single occurence with one additional text range", 1, first.getAdditionalTextRanges().size());
}
/**
* Returns references to the given element. If it is a BashPsiElement a special search scope is used to locate the elements referencing the file.
*
* @param element References to the given element
* @return
*/
@NotNull
@Override
public Collection<PsiReference> findReferences(PsiElement element) {
//fixme fix the custom scope
SearchScope scope = (element instanceof BashPsiElement)
? BashElementSharedImpl.getElementUseScope((BashPsiElement) element, element.getProject())
: GlobalSearchScope.projectScope(element.getProject());
Query<PsiReference> search = ReferencesSearch.search(element, scope);
return search.findAll();
}
@RequiredReadAction
@Nullable
@Override
public HighlightInfoFactory checkImpl(@Nonnull CSharpLanguageVersion languageVersion, @Nonnull CSharpHighlightContext highlightContext, @Nonnull CSharpFieldDeclaration element)
{
if(!element.hasModifier(CSharpModifier.PRIVATE))
{
return null;
}
PsiElement parent = element.getParent();
if(!(parent instanceof CSharpTypeDeclaration))
{
return null;
}
PsiElement nameIdentifier = element.getNameIdentifier();
if(nameIdentifier == null)
{
return null;
}
Query<PsiReference> search = ReferencesSearch.search(element, CSharpCompositeTypeDeclaration.createLocalScope((DotNetTypeDeclaration) parent));
if(search.findFirst() == null)
{
return newBuilder(nameIdentifier, formatElement(element));
}
return null;
}
public static Query<PsiMethod> search(final PsiMethod method, SearchScope scope, final boolean checkDeep, HaxeHierarchyTimeoutHandler timeoutHandler) {
if (ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
@Override
public Boolean compute() {
return cannotBeOverriden(method);
}
})) return EmptyQuery.getEmptyQuery(); // Optimization
return INSTANCE.createUniqueResultsQuery(new SearchParameters(method, scope, checkDeep));
}
public static Query<PsiMethod> search(final PsiMethod method, final boolean checkDeep, HaxeHierarchyTimeoutHandler timeoutHandler) {
return search(method, ApplicationManager.getApplication().runReadAction(new Computable<SearchScope>() {
@Override
public SearchScope compute() {
return method.getUseScope();
}
}), checkDeep, timeoutHandler);
}
private void processMethodsDuplicates() {
ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
if (!myTargetSuperClass.isValid()) return;
final Query<PsiClass> search = ClassInheritorsSearch.search(myTargetSuperClass);
final Set<VirtualFile> hierarchyFiles = new HashSet<VirtualFile>();
for (PsiClass aClass : search) {
final PsiFile containingFile = aClass.getContainingFile();
if (containingFile != null) {
final VirtualFile virtualFile = containingFile.getVirtualFile();
if (virtualFile != null) {
hierarchyFiles.add(virtualFile);
}
}
}
final Set<PsiMember> methodsToSearchDuplicates = new HashSet<PsiMember>();
for (PsiMember psiMember : myMembersAfterMove) {
if (psiMember instanceof PsiMethod && psiMember.isValid() && ((PsiMethod)psiMember).getBody() != null) {
methodsToSearchDuplicates.add(psiMember);
}
}
MethodDuplicatesHandler.invokeOnScope(myProject, methodsToSearchDuplicates, new AnalysisScope(myProject, hierarchyFiles), true);
}
});
}
}, MethodDuplicatesHandler.REFACTORING_NAME, true, myProject);
}
protected Collection<PsiDirectory> getAllDirectories(boolean inLibrarySources) {
List<PsiDirectory> directories = new ArrayList<PsiDirectory>();
PsiManager manager = PsiManager.getInstance(getProject());
Query<VirtualFile> directoriesByPackageName =
DirectoryIndex.getInstance(getProject()).getDirectoriesByPackageName(getQualifiedName(), inLibrarySources);
for (VirtualFile virtualFile : directoriesByPackageName) {
PsiDirectory directory = manager.findDirectory(virtualFile);
if (directory != null) {
directories.add(directory);
}
}
return directories;
}
@Nullable
private static PsiDirectory getWritableModuleDirectory(@Nonnull Query<VirtualFile> vFiles,
GlobalSearchScope scope,
PsiManager manager) {
for (VirtualFile vFile : vFiles) {
if (!scope.contains(vFile)) continue;
PsiDirectory directory = manager.findDirectory(vFile);
if (directory != null && directory.isValid() && directory.isWritable()) {
return directory;
}
}
return null;
}
private static PsiDirectory[] getPackageDirectories(Project project, String rootPackage, final GlobalSearchScope scope) {
final PsiManager manager = PsiManager.getInstance(project);
Query<VirtualFile> query = DirectoryIndex.getInstance(scope.getProject()).getDirectoriesByPackageName(rootPackage, true);
query = new FilteredQuery<>(query, scope::contains);
List<PsiDirectory> directories = ContainerUtil.mapNotNull(query.findAll(), manager::findDirectory);
return directories.toArray(new PsiDirectory[directories.size()]);
}
protected Collection<PsiReference> collectRefs(SearchScope referencesSearchScope) {
final Query<PsiReference> search = ReferencesSearch.search(myElementToRename, referencesSearchScope, false);
final CommonProcessors.CollectProcessor<PsiReference> processor = new CommonProcessors.CollectProcessor<PsiReference>() {
@Override
protected boolean accept(PsiReference reference) {
return acceptReference(reference);
}
};
search.forEach(processor);
return processor.getResults();
}
protected Collection<PsiElement> findElementsToHighlight(M caller, PsiElement callee) {
Query<PsiReference> references = ReferencesSearch.search(callee, new LocalSearchScope(caller), false);
return ContainerUtil.mapNotNull(references, new Function<PsiReference, PsiElement>() {
@Override
public PsiElement fun(PsiReference psiReference) {
return psiReference.getElement();
}
});
}
@Override
protected Query<PsiModifierListOwner> createSearchPattern(SearchContext context, String annotationName) {
return createAnnotationTypeReferenceSearchPattern(context, annotationName);
}
@Override
protected Query<PsiModifierListOwner> createSearchPattern(SearchContext context, String pattern) {
return null;
}
@Override
protected Query<PsiModifierListOwner> createSearchPattern(SearchContext context, String annotationName) {
return createAnnotationTypeDeclarationSearchPattern(context, annotationName);
}
@Nonnull
@RequiredReadAction
public static Collection<DotNetVirtualImplementOwner> collectOverridenMembers(final DotNetVirtualImplementOwner target)
{
PsiElement parent = target.getParent();
if(!(parent instanceof DotNetTypeDeclaration))
{
return Collections.emptyList();
}
final CSharpResolveSelector selector;
if(target instanceof CSharpIndexMethodDeclaration)
{
selector = StaticResolveSelectors.INDEX_METHOD_GROUP;
}
else
{
String name = ((PsiNamedElement) target).getName();
if(name != null)
{
selector = new MemberByNameSelector(name);
}
else
{
selector = null;
}
}
if(selector == null)
{
return Collections.emptyList();
}
final GlobalSearchScope resolveScope = target.getResolveScope();
final List<DotNetVirtualImplementOwner> list = new ArrayList<>();
Query<DotNetTypeDeclaration> search = TypeInheritorsSearch.search((DotNetTypeDeclaration) parent, true, CSharpTransform.INSTANCE);
search.forEach(new Processor<DotNetTypeDeclaration>()
{
@Override
@RequiredReadAction
public boolean process(DotNetTypeDeclaration typeDeclaration)
{
CSharpResolveContext context = CSharpResolveContextUtil.createContext(DotNetGenericExtractor.EMPTY, resolveScope, typeDeclaration);
Collection<PsiElement> elements = selector.doSelectElement(context, false);
for(PsiElement element : CSharpResolveUtil.mergeGroupsToIterable(elements))
{
if(element == target)
{
continue;
}
if(CSharpElementCompareUtil.isEqual(element, target, CSharpElementCompareUtil.CHECK_RETURN_TYPE, target))
{
list.add((DotNetVirtualImplementOwner) element);
}
}
return true;
}
});
return list;
}