Search in sources :

Example 1 with GroovyFile

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

the class GroovyCodeFragmentFactory method externalParameters.

public static Pair<Map<String, String>, GroovyFile> externalParameters(String text, @NotNull final PsiElement context) {
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(context.getProject());
    final GroovyFile toEval = factory.createGroovyFile(text, false, context);
    final GrClosableBlock closure = PsiTreeUtil.getParentOfType(context, GrClosableBlock.class);
    final Map<String, String> parameters = new THashMap<>();
    final Map<GrExpression, String> replacements = new HashMap<>();
    toEval.accept(new GroovyRecursiveElementVisitor() {

        @Override
        public void visitReferenceExpression(@NotNull GrReferenceExpression referenceExpression) {
            super.visitReferenceExpression(referenceExpression);
            if (PsiUtil.isThisReference(referenceExpression) || PsiUtil.isSuperReference(referenceExpression)) {
                replaceWithReference(referenceExpression, "delegate");
                return;
            }
            PsiElement resolved = referenceExpression.resolve();
            if (resolved instanceof PsiMember && (resolved instanceof PsiClass || ((PsiMember) resolved).hasModifierProperty(PsiModifier.STATIC))) {
                String qName = com.intellij.psi.util.PsiUtil.getMemberQualifiedName((PsiMember) resolved);
                if (qName != null && qName.contains(".") && !referenceExpression.isQualified()) {
                    replaceWithReference(referenceExpression, qName);
                    return;
                }
            }
            if (shouldDelegate(referenceExpression, resolved)) {
                replaceWithReference(referenceExpression, "delegate." + referenceExpression.getReferenceName());
                return;
            }
            if (resolved instanceof GrVariable && !(resolved instanceof GrField) && !PsiTreeUtil.isAncestor(toEval, resolved, false)) {
                final String name = ((GrVariable) resolved).getName();
                if (resolved instanceof ClosureSyntheticParameter && PsiTreeUtil.isAncestor(toEval, ((ClosureSyntheticParameter) resolved).getClosure(), false)) {
                    return;
                }
                if (resolved instanceof GrBindingVariable && !PsiTreeUtil.isAncestor(resolved.getContainingFile(), toEval, false)) {
                    return;
                }
                String value;
                if (closure != null && PsiTreeUtil.findCommonParent(resolved, closure) != closure && !(resolved instanceof ClosureSyntheticParameter)) {
                    // Evaluating inside closure for outer variable definitions
                    // All non-local variables are accessed by references
                    value = "this." + name;
                } else {
                    value = name;
                }
                parameters.put(name, value);
                return;
            }
            if (resolved instanceof PsiLocalVariable || resolved instanceof PsiParameter && !(resolved instanceof GrParameter)) {
                String name = referenceExpression.getReferenceName();
                parameters.put(name, name);
            }
        }

        private boolean shouldDelegate(GrReferenceExpression referenceExpression, @Nullable PsiElement resolved) {
            if (referenceExpression.isQualified()) {
                return false;
            }
            if (resolved instanceof GrField) {
                return true;
            }
            if (resolved instanceof PsiMethod) {
                String methodName = ((PsiMethod) resolved).getName();
                if (closure != null && "getDelegate".equals(methodName) || "call".equals(methodName)) {
                    return true;
                }
            }
            return closure != null && resolved instanceof GrLightVariable && "owner".equals(((GrLightVariable) resolved).getName());
        }

        private void replaceWithReference(GrExpression expr, final String exprText) {
            replacements.put(expr, exprText);
        }

        @Override
        public void visitCodeReferenceElement(@NotNull GrCodeReferenceElement refElement) {
            super.visitCodeReferenceElement(refElement);
            if (refElement.getQualifier() == null) {
                PsiElement resolved = refElement.resolve();
                if (resolved instanceof PsiClass) {
                    String qName = ((PsiClass) resolved).getQualifiedName();
                    if (qName != null) {
                        int dotIndex = qName.lastIndexOf(".");
                        if (dotIndex < 0)
                            return;
                        String packageName = qName.substring(0, dotIndex);
                        refElement.setQualifier(factory.createReferenceElementFromText(packageName));
                    }
                }
            }
        }
    });
    for (GrExpression expression : replacements.keySet()) {
        expression.replaceWithExpression(factory.createExpressionFromText(replacements.get(expression)), false);
    }
    return Pair.create(parameters, toEval);
}
Also used : GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) THashMap(gnu.trove.THashMap) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) THashMap(gnu.trove.THashMap) GrBindingVariable(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrBindingVariable) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) ClosureSyntheticParameter(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.ClosureSyntheticParameter) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrCodeReferenceElement(org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement) GrLightVariable(org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightVariable) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile)

Example 2 with GroovyFile

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

the class GroovyTypedHandler method beforeCharTyped.

