com.intellij.openapi.progress.ProgressIndicatorProvider Java Examples

The following examples show how to use com.intellij.openapi.progress.ProgressIndicatorProvider. 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 File: BlazeGoPackage.java    From intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Override {@link GoPackage#processFiles(Processor, Predicate)} to work on specific files instead
 * of by directory.
 */
@Override
public boolean processFiles(
    Processor<? super PsiFile> processor, Predicate<VirtualFile> virtualFileFilter) {
  if (!isValid()) {
    return true;
  }
  FileIndexFacade fileIndexFacade = FileIndexFacade.getInstance(getProject());
  for (PsiFile file : files()) {
    ProgressIndicatorProvider.checkCanceled();
    VirtualFile virtualFile = file.getVirtualFile();
    if (virtualFile.isValid()
        && virtualFileFilter.test(virtualFile)
        && !fileIndexFacade.isExcludedFile(virtualFile)
        && !processor.process(file)) {
      return false;
    }
  }
  return true;
}
 
Example #2
Source File: DefaultChooseByNameItemProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public List<String> filterNames(@Nonnull ChooseByNameBase base, @Nonnull String[] names, @Nonnull String pattern) {
  pattern = convertToMatchingPattern(base, pattern);
  if (pattern.isEmpty() && !base.canShowListForEmptyPattern()) return Collections.emptyList();

  final List<String> filtered = new ArrayList<>();
  processNamesByPattern(base, names, pattern, ProgressIndicatorProvider.getGlobalProgressIndicator(), result -> {
    synchronized (filtered) {
      filtered.add(result.elementName);
    }
  });
  synchronized (filtered) {
    return filtered;
  }
}
 
Example #3
Source File: GotoActionModel.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateOnEdt(Runnable update) {
  Semaphore semaphore = new Semaphore(1);
  ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
  ApplicationManager.getApplication().invokeLater(() -> {
    try {
      update.run();
    }
    finally {
      semaphore.up();
    }
  }, myModality, __ -> indicator != null && indicator.isCanceled());

  while (!semaphore.waitFor(10)) {
    if (indicator != null && indicator.isCanceled()) {
      // don't use `checkCanceled` because some smart devs might suppress PCE and end up with a deadlock like IDEA-177788
      throw new ProcessCanceledException();
    }
  }
}
 
Example #4
Source File: PsiDirectoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean processChildren(PsiElementProcessor<PsiFileSystemItem> processor) {
  checkValid();
  ProgressIndicatorProvider.checkCanceled();

  for (VirtualFile vFile : myFile.getChildren()) {
    boolean isDir = vFile.isDirectory();
    if (processor instanceof PsiFileSystemItemProcessor && !((PsiFileSystemItemProcessor)processor).acceptItem(vFile.getName(), isDir)) {
      continue;
    }
    if (isDir) {
      PsiDirectory dir = myManager.findDirectory(vFile);
      if (dir != null) {
        if (!processor.execute(dir)) return false;
      }
    }
    else {
      PsiFile file = myManager.findFile(vFile);
      if (file != null) {
        if (!processor.execute(file)) return false;
      }
    }
  }
  return true;
}
 
Example #5
Source File: PsiBuilderImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private int insertLeaves(int curToken, int lastIdx, final CompositeElement curNode) {
  lastIdx = Math.min(lastIdx, myLexemeCount);
  while (curToken < lastIdx) {
    ProgressIndicatorProvider.checkCanceled();
    final int start = myLexStarts[curToken];
    final int end = myLexStarts[curToken + 1];
    if (start < end || myLexTypes[curToken] instanceof ILeafElementType) { // Empty token. Most probably a parser directive like indent/dedent in Python
      final IElementType type = myLexTypes[curToken];
      final TreeElement leaf = createLeaf(type, start, end);
      curNode.rawAddChildrenWithoutNotifications(leaf);
    }
    curToken++;
  }

  return curToken;
}
 
Example #6
Source File: ProgressIndicatorUtils.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Run the given computation with its execution time restricted to the given amount of time in milliseconds.<p></p>
 * <p>
 * Internally, it creates a new {@link ProgressIndicator}, runs the computation with that indicator and cancels it after the the timeout.
 * The computation should call {@link ProgressManager#checkCanceled()} frequently enough, so that after the timeout has been exceeded
 * it can stop the execution by throwing {@link ProcessCanceledException}, which will be caught by this {@code withTimeout}.<p></p>
 * <p>
 * If a {@link ProcessCanceledException} happens due to any other reason (e.g. a thread's progress indicator got canceled),
 * it'll be thrown out of this method.
 *
 * @return the computation result or {@code null} if timeout has been exceeded.
 */
@Nullable
public static <T> T withTimeout(long timeoutMs, @Nonnull Computable<T> computation) {
  ProgressManager.checkCanceled();
  ProgressIndicator outer = ProgressIndicatorProvider.getGlobalProgressIndicator();
  ProgressIndicator inner = outer != null ? new SensitiveProgressWrapper(outer) : new ProgressIndicatorBase(false, false);
  AtomicBoolean canceledByTimeout = new AtomicBoolean();
  ScheduledFuture<?> cancelProgress = AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> {
    canceledByTimeout.set(true);
    inner.cancel();
  }, timeoutMs, TimeUnit.MILLISECONDS);
  try {
    return ProgressManager.getInstance().runProcess(computation, inner);
  }
  catch (ProcessCanceledException e) {
    if (canceledByTimeout.get()) {
      return null;
    }
    throw e; // canceled not by timeout
  }
  finally {
    cancelProgress.cancel(false);
  }
}
 
Example #7
Source File: PsiRecursiveElementVisitor.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void visitFile(final PsiFile file) {
  if (myVisitAllFileRoots) {
    final FileViewProvider viewProvider = file.getViewProvider();
    final List<PsiFile> allFiles = viewProvider.getAllFiles();
    if (allFiles.size() > 1) {
      if (file == viewProvider.getPsi(viewProvider.getBaseLanguage())) {
        for (PsiFile lFile : allFiles) {
          ProgressIndicatorProvider.checkCanceled();
          lFile.acceptChildren(this);
        }
        return;
      }
    }
  }

  super.visitFile(file);
}
 
Example #8
Source File: CSharpHighlightVisitor.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Override
public void visitElement(PsiElement element)
{
	ProgressIndicatorProvider.checkCanceled();

	IElementType elementType = PsiUtilCore.getElementType(element);
	if(CSharpSoftTokens.ALL.contains(elementType))
	{
		myHighlightInfoHolder.add(HighlightInfo.newHighlightInfo(HighlightInfoType.INFORMATION).range(element).textAttributes(CSharpHighlightKey.SOFT_KEYWORD).create());
	}
	else if(elementType == CSharpTokens.NON_ACTIVE_SYMBOL || elementType == CSharpPreprocessorElements.DISABLED_PREPROCESSOR_DIRECTIVE)
	{
		if(myDocument == null)
		{
			return;
		}
		int lineNumber = myDocument.getLineNumber(element.getTextOffset());
		if(!myProcessedLines.contains(lineNumber))
		{
			myProcessedLines.add(lineNumber);

			TextRange textRange = new TextRange(myDocument.getLineStartOffset(lineNumber), myDocument.getLineEndOffset(lineNumber));
			myHighlightInfoHolder.add(HighlightInfo.newHighlightInfo(HighlightInfoType.INFORMATION).range(textRange).textAttributes(CSharpHighlightKey.DISABLED_BLOCK).create());
		}
	}
}
 
Example #9
Source File: LSPCompletionContributor.java    From lsp4intellij with Apache License 2.0 6 votes vote down vote up
public LSPCompletionContributor() {
    this.extend(CompletionType.BASIC, usePattern(), new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(@NotNull CompletionParameters parameters, @NotNull ProcessingContext context, @NotNull CompletionResultSet result) {
            try {
                ApplicationUtil.runWithCheckCanceled(() -> {
                    Editor editor = parameters.getEditor();
                    int offset = parameters.getOffset();
                    Position serverPos = DocumentUtils.offsetToLSPPos(editor, offset);

                    EditorEventManager manager = EditorEventManagerBase.forEditor(editor);
                    if (manager != null) {
                        result.addAllElements(manager.completion(serverPos));
                    }
                    return null;
                }, ProgressIndicatorProvider.getGlobalProgressIndicator());
            } catch (ProcessCanceledException ignored) {
                // ProcessCanceledException can be ignored.
            } catch (Exception e) {
                LOG.warn("LSP Completions ended with an error", e);
            }
        }
    });
}
 
Example #10
Source File: PSITokenSource.java    From antlr4-intellij-adaptor with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Create an ANTLR Token from the current token type of the builder
	 *  then advance the builder to next token (which ultimately calls an
	 *  ANTLR lexer).  The {@link ANTLRLexerAdaptor} creates tokens via
	 *  an ANTLR lexer but converts to {@link TokenIElementType} and here
	 *  we have to convert back to an ANTLR token using what info we
	 *  can get from the builder. We lose info such as the original channel.
	 *  So, whitespace and comments (typically hidden channel) will look like
	 *  real tokens. Jetbrains uses {@link ParserDefinition#getWhitespaceTokens()}
	 *  and {@link ParserDefinition#getCommentTokens()} to strip these before
	 *  our ANTLR parser sees them.
	 */
	@Override
	public Token nextToken() {
		ProgressIndicatorProvider.checkCanceled();

		TokenIElementType ideaTType = (TokenIElementType)builder.getTokenType();
		int type = ideaTType!=null ? ideaTType.getANTLRTokenType() : Token.EOF;

		int channel = Token.DEFAULT_CHANNEL;
		Pair<TokenSource, CharStream> source = new Pair<TokenSource, CharStream>(this, null);
		String text = builder.getTokenText();
		int start = builder.getCurrentOffset();
		int length = text != null ? text.length() : 0;
		int stop = start + length - 1;
		// PsiBuilder doesn't provide line, column info
		int line = 0;
		int charPositionInLine = 0;
		Token t = tokenFactory.create(source, type, text, channel, start, stop, line, charPositionInLine);
		builder.advanceLexer();
//		System.out.println("TOKEN: "+t);
		return t;
	}
 
Example #11
Source File: ActionUpdateEdtExecutor.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Compute the supplied value on Swing thread, but try to avoid deadlocks by periodically performing {@link ProgressManager#checkCanceled()} in the current thread.
 * Makes sense to be used in background read actions running with a progress indicator that's canceled when a write action is about to occur.
 *
 * @see com.intellij.openapi.application.ReadAction#nonBlocking(Runnable)
 */
public static <T> T computeOnEdt(Supplier<T> supplier) {
  Application application = ApplicationManager.getApplication();
  if (application.isDispatchThread()) {
    return supplier.get();
  }

  Semaphore semaphore = new Semaphore(1);
  ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
  Ref<T> result = Ref.create();
  ApplicationManager.getApplication().invokeLater(() -> {
    try {
      if (indicator == null || !indicator.isCanceled()) {
        result.set(supplier.get());
      }
    }
    finally {
      semaphore.up();
    }
  });

  while (!semaphore.waitFor(10)) {
    if (indicator != null && indicator.isCanceled()) {
      // don't use `checkCanceled` because some smart devs might suppress PCE and end up with a deadlock like IDEA-177788
      throw new ProcessCanceledException();
    }
  }
  // check cancellation one last time, to ensure the EDT action wasn't no-op due to cancellation
  if (indicator != null && indicator.isCanceled()) {
    throw new ProcessCanceledException();
  }
  return result.get();
}
 
Example #12
Source File: PsiManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean areElementsEquivalent(PsiElement element1, PsiElement element2) {
  ProgressIndicatorProvider.checkCanceled(); // We hope this method is being called often enough to cancel daemon processes smoothly

  if (element1 == element2) return true;
  if (element1 == null || element2 == null) {
    return false;
  }

  return element1.equals(element2) || element1.isEquivalentTo(element2) || element2.isEquivalentTo(element1);
}
 
Example #13
Source File: PsiScopesUtilCore.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean treeWalkUp(@Nonnull final PsiScopeProcessor processor,
                                 @Nonnull final PsiElement entrance,
                                 @Nullable final PsiElement maxScope,
                                 @Nonnull final ResolveState state) {
  if (!entrance.isValid()) {
    LOGGER.error(new PsiInvalidElementAccessException(entrance));
  }
  PsiElement prevParent = entrance;
  PsiElement scope = entrance;

  while (scope != null) {
    ProgressIndicatorProvider.checkCanceled();

    if (!scope.processDeclarations(processor, state, prevParent, entrance)) {
      return false; // resolved
    }


    if (scope == maxScope) break;
    prevParent = scope;
    scope = prevParent.getContext();
    if (scope != null && scope != prevParent.getParent() && !scope.isValid()) {
      break;
    }

  }

  return true;
}
 
Example #14
Source File: PsiBuilderImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private DiffLog merge(@Nonnull final ASTNode oldRoot, @Nonnull StartMarker newRoot, @Nonnull CharSequence lastCommittedText) {
  DiffLog diffLog = new DiffLog();
  DiffTreeChangeBuilder<ASTNode, LighterASTNode> builder = new ConvertFromTokensToASTBuilder(newRoot, diffLog);
  MyTreeStructure treeStructure = new MyTreeStructure(newRoot, null);
  ShallowNodeComparator<ASTNode, LighterASTNode> comparator = new MyComparator(getUserData(CUSTOM_COMPARATOR), treeStructure);

  ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
  BlockSupportImpl.diffTrees(oldRoot, builder, comparator, treeStructure, indicator == null ? new EmptyProgressIndicator() : indicator, lastCommittedText);
  return diffLog;
}
 
Example #15
Source File: PsiBuilderImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void advanceLexer() {
  ProgressIndicatorProvider.checkCanceled();

  if (eof()) return;

  if (!myTokenTypeChecked) {
    LOG.error("Probably a bug: eating token without its type checking");
  }

  myTokenTypeChecked = false;
  myCurrentLexeme++;
  clearCachedTokenType();
}
 
Example #16
Source File: StubBasedPsiElementBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Like {@link #getStub()}, but can return a non-null value after the element has been switched to AST. Can be used
 * to retrieve the information which is cheaper to get from a stub than by tree traversal.
 *
 * @see PsiFileImpl#getGreenStub()
 */
@Nullable
public final T getGreenStub() {
  ProgressIndicatorProvider.checkCanceled(); // Hope, this is called often
  //noinspection unchecked
  return (T)mySubstrateRef.getGreenStub();
}
 
Example #17
Source File: ResolveCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private <TRef extends PsiReference, TResult> TResult resolve(@Nonnull final TRef ref,
                                                             @Nonnull final AbstractResolver<? super TRef, TResult> resolver,
                                                             boolean needToPreventRecursion,
                                                             final boolean incompleteCode,
                                                             boolean isPoly,
                                                             boolean isPhysical) {
  ProgressIndicatorProvider.checkCanceled();
  if (isPhysical) {
    ApplicationManager.getApplication().assertReadAccessAllowed();
  }
  int index = getIndex(incompleteCode, isPoly);
  Map<TRef, TResult> map = getMap(isPhysical, index);
  TResult result = map.get(ref);
  if (result != null) {
    return result;
  }

  RecursionGuard.StackStamp stamp = RecursionManager.markStack();
  result = needToPreventRecursion
           ? RecursionManager.doPreventingRecursion(Trinity.create(ref, incompleteCode, isPoly), true, () -> resolver.resolve(ref, incompleteCode))
           : resolver.resolve(ref, incompleteCode);
  if (result instanceof ResolveResult) {
    ensureValidPsi((ResolveResult)result);
  }
  else if (result instanceof ResolveResult[]) {
    ensureValidResults((ResolveResult[])result);
  }
  else if (result instanceof PsiElement) {
    PsiUtilCore.ensureValid((PsiElement)result);
  }

  if (stamp.mayCacheNow()) {
    cache(ref, map, result);
  }
  return result;
}
 
Example #18
Source File: IdFilter.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static IdFilter buildProjectIdFilter(Project project, boolean includeNonProjectItems) {
  long started = System.currentTimeMillis();
  final BitSet idSet = new BitSet();

  ContentIterator iterator = fileOrDir -> {
    idSet.set(((VirtualFileWithId)fileOrDir).getId());
    ProgressManager.checkCanceled();
    return true;
  };

  if (!includeNonProjectItems) {
    ProjectRootManager.getInstance(project).getFileIndex().iterateContent(iterator);
  }
  else {
    FileBasedIndex.getInstance().iterateIndexableFiles(iterator, project, ProgressIndicatorProvider.getGlobalProgressIndicator());
  }

  if (LOG.isDebugEnabled()) {
    long elapsed = System.currentTimeMillis() - started;
    LOG.debug("Done filter (includeNonProjectItems=" + includeNonProjectItems + ") " + "in " + elapsed + "ms. Total files in set: " + idSet.cardinality());
  }
  return new IdFilter() {
    @Override
    public boolean containsFileId(int id) {
      return id >= 0 && idSet.get(id);
    }

    @Nonnull
    @Override
    public GlobalSearchScope getEffectiveFilteringScope() {
      return includeNonProjectItems ? GlobalSearchScope.allScope(project) : GlobalSearchScope.projectScope(project);
    }
  };
}
 
Example #19
Source File: ProgressIndicatorUtils.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Ensure the current EDT activity finishes in case it requires many write actions, with each being delayed a bit
 * by background thread read action (until its first checkCanceled call). Shouldn't be called from under read action.
 */
public static void yieldToPendingWriteActions() {
  Application application = ApplicationManager.getApplication();
  if (application.isReadAccessAllowed()) {
    throw new IllegalStateException("Mustn't be called from within read action");
  }
  if (application.isDispatchThread()) {
    throw new IllegalStateException("Mustn't be called from EDT");
  }
  Semaphore semaphore = new Semaphore(1);
  application.invokeLater(semaphore::up, ModalityState.any());
  awaitWithCheckCanceled(semaphore, ProgressIndicatorProvider.getGlobalProgressIndicator());
}
 
Example #20
Source File: ResolveScopeManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public GlobalSearchScope getResolveScope(@Nonnull PsiElement element) {
  ProgressIndicatorProvider.checkCanceled();

  VirtualFile vFile;
  final PsiFile contextFile;
  if (element instanceof PsiDirectory) {
    vFile = ((PsiDirectory)element).getVirtualFile();
    contextFile = null;
  }
  else {
    final PsiFile containingFile = element.getContainingFile();
    if (containingFile instanceof PsiCodeFragment) {
      final GlobalSearchScope forcedScope = ((PsiCodeFragment)containingFile).getForcedResolveScope();
      if (forcedScope != null) {
        return forcedScope;
      }
      final PsiElement context = containingFile.getContext();
      if (context == null) {
        return GlobalSearchScope.allScope(myProject);
      }
      return getResolveScope(context);
    }

    contextFile = containingFile != null ? FileContextUtil.getContextFile(containingFile) : null;
    if (contextFile == null) {
      return GlobalSearchScope.allScope(myProject);
    }
    else if (contextFile instanceof FileResolveScopeProvider) {
      return ((FileResolveScopeProvider)contextFile).getFileResolveScope();
    }
    vFile = contextFile.getOriginalFile().getVirtualFile();
  }
  if (vFile == null || contextFile == null) {
    return GlobalSearchScope.allScope(myProject);
  }

  return myDefaultResolveScopesCache.get(vFile);
}
 
Example #21
Source File: IndexCacheManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean processFilesWithWord(@Nonnull final Processor<PsiFile> psiFileProcessor, @Nonnull final String word, final short occurrenceMask, @Nonnull final GlobalSearchScope scope, final boolean caseSensitively) {
  final List<VirtualFile> vFiles = new ArrayList<VirtualFile>(5);
  collectVirtualFilesWithWord(new CommonProcessors.CollectProcessor<VirtualFile>(vFiles), word, occurrenceMask, scope, caseSensitively);
  if (vFiles.isEmpty()) return true;

  final Processor<VirtualFile> virtualFileProcessor = new ReadActionProcessor<VirtualFile>() {
    @RequiredReadAction
    @Override
    public boolean processInReadAction(VirtualFile virtualFile) {
      if (virtualFile.isValid()) {
        final PsiFile psiFile = myPsiManager.findFile(virtualFile);
        return psiFile == null || psiFileProcessor.process(psiFile);
      }
      return true;
    }
  };


  // IMPORTANT!!!
  // Since implementation of virtualFileProcessor.process() may call indices directly or indirectly,
  // we cannot call it inside FileBasedIndex.processValues() method
  // If we do, deadlocks are possible (IDEADEV-42137). So first we obtain files with the word specified,
  // and then process them not holding indices' read lock.
  for (VirtualFile vFile : vFiles) {
    ProgressIndicatorProvider.checkCanceled();
    if (!virtualFileProcessor.process(vFile)) {
      return false;
    }
  }
  return true;
}
 
Example #22
Source File: IndexCacheManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private boolean collectVirtualFilesWithWord(@Nonnull final Processor<VirtualFile> fileProcessor,
                                            @Nonnull final String word, final short occurrenceMask,
                                            @Nonnull final GlobalSearchScope scope, final boolean caseSensitively) {
  if (myProject.isDefault()) {
    return true;
  }

  try {
    return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
      @Override
      public Boolean compute() {
        return FileBasedIndex.getInstance().processValues(IdIndex.NAME, new IdIndexEntry(word, caseSensitively), null, new FileBasedIndex.ValueProcessor<Integer>() {
          final FileIndexFacade index = FileIndexFacade.getInstance(myProject);
          @Override
          public boolean process(final VirtualFile file, final Integer value) {
            ProgressIndicatorProvider.checkCanceled();
            final int mask = value.intValue();
            if ((mask & occurrenceMask) != 0 && index.shouldBeFound(scope, file)) {
              if (!fileProcessor.process(file)) return false;
            }
            return true;
          }
        }, scope);
      }
    });
  }
  catch (IndexNotReadyException e) {
    throw new ProcessCanceledException();
  }
}
 
Example #23
Source File: ResolveCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public <T extends PsiPolyVariantReference> ResolveResult[] resolveWithCaching(@Nonnull final T ref,
                                                                              @Nonnull final PolyVariantContextResolver<T> resolver,
                                                                              boolean needToPreventRecursion,
                                                                              final boolean incompleteCode,
                                                                              @Nonnull final PsiFile containingFile) {
  ProgressIndicatorProvider.checkCanceled();
  ApplicationManager.getApplication().assertReadAccessAllowed();

  boolean physical = containingFile.isPhysical();
  int index = getIndex(incompleteCode, true);
  Map<T, ResolveResult[]> map = getMap(physical, index);
  ResolveResult[] result = map.get(ref);
  if (result != null) {
    return result;
  }

  RecursionGuard.StackStamp stamp = RecursionManager.markStack();
  result = needToPreventRecursion
           ? RecursionManager.doPreventingRecursion(Pair.create(ref, incompleteCode), true, () -> resolver.resolve(ref, containingFile, incompleteCode))
           : resolver.resolve(ref, containingFile, incompleteCode);
  if (result != null) {
    ensureValidResults(result);
  }

  if (stamp.mayCacheNow()) {
    cache(ref, map, result);
  }
  return result == null ? ResolveResult.EMPTY_ARRAY : result;
}
 
Example #24
Source File: CompositeElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public final PsiElement getPsi() {
  ProgressIndicatorProvider.checkCanceled(); // We hope this method is being called often enough to cancel daemon processes smoothly

  PsiElement wrapper = myWrapper;
  if (wrapper != null) return wrapper;

  wrapper = createPsiNoLock();
  return ourPsiUpdater.compareAndSet(this, null, wrapper) ? wrapper : ObjectUtils.assertNotNull(myWrapper);
}
 
Example #25
Source File: LeafPsiElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Contract("-> fail")
private void invalid() {
  ProgressIndicatorProvider.checkCanceled();

  final StringBuilder builder = new StringBuilder();
  TreeElement element = this;
  while (element != null) {
    if (element != this) builder.append(" / ");
    builder.append(element.getClass().getName()).append(':').append(element.getElementType());
    element = element.getTreeParent();
  }

  throw new PsiInvalidElementAccessException(this, builder.toString());
}
 
Example #26
Source File: AstBufferUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void visitLeaf(LeafElement element) {
  ProgressIndicatorProvider.checkCanceled();
  if (!isIgnored(element)) {
    end = element.copyTo(buffer, end);
  }
}
 
Example #27
Source File: AbstractLayoutCodeProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void performFileProcessing(@Nonnull PsiFile file) {
  for (AbstractLayoutCodeProcessor processor : myProcessors) {
    FutureTask<Boolean> writeTask = ReadAction.compute(() -> processor.prepareTask(file, myProcessChangedTextOnly));

    ProgressIndicatorProvider.checkCanceled();

    ApplicationManager.getApplication().invokeAndWait(() -> WriteCommandAction.runWriteCommandAction(myProject, myCommandName, null, writeTask));

    checkStop(writeTask, file);
  }
}
 
Example #28
Source File: ANTLRParseTreeToPSIConverter.java    From antlr4-intellij-adaptor with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void exitEveryRule(ParserRuleContext ctx) {
	ProgressIndicatorProvider.checkCanceled();
	PsiBuilder.Marker marker = markers.pop();
	marker.done(getRuleElementTypes().get(ctx.getRuleIndex()));
}
 
Example #29
Source File: ANTLRParserAdaptor.java    From antlr4-intellij-adaptor with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@NotNull
@Override
public ASTNode parse(IElementType root, PsiBuilder builder) {
	ProgressIndicatorProvider.checkCanceled();

	TokenSource source = new PSITokenSource(builder);
	TokenStream tokens = new CommonTokenStream(source);
	parser.setTokenStream(tokens);
	parser.setErrorHandler(new ErrorStrategyAdaptor()); // tweaks missing tokens
	parser.removeErrorListeners();
	parser.addErrorListener(new SyntaxErrorListener()); // trap errors
	ParseTree parseTree = null;
	PsiBuilder.Marker rollbackMarker = builder.mark();
	try {
		parseTree = parse(parser, root);
	}
	finally {
		rollbackMarker.rollbackTo();
	}

	// Now convert ANTLR parser tree to PSI tree by mimicking subtree
	// enter/exit with mark/done calls. I *think* this creates their parse
	// tree (AST as they call it) when you call {@link PsiBuilder#getTreeBuilt}
	ANTLRParseTreeToPSIConverter listener = createListener(parser, root, builder);
	PsiBuilder.Marker rootMarker = builder.mark();
	ParseTreeWalker.DEFAULT.walk(listener, parseTree);
	while (!builder.eof()) {
		ProgressIndicatorProvider.checkCanceled();
		builder.advanceLexer();
	}
	// NOTE: parse tree returned from parse will be the
	// usual ANTLR tree ANTLRParseTreeToPSIConverter will
	// convert that to the analogous jetbrains AST nodes
	// When parsing an entire file, the root IElementType
	// will be a IFileElementType.
	//
	// When trying to rename IDs and so on, you get a
	// dummy root and a type arg identifier IElementType.
	// This results in a weird tree that has for example
	// (ID (expr (primary ID))) with the ID IElementType
	// as a subtree root as well as the appropriate leaf
	// all the way at the bottom.  The dummy ID root is a
	// CompositeElement and created by
	// ParserDefinition.createElement() despite having
	// being TokenIElementType.
	rootMarker.done(root);
	return builder.getTreeBuilt(); // calls the ASTFactory.createComposite() etc...
}
 
Example #30
Source File: ResolveCache.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static ResolveCache getInstance(Project project) {
  ProgressIndicatorProvider.checkCanceled(); // We hope this method is being called often enough to cancel daemon processes smoothly
  return ServiceManager.getService(project, ResolveCache.class);
}