com.intellij.psi.impl.source.tree.FileElement Java Examples

The following examples show how to use com.intellij.psi.impl.source.tree.FileElement. 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: CodeStyleManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static Pair<PsiElement, CharTable> doFindWhiteSpaceNode(@Nonnull PsiFile file, int offset) {
  ASTNode astNode = SourceTreeToPsiMap.psiElementToTree(file);
  if (!(astNode instanceof FileElement)) {
    return new Pair<>(null, null);
  }
  PsiElement elementAt = InjectedLanguageManager.getInstance(file.getProject()).findInjectedElementAt(file, offset);
  final CharTable charTable = ((FileElement)astNode).getCharTable();
  if (elementAt == null) {
    elementAt = findElementInTreeWithFormatterEnabled(file, offset);
  }

  if (elementAt == null) {
    return new Pair<>(null, charTable);
  }
  ASTNode node = elementAt.getNode();
  if (node == null || node.getElementType() != TokenType.WHITE_SPACE) {
    return new Pair<>(null, charTable);
  }
  return Pair.create(elementAt, charTable);
}
 
Example #2
Source File: PsiDocumentManagerBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("AssignmentToStaticFieldFromInstanceMethod")
public void reparseFileFromText(@Nonnull PsiFileImpl file) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  if (isCommitInProgress()) throw new IllegalStateException("Re-entrant commit is not allowed");

  FileElement node = file.calcTreeElement();
  CharSequence text = node.getChars();
  ourIsFullReparseInProgress = true;
  try {
    WriteAction.run(() -> {
      ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
      if (indicator == null) indicator = new EmptyProgressIndicator();
      DiffLog log = BlockSupportImpl.makeFullParse(file, node, text, indicator, text).log;
      log.doActualPsiChange(file);
      file.getViewProvider().contentsSynchronized();
    });
  }
  finally {
    ourIsFullReparseInProgress = false;
  }
}
 
Example #3
Source File: DummyHolder.java    From consulo with Apache License 2.0 6 votes vote down vote up
public DummyHolder(@Nonnull PsiManager manager, @Nullable TreeElement contentElement, @Nullable PsiElement context, @Nullable CharTable table, @Nullable Boolean validity, Language language) {
  super(TokenType.DUMMY_HOLDER, TokenType.DUMMY_HOLDER, new DummyHolderViewProvider(manager));
  myLanguage = language;
  ((DummyHolderViewProvider)getViewProvider()).setDummyHolder(this);
  myContext = context;
  myTable = table != null ? table : IdentityCharTable.INSTANCE;
  if (contentElement instanceof FileElement) {
    ((FileElement)contentElement).setPsi(this);
    ((FileElement)contentElement).setCharTable(myTable);
    setTreeElementPointer((FileElement)contentElement);
  }
  else if (contentElement != null) {
    getTreeElement().rawAddChildren(contentElement);
    clearCaches();
  }
  myExplicitlyValid = validity;
}
 
Example #4
Source File: StubBasedPsiElementBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private String dumpCreationTraces(@Nonnull FileElement fileElement) {
  final StringBuilder traces = new StringBuilder("\nNow " + Thread.currentThread() + "\n");
  traces.append("My creation trace:\n").append(getUserData(CREATION_TRACE));
  traces.append("AST creation traces:\n");
  fileElement.acceptTree(new RecursiveTreeElementWalkingVisitor(false) {
    @Override
    public void visitComposite(CompositeElement composite) {
      PsiElement psi = composite.getPsi();
      if (psi != null) {
        traces.append(psi).append("@").append(System.identityHashCode(psi)).append("\n");
        String trace = psi.getUserData(CREATION_TRACE);
        if (trace != null) {
          traces.append(trace).append("\n");
        }
      }
      super.visitComposite(composite);
    }
  });
  return traces.toString();
}
 
