Search in sources :

Example 1 with FileASTNode

use of com.intellij.lang.FileASTNode in project intellij-community by JetBrains.

the class PyStubsTest method doTestNamedTuple.

private void doTestNamedTuple(@NotNull String expectedName, @NotNull List<String> expectedFields, @NotNull QualifiedName expectedCalleeName) {
    final PyFile file = getTestFile();
    final PyTargetExpression attribute = file.findTopLevelAttribute("nt");
    assertNotNull(attribute);
    final PyNamedTupleStub stub = attribute.getStub().getCustomStub(PyNamedTupleStub.class);
    assertNotNull(stub);
    assertEquals(expectedCalleeName, stub.getCalleeName());
    final PyType typeFromStub = TypeEvalContext.codeInsightFallback(myFixture.getProject()).getType(attribute);
    doTestNamedTuple(expectedName, expectedFields, typeFromStub);
    assertNotParsed(file);
    final FileASTNode astNode = file.getNode();
    assertNotNull(astNode);
    final PyType typeFromAst = TypeEvalContext.userInitiated(myFixture.getProject(), file).getType(attribute);
    doTestNamedTuple(expectedName, expectedFields, typeFromAst);
}
Also used : FileASTNode(com.intellij.lang.FileASTNode) PyType(com.jetbrains.python.psi.types.PyType) PyNamedTupleStub(com.jetbrains.python.psi.stubs.PyNamedTupleStub)

Example 2 with FileASTNode

use of com.intellij.lang.FileASTNode in project intellij-community by JetBrains.

the class MoveGroovyClassHandler method doMoveClass.

@Override
public PsiClass doMoveClass(@NotNull PsiClass aClass, @NotNull PsiDirectory moveDestination) throws IncorrectOperationException {
    if (!aClass.getLanguage().equals(GroovyLanguage.INSTANCE))
        return null;
    PsiFile file = aClass.getContainingFile();
    if (!(file instanceof GroovyFile))
        return null;
    final PsiPackage newPackage = JavaDirectoryService.getInstance().getPackage(moveDestination);
    LOG.assertTrue(newPackage != null);
    PsiClass newClass = null;
    final String newPackageName = newPackage.getQualifiedName();
    if (aClass instanceof GroovyScriptClass) {
        final PsiClass[] classes = ((GroovyFile) file).getClasses();
        if (classes.length == 1) {
            if (!moveDestination.equals(file.getContainingDirectory())) {
                Project project = file.getProject();
                MoveFilesOrDirectoriesUtil.doMoveFile(file, moveDestination);
                DumbService.getInstance(project).completeJustSubmittedTasks();
                file = moveDestination.findFile(file.getName());
                assert file != null;
                ((PsiClassOwner) file).setPackageName(newPackageName);
            }
            return ((GroovyFile) file).getScriptClass();
        }
        //script class is moved the first from the file due to MoveClassOrPackageProcessor:88 (element sort)
        correctSelfReferences(aClass, newPackage);
        final GroovyFile newFile = generateNewScript((GroovyFile) file, newPackage);
        for (PsiElement child : file.getChildren()) {
            if (!(child instanceof GrTopStatement || child instanceof PsiComment))
                continue;
            if (child instanceof PsiClass || child instanceof GrImportStatement || child instanceof GrPackageDefinition)
                continue;
            if (child instanceof GrDocComment) {
                final GrDocCommentOwner owner = GrDocCommentUtil.findDocOwner((GrDocComment) child);
                if (owner instanceof PsiClass)
                    continue;
            }
            child.delete();
        }
        if (!moveDestination.equals(file.getContainingDirectory())) {
            moveDestination.add(newFile);
        //aClass.getManager().moveFile(newFile, moveDestination);
        }
        newClass = newFile.getClasses()[0];
        correctOldClassReferences(newClass, aClass);
    } else {
        if (!moveDestination.equals(file.getContainingDirectory()) && moveDestination.findFile(file.getName()) != null) {
            // moving second of two classes which were in the same file to a different directory (IDEADEV-3089)
            correctSelfReferences(aClass, newPackage);
            PsiFile newFile = moveDestination.findFile(file.getName());
            final FileASTNode fileNode = newFile.getNode();
            fileNode.addChild(Factory.createSingleLeafElement(GroovyTokenTypes.mNLS, "\n\n", 0, 2, null, aClass.getManager()));
            final PsiDocComment docComment = aClass.getDocComment();
            if (docComment != null) {
                newFile.add(docComment);
                fileNode.addChild(Factory.createSingleLeafElement(GroovyTokenTypes.mNLS, "\n", 0, 1, null, aClass.getManager()));
            }
            newClass = (GrTypeDefinition) newFile.add(aClass);
            correctOldClassReferences(newClass, aClass);
            aClass.delete();
        } else if (((GroovyFile) file).getClasses().length > 1) {
            correctSelfReferences(aClass, newPackage);
            Project project = aClass.getProject();
            PsiFileFactory fileFactory = PsiFileFactory.getInstance(project);
            GroovyFile newFile = (GroovyFile) moveDestination.add(fileFactory.createFileFromText(aClass.getName() + "." + GroovyFileType.DEFAULT_EXTENSION, GroovyLanguage.INSTANCE, "class XXX {}"));
            final PsiClass created = newFile.getClasses()[0];
            PsiDocComment docComment = aClass.getDocComment();
            if (docComment != null) {
                newFile.addBefore(docComment, created);
                docComment.delete();
            }
            newClass = (PsiClass) created.replace(aClass);
            setPackageDefinition((GroovyFile) file, newFile, newPackageName);
            correctOldClassReferences(newClass, aClass);
            aClass.delete();
        }
    }
    return newClass;
}
Also used : PsiDocComment(com.intellij.psi.javadoc.PsiDocComment) GrDocCommentOwner(org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocCommentOwner) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) GrDocComment(org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocComment) Project(com.intellij.openapi.project.Project) FileASTNode(com.intellij.lang.FileASTNode) GroovyScriptClass(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass) GrPackageDefinition(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) GrTopStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.GrTopStatement)

