Search in sources :

Example 36 with Processor

use of com.intellij.util.Processor in project intellij-community by JetBrains.

the class InspectionEngine method inspectElements.

// returns map tool.shortName -> list of descriptors found
@NotNull
static Map<String, List<ProblemDescriptor>> inspectElements(@NotNull List<LocalInspectionToolWrapper> toolWrappers, @NotNull final PsiFile file, @NotNull final InspectionManager iManager, final boolean isOnTheFly, boolean failFastOnAcquireReadAction, @NotNull ProgressIndicator indicator, @NotNull final List<PsiElement> elements, @NotNull final Set<String> elementDialectIds) {
    TextRange range = file.getTextRange();
    final LocalInspectionToolSession session = new LocalInspectionToolSession(file, range.getStartOffset(), range.getEndOffset());
    Map<LocalInspectionToolWrapper, Set<String>> toolToSpecifiedDialectIds = getToolsToSpecifiedLanguages(toolWrappers);
    List<Entry<LocalInspectionToolWrapper, Set<String>>> entries = new ArrayList<>(toolToSpecifiedDialectIds.entrySet());
    final Map<String, List<ProblemDescriptor>> resultDescriptors = new ConcurrentHashMap<>();
    Processor<Entry<LocalInspectionToolWrapper, Set<String>>> processor = entry -> {
        ProblemsHolder holder = new ProblemsHolder(iManager, file, isOnTheFly);
        final LocalInspectionTool tool = entry.getKey().getTool();
        Set<String> dialectIdsSpecifiedForTool = entry.getValue();
        createVisitorAndAcceptElements(tool, holder, isOnTheFly, session, elements, elementDialectIds, dialectIdsSpecifiedForTool);
        tool.inspectionFinished(session, holder);
        if (holder.hasResults()) {
            resultDescriptors.put(tool.getShortName(), ContainerUtil.filter(holder.getResults(), descriptor -> {
                PsiElement element = descriptor.getPsiElement();
                return element == null || !SuppressionUtil.inspectionResultSuppressed(element, tool);
            }));
        }
        return true;
    };
    JobLauncher.getInstance().invokeConcurrentlyUnderProgress(entries, indicator, failFastOnAcquireReadAction, processor);
    return resultDescriptors;
}
Also used : Language(com.intellij.lang.Language) java.util(java.util) JobLauncher(com.intellij.concurrency.JobLauncher) GlobalInspectionToolWrapper(com.intellij.codeInspection.ex.GlobalInspectionToolWrapper) Divider(com.intellij.codeInsight.daemon.impl.Divider) LocalInspectionToolWrapper(com.intellij.codeInspection.ex.LocalInspectionToolWrapper) THashSet(gnu.trove.THashSet) ContainerUtil(com.intellij.util.containers.ContainerUtil) THashMap(gnu.trove.THashMap) Conditions(com.intellij.openapi.util.Conditions) RefVisitor(com.intellij.codeInspection.reference.RefVisitor) Logger(com.intellij.openapi.diagnostic.Logger) CommonProcessors(com.intellij.util.CommonProcessors) RefManagerImpl(com.intellij.codeInspection.reference.RefManagerImpl) ProgressManager(com.intellij.openapi.progress.ProgressManager) RefElement(com.intellij.codeInspection.reference.RefElement) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AnalysisScope(com.intellij.analysis.AnalysisScope) TextRange(com.intellij.openapi.util.TextRange) EmptyProgressIndicator(com.intellij.openapi.progress.EmptyProgressIndicator) Nullable(org.jetbrains.annotations.Nullable) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) Processor(com.intellij.util.Processor) SmartHashSet(com.intellij.util.containers.SmartHashSet) InspectionToolWrapper(com.intellij.codeInspection.ex.InspectionToolWrapper) Entry(java.util.Map.Entry) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) RefEntity(com.intellij.codeInspection.reference.RefEntity) THashSet(gnu.trove.THashSet) SmartHashSet(com.intellij.util.containers.SmartHashSet) TextRange(com.intellij.openapi.util.TextRange) Entry(java.util.Map.Entry) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LocalInspectionToolWrapper(com.intellij.codeInspection.ex.LocalInspectionToolWrapper) NotNull(org.jetbrains.annotations.NotNull)

Example 37 with Processor

use of com.intellij.util.Processor in project intellij-community by JetBrains.

the class LibraryUsageCollector method getProjectUsages.

