Search in sources :

Example 1 with GrField

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField 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 GrField

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

the class CreateParameterForFieldIntention method performForConstructor.

private static void performForConstructor(PsiElement element, final Project project, Editor editor, List<GrField> candidates) {
    final GrMethod constructor = PsiTreeUtil.getParentOfType(element, GrMethod.class);
    if (candidates.isEmpty())
        return;
    if (ApplicationManager.getApplication().isUnitTestMode()) {
        for (GrField candidate : candidates) {
            addParameter(candidate, constructor, project);
        }
        return;
    }
    final JList list = new JBList(candidates.toArray(new GrField[candidates.size()]));
    list.setCellRenderer(new DefaultPsiElementCellRenderer());
    new PopupChooserBuilder(list).setTitle(GroovyIntentionsBundle.message("create.parameter.for.field.intention.name")).setMovable(true).setItemChoosenCallback(() -> {
        final Object[] selectedValues = list.getSelectedValues();
        CommandProcessor.getInstance().executeCommand(project, () -> {
            for (Object selectedValue : selectedValues) {
                LOG.assertTrue(((GrField) selectedValue).isValid());
                addParameter(((GrField) selectedValue), constructor, project);
            }
        }, GroovyIntentionsBundle.message("create.parameter.for.field.intention.name"), null);
    }).createPopup().showInBestPositionFor(editor);
}
Also used : GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) DefaultPsiElementCellRenderer(com.intellij.ide.util.DefaultPsiElementCellRenderer) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) JBList(com.intellij.ui.components.JBList) PopupChooserBuilder(com.intellij.openapi.ui.popup.PopupChooserBuilder)

Example 3 with GrField

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

the class CreateParameterForFieldIntention method performForField.

private static void performForField(PsiElement element, final Project project, Editor editor, List<GrMethod> constructors) {
    final GrField field = PsiTreeUtil.getParentOfType(element, GrField.class);
    if (constructors.isEmpty())
        return;
    if (ApplicationManager.getApplication().isUnitTestMode()) {
        for (GrMethod constructor : constructors) {
            addParameter(field, constructor, project);
        }
        return;
    }
    final JList list = new JBList(constructors.toArray(new GrMethod[constructors.size()]));
    list.setCellRenderer(new MethodCellRenderer(true));
    new PopupChooserBuilder(list).setTitle(GroovyIntentionsBundle.message("create.parameter.for.field.intention.name")).setMovable(true).setItemChoosenCallback(() -> {
        final Object[] selectedValues = list.getSelectedValues();
        Arrays.sort(selectedValues, (o1, o2) -> ((GrMethod) o2).getParameterList().getParametersCount() - ((GrMethod) o1).getParameterList().getParametersCount());
        CommandProcessor.getInstance().executeCommand(project, () -> {
            for (Object selectedValue : selectedValues) {
                LOG.assertTrue(((GrMethod) selectedValue).isValid());
                addParameter(field, ((GrMethod) selectedValue), project);
            }
        }, GroovyIntentionsBundle.message("create.parameter.for.field.intention.name"), null);
    }).createPopup().showInBestPositionFor(editor);
}
Also used : GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) JBList(com.intellij.ui.components.JBList) PopupChooserBuilder(com.intellij.openapi.ui.popup.PopupChooserBuilder) MethodCellRenderer(com.intellij.ide.util.MethodCellRenderer)

Example 4 with GrField

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

the class GroovyLineMarkerProvider method getLineMarkerInfo.

