Search in sources :

Example 81 with GroovyFile

use of org.jetbrains.plugins.groovy.lang.psi.GroovyFile in project intellij-community by JetBrains.

the class MoveClassToNewFileIntention method processIntention.

@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException {
    final GrTypeDefinition psiClass = (GrTypeDefinition) element.getParent();
    final String name = psiClass.getName();
    final PsiFile file = psiClass.getContainingFile();
    final String fileExtension = FileUtilRt.getExtension(file.getName());
    final String newFileName = name + "." + fileExtension;
    final PsiDirectory dir = file.getParent();
    if (dir != null) {
        if (dir.findFile(newFileName) != null) {
            if (!ApplicationManager.getApplication().isUnitTestMode()) {
                final String message = GroovyIntentionsBundle.message("file.exists", newFileName, dir.getName());
                CommonRefactoringUtil.showErrorHint(project, editor, message, getFamilyName(), null);
            }
            return;
        }
    }
    final GroovyFile newFile = (GroovyFile) GroovyTemplatesFactory.createFromTemplate(dir, name, newFileName, GroovyTemplates.GROOVY_CLASS, true);
    final GrTypeDefinition template = newFile.getTypeDefinitions()[0];
    final PsiElement newClass = template.replace(psiClass);
    final GrDocComment docComment = psiClass.getDocComment();
    if (newClass instanceof GrTypeDefinition && docComment != null) {
        final GrDocComment newDoc = ((GrTypeDefinition) newClass).getDocComment();
        if (newDoc != null) {
            newDoc.replace(docComment);
        } else {
            final PsiElement parent = newClass.getParent();
            parent.addBefore(docComment, psiClass);
            parent.getNode().addLeaf(GroovyTokenTypes.mNLS, "\n", psiClass.getNode());
        }
        docComment.delete();
    }
    psiClass.delete();
    IntentionUtils.positionCursor(project, newClass.getContainingFile(), newClass.getNavigationElement());
}
Also used : GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition) PsiDirectory(com.intellij.psi.PsiDirectory) PsiFile(com.intellij.psi.PsiFile) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) PsiElement(com.intellij.psi.PsiElement) GrDocComment(org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocComment)

Example 82 with GroovyFile

use of org.jetbrains.plugins.groovy.lang.psi.GroovyFile in project intellij-community by JetBrains.

the class ImportStaticIntention method processIntention.

@Override
protected void processIntention(@NotNull PsiElement element, @NotNull final Project project, final Editor editor) throws IncorrectOperationException {
    final PsiElement resolved = resolve(element);
    if (!(resolved instanceof PsiMember))
        return;
    final PsiClass containingClass = ((PsiMember) resolved).getContainingClass();
    if (containingClass == null)
        return;
    String originalName = ((PsiMember) resolved).getName();
    final String name = resolved instanceof PsiMethod && GroovyPropertyUtils.isSimplePropertyAccessor((PsiMethod) resolved) ? GroovyPropertyUtils.getPropertyName((PsiMethod) resolved) : originalName;
    final String qname = containingClass.getQualifiedName();
    if (name == null)
        return;
    final PsiFile containingFile = element.getContainingFile();
    if (!(containingFile instanceof GroovyFile))
        return;
    final GroovyFile file = (GroovyFile) containingFile;
    file.accept(new GroovyRecursiveElementVisitor() {

        @Override
        public void visitReferenceExpression(@NotNull GrReferenceExpression expression) {
            super.visitReferenceExpression(expression);
            if (name.equals(expression.getReferenceName())) {
                PsiElement resolved = expression.resolve();
                if (resolved != null) {
                    expression.putUserData(TEMP_REFERENT_USER_DATA, resolved);
                }
            }
        }
    });
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
    final GrImportStatement tempImport = factory.createImportStatementFromText(qname + "." + name, true, false, null);
    final GrImportStatement importStatement = file.addImport(tempImport);
    boolean isAnythingShortened = shortenUsages(resolved, containingFile);
    if (!isAnythingShortened) {
        importStatement.delete();
        return;
    }
    file.accept(new GroovyRecursiveElementVisitor() {

        @Override
        public void visitReferenceExpression(@NotNull GrReferenceExpression expression) {
            super.visitReferenceExpression(expression);
            GrTypeArgumentList typeArgumentList = expression.getTypeArgumentList();
            if (typeArgumentList != null && typeArgumentList.getFirstChild() != null) {
                expression.putUserData(TEMP_REFERENT_USER_DATA, null);
                return;
            }
            if (name.equals(expression.getReferenceName())) {
                if (expression.isQualified()) {
                    GrExpression qualifier = expression.getQualifierExpression();
                    if (qualifier instanceof GrReferenceExpression) {
                        PsiElement aClass = ((GrReferenceExpression) qualifier).resolve();
                        if (aClass == ((PsiMember) resolved).getContainingClass()) {
                            GrReferenceAdjuster.shortenReference(expression);
                        }
                    }
                } else {
                    PsiElement referent = expression.getUserData(TEMP_REFERENT_USER_DATA);
                    if (referent instanceof PsiMember && ((PsiMember) referent).hasModifierProperty(PsiModifier.STATIC) && referent != expression.resolve()) {
                        expression.bindToElement(referent);
                    }
                }
            }
            expression.putUserData(TEMP_REFERENT_USER_DATA, null);
        }
    });
}
Also used : GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrTypeArgumentList(org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeArgumentList) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile)

