@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; } }
@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; } }
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()); }
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); }
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); }
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()); }
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); }
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); }
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); } } } }
/** * 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; }
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); }
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); }
@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; }
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; }
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(); } } } }
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 }
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; }
@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(); }
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"); }
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()); }
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); }
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(); }
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(); } } } } }
@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; }
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); }
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); }
@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; }
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; }
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); }
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); } }); }
@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; }
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 }
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; }
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()); }
@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; } }
@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; }
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); }
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); } } }
/** * 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(); }