@NotNull
@Override
public Set<UsageDescriptor> getProjectUsages(@NotNull Project project) {
    final Set<LibraryKind> usedKinds = new HashSet<>();
    final Processor<Library> processor = library -> {
        usedKinds.addAll(LibraryPresentationManagerImpl.getLibraryKinds(library, null));
        return true;
    };
    for (Module module : ModuleManager.getInstance(project).getModules()) {
        ModuleRootManager.getInstance(module).orderEntries().librariesOnly().forEachLibrary(processor);
    }
    final HashSet<UsageDescriptor> usageDescriptors = new HashSet<>();
    for (LibraryKind kind : usedKinds) {
        usageDescriptors.add(new UsageDescriptor(kind.getKindId(), 1));
    }
    return usageDescriptors;
}
Also used : GroupDescriptor(com.intellij.internal.statistic.beans.GroupDescriptor) ModuleManager(com.intellij.openapi.module.ModuleManager) UsageDescriptor(com.intellij.internal.statistic.beans.UsageDescriptor) AbstractApplicationUsagesCollector(com.intellij.internal.statistic.AbstractApplicationUsagesCollector) NonNls(org.jetbrains.annotations.NonNls) Set(java.util.Set) LibraryKind(com.intellij.openapi.roots.libraries.LibraryKind) HashSet(java.util.HashSet) Library(com.intellij.openapi.roots.libraries.Library) ModuleRootManager(com.intellij.openapi.roots.ModuleRootManager) Processor(com.intellij.util.Processor) Project(com.intellij.openapi.project.Project) Module(com.intellij.openapi.module.Module) NotNull(org.jetbrains.annotations.NotNull) LibraryKind(com.intellij.openapi.roots.libraries.LibraryKind) Library(com.intellij.openapi.roots.libraries.Library) Module(com.intellij.openapi.module.Module) UsageDescriptor(com.intellij.internal.statistic.beans.UsageDescriptor) HashSet(java.util.HashSet) NotNull(org.jetbrains.annotations.NotNull)

Example 38 with Processor

use of com.intellij.util.Processor in project intellij-community by JetBrains.

the class InjectedLanguageManagerImpl method startRunInjectors.