Example 83 with GroovyFile

use of org.jetbrains.plugins.groovy.lang.psi.GroovyFile in project intellij-community by JetBrains.

the class GroovyFoldingBuilder method isRegionCollapsedByDefault.

@Override
protected boolean isRegionCollapsedByDefault(@NotNull ASTNode node) {
    final JavaCodeFoldingSettings settings = JavaCodeFoldingSettings.getInstance();
    if (node.getElementType() == GroovyElementTypes.IMPORT_STATEMENT) {
        return settings.isCollapseImports();
    }
    if (node.getElementType() == GroovyDocElementTypes.GROOVY_DOC_COMMENT || node.getElementType() == GroovyTokenTypes.mML_COMMENT) {
        PsiElement element = node.getPsi();
        PsiElement parent = element.getParent();
        if (parent instanceof GroovyFile) {
            PsiElement firstChild = parent.getFirstChild();
            if (firstChild instanceof PsiWhiteSpace) {
                firstChild = firstChild.getNextSibling();
            }
            if (element.equals(firstChild)) {
                return settings.isCollapseFileHeader();
            }
        }
        if (node.getElementType() == GroovyDocElementTypes.GROOVY_DOC_COMMENT) {
            return settings.isCollapseJavadocs();
        }
    }
    if ((node.getElementType() == GroovyElementTypes.OPEN_BLOCK || node.getElementType() == GroovyElementTypes.CONSTRUCTOR_BODY) && node.getTreeParent().getElementType() == GroovyElementTypes.METHOD_DEFINITION) {
        return settings.isCollapseMethods();
    }
    if (node.getElementType() == GroovyElementTypes.CLOSABLE_BLOCK) {
        return settings.isCollapseAnonymousClasses();
    }
    if (node.getElementType() == GroovyElementTypes.CLASS_BODY) {
        final PsiElement parent = node.getPsi().getParent();
        if (parent instanceof PsiClass) {
            if (parent instanceof PsiAnonymousClass) {
                return settings.isCollapseAnonymousClasses();
            }
            if (((PsiClass) parent).getContainingClass() != null) {
                return settings.isCollapseInnerClasses();
            }
        }
    }
    if (node.getElementType() == GroovyTokenTypes.mSL_COMMENT) {
        return settings.isCollapseEndOfLineComments();
    }
    return false;
}
Also used : JavaCodeFoldingSettings(com.intellij.codeInsight.folding.JavaCodeFoldingSettings) LeafPsiElement(com.intellij.psi.impl.source.tree.LeafPsiElement) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile)

Example 84 with GroovyFile

use of org.jetbrains.plugins.groovy.lang.psi.GroovyFile in project intellij-community by JetBrains.

the class GroovyImportUtil method processFile.