Example 3 with FileASTNode

use of com.intellij.lang.FileASTNode in project intellij-community by JetBrains.

the class DocumentCommitThread method doCommit.

// public for Upsource
@Nullable("returns runnable to execute under write action in AWT to finish the commit")
public Processor<Document> doCommit(@NotNull final CommitTask task, @NotNull final PsiFile file, @NotNull final FileASTNode oldFileNode) {
    Document document = task.getDocument();
    final CharSequence newDocumentText = document.getImmutableCharSequence();
    final TextRange changedPsiRange = getChangedPsiRange(file, task.myLastCommittedText, newDocumentText);
    if (changedPsiRange == null) {
        return null;
    }
    final Boolean data = document.getUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY);
    if (data != null) {
        document.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, null);
        file.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, data);
    }
    BlockSupport blockSupport = BlockSupport.getInstance(file.getProject());
    final DiffLog diffLog = blockSupport.reparseRange(file, oldFileNode, changedPsiRange, newDocumentText, task.indicator, task.myLastCommittedText);
    return document1 -> {
        FileViewProvider viewProvider = file.getViewProvider();
        if (!task.isStillValid() || ((PsiDocumentManagerBase) PsiDocumentManager.getInstance(file.getProject())).getCachedViewProvider(document1) != viewProvider) {
            return false;
        }
        if (file.isPhysical() && !ApplicationManager.getApplication().isWriteAccessAllowed()) {
            VirtualFile vFile = viewProvider.getVirtualFile();
            LOG.error("Write action expected" + "; document=" + document1 + "; file=" + file + " of " + file.getClass() + "; file.valid=" + file.isValid() + "; file.eventSystemEnabled=" + viewProvider.isEventSystemEnabled() + "; viewProvider=" + viewProvider + " of " + viewProvider.getClass() + "; language=" + file.getLanguage() + "; vFile=" + vFile + " of " + vFile.getClass() + "; free-threaded=" + SingleRootFileViewProvider.isFreeThreaded(viewProvider));
        }
        doActualPsiChange(file, diffLog);
        assertAfterCommit(document1, file, (FileElement) oldFileNode);
        return true;
    };
}
Also used : com.intellij.openapi.util(com.intellij.openapi.util) PomModelEvent(com.intellij.pom.event.PomModelEvent) UIUtil(com.intellij.util.ui.UIUtil) VirtualFile(com.intellij.openapi.vfs.VirtualFile) Date(java.util.Date) Document(com.intellij.openapi.editor.Document) TimeoutException(java.util.concurrent.TimeoutException) ApplicationEx(com.intellij.openapi.application.ex.ApplicationEx) com.intellij.openapi.application(com.intellij.openapi.application) SmartList(com.intellij.util.SmartList) FileASTNode(com.intellij.lang.FileASTNode) PomModel(com.intellij.pom.PomModel) DocumentEx(com.intellij.openapi.editor.ex.DocumentEx) Logger(com.intellij.openapi.diagnostic.Logger) ProgressManager(com.intellij.openapi.progress.ProgressManager) BlockSupport(com.intellij.psi.text.BlockSupport) Set(java.util.Set) FileElement(com.intellij.psi.impl.source.tree.FileElement) Nullable(org.jetbrains.annotations.Nullable) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) List(java.util.List) ServiceManager(com.intellij.openapi.components.ServiceManager) Processor(com.intellij.util.Processor) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) TreeAspect(com.intellij.pom.tree.TreeAspect) PooledThreadExecutor(org.jetbrains.ide.PooledThreadExecutor) PomTransactionBase(com.intellij.pom.impl.PomTransactionBase) PsiFileImpl(com.intellij.psi.impl.source.PsiFileImpl) NonNls(org.jetbrains.annotations.NonNls) SimpleDateFormat(java.text.SimpleDateFormat) ForeignLeafPsiElement(com.intellij.psi.impl.source.tree.ForeignLeafPsiElement) ContainerUtil(com.intellij.util.containers.ContainerUtil) PomManager(com.intellij.pom.PomManager) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) TreeAspectEvent(com.intellij.pom.tree.TreeAspectEvent) Project(com.intellij.openapi.project.Project) ExecutorService(java.util.concurrent.ExecutorService) BoundedTaskExecutor(com.intellij.util.concurrency.BoundedTaskExecutor) DiffLog(com.intellij.psi.impl.source.text.DiffLog) HashSetQueue(com.intellij.util.containers.HashSetQueue) ReentrantLock(java.util.concurrent.locks.ReentrantLock) StandardProgressIndicatorBase(com.intellij.openapi.progress.util.StandardProgressIndicatorBase) StringUtil(com.intellij.openapi.util.text.StringUtil) TreeUtil(com.intellij.psi.impl.source.tree.TreeUtil) Disposable(com.intellij.openapi.Disposable) TestOnly(org.jetbrains.annotations.TestOnly) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) ASTNode(com.intellij.lang.ASTNode) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) Lock(java.util.concurrent.locks.Lock) ExceptionUtil(com.intellij.util.ExceptionUtil) Collections(java.util.Collections) javax.swing(javax.swing) VirtualFile(com.intellij.openapi.vfs.VirtualFile) FileElement(com.intellij.psi.impl.source.tree.FileElement) Document(com.intellij.openapi.editor.Document) BlockSupport(com.intellij.psi.text.BlockSupport) DiffLog(com.intellij.psi.impl.source.text.DiffLog) Nullable(org.jetbrains.annotations.Nullable)