Example #5
Source File: StubBasedPsiElementBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
private ASTNode failedToBindStubToAst(@Nonnull PsiFileImpl file, @Nonnull final FileElement fileElement) {
  VirtualFile vFile = file.getVirtualFile();
  StubTree stubTree = file.getStubTree();
  final String stubString = stubTree != null ? ((PsiFileStubImpl)stubTree.getRoot()).printTree() : null;
  final String astString = RecursionManager.doPreventingRecursion("failedToBindStubToAst", true, () -> DebugUtil.treeToString(fileElement, true));

  @NonNls final String message =
          "Failed to bind stub to AST for element " + getClass() + " in " + (vFile == null ? "<unknown file>" : vFile.getPath()) + "\nFile:\n" + file + "@" + System.identityHashCode(file);

  final String creationTraces = ourTraceStubAstBinding ? dumpCreationTraces(fileElement) : null;

  List<Attachment> attachments = new ArrayList<>();
  if (stubString != null) {
    attachments.add(new Attachment("stubTree.txt", stubString));
  }
  if (astString != null) {
    attachments.add(new Attachment("ast.txt", astString));
  }
  if (creationTraces != null) {
    attachments.add(new Attachment("creationTraces.txt", creationTraces));
  }

  throw new RuntimeExceptionWithAttachments(message, attachments.toArray(Attachment.EMPTY_ARRAY));
}
 