public static void processFile(@Nullable final PsiFile file, @Nullable final Set<String> importedClasses, @Nullable final Set<String> staticallyImportedMembers, @Nullable final Set<GrImportStatement> usedImports, @Nullable final Set<GrImportStatement> unresolvedOnDemandImports, @Nullable final Set<String> implicitlyImported, @Nullable final Set<String> innerClasses, @Nullable final Map<String, String> aliased, @Nullable final Map<String, String> annotations) {
    if (!(file instanceof GroovyFile))
        return;
    final Set<String> unresolvedReferenceNames = ContainerUtil.newLinkedHashSet();
    file.accept(new PsiRecursiveElementWalkingVisitor() {

        @Override
        public void visitElement(PsiElement element) {
            if (!(element instanceof GrImportStatement) && !(element instanceof GrPackageDefinition)) {
                super.visitElement(element);
            }
            if (element instanceof GrReferenceElement) {
                visitRefElement((GrReferenceElement) element);
            }
        }

        private void visitRefElement(GrReferenceElement refElement) {
            if (refElement.isQualified())
                return;
            final String refName = refElement.getReferenceName();
            if ("super".equals(refName))
                return;
            final GroovyResolveResult[] resolveResults = refElement.multiResolve(false);
            if (resolveResults.length == 0 && refName != null) {
                if (PsiTreeUtil.getParentOfType(refElement, GrImportStatement.class) == null) {
                    unresolvedReferenceNames.add(refName);
                }
            }
            for (GroovyResolveResult resolveResult : resolveResults) {
                final PsiElement context = resolveResult.getCurrentFileResolveContext();
                final PsiElement resolved = resolveResult.getElement();
                if (resolved == null)
                    return;
                if (context instanceof GrImportStatement) {
                    final GrImportStatement importStatement = (GrImportStatement) context;
                    if (usedImports != null && isImportUsed(refElement, resolved)) {
                        usedImports.add(importStatement);
                    }
                    if (GroovyImportHelper.isImplicitlyImported(resolved, refName, (GroovyFile) file)) {
                        addImplicitClass(resolved);
                    }
                    if (!importStatement.isAliasedImport() && !isAnnotatedImport(importStatement)) {
                        String importedName = null;
                        if (importStatement.isOnDemand()) {
                            if (importStatement.isStatic()) {
                                if (resolved instanceof PsiMember) {
                                    final PsiMember member = (PsiMember) resolved;
                                    final PsiClass clazz = member.getContainingClass();
                                    if (clazz != null) {
                                        final String classQName = clazz.getQualifiedName();
                                        if (classQName != null) {
                                            final String name = member.getName();
                                            if (name != null) {
                                                importedName = classQName + "." + name;
                                            }
                                        }
                                    }
                                }
                            } else {
                                importedName = getTargetQualifiedName(resolved);
                            }
                        } else {
                            final GrCodeReferenceElement importReference = importStatement.getImportReference();
                            if (importReference != null) {
                                importedName = PsiUtil.getQualifiedReferenceText(importReference);
                            }
                        }
                        if (importedName == null)
                            return;
                        final String importRef = getImportReferenceText(importStatement);
                        if (importStatement.isAliasedImport()) {
                            if (aliased != null) {
                                aliased.put(importRef, importedName);
                            }
                            return;
                        }
                        if (importStatement.isStatic()) {
                            if (staticallyImportedMembers != null) {
                                staticallyImportedMembers.add(importedName);
                            }
                        } else {
                            if (importedClasses != null) {
                                importedClasses.add(importedName);
                            }
                            if (resolved instanceof PsiClass && ((PsiClass) resolved).getContainingClass() != null && innerClasses != null) {
                                innerClasses.add(importedName);
                            }
                        }
                    }
                } else if (context == null && !(refElement.getParent() instanceof GrImportStatement) && refElement.getQualifier() == null) {
                    addImplicitClass(resolved);
                }
            }
        }

        private void addImplicitClass(PsiElement element) {
            final String qname = getTargetQualifiedName(element);
            if (qname != null) {
                if (implicitlyImported != null) {
                    implicitlyImported.add(qname);
                }
                if (importedClasses != null) {
                    importedClasses.add(qname);
                }
            }
        }

        /**
       * checks if import for implicitly imported class is needed
       */
        private boolean isImportUsed(GrReferenceElement refElement, PsiElement resolved) {
            if (GroovyImportHelper.isImplicitlyImported(resolved, refElement.getReferenceName(), (GroovyFile) file)) {
                final ClassResolverProcessor processor = new ClassResolverProcessor(refElement.getReferenceName(), refElement, ClassHint.RESOLVE_KINDS_CLASS);
                GroovyImportHelper.processImports(ResolveState.initial(), null, refElement, processor, ((GroovyFile) file).getImportStatements(), ON_DEMAND, null);
                if (!processor.hasCandidates()) {
                    return false;
                }
            }
            return true;
        }
    });
    final Set<GrImportStatement> importsToCheck = ContainerUtil.newLinkedHashSet(PsiUtil.getValidImportStatements((GroovyFile) file));
    for (GrImportStatement anImport : importsToCheck) {
        if (usedImports != null && usedImports.contains(anImport))
            continue;
        final GrCodeReferenceElement ref = anImport.getImportReference();
        assert ref != null : "invalid import!";
        if (ref.resolve() == null) {
            if (anImport.isOnDemand()) {
                if (usedImports != null) {
                    usedImports.add(anImport);
                }
                if (unresolvedOnDemandImports != null) {
                    unresolvedOnDemandImports.add(anImport);
                }
            } else {
                String importedName = anImport.getImportedName();
                if (importedName != null && unresolvedReferenceNames.contains(importedName)) {
                    if (usedImports != null) {
                        usedImports.add(anImport);
                    }
                    final String symbolName = getImportReferenceText(anImport);
                    if (anImport.isAliasedImport()) {
                        if (aliased != null) {
                            aliased.put(symbolName, importedName);
                        }
                    } else {
                        if (anImport.isStatic()) {
                            if (staticallyImportedMembers != null) {
                                staticallyImportedMembers.add(symbolName);
                            }
                        } else {
                            if (importedClasses != null) {
                                importedClasses.add(symbolName);
                            }
                        }
                    }
                }
            }
        }
    }
    if (annotations != null) {
        ((GroovyFile) file).acceptChildren(new GroovyElementVisitor() {

            @Override
            public void visitImportStatement(@NotNull GrImportStatement importStatement) {
                final String annotationText = importStatement.getAnnotationList().getText();
                if (!StringUtil.isEmptyOrSpaces(annotationText)) {
                    final String importRef = getImportReferenceText(importStatement);
                    annotations.put(importRef, annotationText);
                }
            }
        });
    }
}
Also used : GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) GrCodeReferenceElement(org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement) GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) ClassResolverProcessor(org.jetbrains.plugins.groovy.lang.resolve.processors.ClassResolverProcessor) GroovyElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor) GrPackageDefinition(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) GrReferenceElement(org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement)