Example 4 with FileASTNode

use of com.intellij.lang.FileASTNode in project intellij-community by JetBrains.

the class DocumentCommitThread method commitUnderProgress.

// returns (finish commit Runnable (to be invoked later in EDT), null) on success or (null, failure reason) on failure
@NotNull
private Pair<Runnable, Object> commitUnderProgress(@NotNull final CommitTask task, final boolean synchronously) {
    if (synchronously) {
        assert !task.indicator.isCanceled();
    }
    final Document document = task.getDocument();
    final Project project = task.project;
    final PsiDocumentManagerBase documentManager = (PsiDocumentManagerBase) PsiDocumentManager.getInstance(project);
    final List<Processor<Document>> finishProcessors = new SmartList<>();
    Runnable runnable = () -> {
        myApplication.assertReadAccessAllowed();
        if (project.isDisposed())
            return;
        Lock lock = getDocumentLock(document);
        if (!lock.tryLock()) {
            task.cancel("Can't obtain document lock", this);
            return;
        }
        boolean canceled = false;
        try {
            if (documentManager.isCommitted(document))
                return;
            if (!task.isStillValid()) {
                canceled = true;
                return;
            }
            FileViewProvider viewProvider = documentManager.getCachedViewProvider(document);
            if (viewProvider == null) {
                finishProcessors.add(handleCommitWithoutPsi(documentManager, task));
                return;
            }
            for (Pair<PsiFileImpl, FileASTNode> pair : task.myOldFileNodes) {
                PsiFileImpl file = pair.first;
                if (file.isValid()) {
                    FileASTNode oldFileNode = pair.second;
                    Processor<Document> finishProcessor = doCommit(task, file, oldFileNode);
                    if (finishProcessor != null) {
                        finishProcessors.add(finishProcessor);
                    }
                } else {
                    // file became invalid while sitting in the queue
                    if (task.reason.equals(SYNC_COMMIT_REASON)) {
                        throw new PsiInvalidElementAccessException(file, "File " + file + " invalidated during sync commit");
                    }
                    commitAsynchronously(project, document, "File " + file + " invalidated during background commit; task: " + task, task.myCreationContext);
                }
            }
        } finally {
            lock.unlock();
            if (canceled) {
                task.cancel("Task invalidated", this);
            }
        }
    };
    if (synchronously) {
        runnable.run();
    } else if (!myApplication.tryRunReadAction(runnable)) {
        log(project, "Could not start read action", task, myApplication.isReadAccessAllowed(), Thread.currentThread());
        return new Pair<>(null, "Could not start read action");
    }
    boolean canceled = task.indicator.isCanceled();
    assert !synchronously || !canceled;
    if (canceled) {
        return new Pair<>(null, "Indicator was canceled");
    }
    Runnable result = createEdtRunnable(task, synchronously, finishProcessors);
    return Pair.create(result, null);
}
Also used : Processor(com.intellij.util.Processor) PsiFileImpl(com.intellij.psi.impl.source.PsiFileImpl) Document(com.intellij.openapi.editor.Document) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock) Project(com.intellij.openapi.project.Project) FileASTNode(com.intellij.lang.FileASTNode) SmartList(com.intellij.util.SmartList) NotNull(org.jetbrains.annotations.NotNull)