Example #6
Source File: StubBasedPsiElementBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Ensures this element is AST-based. This is an expensive operation that might take significant time and allocate lots of objects,
 * so it should be to be avoided if possible.
 *
 * @return an AST node corresponding to this element. If the element is currently operating via stubs,
 * this causes AST to be loaded for the whole file and all stub-based PSI elements in this file (including the current one)
 * to be switched from stub to AST. So, after this call {@link #getStub()} will return null.
 */
@Override
@Nonnull
public ASTNode getNode() {
  if (mySubstrateRef instanceof SubstrateRef.StubRef) {
    ApplicationManager.getApplication().assertReadAccessAllowed();
    PsiFileImpl file = (PsiFileImpl)getContainingFile();
    if (!file.isValid()) throw new PsiInvalidElementAccessException(file);

    FileElement treeElement = file.getTreeElement();
    if (treeElement != null && mySubstrateRef instanceof SubstrateRef.StubRef) {
      return notBoundInExistingAst(file, treeElement);
    }

    treeElement = file.calcTreeElement();
    if (mySubstrateRef instanceof SubstrateRef.StubRef) {
      return failedToBindStubToAst(file, treeElement);
    }
  }

  return mySubstrateRef.getNode();
}
 
Example #7
Source File: PomModelImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static PsiFile getContainingFileByTree(@Nonnull final PsiElement changeScope) {
  // there could be pseudo physical trees (JSPX/JSP/etc.) which must not translate
  // any changes to document and not to fire any PSI events
  final PsiFile psiFile;
  final ASTNode node = changeScope.getNode();
  if (node == null) {
    psiFile = changeScope.getContainingFile();
  }
  else {
    final FileElement fileElement = TreeUtil.getFileElement((TreeElement)node);
    // assert fileElement != null : "Can't find file element for node: " + node;
    // Hack. the containing tree can be invalidated if updating supplementary trees like HTML in JSP.
    if (fileElement == null) return null;

    psiFile = (PsiFile)fileElement.getPsi();
  }
  return psiFile.getNode() != null ? psiFile : null;
}
 
Example #8
Source File: PomModelImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void reparseParallelTrees(PsiFile changedFile, PsiToDocumentSynchronizer synchronizer) {
  List<PsiFile> allFiles = changedFile.getViewProvider().getAllFiles();
  if (allFiles.size() <= 1) {
    return;
  }

  CharSequence newText = changedFile.getNode().getChars();
  for (final PsiFile file : allFiles) {
    FileElement fileElement = file == changedFile ? null : ((PsiFileImpl)file).getTreeElement();
    Runnable changeAction = fileElement == null ? null : reparseFile(file, fileElement, newText);
    if (changeAction == null) continue;

    synchronizer.setIgnorePsiEvents(true);
    try {
      CodeStyleManager.getInstance(file.getProject()).performActionWithFormatterDisabled(changeAction);
    }
    finally {
      synchronizer.setIgnorePsiEvents(false);
    }
  }
}
 
Example #9
Source File: ChangedPsiRangeUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static int getMatchingLength(@Nonnull FileElement treeElement, @Nonnull CharSequence text, boolean fromStart) {
  int patternIndex = fromStart ? 0 : text.length() - 1;
  int finalPatternIndex = fromStart ? text.length() - 1 : 0;
  int direction = fromStart ? 1 : -1;
  ASTNode leaf = fromStart ? TreeUtil.findFirstLeaf(treeElement, false) : TreeUtil.findLastLeaf(treeElement, false);
  int result = 0;
  while (leaf != null && (fromStart ? patternIndex <= finalPatternIndex : patternIndex >= finalPatternIndex)) {
    if (!(leaf instanceof ForeignLeafPsiElement)) {
      CharSequence chars = leaf.getChars();
      if (chars.length() > 0) {
        int matchingLength = getLeafMatchingLength(chars, text, patternIndex, finalPatternIndex, direction);
        result += matchingLength;
        if (matchingLength != chars.length()) {
          break;
        }
        patternIndex += fromStart ? matchingLength : -matchingLength;
      }
    }
    leaf = fromStart ? TreeUtil.nextLeaf(leaf, false) : TreeUtil.prevLeaf(leaf, false);
  }
  return result;
}
 
Example #10
Source File: PsiFileFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public PsiElement createElementFromText(@Nullable final String text,
                                        @Nonnull final Language language,
                                        @Nonnull final LanguageVersion languageVersion,
                                        @Nonnull final IElementType type,
                                        @Nullable final PsiElement context) {
  if (text == null) return null;
  final DummyHolder result = DummyHolderFactory.createHolder(myManager, language, context);
  final FileElement holder = result.getTreeElement();

  final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(language);
  if (parserDefinition == null) {
    throw new AssertionError("No parser definition for " + language);
  }
  final Project project = myManager.getProject();
  final Lexer lexer = parserDefinition.createLexer(languageVersion);
  final PsiBuilder builder = PsiBuilderFactory.getInstance().createBuilder(project, holder, lexer, language, languageVersion, text);
  final ASTNode node = parserDefinition.createParser(languageVersion).parse(type, builder, languageVersion);
  holder.rawAddChildren((TreeElement)node);
  markGenerated(result);
  return node.getPsi();
}
 
Example #11
Source File: InjectionRegistrarImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void patchLeaves(@Nonnull List<? extends PlaceInfo> placeInfos, @Nonnull InjectedFileViewProvider viewProvider, @Nonnull ASTNode parsedNode, @Nonnull CharSequence documentText)
        throws PatchException {
  Runnable patch = () -> {
    LeafPatcher patcher = new LeafPatcher(placeInfos, parsedNode.getTextLength());
    patcher.patch(parsedNode, placeInfos);
  };
  if (viewProvider instanceof SingleRootInjectedFileViewProvider) {
    ((SingleRootInjectedFileViewProvider)viewProvider).doNotInterruptMeWhileImPatchingLeaves(patch);
  }
  else if (viewProvider instanceof MultipleRootsInjectedFileViewProvider) {
    ((MultipleRootsInjectedFileViewProvider)viewProvider).doNotInterruptMeWhileImPatchingLeaves(patch);
  }
  if (!((FileElement)parsedNode).textMatches(documentText)) {
    throw new PatchException("After patch: doc:\n'" + documentText + "'\n---PSI:\n'" + parsedNode.getText());
  }
}
 
Example #12
Source File: DummyHolder.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings({"CloneDoesntDeclareCloneNotSupportedException"})
protected PsiFileImpl clone() {
  final PsiFileImpl psiClone = cloneImpl(getTreeElement());
  final DummyHolderViewProvider dummyHolderViewProvider = new DummyHolderViewProvider(getManager());
  myViewProvider = dummyHolderViewProvider;
  dummyHolderViewProvider.setDummyHolder((DummyHolder)psiClone);
  final FileElement treeClone = (FileElement)calcTreeElement().clone();
  psiClone.setTreeElementPointer(treeClone); // should not use setTreeElement here because cloned file still have VirtualFile (SCR17963)
  psiClone.myOriginalFile = isPhysical() ? this : myOriginalFile;
  treeClone.setPsi(psiClone);
  return psiClone;
}
 
Example #13
Source File: FileTrees.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures {@link #myRefToPsi}, stubs and AST all have the same PSI at corresponding indices.
 * In case several sources already have PSI (e.g. created during AST parsing), overwrites them with the "correct" one,
 * which is taken from {@link #myRefToPsi} if exists, otherwise from either stubs or AST depending on {@code takePsiFromStubs}.
 */
private FileTrees reconcilePsi(@Nullable StubTree stubTree, @Nullable FileElement astRoot, boolean takePsiFromStubs) {
  assert stubTree != null || astRoot != null;

  if ((stubTree == null || astRoot == null) && !hasCachedPsi()) {
    // there's only one source of PSI, nothing to reconcile
    return new FileTrees(myFile, myStub, myTreeElementPointer, null);
  }

  List<StubElement<?>> stubList = stubTree == null ? null : stubTree.getPlainList();
  List<CompositeElement> nodeList = astRoot == null ? null : astRoot.getStubbedSpine().getSpineNodes();
  List<PsiElement> srcSpine = stubList == null || nodeList == null ? null : getAllSpinePsi(takePsiFromStubs ? stubTree.getSpine() : astRoot.getStubbedSpine());

  try {
    return DebugUtil.performPsiModification("reconcilePsi", () -> {
      if (myRefToPsi != null) {
        assert myRefToPsi.length == (stubList != null ? stubList.size() : nodeList.size()) : "Cached PSI count doesn't match actual one";
        bindSubstratesToCachedPsi(stubList, nodeList);
      }

      if (stubList != null && nodeList != null) {
        assert stubList.size() == nodeList.size() : "Stub count doesn't match stubbed node length";

        FileTrees result = switchToSpineRefs(srcSpine);
        bindStubsWithAst(srcSpine, stubList, nodeList, takePsiFromStubs);
        return result;
      }
      return this;
    });
  }
  catch (Throwable e) {
    myFile.clearContent(PsiFileImpl.STUB_PSI_MISMATCH);
    myFile.rebuildStub();
    throw StubTreeLoader.getInstance().stubTreeAndIndexDoNotMatch(stubTree, myFile, e);
  }
}
 
Example #14
Source File: ChangedPsiRangeUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static TextRange getChangedPsiRange(@Nonnull PsiFile file, @Nonnull FileElement treeElement, @Nonnull CharSequence newDocumentText) {
  int psiLength = treeElement.getTextLength();
  if (!file.getViewProvider().supportsIncrementalReparse(file.getLanguage())) {
    return new TextRange(0, psiLength);
  }

  int commonPrefixLength = getMatchingLength(treeElement, newDocumentText, true);
  if (commonPrefixLength == newDocumentText.length() && newDocumentText.length() == psiLength) {
    return null;
  }

  int commonSuffixLength = Math.min(getMatchingLength(treeElement, newDocumentText, false), psiLength - commonPrefixLength);
  return new TextRange(commonPrefixLength, psiLength - commonSuffixLength);
}
 
Example #15
Source File: PsiParserFacadeImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public PsiElement createWhiteSpaceFromText(@Nonnull @NonNls String text) throws IncorrectOperationException {
  final FileElement holderElement = DummyHolderFactory.createHolder(myManager, null).getTreeElement();
  final LeafElement newElement = ASTFactory.leaf(TokenType.WHITE_SPACE, holderElement.getCharTable().intern(text));
  holderElement.rawAddChildren(newElement);
  GeneratedMarkerVisitor.markGenerated(newElement.getPsi());
  return newElement.getPsi();
}
 
Example #16
Source File: DefaultStubBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void visitNode(StubElement parentStub, ASTNode node, boolean immediateParentStubbed) {
  StubElement stub = createStub(parentStub, node);
  if (stub != null && !immediateParentStubbed) {
    ((ObjectStubBase)stub).markDangling();
  }

  pushChildren(node, node instanceof FileElement || stub != null, stub != null ? stub : parentStub);
}
 
Example #17
Source File: DocumentCommitThread.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void assertAfterCommit(@Nonnull Document document, @Nonnull final PsiFile file, @Nonnull FileElement oldFileNode) {
  if (oldFileNode.getTextLength() != document.getTextLength()) {
    final String documentText = document.getText();
    String fileText = file.getText();
    boolean sameText = Comparing.equal(fileText, documentText);
    String errorMessage = "commitDocument() left PSI inconsistent: " +
                          DebugUtil.diagnosePsiDocumentInconsistency(file, document) +
                          "; node.length=" +
                          oldFileNode.getTextLength() +
                          "; doc.text" +
                          (sameText ? "==" : "!=") +
                          "file.text" +
                          "; file name:" +
                          file.getName() +
                          "; type:" +
                          file.getFileType() +
                          "; lang:" +
                          file.getLanguage();
    //PluginException.logPluginError(LOG, errorMessage, null, file.getLanguage().getClass());
    LOG.error(errorMessage);

    file.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, Boolean.TRUE);
    try {
      BlockSupport blockSupport = BlockSupport.getInstance(file.getProject());
      final DiffLog diffLog = blockSupport.reparseRange(file, file.getNode(), new TextRange(0, documentText.length()), documentText, createProgressIndicator(), oldFileNode.getText());
      diffLog.doActualPsiChange(file);

      if (oldFileNode.getTextLength() != document.getTextLength()) {
        LOG.error("PSI is broken beyond repair in: " + file);
        //PluginException.logPluginError(LOG, "PSI is broken beyond repair in: " + file, null, file.getLanguage().getClass());
      }
    }
    finally {
      file.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, null);
    }
  }
}
 
Example #18
Source File: DiffLog.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void nodeReplaced(@Nonnull ASTNode oldNode, @Nonnull ASTNode newNode) {
  if (oldNode instanceof FileElement && newNode instanceof FileElement) {
    appendReplaceFileElement((FileElement)oldNode, (FileElement)newNode);
  }
  else {
    myEntries.add(new ReplaceEntry(oldNode, newNode));
  }
}
 
Example #19
Source File: SingleRootFileViewProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public final List<FileElement> getKnownTreeRoots() {
  PsiFile psiFile = getCachedPsi(getBaseLanguage());
  if (!(psiFile instanceof PsiFileImpl)) return Collections.emptyList();
  FileElement element = ((PsiFileImpl)psiFile).getTreeElement();
  return ContainerUtil.createMaybeSingletonList(element);
}
 
Example #20
Source File: CsvHelper.java    From intellij-csv-validator with Apache License 2.0 5 votes vote down vote up
public static PsiElement createEmptyCsvField(PsiFile psiFile) {
    final Project project = psiFile.getProject();
    final String text = "<undefined>";
    final IElementType type = CsvTypes.FIELD;
    final PsiManager psiManager = PsiManager.getInstance(project);
    final DummyHolder dummyHolder = DummyHolderFactory.createHolder(psiManager, null);
    final FileElement fileElement = dummyHolder.getTreeElement();
    final FileParserDefinition parserDefinition = (FileParserDefinition) LanguageParserDefinitions.INSTANCE.forLanguage(CsvLanguage.INSTANCE);
    final Lexer lexer = parserDefinition.createLexer(psiFile);
    final PsiBuilder psiBuilder = PsiBuilderFactory.getInstance().createBuilder(project, fileElement, lexer, CsvLanguage.INSTANCE, text);
    final ASTNode node = parserDefinition.createParser(project).parse(type, psiBuilder);
    fileElement.rawAddChildren((com.intellij.psi.impl.source.tree.TreeElement) node);
    return node.getPsi();
}
 
Example #21
Source File: CsvAnnotatorTest.java    From intellij-csv-validator with Apache License 2.0 5 votes vote down vote up
private long collectAndCheckHighlighting(@NotNull ExpectedHighlightingDataWrapper data) {
    Project project = myFixture.getProject();
    EdtTestUtil.runInEdtAndWait(() -> {
        PsiDocumentManager.getInstance(project).commitAllDocuments();
    });
    PsiFileImpl file = (PsiFileImpl)this.getHostFile();
    FileElement hardRefToFileElement = file.calcTreeElement();
    if (!DumbService.isDumb(project)) {
        ServiceManager.getService(project, CacheManager.class).getFilesWithWord("XXX", (short)2, GlobalSearchScope.allScope(project), true);
    }

    long start = System.currentTimeMillis();
    Disposable disposable = Disposer.newDisposable();

    List<HighlightInfo> infos;
    try {
        infos = myFixture.doHighlighting();
        this.removeDuplicatedRangesForInjected(infos);
    } finally {
        Disposer.dispose(disposable);
    }

    long elapsed = System.currentTimeMillis() - start;
    data.checkResultWrapper(file, infos, file.getText());
    hardRefToFileElement.hashCode();
    return elapsed;
}
 
Example #22
Source File: ANTLRv4ASTFactory.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Create a FileElement for root or a parse tree CompositeElement (not
*  PSI) for the token. This impl is more or less the default.
*/
  @Override
  public CompositeElement createComposite(IElementType type) {
      if (type instanceof IFileElementType) {
          return new FileElement(type, null);
}
      return new CompositeElement(type);
  }
 
Example #23
Source File: CodeInsightTestFixtureImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private long collectAndCheckHighlighting(@Nonnull ExpectedHighlightingData data) {
    final Project project = getProject();
    PsiDocumentManager.getInstance(project).commitAllDocuments();

    PsiFileImpl file = (PsiFileImpl)getHostFile();
    FileElement hardRefToFileElement = file.calcTreeElement();//to load text

    //to initialize caches
    if (!DumbService.isDumb(project)) {
      CacheManager.getInstance(project).getFilesWithWord(XXX, UsageSearchContext.IN_COMMENTS, GlobalSearchScope.allScope(project), true);
    }

    List<HighlightInfo> infos;
    final long start = System.currentTimeMillis();
    try {
      ((PsiManagerImpl)PsiManager.getInstance(project)).setAssertOnFileLoadingFilter(myJavaFilesFilter, myTestRootDisposable);

//    ProfilingUtil.startCPUProfiling();
      infos = doHighlighting();
      removeDuplicatedRangesForInjected(infos);
//    ProfilingUtil.captureCPUSnapshot("testing");
    }
    finally {
      ((PsiManagerImpl)PsiManager.getInstance(project)).setAssertOnFileLoadingFilter(VirtualFileFilter.NONE, myTestRootDisposable);
    }
    final long elapsed = System.currentTimeMillis() - start;

    data.checkResult(infos, file.getText());
    hardRefToFileElement.hashCode(); // use it so gc won't collect it
    return elapsed;
  }
 
Example #24
Source File: DefaultASTCompositeFactory.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public CompositeElement createComposite(@Nonnull IElementType type) {
  if (type instanceof IFileElementType) {
    return new FileElement(type, null);
  }
  if (type instanceof ICompositeElementType) {
    return (CompositeElement)((ICompositeElementType)type).createCompositeNode();
  }
  return new CompositeElement(type);
}
 
Example #25
Source File: AbstractFileViewProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
private boolean isDocumentConsistentWithPsi(int fileLength, FileElement fileElement, int nodeLength) {
  if (nodeLength != fileLength) return false;

  if (ApplicationManager.getApplication().isUnitTestMode() && !ApplicationInfoImpl.isInPerformanceTest()) {
    return fileElement.textMatches(myContent.getText());
  }

  return true;
}
 
Example #26
Source File: AbstractFileViewProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void checkLengthConsistency() {
  Document document = getCachedDocument();
  if (document instanceof DocumentWindow) {
    return;
  }
  if (document != null && ((PsiDocumentManagerBase)PsiDocumentManager.getInstance(myManager.getProject())).getSynchronizer().isInSynchronization(document)) {
    return;
  }

  List<FileElement> knownTreeRoots = getKnownTreeRoots();
  if (knownTreeRoots.isEmpty()) return;

  int fileLength = myContent.getTextLength();
  for (FileElement fileElement : knownTreeRoots) {
    int nodeLength = fileElement.getTextLength();
    if (!isDocumentConsistentWithPsi(fileLength, fileElement, nodeLength)) {
      PsiUtilCore.ensureValid(fileElement.getPsi());
      List<Attachment> attachments = ContainerUtil
              .newArrayList(new Attachment(myVirtualFile.getName(), myContent.getText().toString()), new Attachment(myVirtualFile.getNameWithoutExtension() + ".tree.txt", fileElement.getText()));
      if (document != null) {
        attachments.add(new Attachment(myVirtualFile.getNameWithoutExtension() + ".document.txt", document.getText()));
      }
      // exceptions here should be assigned to peter
      LOG.error("Inconsistent " + fileElement.getElementType() + " tree in " + this + "; nodeLength=" + nodeLength + "; fileLength=" + fileLength, attachments.toArray(Attachment.EMPTY_ARRAY));
    }
  }
}
 
Example #27
Source File: MultiplePsiFilesPerDocumentFileViewProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public final List<FileElement> getKnownTreeRoots() {
  List<FileElement> files = new ArrayList<>(myRoots.size());
  for (PsiFile file : myRoots.values()) {
    final FileElement treeElement = ((PsiFileImpl)file).getTreeElement();
    if (treeElement != null) {
      files.add(treeElement);
    }
  }

  return files;
}
 
Example #28
Source File: StubBasedPsiElementBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"NonConstantStringShouldBeStringBuffer", "StringConcatenationInLoop"})
private ASTNode notBoundInExistingAst(@Nonnull PsiFileImpl file, @Nonnull FileElement treeElement) {
  String message = "file=" + file + "; tree=" + treeElement;
  PsiElement each = this;
  while (each != null) {
    message += "\n each of class " + each.getClass() + "; valid=" + each.isValid();
    if (each instanceof StubBasedPsiElementBase) {
      message += "; ref=" + ((StubBasedPsiElementBase<?>)each).mySubstrateRef;
      each = ((StubBasedPsiElementBase<?>)each).getParentByStub();
    }
    else {
      if (each instanceof PsiFile) {
        message += "; same file=" + (each == file) + "; current tree= " + file.getTreeElement() + "; stubTree=" + file.getStubTree() + "; physical=" + file.isPhysical();
      }
      break;
    }
  }
  StubElement<?> eachStub = getStub();
  while (eachStub != null) {
    message += "\n each stub " + (eachStub instanceof PsiFileStubImpl ? ((PsiFileStubImpl<?>)eachStub).getDiagnostics() : eachStub);
    eachStub = eachStub.getParentStub();
  }

  if (ourTraceStubAstBinding) {
    message += dumpCreationTraces(treeElement);
  }
  throw new AssertionError(message);
}
 
Example #29
Source File: PomModelImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private Runnable reparseFile(@Nonnull final PsiFile file, @Nonnull FileElement treeElement, @Nonnull CharSequence newText) {
  TextRange changedPsiRange = ChangedPsiRangeUtil.getChangedPsiRange(file, treeElement, newText);
  if (changedPsiRange == null) return null;

  final DiffLog log = BlockSupport.getInstance(myProject).reparseRange(file, treeElement, changedPsiRange, newText, new EmptyProgressIndicator(), treeElement.getText());
  return () -> runTransaction(new PomTransactionBase(file, getModelAspect(TreeAspect.class)) {
    @Override
    public PomModelEvent runInner() throws IncorrectOperationException {
      return new TreeAspectEvent(PomModelImpl.this, log.performActualPsiChange(file));
    }
  });
}
 
Example #30
Source File: FileTrees.java    From consulo with Apache License 2.0 4 votes vote down vote up
private FileTrees(@Nonnull PsiFileImpl file, @Nullable Reference<StubTree> stub, @Nullable Getter<FileElement> ast, @Nullable Reference<StubBasedPsiElementBase>[] refToPsi) {
  myFile = file;
  myStub = stub;
  myTreeElementPointer = ast;
  myRefToPsi = refToPsi;
}