Example 85 with GroovyFile

use of org.jetbrains.plugins.groovy.lang.psi.GroovyFile in project intellij-community by JetBrains.

the class GroovyResolveScopeProvider method getResolveScope.

@Override
public GlobalSearchScope getResolveScope(@NotNull VirtualFile file, Project project) {
    if (file.getFileType() != GroovyFileType.GROOVY_FILE_TYPE)
        return null;
    ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    Module module = projectFileIndex.getModuleForFile(file);
    //groovy files are only in modules
    if (module == null)
        return null;
    boolean includeTests = projectFileIndex.isInTestSourceContent(file) || !projectFileIndex.isInSourceContent(file);
    final GlobalSearchScope scope;
    if (projectFileIndex.isUnderSourceRootOfType(file, JavaModuleSourceRootTypes.RESOURCES)) {
        scope = GlobalSearchScope.moduleRuntimeScope(module, includeTests);
    } else {
        scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module, includeTests);
    }
    final PsiFile psi = PsiManager.getInstance(project).findFile(file);
    if (psi instanceof GroovyFile && ((GroovyFile) psi).isScript()) {
        return GroovyScriptTypeDetector.patchResolveScope((GroovyFile) psi, scope);
    } else {
        return scope;
    }
}
Also used : ProjectFileIndex(com.intellij.openapi.roots.ProjectFileIndex) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) PsiFile(com.intellij.psi.PsiFile) Module(com.intellij.openapi.module.Module) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile)

Aggregations

GroovyFile (org.jetbrains.plugins.groovy.lang.psi.GroovyFile)91 PsiFile (com.intellij.psi.PsiFile)26 PsiElement (com.intellij.psi.PsiElement)21 NotNull (org.jetbrains.annotations.NotNull)17 GrImportStatement (org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement)17 VirtualFile (com.intellij.openapi.vfs.VirtualFile)13 Project (com.intellij.openapi.project.Project)10 GrTypeDefinition (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition)10 PsiClass (com.intellij.psi.PsiClass)9 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)9 Nullable (org.jetbrains.annotations.Nullable)8 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)8 GroovyScriptClass (org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass)8 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)7 Module (com.intellij.openapi.module.Module)6 IncorrectOperationException (com.intellij.util.IncorrectOperationException)6 GrReferenceElement (org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement)6 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)6 GrParameter (org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)6 ASTNode (com.intellij.lang.ASTNode)5