@Override
public void startRunInjectors(@NotNull final Document hostDocument, final boolean synchronously) {
    if (myProject.isDisposed())
        return;
    if (!synchronously && ApplicationManager.getApplication().isWriteAccessAllowed())
        return;
    // use cached to avoid recreate PSI in alien project
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
    final PsiFile hostPsiFile = documentManager.getCachedPsiFile(hostDocument);
    if (hostPsiFile == null)
        return;
    final ConcurrentList<DocumentWindow> injected = InjectedLanguageUtil.getCachedInjectedDocuments(hostPsiFile);
    if (injected.isEmpty())
        return;
    if (myProgress.isCanceled()) {
        myProgress = new DaemonProgressIndicator();
    }
    final Set<DocumentWindow> newDocuments = Collections.synchronizedSet(new THashSet<>());
    final Processor<DocumentWindow> commitProcessor = documentWindow -> {
        if (myProject.isDisposed())
            return false;
        ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
        if (indicator != null && indicator.isCanceled())
            return false;
        if (documentManager.isUncommited(hostDocument) || !hostPsiFile.isValid())
            return false;
        InjectedLanguageUtil.enumerate(documentWindow, hostPsiFile, (injectedPsi, places) -> {
            DocumentWindow newDocument = (DocumentWindow) injectedPsi.getViewProvider().getDocument();
            if (newDocument != null) {
                PsiDocumentManagerBase.checkConsistency(injectedPsi, newDocument);
                newDocuments.add(newDocument);
            }
        });
        return true;
    };
    final Runnable commitInjectionsRunnable = () -> {
        if (myProgress.isCanceled())
            return;
        JobLauncher.getInstance().invokeConcurrentlyUnderProgress(new ArrayList<>(injected), myProgress, true, commitProcessor);
        synchronized (ourInjectionPsiLock) {
            injected.clear();
            injected.addAll(newDocuments);
        }
    };
    if (synchronously) {
        if (Thread.holdsLock(PsiLock.LOCK)) {
            // hack for the case when docCommit was called from within PSI modification, e.g. in formatter.
            // we can't spawn threads to do injections there, otherwise a deadlock is imminent
            ContainerUtil.process(new ArrayList<>(injected), commitProcessor);
        } else {
            commitInjectionsRunnable.run();
        }
    } else {
        JobLauncher.getInstance().submitToJobThread(() -> ApplicationManagerEx.getApplicationEx().tryRunReadAction(commitInjectionsRunnable), null);
    }
}
Also used : InjectedLanguageManager(com.intellij.lang.injection.InjectedLanguageManager) VirtualFileWindow(com.intellij.injected.editor.VirtualFileWindow) java.util(java.util) ArrayUtil(com.intellij.util.ArrayUtil) JobLauncher(com.intellij.concurrency.JobLauncher) VirtualFile(com.intellij.openapi.vfs.VirtualFile) EditorWindowImpl(com.intellij.injected.editor.EditorWindowImpl) Document(com.intellij.openapi.editor.Document) THashSet(gnu.trove.THashSet) DaemonCodeAnalyzer(com.intellij.codeInsight.daemon.DaemonCodeAnalyzer) ContainerUtil(com.intellij.util.containers.ContainerUtil) FileContextUtil(com.intellij.psi.impl.source.resolve.FileContextUtil) SmartList(com.intellij.util.SmartList) MultiHostInjector(com.intellij.lang.injection.MultiHostInjector) Project(com.intellij.openapi.project.Project) Segment(com.intellij.openapi.util.Segment) Logger(com.intellij.openapi.diagnostic.Logger) MultiHostRegistrar(com.intellij.lang.injection.MultiHostRegistrar) Extensions(com.intellij.openapi.extensions.Extensions) ProgressManager(com.intellij.openapi.progress.ProgressManager) DumbService(com.intellij.openapi.project.DumbService) DocumentWindow(com.intellij.injected.editor.DocumentWindow) ExtensionPoint(com.intellij.openapi.extensions.ExtensionPoint) ExtensionPointListener(com.intellij.openapi.extensions.ExtensionPointListener) DocumentWindowImpl(com.intellij.injected.editor.DocumentWindowImpl) TextRange(com.intellij.openapi.util.TextRange) Disposable(com.intellij.openapi.Disposable) TestOnly(org.jetbrains.annotations.TestOnly) Nullable(org.jetbrains.annotations.Nullable) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) ExtensionPointImpl(com.intellij.openapi.extensions.impl.ExtensionPointImpl) ConcurrentList(com.intellij.util.containers.ConcurrentList) PsiDocumentManagerBase(com.intellij.psi.impl.PsiDocumentManagerBase) Processor(com.intellij.util.Processor) Pair(com.intellij.openapi.util.Pair) ApplicationManager(com.intellij.openapi.application.ApplicationManager) DaemonProgressIndicator(com.intellij.codeInsight.daemon.impl.DaemonProgressIndicator) ApplicationManagerEx(com.intellij.openapi.application.ex.ApplicationManagerEx) PluginDescriptor(com.intellij.openapi.extensions.PluginDescriptor) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) DaemonProgressIndicator(com.intellij.codeInsight.daemon.impl.DaemonProgressIndicator) DocumentWindow(com.intellij.injected.editor.DocumentWindow) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) DaemonProgressIndicator(com.intellij.codeInsight.daemon.impl.DaemonProgressIndicator)

Example 39 with Processor

use of com.intellij.util.Processor in project intellij-community by JetBrains.

the class BaseRefactoringProcessor method previewRefactoring.

