Java 类com.intellij.psi.impl.source.PsiFileImpl 实例源码

项目:bamboo-soy    文件:SoyFileViewProvider.java   
@Override
protected PsiFile createFile(@NotNull Language lang) {
  ParserDefinition parserDefinition = getDefinition(lang);
  if (parserDefinition == null) {
    return null;
  }

  if (lang.is(templateDataLanguage)) {
    PsiFileImpl file = (PsiFileImpl) parserDefinition.createFile(this);
    file.setContentElementType(templateDataLanguageType);
    return file;
  } else if (lang.isKindOf(baseLanguage)) {
    return parserDefinition.createFile(this);
  } else {
    return null;
  }
}
项目:rythm_plugin    文件:RythmFileViewProvider.java   
@Override
protected PsiFile createFile(@NotNull Language lang) {
    ParserDefinition parserDefinition = getDefinition(lang);
    if (parserDefinition == null) {
        return null;
    }
    if (lang.is(getTemplateDataLanguage())) {
        PsiFileImpl file = (PsiFileImpl) parserDefinition.createFile(this);
        file.setContentElementType(getTemplateDataElementType(getBaseLanguage()));
        return file;
    } else if (lang.isKindOf(getBaseLanguage())) {
        return parserDefinition.createFile(this);
    } else {
        return null;
    }
}
项目:intellij-ce-playground    文件:SmartPsiElementPointersTest.java   
public void testNoAstLoadingWithoutDocumentChanges() {
  PsiClass aClass = myJavaFacade.findClass("Test",GlobalSearchScope.allScope(getProject()));
  assertNotNull(aClass);
  PsiFileImpl file = (PsiFileImpl)aClass.getContainingFile();

  createEditor(file.getVirtualFile());
  assertFalse(file.isContentsLoaded());

  SmartPointerEx pointer = (SmartPointerEx)createPointer(aClass);
  assertFalse(file.isContentsLoaded());

  //noinspection UnusedAssignment
  aClass = null;
  PlatformTestUtil.tryGcSoftlyReachableObjects();
  assertNull(pointer.getCachedElement());

  assertNotNull(pointer.getElement());
  assertFalse(file.isContentsLoaded());
}
项目:intellij-ce-playground    文件:SmartPsiElementPointersTest.java   
public void testEqualPointerRangesWhenCreatedFromStubAndAST() {
  final PsiFile file = configureByText(JavaFileType.INSTANCE,
                                       "class S {\n" +
                                       "}");

  PsiClass aClass = ((PsiJavaFile)file).getClasses()[0];
  assertNotNull(((PsiFileImpl)file).getStubTree());

  final SmartPointerManager manager = getPointerManager();
  final SmartPsiElementPointer<PsiClass> pointer1 = createPointer(aClass);
  Segment range1 = pointer1.getRange();
  manager.removePointer(pointer1);

  final FileASTNode node = file.getNode();
  final SmartPsiElementPointer<PsiClass> pointer2 = createPointer(aClass);
  assertEquals(range1, pointer2.getRange());
  assertNotNull(node);
}
项目:intellij-ce-playground    文件:SmartPsiElementPointersTest.java   
public void testEqualPointersWhenCreatedFromStubAndAST() {
  PsiJavaFile file = (PsiJavaFile)myJavaFacade.findClass("AClass", GlobalSearchScope.allScope(getProject())).getContainingFile();

  int hash1 = file.getClasses()[0].hashCode();
  final SmartPsiElementPointer<PsiClass> pointer1 = createPointer(file.getClasses()[0]);
  assertNotNull(((PsiFileImpl)file).getStubTree());

  PlatformTestUtil.tryGcSoftlyReachableObjects();

  final FileASTNode node = file.getNode();
  final SmartPsiElementPointer<PsiClass> pointer2 = createPointer(file.getClasses()[0]);
  assertFalse(hash1 == file.getClasses()[0].hashCode());
  assertEquals(pointer1, pointer2);
  assertEquals(pointer1.getRange(), pointer2.getRange());
  assertNotNull(node);
}
项目:intellij-ce-playground    文件:SmartPsiElementPointersTest.java   
public void testNonAnchoredStubbedElement() {
  PsiFile file = configureByText(JavaFileType.INSTANCE, "class Foo { { @NotNull String foo; } }");
  StubTree stubTree = ((PsiFileImpl)file).getStubTree();
  assertNotNull(stubTree);
  PsiElement anno = stubTree.getPlainList().stream().map(StubElement::getPsi).filter(psiElement -> psiElement instanceof PsiAnnotation).findFirst().get();

  SmartPsiElementPointer<PsiElement> pointer = createPointer(anno);
  assertNotNull(((PsiFileImpl)file).getStubTree());

  stubTree = null;
  anno = null;
  PlatformTestUtil.tryGcSoftlyReachableObjects();
  assertNull(((SmartPointerEx) pointer).getCachedElement());

  file.getViewProvider().getDocument().insertString(0, " ");
  PsiDocumentManager.getInstance(myProject).commitAllDocuments();

  assertNotNull(pointer.getElement());
}
项目:intellij-ce-playground    文件:LowLevelSearchUtil.java   
private static void diagnoseInvalidRange(@NotNull PsiElement scope,
                                         PsiFile file,
                                         FileViewProvider viewProvider,
                                         CharSequence buffer,
                                         TextRange range) {
  String msg = "Range for element: '" + scope + "' = " + range + " is out of file '" + file + "' range: " + file.getTextRange();
  msg += "; file contents length: " + buffer.length();
  msg += "\n file provider: " + viewProvider;
  Document document = viewProvider.getDocument();
  if (document != null) {
    msg += "\n committed=" + PsiDocumentManager.getInstance(file.getProject()).isCommitted(document);
  }
  for (Language language : viewProvider.getLanguages()) {
    final PsiFile root = viewProvider.getPsi(language);
    msg += "\n root " + language + " length=" + root.getTextLength() + (root instanceof PsiFileImpl
                                                                        ? "; contentsLoaded=" + ((PsiFileImpl)root).isContentsLoaded() : "");
  }

  LOG.error(msg);
}
项目:intellij-ce-playground    文件:UsageViewTest.java   
public void testUsageViewDoesNotHoldPsiFilesOrDocuments() throws Exception {
  PsiFile psiFile = myFixture.addFileToProject("X.java", "public class X{} //iuggjhfg");
  Usage[] usages = new Usage[100];
  for (int i = 0; i < usages.length; i++) {
    usages[i] = createUsage(psiFile,i);
  }

  UsageView usageView = UsageViewManager.getInstance(getProject()).createUsageView(UsageTarget.EMPTY_ARRAY, usages, new UsageViewPresentation(), null);

  Disposer.register(getTestRootDisposable(), usageView);

  ((EncodingManagerImpl)EncodingManager.getInstance()).clearDocumentQueue();
  FileDocumentManager.getInstance().saveAllDocuments();
  UIUtil.dispatchAllInvocationEvents();

  LeakHunter.checkLeak(usageView, PsiFileImpl.class);
  LeakHunter.checkLeak(usageView, Document.class);
}
项目:intellij-ce-playground    文件:PomModelImpl.java   
private void reparseParallelTrees(PsiFile changedFile) {
  List<PsiFile> allFiles = changedFile.getViewProvider().getAllFiles();
  if (allFiles.size() <= 1) {
    return;
  }

  CharSequence newText = changedFile.getNode().getChars();
  for (final PsiFile file : allFiles) {
    if (file != changedFile) {
      FileElement fileElement = ((PsiFileImpl)file).getTreeElement();
      if (fileElement != null) {
        reparseFile(file, fileElement, newText);
      }
    }
  }
}
项目:intellij-ce-playground    文件:StubBasedPsiElementBase.java   
/**
 * 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
@NotNull
public ASTNode getNode() {
  ASTNode node = myNode;
  if (node == null) {
    ApplicationManager.getApplication().assertReadAccessAllowed();
    PsiFileImpl file = (PsiFileImpl)getContainingFile();
    if (!file.isValid()) throw new PsiInvalidElementAccessException(this);

    FileElement treeElement = file.getTreeElement();
    if (treeElement != null && myNode == null) {
      return notBoundInExistingAst(file, treeElement);
    }

    treeElement = file.calcTreeElement();
    node = myNode;
    if (node == null) {
      return failedToBindStubToAst(file, treeElement);
    }
  }

  return node;
}
项目:intellij-ce-playground    文件:StubBasedPsiElementBase.java   
private ASTNode failedToBindStubToAst(PsiFileImpl file, FileElement fileElement) {
  VirtualFile vFile = file.getVirtualFile();
  StubTree stubTree = file.getStubTree();
  String stubString = stubTree != null ? ((PsiFileStubImpl)stubTree.getRoot()).printTree() : "is null";
  String astString = DebugUtil.treeToString(fileElement, true);
  if (!ourTraceStubAstBinding) {
    stubString = StringUtil.trimLog(stubString, 1024);
    astString = StringUtil.trimLog(astString, 1024);
  }

  @NonNls String message = "Failed to bind stub to AST for element " + getClass() + " in " +
                           (vFile == null ? "<unknown file>" : vFile.getPath()) +
                           "\nFile:\n" + file + "@" + System.identityHashCode(file) +
                           "\nFile stub tree:\n" + stubString +
                           "\nLoaded file AST:\n" + astString;
  if (ourTraceStubAstBinding) {
    message += dumpCreationTraces(fileElement);
  }
  throw new IllegalArgumentException(message);
}
项目:intellij-ce-playground    文件:StubBasedPsiElementBase.java   
private ASTNode notBoundInExistingAst(PsiFileImpl file, 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 += "; node=" + ((StubBasedPsiElementBase)each).myNode + "; stub=" + ((StubBasedPsiElementBase)each).myStub;
      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 = myStub;
  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);
}
项目:intellij-ce-playground    文件:AnchorElementInfoFactory.java   
@Override
@Nullable
public SmartPointerElementInfo createElementInfo(@NotNull PsiElement element, @NotNull PsiFile containingFile) {
  if (element instanceof StubBasedPsiElement && containingFile instanceof PsiFileWithStubSupport) {
    PsiFileWithStubSupport stubFile = (PsiFileWithStubSupport)containingFile;
    StubTree stubTree = stubFile.getStubTree();
    if (stubTree != null) {
      // use stubs when tree is not loaded
      StubBasedPsiElement stubPsi = (StubBasedPsiElement)element;
      int stubId = PsiAnchor.calcStubIndex(stubPsi);
      IStubElementType myStubElementType = stubPsi.getElementType();
      IElementType contentElementType = ((PsiFileImpl)containingFile).getContentElementType();
      if (stubId != -1 && contentElementType instanceof IStubFileElementType) { // TemplateDataElementType is not IStubFileElementType
        return new AnchorElementInfo(element, stubFile, stubId, myStubElementType);
      }
    }
  }

  PsiElement anchor = getAnchor(element);
  if (anchor != null) {
    return new AnchorElementInfo(anchor, containingFile);
  }
  return null;
}
项目:intellij-ce-playground    文件:BlockSupportImpl.java   
private static boolean isReplaceWholeNode(@NotNull PsiFileImpl fileImpl, @NotNull ASTNode newRoot) throws ReparsedSuccessfullyException {
  final Boolean data = fileImpl.getUserData(DO_NOT_REPARSE_INCREMENTALLY);
  if (data != null) fileImpl.putUserData(DO_NOT_REPARSE_INCREMENTALLY, null);

  boolean explicitlyMarkedDeep = Boolean.TRUE.equals(data);

  if (explicitlyMarkedDeep || isTooDeep(fileImpl)) {
    return true;
  }

  final ASTNode childNode = newRoot.getFirstChildNode();  // maybe reparsed in PsiBuilderImpl and have thrown exception here
  boolean childTooDeep = isTooDeep(childNode);
  if (childTooDeep) {
    childNode.putUserData(TREE_DEPTH_LIMIT_EXCEEDED, null);
    fileImpl.putUserData(TREE_DEPTH_LIMIT_EXCEEDED, Boolean.TRUE);
  }
  return childTooDeep;
}
项目:intellij-ce-playground    文件:FileManagerImpl.java   
public static void clearPsiCaches(FileViewProvider provider) {
  if (provider instanceof SingleRootFileViewProvider) {
    for (PsiFile root : ((SingleRootFileViewProvider)provider).getCachedPsiFiles()) {
      if (root instanceof PsiFileImpl) {
        ((PsiFileImpl)root).clearCaches();
      }
    }
  } else {
    for (Language language : provider.getLanguages()) {
      final PsiFile psi = provider.getPsi(language);
      if (psi instanceof PsiFileImpl) {
        ((PsiFileImpl)psi).clearCaches();
      }
    }
  }
}
项目:intellij-ce-playground    文件:PsiAnchor.java   
public static int calcStubIndex(@NotNull StubBasedPsiElement psi) {
  if (psi instanceof PsiFile) {
    return 0;
  }

  final StubElement liveStub = psi.getStub();
  if (liveStub != null) {
    return ((StubBase)liveStub).id;
  }

  PsiFileImpl file = (PsiFileImpl)psi.getContainingFile();
  final StubTree stubTree = file.calcStubTree();
  for (StubElement<?> stb : stubTree.getPlainList()) {
    if (stb.getPsi() == psi) {
      return ((StubBase)stb).id;
    }
  }

  return -1; // it is possible via custom stub builder intentionally not producing stubs for stubbed elements
}
项目:intellij-ce-playground    文件:CodeCompletionHandlerBase.java   
private static CompletionContext createCompletionContext(PsiFile hostCopy,
                                                         int hostStartOffset,
                                                         OffsetMap hostMap, PsiFile originalFile) {
  CompletionAssertions.assertHostInfo(hostCopy, hostMap);

  InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(hostCopy.getProject());
  CompletionContext context;
  PsiFile injected = InjectedLanguageUtil.findInjectedPsiNoCommit(hostCopy, hostStartOffset);
  if (injected != null) {
    if (injected instanceof PsiFileImpl) {
      ((PsiFileImpl)injected).setOriginalFile(originalFile);
    }
    DocumentWindow documentWindow = InjectedLanguageUtil.getDocumentWindow(injected);
    CompletionAssertions.assertInjectedOffsets(hostStartOffset, injectedLanguageManager, injected, documentWindow);

    context = new CompletionContext(injected, translateOffsetMapToInjected(hostMap, documentWindow));
  } else {
    context = new CompletionContext(hostCopy, hostMap);
  }

  CompletionAssertions.assertFinalOffsets(originalFile, context, injected);

  return context;
}
项目:intellij-ce-playground    文件:FileIncludeManagerImpl.java   
@Nullable
private PsiFileSystemItem doResolve(@NotNull final FileIncludeInfo info, @NotNull final PsiFile context) {
  if (info instanceof FileIncludeInfoImpl) {
    String id = ((FileIncludeInfoImpl)info).providerId;
    FileIncludeProvider provider = id == null ? null : myProviderMap.get(id);
    final PsiFileSystemItem resolvedByProvider = provider == null ? null : provider.resolveIncludedFile(info, context);
    if (resolvedByProvider != null) {
      return resolvedByProvider;
    }
  }

  PsiFileImpl psiFile = (PsiFileImpl)myPsiFileFactory.createFileFromText("dummy.txt", FileTypes.PLAIN_TEXT, info.path);
  psiFile.setOriginalFile(context);
  return new FileReferenceSet(psiFile) {
    @Override
    protected boolean useIncludingFileAsContext() {
      return false;
    }
  }.resolve();
}
项目:intellij-ce-playground    文件:PyMultiFileResolveTest.java   
public void testKeywordArgument() {
  final PsiFile file = prepareFile();
  final PsiManager psiManager = myFixture.getPsiManager();
  final VirtualFile dir = myFixture.findFileInTempDir("a.py");
  final PsiFile psiFile = psiManager.findFile(dir);
  //noinspection ConstantConditions   we need to unstub a.py here
  ((PsiFileImpl)psiFile).calcTreeElement();
  final PsiElement element;
  try {
    element = doResolve(file);
  }
  catch (Exception e) {
    throw new RuntimeException(e);
  }
  assertResolveResult(element, PyClass.class, "A");
}
项目:intellij-ce-playground    文件:XmlEventsTest.java   
private void checkEventsByDocumentChange(final String rootTagText, final int positionToInsert, final String stringToInsert, String events)
  throws Exception {
  final Listener listener = addPomListener();
  final XmlTag tagFromText = ((XmlFile)createFile("file.xml", rootTagText)).getDocument().getRootTag();
  final PsiFileImpl containingFile = (PsiFileImpl)tagFromText.getContainingFile();
  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
  final Document document = documentManager.getDocument(containingFile);
  WriteCommandAction.runWriteCommandAction(null, new Runnable(){
    @Override
    public void run() {
          document.insertString(positionToInsert, stringToInsert);
          documentManager.commitDocument(document);
        }
      });

  assertEquals(events, listener.getEventString());
}
项目:tools-idea    文件:UsageViewTest.java   
public void testUsageViewDoesNotHoldPsiFilesOrDocuments() throws Exception {
  PsiFile psiFile = createFile("X.java", "public class X{} //iuggjhfg");
  Usage[] usages = new Usage[100];
  for (int i = 0; i < usages.length; i++) {
    usages[i] = createUsage(psiFile,i);
  }

  UsageView usageView = UsageViewManager.getInstance(getProject()).createUsageView(UsageTarget.EMPTY_ARRAY, usages, new UsageViewPresentation(), null);

  Disposer.register(getTestRootDisposable(), usageView);

  ((EncodingManagerImpl)EncodingManager.getInstance()).clearDocumentQueue();
  FileDocumentManager.getInstance().saveAllDocuments();
  UIUtil.dispatchAllInvocationEvents();

  LeakHunter.checkLeak(usageView, PsiFileImpl.class);
  LeakHunter.checkLeak(usageView, Document.class);
}
项目:tools-idea    文件:PomModelImpl.java   
private void commitTransaction(final PomTransaction transaction) {
  final ProgressIndicator progressIndicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
  final PsiDocumentManagerBase manager = (PsiDocumentManagerBase)PsiDocumentManager.getInstance(myProject);
  final PsiToDocumentSynchronizer synchronizer = manager.getSynchronizer();
  final PsiFile containingFileByTree = getContainingFileByTree(transaction.getChangeScope());
  Document document = containingFileByTree != null ? manager.getCachedDocument(containingFileByTree) : null;
  if (document != null) {
    final int oldLength = containingFileByTree.getTextLength();
    boolean success = synchronizer.commitTransaction(document);
    if (success) {
      BlockSupportImpl.sendAfterChildrenChangedEvent((PsiManagerImpl)PsiManager.getInstance(myProject), (PsiFileImpl)containingFileByTree, oldLength, true);
    }
  }
  if (containingFileByTree != null) {
    boolean isFromCommit = ApplicationManager.getApplication().isDispatchThread() &&
                           ApplicationManager.getApplication().hasWriteAction(CommitToPsiFileAction.class);
    if (!isFromCommit && !synchronizer.isIgnorePsiEvents()) {
      reparseParallelTrees(containingFileByTree);
    }
  }

  if (progressIndicator != null) progressIndicator.finishNonCancelableSection();
}
项目:tools-idea    文件:PomModelImpl.java   
private void reparseParallelTrees(PsiFile changedFile) {
  List<PsiFile> allFiles = changedFile.getViewProvider().getAllFiles();
  if (allFiles.size() <= 1) {
    return;
  }

  String newText = changedFile.getNode().getText();
  for (final PsiFile file : allFiles) {
    if (file != changedFile) {
      FileElement fileElement = ((PsiFileImpl)file).getTreeElement();
      if (fileElement != null) {
        String oldText = fileElement.getText();
        try {
          reparseFile(file, newText, oldText);
        }
        finally {
          TextBlock.get(file).clear();
        }
      }
    }
  }
}
项目:tools-idea    文件:StubBasedPsiElementBase.java   
@Override
@NotNull
public ASTNode getNode() {
  ASTNode node = myNode;
  if (node == null) {
    ApplicationManager.getApplication().assertReadAccessAllowed();
    PsiFileImpl file = (PsiFileImpl)getContainingFile();
    if (!file.isValid()) throw new PsiInvalidElementAccessException(this);

    FileElement treeElement = file.getTreeElement();
    StubTree stubTree = file.getStubTree();
    if (treeElement != null && myNode == null) {
      return notBoundInExistingAst(file, treeElement, stubTree);
    }

    final FileElement fileElement = file.calcTreeElement();
    node = myNode;
    if (node == null) {
      return failedToBindStubToAst(file, stubTree, fileElement);
    }
  }

  return node;
}
项目:tools-idea    文件:StubBasedPsiElementBase.java   
private ASTNode failedToBindStubToAst(PsiFileImpl file, StubTree stubTree, FileElement fileElement) {
  VirtualFile vFile = file.getVirtualFile();
  String stubString = stubTree != null ? ((PsiFileStubImpl)stubTree.getRoot()).printTree() : "is null";
  String astString = DebugUtil.treeToString(fileElement, true);
  if (!ourTraceStubAstBinding) {
    stubString = StringUtil.trimLog(stubString, 1024);
    astString = StringUtil.trimLog(astString, 1024);
  }

  @NonNls String message = "Failed to bind stub to AST for element " + getClass() + " in " +
                           (vFile == null ? "<unknown file>" : vFile.getPath()) +
                           "\nFile:\n" + file.toString() + "@" + System.identityHashCode(file) +
                           "\nFile stub tree:\n" + stubString +
                           "\nLoaded file AST:\n" + astString;
  if (ourTraceStubAstBinding) {
    message += dumpCreationTraces(fileElement);
  }
  throw new IllegalArgumentException(message);
}
项目:tools-idea    文件:StubBasedPsiElementBase.java   
private ASTNode notBoundInExistingAst(PsiFileImpl file, FileElement treeElement, StubTree stubTree) {
  @NonNls String message = "this=" + this.getClass() + "; file.isPhysical=" + file.isPhysical() + "; node=" + myNode + "; file=" + file +
                           "; tree=" + treeElement + "; stubTree=" + stubTree;
  PsiElement each = this;
  while (each != null) {
    message += "\n each of class " + each.getClass();
    if (each instanceof StubBasedPsiElementBase) {
      message += "; node=" + ((StubBasedPsiElementBase)each).myNode + "; stub=" + ((StubBasedPsiElementBase)each).myStub;
      each = ((StubBasedPsiElementBase)each).getParentByStub();
    } else {
      break;
    }
  }
  if (ourTraceStubAstBinding) {
    message += dumpCreationTraces(treeElement);
  }
  throw new AssertionError(message);
}
项目:tools-idea    文件:MultiplePsiFilesPerDocumentFileViewProvider.java   
@Override
protected PsiFile getPsiInner(@NotNull final Language target) {
  PsiFile file = myRoots.get(target);
  if (file == null) {
    if (isPhysical()) {
      VirtualFile virtualFile = getVirtualFile();
      if (isIgnored()) return null;
      VirtualFile parent = virtualFile.getParent();
      if (parent != null) {
        getManager().findDirectory(parent);
      }
    }
    file = createFile(target);
    if (file == null) return null;
    if (myOriginal != null) {
      final PsiFile originalFile = myOriginal.getPsi(target);
      if (originalFile != null) {
        ((PsiFileImpl)file).setOriginalFile(originalFile);
      }
    }
    file = ConcurrencyUtil.cacheOrGet(myRoots, target, file);
  }
  return file;
}
项目:tools-idea    文件:BlockSupportImpl.java   
private static boolean isReplaceWholeNode(@NotNull PsiFileImpl fileImpl, @NotNull ASTNode newRoot) throws ReparsedSuccessfullyException{
  final Boolean data = fileImpl.getUserData(DO_NOT_REPARSE_INCREMENTALLY);
  if (data != null) fileImpl.putUserData(DO_NOT_REPARSE_INCREMENTALLY, null);

  boolean explicitlyMarkedDeep = Boolean.TRUE.equals(data);

  if (explicitlyMarkedDeep || isTooDeep(fileImpl)) {
    return true;
  }

  final ASTNode childNode = newRoot.getFirstChildNode();  // maybe reparsed in PsiBuilderImpl and have thrown exception here
  boolean childTooDeep = isTooDeep(childNode);
  if (childTooDeep) {
    childNode.putUserData(TREE_DEPTH_LIMIT_EXCEEDED, null);
    fileImpl.putUserData(TREE_DEPTH_LIMIT_EXCEEDED, Boolean.TRUE);
  }
  return childTooDeep;
}
项目:tools-idea    文件:BlockSupportImpl.java   
public static void sendAfterChildrenChangedEvent(@NotNull PsiManagerImpl manager,
                                                 @NotNull PsiFileImpl scope,
                                                 int oldLength,
                                                 boolean isGenericChange) {
  if(!scope.isPhysical()) {
    manager.afterChange(false);
    return;
  }
  PsiTreeChangeEventImpl event = new PsiTreeChangeEventImpl(manager);
  event.setParent(scope);
  event.setFile(scope);
  event.setOffset(0);
  event.setOldLength(oldLength);
  event.setGeneric(isGenericChange);
  manager.childrenChanged(event);
}
项目:tools-idea    文件:FileManagerImpl.java   
private void updateAllViewProviders() {
  handleFileTypesChange(new FileTypesChanged() {
    @Override
    protected void updateMaps() {
      for (final FileViewProvider provider : myVFileToViewProviderMap.values()) {
        if (!provider.getVirtualFile().isValid()) {
          continue;
        }

        for (Language language : provider.getLanguages()) {
          final PsiFile psi = provider.getPsi(language);
          if (psi instanceof PsiFileImpl) {
            ((PsiFileImpl)psi).clearCaches();
          }
        }
      }
      removeInvalidFilesAndDirs(false);
    }
  });
}
项目:tools-idea    文件:PsiAnchor.java   
@Nullable
public static StubIndexReference createStubReference(@NotNull PsiElement element, @NotNull PsiFile containingFile) {
  if (element instanceof StubBasedPsiElement &&
      element.isPhysical() &&
      (element instanceof PsiCompiledElement || ((PsiFileImpl)containingFile).getContentElementType() instanceof IStubFileElementType)) {
    final StubBasedPsiElement elt = (StubBasedPsiElement)element;
    final IStubElementType elementType = elt.getElementType();
    if (elt.getStub() != null || elementType.shouldCreateStub(element.getNode())) {
      int index = calcStubIndex((StubBasedPsiElement)element);
      if (index != -1) {
        return new StubIndexReference(containingFile, index, containingFile.getLanguage(), elementType);
      }
    }
  }
  return null;
}
项目:tools-idea    文件:PsiAnchor.java   
public static int calcStubIndex(StubBasedPsiElement psi) {
  if (psi instanceof PsiFile) {
    return 0;
  }

  final StubElement liveStub = psi.getStub();
  if (liveStub != null) {
    return ((StubBase)liveStub).id;
  }

  PsiFileImpl file = (PsiFileImpl)psi.getContainingFile();
  final StubTree stubTree = file.calcStubTree();
  for (StubElement<?> stb : stubTree.getPlainList()) {
    if (stb.getPsi() == psi) {
      return ((StubBase)stb).id;
    }
  }

  return -1; // it is possible via custom stub builder intentionally not producing stubs for stubbed elements
}
项目:tools-idea    文件:CodeCompletionHandlerBase.java   
private static CompletionContext createCompletionContext(PsiFile hostCopy,
                                                         int hostStartOffset,
                                                         OffsetMap hostMap, PsiFile originalFile) {
  CompletionAssertions.assertHostInfo(hostCopy, hostMap);

  InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(hostCopy.getProject());
  CompletionContext context;
  PsiFile injected = InjectedLanguageUtil.findInjectedPsiNoCommit(hostCopy, hostStartOffset);
  if (injected != null) {
    if (injected instanceof PsiFileImpl && injectedLanguageManager.isInjectedFragment(originalFile)) {
      ((PsiFileImpl)injected).setOriginalFile(originalFile);
    }
    DocumentWindow documentWindow = InjectedLanguageUtil.getDocumentWindow(injected);
    CompletionAssertions.assertInjectedOffsets(hostStartOffset, injectedLanguageManager, injected, documentWindow);

    context = new CompletionContext(injected, translateOffsetMapToInjected(hostMap, documentWindow));
  } else {
    context = new CompletionContext(hostCopy, hostMap);
  }

  CompletionAssertions.assertFinalOffsets(originalFile, context, injected);

  return context;
}
项目:tools-idea    文件:XmlEventsTest.java   
private void checkEventsByDocumentChange(final String rootTagText, final int positionToInsert, final String stringToInsert)
  throws Exception {
  final PomModel model = PomManager.getModel(getProject());
  final Listener listener = new Listener(model.getModelAspect(XmlAspect.class));
  model.addModelListener(listener);
  final XmlTag tagFromText = ((XmlFile)createFile("file.xml", rootTagText)).getDocument().getRootTag();
  final PsiFileImpl containingFile = (PsiFileImpl)tagFromText.getContainingFile();
  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
  final Document document = documentManager.getDocument(containingFile);
  CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
    @Override
    public void run() {
      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
          document.insertString(positionToInsert, stringToInsert);
          documentManager.commitDocument(document);
        }
      });
    }
  }, "", null);

  assertFileTextEquals(getTestName(false) + ".txt", listener.getEventString());
}
项目:idea-doT    文件:DotFileViewProvider.java   
@Override
protected PsiFile createFile(@NotNull Language lang) {
    ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(lang);
    if (parserDefinition == null) {
        return null;
    }

    Language templateDataLanguage = getTemplateDataLanguage(myManager, myFile);
    if (lang == templateDataLanguage) {
        PsiFileImpl file = (PsiFileImpl) parserDefinition.createFile(this);
        file.setContentElementType(new TemplateDataElementType("Dot_TEMPLATE_DATA", templateDataLanguage, DotTokenTypes.CONTENT, DotTokenTypes.OUTER_ELEMENT_TYPE));
        return file;
    } else if (lang == DotLanguage.INSTANCE) {
        return parserDefinition.createFile(this);
    } else {
        return null;
    }
}
项目:consulo-javaee    文件:JspFileViewProviderImpl.java   
@Nullable
@Override
protected PsiFile createFile(@NotNull final Language lang)
{
    if(lang == getBaseLanguage())
    {
        return LanguageParserDefinitions.INSTANCE.forLanguage(lang).createFile(this);
    }

    if(lang == JavaLanguage.INSTANCE)
    {
        return new JspJavaFileImpl(this);
    }

    if(lang == getTemplateDataLanguage())
    {
        PsiFileImpl file = (PsiFileImpl) LanguageParserDefinitions.INSTANCE.forLanguage(lang).createFile(this);
        file.setContentElementType(JspTemplateTokens.HTML_TEMPLATE_DATA);
        return file;
    }
    return null;
}
项目:consulo    文件:UsageViewTest.java   
public void testUsageViewDoesNotHoldPsiFilesOrDocuments() throws Exception {
  PsiFile psiFile = createFile("X.java", "public class X{} //iuggjhfg");
  Usage[] usages = new Usage[100];
  for (int i = 0; i < usages.length; i++) {
    usages[i] = createUsage(psiFile,i);
  }

  UsageView usageView = UsageViewManager.getInstance(getProject()).createUsageView(UsageTarget.EMPTY_ARRAY, usages, new UsageViewPresentation(), null);

  Disposer.register(getTestRootDisposable(), usageView);

  ((EncodingManagerImpl)EncodingManager.getInstance()).clearDocumentQueue();
  FileDocumentManager.getInstance().saveAllDocuments();
  UIUtil.dispatchAllInvocationEvents();

  LeakHunter.checkLeak(usageView, PsiFileImpl.class);
  LeakHunter.checkLeak(usageView, Document.class);
}
项目:consulo    文件:LowLevelSearchUtil.java   
private static void diagnoseInvalidRange(@Nonnull PsiElement scope, PsiFile file, FileViewProvider viewProvider, CharSequence buffer, TextRange range) {
  String msg = "Range for element: '" + scope + "' = " + range + " is out of file '" + file + "' range: " + file.getTextRange();
  msg += "; file contents length: " + buffer.length();
  msg += "\n file provider: " + viewProvider;
  Document document = viewProvider.getDocument();
  if (document != null) {
    msg += "\n committed=" + PsiDocumentManager.getInstance(file.getProject()).isCommitted(document);
  }
  for (Language language : viewProvider.getLanguages()) {
    final PsiFile root = viewProvider.getPsi(language);
    msg += "\n root " +
           language +
           " length=" +
           root.getTextLength() +
           (root instanceof PsiFileImpl ? "; contentsLoaded=" + ((PsiFileImpl)root).isContentsLoaded() : "");
  }

  LOG.error(msg);
}
项目:consulo    文件:PomModelImpl.java   
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);
    }
  }
}
项目:consulo    文件:StubBasedPsiElementBase.java   
/**
 * 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(this);

    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();
}