下面列出了com.intellij.psi.PsiRecursiveElementVisitor#com.intellij.util.Processor 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@RequiredReadAction
@Override
public void process(@Nonnull CSharpResolveOptions options,
@Nonnull DotNetGenericExtractor defaultExtractor,
@Nullable PsiElement forceQualifierElement,
@Nonnull Processor<ResolveResult> processor)
{
PsiElement element = options.getElement();
SimpleNamedScopeProcessor scopeProcessor = new SimpleNamedScopeProcessor(processor, options.isCompletion(), ExecuteTarget.LABEL);
DotNetQualifiedElement parentOfType = PsiTreeUtil.getParentOfType(element, DotNetQualifiedElement.class);
assert parentOfType != null;
ResolveState state = ResolveState.initial();
state = state.put(CSharpResolveUtil.SELECTOR, options.getSelector());
CSharpResolveUtil.walkForLabel(scopeProcessor, parentOfType, state);
}
@RequiredReadAction
@Override
public void process(@Nonnull CSharpResolveOptions options,
@Nonnull DotNetGenericExtractor defaultExtractor,
@Nullable PsiElement forceQualifierElement,
@Nonnull Processor<ResolveResult> processor)
{
PsiElement element = options.getElement();
DotNetParameterListOwner parameterListOwner = CSharpReferenceExpressionImplUtil.findParentOrNextIfDoc(element, DotNetParameterListOwner
.class);
if(parameterListOwner == null)
{
return;
}
SimpleNamedScopeProcessor scopeProcessor = new SimpleNamedScopeProcessor(processor, options.isCompletion(),
ExecuteTarget.LOCAL_VARIABLE_OR_PARAMETER_OR_LOCAL_METHOD);
ResolveState state = ResolveState.initial();
state = state.put(CSharpResolveUtil.SELECTOR, options.getSelector());
parameterListOwner.processDeclarations(scopeProcessor, state, null, element);
}
@NotNull
public static List<VirtualFile> getFilesNameByQName(@NotNull String qName, @NotNull final GlobalSearchScope filter) {
Project project = filter.getProject();
if (project != null) {
if (DumbService.isDumb(project)) {
return DUMB_MODE_LIST;
}
}
final List<VirtualFile> result = new ArrayList<VirtualFile>();
getFileNames(qName, new Processor<VirtualFile>() {
@Override
public boolean process(VirtualFile file) {
result.add(file);
return true;
}
}, filter);
return result;
}
/**
* @param project project
* @param key environment variable key
* @return All key usages, like getenv('KEY')
*/
@NotNull
public static PsiElement[] getKeyUsages(Project project, String key) {
List<PsiElement> targets = new ArrayList<>();
PsiSearchHelper searchHelper = PsiSearchHelper.getInstance(project);
Processor<PsiFile> psiFileProcessor = psiFile -> {
for (EnvironmentVariablesUsagesProvider provider : EnvironmentVariablesProviderUtil.USAGES_PROVIDERS) {
targets.addAll(EnvironmentVariablesUtil.getUsagesElementsByKey(key, provider.getUsages(psiFile)));
}
return true;
};
searchHelper.processAllFilesWithWord(key, GlobalSearchScope.allScope(project), psiFileProcessor, true);
searchHelper.processAllFilesWithWordInLiterals(key, GlobalSearchScope.allScope(project), psiFileProcessor);
return targets.toArray(PsiElement.EMPTY_ARRAY);
}
int findUsage(XmlTag element) {
final FindUsagesHandler handler = FindUsagesImpl171.getFindUsagesHandler(element, element.getProject());
if (handler != null) {
final FindUsagesOptions findUsagesOptions = handler.getFindUsagesOptions();
final PsiElement[] primaryElements = handler.getPrimaryElements();
final PsiElement[] secondaryElements = handler.getSecondaryElements();
Factory factory = new Factory() {
public UsageSearcher create() {
return FindUsagesImpl171.createUsageSearcher(primaryElements, secondaryElements, handler, findUsagesOptions, (PsiFile) null);
}
};
UsageSearcher usageSearcher = (UsageSearcher)factory.create();
final AtomicInteger mCount = new AtomicInteger(0);
usageSearcher.generate(new Processor<Usage>() {
@Override
public boolean process(Usage usage) {
if (ResourceUsageCountUtils.isUsefulUsageToCount(usage)) {
mCount.incrementAndGet();
}
return true;
}
});
return mCount.get();
}
return 0;
}
@Override
public boolean filterElements(@NotNull ChooseByNameBase base,
@NotNull String pattern,
boolean everywhere,
@NotNull ProgressIndicator indicator,
@NotNull Processor<Object> consumer) {
Collection<StringElement> elements = ((SearchStringModel) base.getModel()).getFilterItems();
if (elements != null) {
for (StringElement element : elements) {
String value = element.getValue();
if (value == null) {
return false;
}
if (value.toLowerCase().contains(pattern.toLowerCase()) && !consumer.process(element)) {
return false;
}
}
}
return false;
}
@Override
public void processQuery(
SearchParameters queryParameters, Processor<? super PsiReference> consumer) {
PsiFileSystemItem file =
ResolveUtil.asFileSystemItemSearch(queryParameters.getElementToSearch());
if (file == null) {
return;
}
BlazePackage containingPackage = BlazePackage.getContainingPackage(file);
if (containingPackage == null || !inScope(queryParameters, containingPackage.buildFile)) {
return;
}
String relativePath = containingPackage.getRelativePathToChild(file.getVirtualFile());
if (relativePath == null) {
return;
}
List<GlobExpression> globs =
PsiUtils.findAllChildrenOfClassRecursive(containingPackage.buildFile, GlobExpression.class);
for (GlobExpression glob : globs) {
if (glob.matches(relativePath, file.isDirectory())) {
consumer.process(globReference(glob, file));
}
}
}
public BuildElement findSymbolInScope(String name) {
BuildElement[] resultHolder = new BuildElement[1];
Processor<BuildElement> processor =
buildElement -> {
if (buildElement instanceof LoadedSymbol) {
buildElement =
BuildElement.asBuildElement(((LoadedSymbol) buildElement).getVisibleElement());
}
if (buildElement instanceof PsiNamedElement && name.equals(buildElement.getName())) {
resultHolder[0] = buildElement;
return false;
}
return true;
};
searchSymbolsInScope(processor, null);
return resultHolder[0];
}
@Override
public void processElementsWithName(
@Nonnull String name, @Nonnull Processor<NavigationItem> navigationItemProcessor, @Nonnull FindSymbolParameters findSymbolParameters)
{
Project project = findSymbolParameters.getProject();
IdFilter idFilter = findSymbolParameters.getIdFilter();
GlobalSearchScope searchScope = findSymbolParameters.getSearchScope();
StubIndex.getInstance().processElements(CSharpIndexKeys.METHOD_INDEX, name, project, searchScope, idFilter,
DotNetLikeMethodDeclaration.class, (Processor) navigationItemProcessor);
StubIndex.getInstance().processElements(CSharpIndexKeys.EVENT_INDEX, name, project, searchScope, idFilter,
DotNetEventDeclaration.class, (Processor) navigationItemProcessor);
StubIndex.getInstance().processElements(CSharpIndexKeys.PROPERTY_INDEX, name, project, searchScope, idFilter,
DotNetPropertyDeclaration.class, (Processor) navigationItemProcessor);
StubIndex.getInstance().processElements(CSharpIndexKeys.FIELD_INDEX, name, project, searchScope, idFilter,
DotNetFieldDeclaration.class, (Processor) navigationItemProcessor);
}
/**
* Walk through entire PSI tree rooted at 'element', processing all children of the given type.
*
* @return true if processing was stopped by the processor
*/
private static <T extends PsiElement> boolean processChildrenOfType(
PsiElement element, Processor<T> processor, Class<T> psiClass, boolean reverseOrder) {
PsiElement child = reverseOrder ? element.getLastChild() : element.getFirstChild();
while (child != null) {
if (psiClass.isInstance(child)) {
if (!processor.process((T) child)) {
return true;
}
}
if (processChildrenOfType(child, processor, psiClass, reverseOrder)) {
return true;
}
child = reverseOrder ? child.getPrevSibling() : child.getNextSibling();
}
return false;
}
@RequiredReadAction
@Override
public void process(@Nonnull CSharpResolveOptions options,
@Nonnull DotNetGenericExtractor defaultExtractor,
@Nullable PsiElement forceQualifierElement,
@Nonnull Processor<ResolveResult> processor)
{
PsiElement element = options.getElement();
DotNetNamespaceAsElement temp = DotNetPsiSearcher.getInstance(element.getProject()).findNamespace("", element.getResolveScope());
if(temp == null)
{
return;
}
processor.process(new CSharpResolveResult(temp));
}
@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;
}
}
/**
* {@code processor} should return false if we don't want to step into the directory.
*/
public static void traverseDirectoriesRecursively(@NotNull File root, @NotNull Processor<File> processor) {
final LinkedList<File> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
final File file = queue.removeFirst();
if (file.isFile()) {
continue;
}
if (!processor.process(file)) {
continue;
}
final File[] children = file.listFiles();
if (children != null) {
ContainerUtil.addAll(queue, children);
}
}
}
@RequiredReadAction
public static void sortAndProcess(@Nonnull List<MethodResolveResult> list, @Nonnull Processor<ResolveResult> processor, @Nonnull PsiElement place)
{
if(list.isEmpty())
{
return;
}
ContainerUtil.sort(list, ourComparator);
for(MethodResolveResult methodResolveResult : list)
{
ProgressManager.checkCanceled();
methodResolveResult.setAssignable(place);
if(!processor.process(methodResolveResult))
{
return;
}
}
}
private static List<String> getLibrariesName(Project project) {
Module[] modules = ModuleManager.getInstance(project).getModules();
final List<String> libraryNames = new ArrayList<String>();
for (Module module : modules) {
ModuleRootManager.getInstance(module).orderEntries().forEachLibrary(new Processor<Library>() {
@Override
public boolean process(Library library) {
libraryNames.add(library.getName());
return true;
}
});
}
return libraryNames;
}
@RequiredReadAction
@Override
public boolean processElements(@Nonnull Processor<PsiElement> processor, boolean deep)
{
DotNetNamespaceAsElement.ChildrenFilter filter = DotNetNamespaceAsElement.ChildrenFilter.ONLY_ELEMENTS;
if(StringUtil.isEmpty(myNamespaceAsElement.getPresentableQName()))
{
filter = DotNetNamespaceAsElement.ChildrenFilter.NONE;
}
Collection<PsiElement> children = myNamespaceAsElement.getChildren(myResolveScope, CSharpTransformer.INSTANCE, filter);
children = CSharpCompositeTypeDeclaration.wrapPartialTypes(myResolveScope, myNamespaceAsElement.getProject(), children);
for(PsiElement element : children)
{
ProgressManager.checkCanceled();
if(!processor.process(element))
{
return false;
}
}
return true;
}
@RequiredReadAction
@Override
public void process(@Nonnull CSharpResolveOptions options,
@Nonnull DotNetGenericExtractor defaultExtractor,
@Nullable PsiElement forceQualifierElement,
@Nonnull Processor<ResolveResult> processor)
{
DotNetTypeDeclaration thisTypeDeclaration = PsiTreeUtil.getContextOfType(options.getElement(), DotNetTypeDeclaration.class);
if(thisTypeDeclaration != null)
{
thisTypeDeclaration = CSharpCompositeTypeDeclaration.selectCompositeOrSelfType(thisTypeDeclaration);
DotNetGenericExtractor genericExtractor = DotNetGenericExtractor.EMPTY;
int genericParametersCount = thisTypeDeclaration.getGenericParametersCount();
if(genericParametersCount > 0)
{
Map<DotNetGenericParameter, DotNetTypeRef> map = new THashMap<>(genericParametersCount);
for(DotNetGenericParameter genericParameter : thisTypeDeclaration.getGenericParameters())
{
map.put(genericParameter, new CSharpTypeRefFromGenericParameter(genericParameter));
}
genericExtractor = CSharpGenericExtractor.create(map);
}
processor.process(new CSharpResolveResultWithExtractor(thisTypeDeclaration, genericExtractor));
}
}
@Override
public boolean execute(@Nonnull DefinitionsScopedSearch.SearchParameters queryParameters, @Nonnull final Processor<? super PsiElement> consumer)
{
final PsiElement element = queryParameters.getElement();
if(element instanceof DotNetTypeDeclaration)
{
return TypeInheritorsSearch.search((DotNetTypeDeclaration) element, queryParameters.getScope(), queryParameters.isCheckDeep(), true,
CSharpTransform.INSTANCE).forEach(new Processor<DotNetTypeDeclaration>()
{
@Override
public boolean process(DotNetTypeDeclaration typeDeclaration)
{
return consumer.process(typeDeclaration);
}
});
}
return true;
}
@Override
public void navigate(final boolean requestFocus)
{
process(new Processor<T>()
{
@Override
public boolean process(T t)
{
if(t instanceof Navigatable)
{
((Navigatable) t).navigate(requestFocus);
return false;
}
return true;
}
});
}
@Override
public void processNames(@NotNull Processor<? super String> processor, @NotNull GlobalSearchScope globalSearchScope, @Nullable IdFilter idFilter) {
String queryString = Optional.ofNullable(globalSearchScope.getProject())
.map(p -> p.getUserData(ChooseByNamePopup.CURRENT_SEARCH_PATTERN)).orElse("");
workspaceSymbolProvider.workspaceSymbols(queryString, globalSearchScope.getProject()).stream()
.filter(ni -> globalSearchScope.accept(ni.getFile()))
.map(NavigationItem::getName)
.forEach(processor::process);
}
@NotNull
@Override
public Collection<PsiElement> getPsiTargets(StringLiteralExpression element) {
final Set<PsiElement> targets = new HashSet<>();
final String contents = element.getContents();
if (StringUtils.isBlank(contents)) {
return targets;
}
FileBasedIndex.getInstance().getFilesWithKey(ConfigKeyStubIndex.KEY, new HashSet<>(Collections.singletonList(contents)), new Processor<VirtualFile>() {
@Override
public boolean process(VirtualFile virtualFile) {
PsiFile psiFileTarget = PsiManager.getInstance(ConfigKeyProvider.this.getProject()).findFile(virtualFile);
if (psiFileTarget == null) {
return true;
}
psiFileTarget.acceptChildren(new ArrayReturnPsiRecursiveVisitor(
ConfigFileUtil.matchConfigFile(ConfigKeyProvider.this.getProject(), virtualFile).getKeyPrefix(),
new ArrayKeyVisitor() {
@Override
public void visit(String key, PsiElement psiKey, boolean isRootElement) {
if (!isRootElement && key.equals(contents)) {
targets.add(psiKey);
}
}
}));
return true;
}
}, GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.allScope(getProject()), PhpFileType.INSTANCE));
return targets;
}
public static void printFileIndex(Project project) {
final String test = "index/Index2/test";
List<String> strings = Collections.singletonList(test);
System.out.println(strings);
FileBasedIndex.getInstance().getFilesWithKey(RouteValStubIndex.KEY, new HashSet<>(strings), new Processor<VirtualFile>() {
@Override
public boolean process(VirtualFile virtualFile) {
String name = virtualFile.getName();
System.out.println(name);
return true;
}
}, GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.allScope(project), PhpFileType.INSTANCE));
}
@Override
public void processElementsWithName(@NotNull String name, @NotNull Processor<? super NavigationItem> processor, @NotNull FindSymbolParameters parameters) {
Project project = parameters.getProject();
GlobalSearchScope scope = parameters.getSearchScope();
for (PsiModule psiModule : PsiFinder.getInstance(project).findModulesbyName(name, ORFileType.both, null, scope)) {
processor.process(psiModule);
}
}
@Override
public void processQuery(
@NotNull final ReferencesSearch.SearchParameters queryParameters,
@NotNull final Processor<? super PsiReference> consumer) {
final PsiElement elementToSearch = queryParameters.getElementToSearch();
final Project project = queryParameters.getProject();
if (indexFacade.isIndexReady(project)) {
if (isSpec(elementToSearch, project)) {
process(queryParameters, elementToSearch, project);
}
}
}
public MemberResolveScopeProcessor(@Nonnull CSharpResolveOptions options, @Nonnull Processor<ResolveResult> resultProcessor, ExecuteTarget[] targets)
{
myScopeElement = options.getElement();
myResolveScope = myScopeElement.getResolveScope();
myResultProcessor = resultProcessor;
myOverrideProcessor = OverrideProcessor.ALWAYS_TRUE;
putUserData(ExecuteTargetUtil.EXECUTE_TARGETS, ExecuteTargetUtil.of(targets));
}
/** Walks up PSI tree of local file, checking PsiNamedElements */
public static void searchInScope(PsiElement originalElement, Processor<BuildElement> processor) {
// TODO: Handle list comprehension (where variable is defined *later* in the code)
boolean topLevelScope = true;
PsiElement element = originalElement;
while (!(element instanceof PsiFileSystemItem)) {
PsiElement parent = element.getParent();
if (parent instanceof BuildFile) {
if (!((BuildFile) parent).searchSymbolsInScope(processor, topLevelScope ? element : null)) {
return;
}
} else if (parent instanceof FunctionStatement) {
topLevelScope = false;
for (Parameter param : ((FunctionStatement) parent).getParameters()) {
if (!processor.process(param)) {
return;
}
}
} else if (parent instanceof ForStatement) {
for (Expression expr : ((ForStatement) parent).getForLoopVariables()) {
if (expr instanceof TargetExpression && !processor.process(expr)) {
return;
}
}
} else if (parent instanceof StatementList) {
if (!visitChildAssignmentStatements((BuildElement) parent, (Processor) processor)) {
return;
}
}
element = parent;
}
}
/** @return false if processing was stopped */
public static boolean visitChildAssignmentStatements(
BuildElement parent, Processor<TargetExpression> processor) {
for (AssignmentStatement stmt : parent.childrenOfClass(AssignmentStatement.class)) {
TargetExpression target = stmt.getLeftHandSideExpression();
if (target != null && !processor.process(target)) {
return false;
}
}
return true;
}
/**
* Walks the directory tree, processing all files accessible by this package (i.e. not processing
* child packages).
*/
public void processPackageFiles(Processor<PsiFile> processor) {
PsiDirectory dir = getContainingDirectory();
if (dir == null) {
return;
}
processPackageFiles(processor, dir);
}
private static void processPackageFiles(Processor<PsiFile> processor, PsiDirectory directory) {
processDirectory(processor, directory);
for (PsiDirectory child : directory.getSubdirectories()) {
if (!isBlazePackage(child)) {
processPackageFiles(processor, directory);
}
}
}
public SortedMemberResolveScopeProcessor(@Nonnull CSharpResolveOptions options,
@Nonnull Processor<ResolveResult> resultProcessor,
@Nonnull Comparator<ResolveResult> comparator,
ExecuteTarget[] targets)
{
super(options, CommonProcessors.<ResolveResult>alwaysTrue(), targets);
myOriginalProcessor = resultProcessor;
myComparator = comparator;
initThisProcessor();
}