@Override
public LineMarkerInfo getLineMarkerInfo(@NotNull final PsiElement element) {
    final PsiElement parent = element.getParent();
    if (parent instanceof PsiNameIdentifierOwner) {
        if (parent instanceof GrField && element == ((GrField) parent).getNameIdentifierGroovy()) {
            for (GrAccessorMethod method : GroovyPropertyUtils.getFieldAccessors((GrField) parent)) {
                MethodSignatureBackedByPsiMethod superSignature = SuperMethodsSearch.search(method, null, true, false).findFirst();
                if (superSignature != null) {
                    PsiMethod superMethod = superSignature.getMethod();
                    boolean overrides = method.hasModifierProperty(PsiModifier.ABSTRACT) == superMethod.hasModifierProperty(PsiModifier.ABSTRACT) || superMethod.getBody() != null && GrTraitUtil.isTrait(superMethod.getContainingClass());
                    final Icon icon = overrides ? AllIcons.Gutter.OverridingMethod : AllIcons.Gutter.ImplementingMethod;
                    final MarkerType type = GroovyMarkerTypes.OVERRIDING_PROPERTY_TYPE;
                    return new LineMarkerInfo<>(element, element.getTextRange(), icon, Pass.LINE_MARKERS, type.getTooltip(), type.getNavigationHandler(), GutterIconRenderer.Alignment.LEFT);
                }
            }
        } else if (parent instanceof GrMethod && element == ((GrMethod) parent).getNameIdentifierGroovy() && hasSuperMethods((GrMethod) element.getParent())) {
            final Icon icon = AllIcons.Gutter.OverridingMethod;
            final MarkerType type = GroovyMarkerTypes.GR_OVERRIDING_METHOD;
            return new LineMarkerInfo<>(element, element.getTextRange(), icon, Pass.LINE_MARKERS, type.getTooltip(), type.getNavigationHandler(), GutterIconRenderer.Alignment.LEFT);
        }
    }
    //need to draw method separator above docComment
    if (myDaemonSettings.SHOW_METHOD_SEPARATORS && element.getFirstChild() == null) {
        PsiElement element1 = element;
        boolean isMember = false;
        while (element1 != null && !(element1 instanceof PsiFile) && element1.getPrevSibling() == null) {
            element1 = element1.getParent();
            if (element1 instanceof PsiMember || element1 instanceof GrVariableDeclarationImpl) {
                isMember = true;
                break;
            }
        }
        if (isMember && !(element1 instanceof PsiAnonymousClass || element1.getParent() instanceof PsiAnonymousClass)) {
            PsiFile file = element1.getContainingFile();
            Document document = file == null ? null : PsiDocumentManager.getInstance(file.getProject()).getLastCommittedDocument(file);
            boolean drawSeparator = false;
            if (document != null) {
                CharSequence documentChars = document.getCharsSequence();
                int category = getGroovyCategory(element1, documentChars);
                for (PsiElement child = element1.getPrevSibling(); child != null; child = child.getPrevSibling()) {
                    int category1 = getGroovyCategory(child, documentChars);
                    if (category1 == 0)
                        continue;
                    drawSeparator = category != 1 || category1 != 1;
                    break;
                }
            }
            if (drawSeparator) {
                GrDocComment comment = null;
                if (element1 instanceof GrDocCommentOwner) {
                    comment = ((GrDocCommentOwner) element1).getDocComment();
                }
                LineMarkerInfo info = new LineMarkerInfo<>(element, comment != null ? comment.getTextRange() : element.getTextRange(), null, Pass.LINE_MARKERS, FunctionUtil.<Object, String>nullConstant(), null, GutterIconRenderer.Alignment.RIGHT);
                EditorColorsScheme scheme = myColorsManager.getGlobalScheme();
                info.separatorColor = scheme.getColor(CodeInsightColors.METHOD_SEPARATORS_COLOR);
                info.separatorPlacement = SeparatorPlacement.TOP;
                return info;
            }
        }
    }
    return null;
}
Also used : GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) MethodSignatureBackedByPsiMethod(com.intellij.psi.util.MethodSignatureBackedByPsiMethod) MethodSignatureBackedByPsiMethod(com.intellij.psi.util.MethodSignatureBackedByPsiMethod) GrDocCommentOwner(org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocCommentOwner) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) Document(com.intellij.openapi.editor.Document) GrDocComment(org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocComment) GrAccessorMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod) LineMarkerInfo(com.intellij.codeInsight.daemon.LineMarkerInfo) MarkerType(com.intellij.codeInsight.daemon.impl.MarkerType) GrVariableDeclarationImpl(org.jetbrains.plugins.groovy.lang.psi.impl.statements.GrVariableDeclarationImpl) EditorColorsScheme(com.intellij.openapi.editor.colors.EditorColorsScheme)

Example 5 with GrField

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

the class GrPullUpHandler method invoke.

@Override
public void invoke(@NotNull final Project project, @NotNull PsiElement[] elements, DataContext dataContext) {
    if (elements.length != 1)
        return;
    myProject = project;
    PsiElement element = elements[0];
    GrTypeDefinition aClass;
    PsiElement aMember = null;
    if (element instanceof GrTypeDefinition) {
        aClass = (GrTypeDefinition) element;
    } else if (element instanceof GrMethod) {
        aClass = DefaultGroovyMethods.asType(((GrMethod) element).getContainingClass(), GrTypeDefinition.class);
        aMember = element;
    } else if (element instanceof GrField) {
        aClass = DefaultGroovyMethods.asType(((GrField) element).getContainingClass(), GrTypeDefinition.class);
        aMember = element;
    } else {
        return;
    }
    invokeImpl(project, dataContext, aClass, aMember);
}
Also used : GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)

Aggregations

GrField (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField)55 GrMethod (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)17 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)16 GrVariable (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable)13 GrAccessorMethod (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod)13 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)12 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)11 PsiElement (com.intellij.psi.PsiElement)10 GrTypeDefinition (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition)9 NotNull (org.jetbrains.annotations.NotNull)8 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)8 Nullable (org.jetbrains.annotations.Nullable)7 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)7 GroovyResolveResult (org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult)7 GrParameter (org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)7 ArrayList (java.util.ArrayList)6 GroovyRecursiveElementVisitor (org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor)6 Project (com.intellij.openapi.project.Project)4 PsiClass (com.intellij.psi.PsiClass)4 UsageInfo (com.intellij.usageView.UsageInfo)4