Java Code Examples for com.intellij.psi.PsiFile#putUserData()

The following examples show how to use com.intellij.psi.PsiFile#putUserData() . 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
public static void annotatePsiFile(@NotNull Project project, @NotNull Language lang, @Nullable VirtualFile sourceFile, @Nullable InferredTypes types) {
    if (types == null || sourceFile == null) {
        return;
    }

    if (FileHelper.isInterface(sourceFile.getFileType())) {
        return;
    }

    LOG.debug("Updating signatures in user data cache for file", sourceFile);

    TextEditor selectedEditor = (TextEditor) FileEditorManager.getInstance(project).getSelectedEditor(sourceFile);
    if (selectedEditor != null) {
        CodeLensView.CodeLensInfo userData = getCodeLensData(project);
        userData.putAll(sourceFile, types.signaturesByLines(lang));
    }

    PsiFile psiFile = PsiManager.getInstance(project).findFile(sourceFile);
    if (psiFile != null && !FileHelper.isInterface(psiFile.getFileType())) {
        String[] lines = psiFile.getText().split("\n");
        psiFile.putUserData(SignatureProvider.SIGNATURE_CONTEXT, new SignatureProvider.InferredTypesWithLines(types, lines));
    }
}
 
Example 2
Source Project: idea-php-typo3-plugin   File: JavaScriptUtil.java    License: MIT License 6 votes vote down vote up
@NotNull
private static Map<String, List<PsiFile>> doGetModuleMap(@NotNull Project project) {
    Map<String, List<PsiFile>> map = new HashMap<>();
    for (PsiFile psiFile : findModuleFiles(project)) {
        if (psiFile.getUserData(MODULE_NAME_DATA_KEY) != null) {
            map.put(psiFile.getUserData(MODULE_NAME_DATA_KEY), Collections.singletonList(psiFile));

            continue;
        }

        String name = calculateModuleName(psiFile);
        if (name != null) {
            psiFile.putUserData(MODULE_NAME_DATA_KEY, name);
            map.put(name, Collections.singletonList(psiFile));
        }
    }

    return map;
}
 
Example 3
private synchronized Collection<FluidNamespace> doProvide(@NotNull PsiElement element) {
    FileViewProvider viewProvider = element.getContainingFile().getViewProvider();
    if (!viewProvider.getLanguages().contains(HTMLLanguage.INSTANCE)) {
        return ContainerUtil.emptyList();
    }

    PsiFile htmlFile = viewProvider.getPsi(HTMLLanguage.INSTANCE);
    CachedValue userData = htmlFile.getUserData(HTML_NS_KEY);
    if (userData != null) {
        return (Collection<FluidNamespace>) userData.getValue();
    }

    CachedValue<Collection<FluidNamespace>> cachedValue = CachedValuesManager.getManager(element.getProject()).createCachedValue(() -> {
        HtmlNSVisitor visitor = new HtmlNSVisitor();
        htmlFile.accept(visitor);

        return CachedValueProvider.Result.createSingleDependency(visitor.namespaces, htmlFile);
    }, false);

    htmlFile.putUserData(HTML_NS_KEY, cachedValue);

    return cachedValue.getValue();
}
 
Example 4
Source Project: consulo   File: Divider.java    License: Apache License 2.0 6 votes vote down vote up
static void divideInsideAndOutsideInOneRoot(@Nonnull PsiFile root,
                                            @Nonnull TextRange restrictRange,
                                            @Nonnull TextRange priorityRange,
                                            @Nonnull Processor<DividedElements> processor) {
  long modificationStamp = root.getModificationStamp();
  DividedElements cached = SoftReference.dereference(root.getUserData(DIVIDED_ELEMENTS_KEY));
  DividedElements elements;
  if (cached == null || cached.modificationStamp != modificationStamp || !cached.restrictRange.equals(restrictRange) || !cached.priorityRange.contains(priorityRange)) {
    elements = new DividedElements(modificationStamp, root, restrictRange, priorityRange);
    divideInsideAndOutsideInOneRoot(root, restrictRange, priorityRange, elements.inside, elements.insideRanges, elements.outside,
                                    elements.outsideRanges, elements.parents,
                                    elements.parentRanges, true);
    root.putUserData(DIVIDED_ELEMENTS_KEY, new java.lang.ref.SoftReference<>(elements));
  }
  else {
    elements = cached;
  }
  processor.process(elements);
}
 