Example 5 with FileASTNode

use of com.intellij.lang.FileASTNode in project intellij-community by JetBrains.

the class PsiInvalidElementAccessException method findInvalidationTrace.

public static Object findInvalidationTrace(@Nullable ASTNode element) {
    while (element != null) {
        Object trace = element.getUserData(INVALIDATION_TRACE);
        if (trace != null) {
            return trace;
        }
        ASTNode parent = element.getTreeParent();
        if (parent == null && element instanceof FileASTNode) {
            PsiElement psi = element.getPsi();
            trace = psi == null ? null : psi.getUserData(INVALIDATION_TRACE);
            if (trace != null) {
                return trace;
            }
        }
        element = parent;
    }
    return null;
}
Also used : FileASTNode(com.intellij.lang.FileASTNode) ASTNode(com.intellij.lang.ASTNode) FileASTNode(com.intellij.lang.FileASTNode)

Aggregations

FileASTNode (com.intellij.lang.FileASTNode)20 ASTNode (com.intellij.lang.ASTNode)6 Project (com.intellij.openapi.project.Project)5 NotNull (org.jetbrains.annotations.NotNull)5 Document (com.intellij.openapi.editor.Document)3 VirtualFile (com.intellij.openapi.vfs.VirtualFile)3 PsiElement (com.intellij.psi.PsiElement)3 PsiFileImpl (com.intellij.psi.impl.source.PsiFileImpl)3 SmartList (com.intellij.util.SmartList)3 Nullable (org.jetbrains.annotations.Nullable)3 LighterAST (com.intellij.lang.LighterAST)2 TreeBackedLighterAST (com.intellij.lang.TreeBackedLighterAST)2 TextRange (com.intellij.openapi.util.TextRange)2 StubElement (com.intellij.psi.stubs.StubElement)2 Processor (com.intellij.util.Processor)2 Lock (java.util.concurrent.locks.Lock)2 ReentrantLock (java.util.concurrent.locks.ReentrantLock)2 LogEventException (com.intellij.diagnostic.LogEventException)1 DuplicatesProfile (com.intellij.dupLocator.DuplicatesProfile)1 DuplocatorState (com.intellij.dupLocator.DuplocatorState)1