@Override
public Result beforeCharTyped(final char c, final Project project, final Editor editor, final PsiFile file, final FileType fileType) {
    int offsetBefore = editor.getCaretModel().getOffset();
    //important to calculate before inserting charTyped
    myJavaLTTyped = '<' == c && file instanceof GroovyFile && CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET && isAfterClassLikeIdentifier(offsetBefore, editor);
    if ('>' == c) {
        if (file instanceof GroovyFile && CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET) {
            if (JavaTypedHandler.handleJavaGT(editor, GroovyTokenTypes.mLT, GroovyTokenTypes.mGT, INVALID_INSIDE_REFERENCE))
                return Result.STOP;
        }
    }
    if (c == '@' && file instanceof GroovyFile) {
        autoPopupMemberLookup(project, editor, file12 -> {
            int offset = editor.getCaretModel().getOffset();
            PsiElement lastElement = file12.findElementAt(offset - 1);
            if (lastElement == null)
                return false;
            final PsiElement prevSibling = PsiTreeUtil.prevVisibleLeaf(lastElement);
            return prevSibling != null && ".".equals(prevSibling.getText());
        });
    }
    if (c == '&' && file instanceof GroovyFile) {
        autoPopupMemberLookup(project, editor, file1 -> {
            int offset = editor.getCaretModel().getOffset();
            PsiElement lastElement = file1.findElementAt(offset - 1);
            return lastElement != null && ".&".equals(lastElement.getText());
        });
    }
    return Result.CONTINUE;
}
Also used : GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) PsiElement(com.intellij.psi.PsiElement)

Example 3 with GroovyFile

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

the class GroovyScriptClassSearcher method findClass.

@Nullable
@Override
public PsiClass findClass(@NotNull PsiElement place) {
    if (place.getLanguage() == GroovyLanguage.INSTANCE) {
        PsiClass containingClass = PsiTreeUtil.getParentOfType(place, PsiClass.class, false);
        while (containingClass instanceof PsiTypeParameter) {
            containingClass = PsiTreeUtil.getParentOfType(containingClass, PsiClass.class);
        }
        if (containingClass != null)
            return containingClass;
        PsiFile file = place.getContainingFile();
        if (file instanceof GroovyFile && ((GroovyFile) file).isScript()) {
            return ((GroovyFile) file).getScriptClass();
        }
    }
    return null;
}
Also used : PsiTypeParameter(com.intellij.psi.PsiTypeParameter) PsiClass(com.intellij.psi.PsiClass) PsiFile(com.intellij.psi.PsiFile) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) Nullable(org.jetbrains.annotations.Nullable)

Example 4 with GroovyFile

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

the class GrImportFilteringRule method isVisible.

@Override
public boolean isVisible(@NotNull Usage usage) {
    if (usage instanceof PsiElementUsage) {
        final PsiElement psiElement = ((PsiElementUsage) usage).getElement();
        final PsiFile containingFile = psiElement.getContainingFile();
        if (containingFile instanceof GroovyFile) {
            // check whether the element is in the import list
            return PsiTreeUtil.getParentOfType(psiElement, GrImportStatement.class, true) == null;
        }
    }
    return true;
}
Also used : PsiFile(com.intellij.psi.PsiFile) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) PsiElement(com.intellij.psi.PsiElement) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) PsiElementUsage(com.intellij.usages.rules.PsiElementUsage)

Example 5 with GroovyFile

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

the class GroovyImportOptimizerRefactoringHelper method performOperation.

@Override
public void performOperation(final Project project, final Set<GroovyFile> files) {
    final ProgressManager progressManager = ProgressManager.getInstance();
    final Map<GroovyFile, Pair<List<GrImportStatement>, Set<GrImportStatement>>> redundants = new HashMap<>();
    final Runnable findUnusedImports = () -> {
        final ProgressIndicator progressIndicator = progressManager.getProgressIndicator();
        final int total = files.size();
        int i = 0;
        for (final GroovyFile file : files) {
            if (!file.isValid())
                continue;
            final VirtualFile virtualFile = file.getVirtualFile();
            if (!ProjectRootManager.getInstance(project).getFileIndex().isInSource(virtualFile)) {
                continue;
            }
            if (progressIndicator != null) {
                progressIndicator.setText2(virtualFile.getPresentableUrl());
                progressIndicator.setFraction((double) i++ / total);
            }
            ApplicationManager.getApplication().runReadAction(() -> {
                final Set<GrImportStatement> usedImports = GroovyImportUtil.findUsedImports(file);
                final List<GrImportStatement> validImports = PsiUtil.getValidImportStatements(file);
                redundants.put(file, Pair.create(validImports, usedImports));
            });
        }
    };
    if (!progressManager.runProcessWithProgressSynchronously(findUnusedImports, "Optimizing imports (Groovy) ... ", false, project)) {
        return;
    }
    WriteAction.run(() -> {
        for (GroovyFile groovyFile : redundants.keySet()) {
            if (!groovyFile.isValid())
                continue;
            final Pair<List<GrImportStatement>, Set<GrImportStatement>> pair = redundants.get(groovyFile);
            final List<GrImportStatement> validImports = pair.getFirst();
            final Set<GrImportStatement> usedImports = pair.getSecond();
            for (GrImportStatement importStatement : validImports) {
                if (!usedImports.contains(importStatement)) {
                    groovyFile.removeImport(importStatement);
                }
            }
        }
    });
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Set(java.util.Set) HashSet(com.intellij.util.containers.hash.HashSet) HashMap(java.util.HashMap) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) ProgressManager(com.intellij.openapi.progress.ProgressManager) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) List(java.util.List) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile) Pair(com.intellij.openapi.util.Pair)

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