Example 5
Source Project: consulo   File: FileBasedIndexImpl.java    License: Apache License 2.0 5 votes vote down vote up
private static void initFileContent(@Nonnull FileContentImpl fc, Project project, PsiFile psiFile) {
  if (psiFile != null) {
    psiFile.putUserData(PsiFileImpl.BUILDING_STUB, true);
    fc.putUserData(IndexingDataKeys.PSI_FILE, psiFile);
  }

  fc.putUserData(IndexingDataKeys.PROJECT, project);
}
 
Example 6
Source Project: consulo   File: PsiFileGistImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Data getFileData(@Nonnull PsiFile file) {
  ApplicationManager.getApplication().assertReadAccessAllowed();

  if (shouldUseMemoryStorage(file)) {
    return CachedValuesManager.getManager(file.getProject()).getCachedValue(file, myCacheKey, () -> {
      Data data = myCalculator.calcData(file.getProject(), file.getViewProvider().getVirtualFile());
      return CachedValueProvider.Result.create(data, file, ourReindexTracker);
    }, false);
  }

  file.putUserData(myCacheKey, null);
  return myPersistence.getFileData(file.getProject(), file.getVirtualFile());
}
 
Example 7
private RenderErrorModel createRenderErrorModelWithBrokenClasses() {
  PsiFile file = new MockPsiFile(new MockPsiManager(project));
  file.putUserData(ModuleUtilCore.KEY_MODULE, module);
  RenderResult result = RenderResult.createBlank(file);
  result
      .getLogger()
      .addBrokenClass("com.google.example.CustomView", new Exception("resource not found"));
  return RenderErrorModelFactory.createErrorModel(null, result, null);
}
 
Example 8
private RenderErrorModel createRenderErrorModelWithMissingClasses(String... classNames) {
  PsiFile file = new MockPsiFile(new MockPsiManager(project));
  file.putUserData(ModuleUtilCore.KEY_MODULE, module);
  RenderResult result = RenderResult.createBlank(file);
  for (String className : classNames) {
    result.getLogger().addMissingClass(className);
  }
  return RenderErrorModelFactory.createErrorModel(null, result, null);
}
 
Example 9
Source Project: intellij-haxe   File: HaxeFileModel.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
static public HaxeFileModel fromElement(PsiElement element) {
  if (element == null) return null;

  final PsiFile file = element instanceof PsiFile ? (PsiFile)element : element.getContainingFile();
  if (file instanceof HaxeFile) {
    HaxeFileModel model = file.getUserData(HAXE_FILE_MODEL_KEY);
    if (model == null) {
      model = new HaxeFileModel((HaxeFile)file);
      file.putUserData(HAXE_FILE_MODEL_KEY, model);
    }
    return model;
  }
  return null;
}
 
Example 10
Source Project: CppTools   File: HighlightUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static HighlightCommand getUpToDateHighlightCommand(PsiFile psiFile, Project project) {
  HighlightCommand command = psiFile.getUserData(ourCurrentHighlightingCommandKey);

  if (command == null || !command.isUpToDate() || command.isFailedOrCancelled()) {
    command = new HighlightCommand(psiFile);
    psiFile.putUserData(ourCurrentHighlightingCommandKey, command);
    command.nonblockingPost(project);
  }
  return command;
}
 
Example 11
@NotNull
private Collection<String> suggestKeywordsBasedOnParserExpectedKeywords(@NotNull PsiElement position) {
    String text = getPrecedingText(position, CompletionInitializationContext.DUMMY_IDENTIFIER);
    Project project = position.getProject();
    PsiFile temporaryFileForCompletionCheck = createFileForText(project, text + "          ");
    int completionOffset = calculateCompletionOffset(position);
    GeneratedParserUtilBase.CompletionState completionStateInTemporaryFile = getCompletionStateForKeywords(completionOffset);
    temporaryFileForCompletionCheck.putUserData(COMPLETION_STATE_KEY, completionStateInTemporaryFile);
    triggerParsingInFile(temporaryFileForCompletionCheck);
    List<String> stripped = stringPrecedingText(StringUtils.normalizeWhitespaces(text), completionStateInTemporaryFile.items);
    return expandMultiWordOptions(stripped);
}
 