protected void previewRefactoring(@NotNull UsageInfo[] usages) {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
        if (!PREVIEW_IN_TESTS)
            throw new RuntimeException("Unexpected preview in tests: " + StringUtil.join(usages, info -> info.toString(), ", "));
        ensureElementsWritable(usages, createUsageViewDescriptor(usages));
        execute(usages);
        return;
    }
    final UsageViewDescriptor viewDescriptor = createUsageViewDescriptor(usages);
    final PsiElement[] elements = viewDescriptor.getElements();
    final PsiElement2UsageTargetAdapter[] targets = PsiElement2UsageTargetAdapter.convert(elements);
    Factory<UsageSearcher> factory = new Factory<UsageSearcher>() {

        @Override
        public UsageSearcher create() {
            return new UsageInfoSearcherAdapter() {

                @Override
                public void generate(@NotNull final Processor<Usage> processor) {
                    ApplicationManager.getApplication().runReadAction(new Runnable() {

                        @Override
                        public void run() {
                            for (int i = 0; i < elements.length; i++) {
                                elements[i] = targets[i].getElement();
                            }
                            refreshElements(elements);
                        }
                    });
                    processUsages(processor, myProject);
                }

                @NotNull
                @Override
                protected UsageInfo[] findUsages() {
                    return BaseRefactoringProcessor.this.findUsages();
                }
            };
        }
    };
    showUsageView(viewDescriptor, factory, usages);
}
Also used : Language(com.intellij.lang.Language) LocalHistoryAction(com.intellij.history.LocalHistoryAction) HashSet(com.intellij.util.containers.HashSet) THashSet(gnu.trove.THashSet) RefactoringListenerManager(com.intellij.refactoring.listeners.RefactoringListenerManager) PsiElementUsage(com.intellij.usages.rules.PsiElementUsage) Messages(com.intellij.openapi.ui.Messages) CommonDataKeys(com.intellij.openapi.actionSystem.CommonDataKeys) RefactoringEventData(com.intellij.refactoring.listeners.RefactoringEventData) UndoConfirmationPolicy(com.intellij.openapi.command.UndoConfirmationPolicy) Logger(com.intellij.openapi.diagnostic.Logger) MultiMap(com.intellij.util.containers.MultiMap) Extensions(com.intellij.openapi.extensions.Extensions) ProgressManager(com.intellij.openapi.progress.ProgressManager) DumbService(com.intellij.openapi.project.DumbService) RefactoringTransaction(com.intellij.refactoring.listeners.impl.RefactoringTransaction) BasicUndoableAction(com.intellij.openapi.command.undo.BasicUndoableAction) MoveRenameUsageInfo(com.intellij.refactoring.util.MoveRenameUsageInfo) NonProjectFileWritingAccessProvider(com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessProvider) InvocationTargetException(java.lang.reflect.InvocationTargetException) Nullable(org.jetbrains.annotations.Nullable) ApplicationImpl(com.intellij.openapi.application.impl.ApplicationImpl) PsiUtilCore(com.intellij.psi.util.PsiUtilCore) ConflictsDialog(com.intellij.refactoring.ui.ConflictsDialog) Processor(com.intellij.util.Processor) ApplicationManager(com.intellij.openapi.application.ApplicationManager) Registry(com.intellij.openapi.util.registry.Registry) LocalHistory(com.intellij.history.LocalHistory) NotNull(org.jetbrains.annotations.NotNull) Factory(com.intellij.openapi.util.Factory) Ref(com.intellij.openapi.util.Ref) java.util(java.util) RefactoringListenerManagerImpl(com.intellij.refactoring.listeners.impl.RefactoringListenerManagerImpl) Computable(com.intellij.openapi.util.Computable) UsageInfo(com.intellij.usageView.UsageInfo) RefactoringEventListener(com.intellij.refactoring.listeners.RefactoringEventListener) ContainerUtil(com.intellij.util.containers.ContainerUtil) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) StatusBarUtil(com.intellij.openapi.wm.impl.status.StatusBarUtil) PsiElement(com.intellij.psi.PsiElement) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) DataManager(com.intellij.ide.DataManager) PsiDocumentManager(com.intellij.psi.PsiDocumentManager) ThrowableRunnable(com.intellij.util.ThrowableRunnable) StringUtil(com.intellij.openapi.util.text.StringUtil) com.intellij.usages(com.intellij.usages) UndoableAction(com.intellij.openapi.command.undo.UndoableAction) GuiUtils(com.intellij.ui.GuiUtils) UsageViewUtil(com.intellij.usageView.UsageViewUtil) UsageViewDescriptor(com.intellij.usageView.UsageViewDescriptor) TestOnly(org.jetbrains.annotations.TestOnly) CommandProcessor(com.intellij.openapi.command.CommandProcessor) CommonRefactoringUtil(com.intellij.refactoring.util.CommonRefactoringUtil) PsiElement2UsageTargetAdapter(com.intellij.find.findUsages.PsiElement2UsageTargetAdapter) UndoManager(com.intellij.openapi.command.undo.UndoManager) ApplicationManagerEx(com.intellij.openapi.application.ex.ApplicationManagerEx) TransactionGuard(com.intellij.openapi.application.TransactionGuard) EmptyRunnable(com.intellij.openapi.util.EmptyRunnable) UsageViewDescriptor(com.intellij.usageView.UsageViewDescriptor) Processor(com.intellij.util.Processor) CommandProcessor(com.intellij.openapi.command.CommandProcessor) PsiElement2UsageTargetAdapter(com.intellij.find.findUsages.PsiElement2UsageTargetAdapter) Factory(com.intellij.openapi.util.Factory) NotNull(org.jetbrains.annotations.NotNull) ThrowableRunnable(com.intellij.util.ThrowableRunnable) EmptyRunnable(com.intellij.openapi.util.EmptyRunnable) PsiElement(com.intellij.psi.PsiElement) MoveRenameUsageInfo(com.intellij.refactoring.util.MoveRenameUsageInfo) UsageInfo(com.intellij.usageView.UsageInfo)

Example 40 with Processor

use of com.intellij.util.Processor in project intellij-community by JetBrains.

the class JavaClassInheritorsSearcher method getOrComputeSubClasses.

