Java Code Examples for com.intellij.util.Processor

The following examples show how to use com.intellij.util.Processor. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: consulo-csharp   Source File: LabelKindProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 2
@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);
}
 
Example 3
Source Project: intellij-haxe   Source File: HaxeComponentFileNameIndex.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 4
Source Project: idea-php-dotenv-plugin   Source File: EnvironmentVariablesApi.java    License: MIT License 6 votes vote down vote up
/**
 * @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);
}
 
Example 5
Source Project: Android-Resource-Usage-Count   Source File: FindUsagesImpl171.java    License: MIT License 6 votes vote down vote up
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;
}
 
Example 6
@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;
}
 
Example 7
Source Project: intellij   Source File: GlobReferenceSearcher.java    License: Apache License 2.0 6 votes vote down vote up
@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));
    }
  }
}
 
Example 8
Source Project: intellij   Source File: BuildFile.java    License: Apache License 2.0 6 votes vote down vote up
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];
}
 
Example 9
@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);
}
 
Example 10
Source Project: intellij   Source File: PsiUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 11
Source Project: consulo-csharp   Source File: RootNamespaceKindProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 12
Source Project: netbeans-mmd-plugin   Source File: FileMoveHandler.java    License: Apache License 2.0 6 votes vote down vote up
@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;
  }
}
 
Example 13
Source Project: intellij-pants-plugin   Source File: PantsUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@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);
    }
  }
}
 
Example 14
Source Project: consulo-csharp   Source File: WeightUtil.java    License: Apache License 2.0 6 votes vote down vote up
@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;
		}
	}
}
 
Example 15
Source Project: r2m-plugin-android   Source File: ProjectHelper.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 16
@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;
}
 
Example 17
Source Project: consulo-csharp   Source File: ThisKindProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@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));
	}
}
 
Example 18
@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;
}
 
Example 19
@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;
		}
	});
}
 
Example 20
Source Project: lsp4intellij   Source File: LSPSymbolContributor.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 21
Source Project: Thinkphp5-Plugin   Source File: AppConfigReferences.java    License: MIT License 5 votes vote down vote up
@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;
}
 
Example 22
Source Project: Thinkphp5-Plugin   Source File: Tool.java    License: MIT License 5 votes vote down vote up
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));
}
 
Example 23
Source Project: reasonml-idea-plugin   Source File: ORModuleContributor.java    License: MIT License 5 votes vote down vote up
@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);
    }
}
 
Example 24
Source Project: intellij-swagger   Source File: SpecReferenceSearch.java    License: MIT License 5 votes vote down vote up
@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);
    }
  }
}
 
Example 25
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));
}
 
Example 26
Source Project: intellij   Source File: ResolveUtil.java    License: Apache License 2.0 5 votes vote down vote up
/** 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;
  }
}
 
Example 27
Source Project: intellij   Source File: ResolveUtil.java    License: Apache License 2.0 5 votes vote down vote up
/** @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;
}
 
Example 28
Source Project: intellij   Source File: BlazePackage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 29
Source Project: intellij   Source File: BlazePackage.java    License: Apache License 2.0 5 votes vote down vote up
private static void processPackageFiles(Processor<PsiFile> processor, PsiDirectory directory) {
  processDirectory(processor, directory);
  for (PsiDirectory child : directory.getSubdirectories()) {
    if (!isBlazePackage(child)) {
      processPackageFiles(processor, directory);
    }
  }
}
 
Example 30
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();
}