Example 12
private Collection<String> suggestKeywords(@NotNull PsiElement position) {
  PsiFile psiFile = position.getContainingFile();
  PsiElement topLevelElement = position;
  while (!(topLevelElement.getParent() instanceof PsiFile)) {
    topLevelElement = topLevelElement.getParent();
  }
  PsiFile file = PsiFileFactory.getInstance(psiFile.getProject())
    .createFileFromText("a.thrift", ThriftLanguage.INSTANCE, topLevelElement.getText(), true, false);
  GeneratedParserUtilBase.CompletionState state =
    new GeneratedParserUtilBase.CompletionState(position.getTextOffset() - topLevelElement.getTextOffset());
  file.putUserData(GeneratedParserUtilBase.COMPLETION_STATE_KEY, state);
  TreeUtil.ensureParsed(file.getNode());
  return state.items;
}
 
Example 13
Source Project: consulo   File: PsiBuilderImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void checkTreeDepth(final int maxDepth, final boolean isFileRoot) {
  if (myFile == null) return;
  final PsiFile file = myFile.getOriginalFile();
  final Boolean flag = file.getUserData(BlockSupport.TREE_DEPTH_LIMIT_EXCEEDED);
  if (maxDepth > BlockSupport.INCREMENTAL_REPARSE_DEPTH_LIMIT) {
    if (!Boolean.TRUE.equals(flag)) {
      file.putUserData(BlockSupport.TREE_DEPTH_LIMIT_EXCEEDED, Boolean.TRUE);
    }
  }
  else if (isFileRoot && flag != null) {
    file.putUserData(BlockSupport.TREE_DEPTH_LIMIT_EXCEEDED, null);
  }
}
 
Example 14
Source Project: consulo   File: FileContentImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
private PsiFile getFileFromText() {
  PsiFile psi = getUserData(IndexingDataKeys.PSI_FILE);

  if (psi == null) {
    psi = getUserData(CACHED_PSI);
  }

  if (psi == null) {
    psi = createFileFromText(getContentAsText());
    psi.putUserData(IndexingDataKeys.VIRTUAL_FILE, getFile());
    putUserData(CACHED_PSI, psi);
  }
  return psi;
}
 
Example 15
Source Project: consulo   File: QuickEditAction.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
private QuickEditHandler getHandler(Project project, PsiFile injectedFile, Editor editor, PsiFile origFile) {
  QuickEditHandler handler = getExistingHandler(injectedFile);
  if (handler != null && handler.isValid()) {
    return handler;
  }
  handler = new QuickEditHandler(project, injectedFile, origFile, editor, this);
  if (ApplicationManager.getApplication().isUnitTestMode()) {
    // todo remove and hide QUICK_EDIT_HANDLER
    injectedFile.putUserData(QUICK_EDIT_HANDLER, handler);
  }
  return handler;
}
 
Example 16
public static <T> void installCompletion(Document document,
                                         Project project,
                                         @Nullable TextFieldWithAutoCompletionListProvider<T> consumer,
                                         boolean autoPopup) {
  PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
  if (psiFile != null) {
    //noinspection unchecked
    psiFile.putUserData(KEY, consumer == null ? TextFieldWithAutoCompletion.EMPTY_COMPLETION : consumer);
    psiFile.putUserData(AUTO_POPUP_KEY, autoPopup);
  }
}
 
Example 17
Source Project: consulo   File: TextCompletionUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static void installProvider(@Nonnull PsiFile psiFile, @Nonnull TextCompletionProvider provider, boolean autoPopup) {
  psiFile.putUserData(COMPLETING_TEXT_FIELD_KEY, provider);
  psiFile.putUserData(AUTO_POPUP_KEY, autoPopup);
}
 