@NotNull
private static Iterable<PsiClass> getOrComputeSubClasses(@NotNull Project project, @NotNull PsiClass baseClass, @NotNull SearchScope searchScopeForNonPhysical) {
    ConcurrentMap<PsiClass, Iterable<PsiClass>> map = HighlightingCaches.getInstance(project).ALL_SUB_CLASSES;
    Iterable<PsiClass> cached = map.get(baseClass);
    if (cached == null) {
        // returns lazy collection of subclasses. Each call to next() leads to calculation of next batch of subclasses.
        Function<PsiAnchor, PsiClass> converter = anchor -> ReadAction.compute(() -> (PsiClass) anchor.retrieve());
        Predicate<PsiClass> applicableFilter = candidate -> !(candidate instanceof PsiAnonymousClass) && candidate != null && !candidate.hasModifierProperty(PsiModifier.FINAL);
        // for non-physical elements ignore the cache completely because non-physical elements created so often/unpredictably so I can't figure out when to clear caches in this case
        boolean isPhysical = ReadAction.compute(baseClass::isPhysical);
        SearchScope scopeToUse = isPhysical ? GlobalSearchScope.allScope(project) : searchScopeForNonPhysical;
        LazyConcurrentCollection.MoreElementsGenerator<PsiAnchor, PsiClass> generator = (candidate, processor) -> DirectClassInheritorsSearch.search(candidate, scopeToUse).forEach(subClass -> {
            ProgressManager.checkCanceled();
            PsiAnchor pointer = ReadAction.compute(() -> PsiAnchor.create(subClass));
            processor.consume(pointer);
            return true;
        });
        PsiAnchor seed = ReadAction.compute(() -> PsiAnchor.create(baseClass));
        // lazy collection: store underlying queue as PsiAnchors, generate new elements by running direct inheritors
        Iterable<PsiClass> computed = new LazyConcurrentCollection<>(seed, converter, applicableFilter, generator);
        // make sure concurrent calls of this method always return the same collection to avoid expensive duplicate work
        cached = isPhysical ? ConcurrencyUtil.cacheOrGet(map, baseClass, computed) : computed;
    }
    return cached;
}
Also used : ProgressManager(com.intellij.openapi.progress.ProgressManager) VirtualFile(com.intellij.openapi.vfs.VirtualFile) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) ConcurrencyUtil(com.intellij.util.ConcurrencyUtil) SearchScope(com.intellij.psi.search.SearchScope) ReadAction(com.intellij.openapi.application.ReadAction) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) Predicate(com.intellij.util.containers.Predicate) QueryExecutorBase(com.intellij.openapi.application.QueryExecutorBase) ProgressIndicatorProvider(com.intellij.openapi.progress.ProgressIndicatorProvider) ConcurrentMap(java.util.concurrent.ConcurrentMap) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) PsiSearchScopeUtil(com.intellij.psi.search.PsiSearchScopeUtil) PsiUtilCore(com.intellij.psi.util.PsiUtilCore) Function(com.intellij.util.Function) Processor(com.intellij.util.Processor) ApplicationManager(com.intellij.openapi.application.ApplicationManager) Project(com.intellij.openapi.project.Project) com.intellij.psi(com.intellij.psi) AllClassesSearch(com.intellij.psi.search.searches.AllClassesSearch) ClassInheritorsSearch(com.intellij.psi.search.searches.ClassInheritorsSearch) NotNull(org.jetbrains.annotations.NotNull) DirectClassInheritorsSearch(com.intellij.psi.search.searches.DirectClassInheritorsSearch) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

Processor (com.intellij.util.Processor)83 NotNull (org.jetbrains.annotations.NotNull)65 Project (com.intellij.openapi.project.Project)49 Nullable (org.jetbrains.annotations.Nullable)49 ContainerUtil (com.intellij.util.containers.ContainerUtil)42 com.intellij.psi (com.intellij.psi)31 List (java.util.List)28 ApplicationManager (com.intellij.openapi.application.ApplicationManager)25 StringUtil (com.intellij.openapi.util.text.StringUtil)25 VirtualFile (com.intellij.openapi.vfs.VirtualFile)25 java.util (java.util)25 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)24 ProgressManager (com.intellij.openapi.progress.ProgressManager)21 Logger (com.intellij.openapi.diagnostic.Logger)20 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)20 NonNls (org.jetbrains.annotations.NonNls)18 Ref (com.intellij.openapi.util.Ref)16 Collection (java.util.Collection)16 SmartList (com.intellij.util.SmartList)14 Document (com.intellij.openapi.editor.Document)13