Example 18
Source Project: consulo   File: StubTreeBuilder.java    License: Apache License 2.0 4 votes vote down vote up
@Nullable
public static Stub buildStubTree(final FileContent inputData) {
  Stub data = inputData.getUserData(stubElementKey);
  if (data != null) return data;

  //noinspection SynchronizationOnLocalVariableOrMethodParameter
  synchronized (inputData) {
    data = inputData.getUserData(stubElementKey);
    if (data != null) return data;

    final FileType fileType = inputData.getFileType();

    final BinaryFileStubBuilder builder = BinaryFileStubBuilders.INSTANCE.forFileType(fileType);
    if (builder != null) {
      data = builder.buildStubTree(inputData);
      if (data instanceof PsiFileStubImpl && !((PsiFileStubImpl)data).rootsAreSet()) {
        ((PsiFileStubImpl)data).setStubRoots(new PsiFileStub[]{(PsiFileStubImpl)data});
      }
    }
    else {
      CharSequence contentAsText = inputData.getContentAsText();
      PsiDependentFileContent fileContent = (PsiDependentFileContent)inputData;
      PsiFile psi = fileContent.getPsiFile();
      final FileViewProvider viewProvider = psi.getViewProvider();
      psi = viewProvider.getStubBindingRoot();
      psi.putUserData(IndexingDataKeys.FILE_TEXT_CONTENT_KEY, contentAsText);

      // if we load AST, it should be easily gc-able. See PsiFileImpl.createTreeElementPointer()
      psi.getManager().startBatchFilesProcessingMode();

      try {
        IStubFileElementType stubFileElementType = ((PsiFileImpl)psi).getElementTypeForStubBuilder();
        if (stubFileElementType != null) {
          final StubBuilder stubBuilder = stubFileElementType.getBuilder();
          if (stubBuilder instanceof LightStubBuilder) {
            LightStubBuilder.FORCED_AST.set(fileContent.getLighterAST());
          }
          data = stubBuilder.buildStubTree(psi);

          final List<Pair<IStubFileElementType, PsiFile>> stubbedRoots = getStubbedRoots(viewProvider);
          final List<PsiFileStub> stubs = new ArrayList<>(stubbedRoots.size());
          stubs.add((PsiFileStub)data);

          for (Pair<IStubFileElementType, PsiFile> stubbedRoot : stubbedRoots) {
            final PsiFile secondaryPsi = stubbedRoot.second;
            if (psi == secondaryPsi) continue;
            final StubBuilder stubbedRootBuilder = stubbedRoot.first.getBuilder();
            if (stubbedRootBuilder instanceof LightStubBuilder) {
              LightStubBuilder.FORCED_AST.set(new TreeBackedLighterAST(secondaryPsi.getNode()));
            }
            final StubElement element = stubbedRootBuilder.buildStubTree(secondaryPsi);
            if (element instanceof PsiFileStub) {
              stubs.add((PsiFileStub)element);
            }
            ensureNormalizedOrder(element);
          }
          final PsiFileStub[] stubsArray = stubs.toArray(PsiFileStub.EMPTY_ARRAY);
          for (PsiFileStub stub : stubsArray) {
            if (stub instanceof PsiFileStubImpl) {
              ((PsiFileStubImpl)stub).setStubRoots(stubsArray);
            }
          }
        }
      }
      finally {
        psi.putUserData(IndexingDataKeys.FILE_TEXT_CONTENT_KEY, null);
        psi.getManager().finishBatchFilesProcessingMode();
      }
    }

    ensureNormalizedOrder(data);
    inputData.putUserData(stubElementKey, data);
    return data;
  }
}
 
Example 19
Source Project: consulo   File: CodeFoldingPass.java    License: Apache License 2.0 4 votes vote down vote up
static void clearFirstTimeFlag(PsiFile file, Editor editor, Key<Boolean> key) {
  file.putUserData(key, Boolean.FALSE);
  editor.putUserData(key, Boolean.FALSE);
}
 
Example 20
Source Project: consulo   File: FileBasedIndexImpl.java    License: Apache License 2.0 4 votes vote down vote up
private static void cleanFileContent(@Nonnull FileContentImpl fc, PsiFile psiFile) {
  if (psiFile != null) psiFile.putUserData(PsiFileImpl.BUILDING_STUB, null);
  fc.putUserData(IndexingDataKeys.PSI_FILE, null);
}