Search in sources :

Example 91 with GrMethod

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

the class CreateParameterForFieldIntention method findCandidates.

private static List<GrField> findCandidates(PsiMethod constructor, final GrTypeDefinition clazz) {
    final List<GrField> usedFields = new ArrayList<>();
    final GrOpenBlock block = constructor instanceof GrMethod ? ((GrMethod) constructor).getBlock() : null;
    if (block == null) {
        return usedFields;
    }
    final PsiManager manager = clazz.getManager();
    block.accept(new GroovyRecursiveElementVisitor() {

        @Override
        public void visitReferenceExpression(@NotNull GrReferenceExpression referenceExpression) {
            super.visitReferenceExpression(referenceExpression);
            final PsiElement resolved = referenceExpression.resolve();
            if (resolved instanceof GrField && manager.areElementsEquivalent(((GrField) resolved).getContainingClass(), clazz) && PsiUtil.isAccessedForWriting(referenceExpression)) {
                usedFields.add((GrField) resolved);
            }
        }

        @Override
        public void visitTypeDefinition(@NotNull GrTypeDefinition typeDefinition) {
        }

        @Override
        public void visitClosure(@NotNull GrClosableBlock closure) {
        }
    });
    List<GrField> fields = new ArrayList<>();
    for (final GrField field : clazz.getFields()) {
        if (field.getInitializerGroovy() != null)
            continue;
        if (ContainerUtil.find(usedFields, new Condition<PsiField>() {

            @Override
            public boolean value(PsiField o) {
                return manager.areElementsEquivalent(o, field);
            }
        }) == null) {
            fields.add(field);
        }
    }
    return fields;
}
Also used : Condition(com.intellij.openapi.util.Condition) GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) ArrayList(java.util.ArrayList) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition) GrOpenBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock)

Example 92 with GrMethod

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

the class ConvertClosureToMethodIntention method execute.

private static void execute(final GrField field, final Collection<PsiElement> fieldUsages) {
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(field.getProject());
    final StringBuilder builder = new StringBuilder(field.getTextLength());
    final GrClosableBlock block = (GrClosableBlock) field.getInitializerGroovy();
    final GrModifierList modifierList = field.getModifierList();
    if (modifierList.getModifiers().length > 0 || modifierList.getAnnotations().length > 0) {
        builder.append(modifierList.getText());
    } else {
        builder.append(GrModifier.DEF);
    }
    builder.append(' ').append(field.getName());
    builder.append('(');
    if (block.hasParametersSection()) {
        builder.append(block.getParameterList().getText());
    } else {
        builder.append("def it = null");
    }
    builder.append(") {");
    ApplicationManager.getApplication().runWriteAction(() -> {
        block.getParameterList().delete();
        block.getLBrace().delete();
        final PsiElement psiElement = PsiUtil.skipWhitespacesAndComments(block.getFirstChild(), true);
        if (psiElement != null && "->".equals(psiElement.getText())) {
            psiElement.delete();
        }
        builder.append(block.getText());
        final GrMethod method = GroovyPsiElementFactory.getInstance(field.getProject()).createMethodFromText(builder.toString());
        field.getParent().replace(method);
        for (PsiElement usage : fieldUsages) {
            if (usage instanceof GrReferenceExpression) {
                final PsiElement parent = usage.getParent();
                StringBuilder newRefText = new StringBuilder();
                if (parent instanceof GrReferenceExpression && usage == ((GrReferenceExpression) parent).getQualifier() && "call".equals(((GrReferenceExpression) parent).getReferenceName())) {
                    newRefText.append(usage.getText());
                    usage = parent;
                } else {
                    PsiElement qualifier = ((GrReferenceExpression) usage).getQualifier();
                    if (qualifier == null) {
                        if (parent instanceof GrReferenceExpression && ((GrReferenceExpression) parent).getQualifier() != null && usage != ((GrReferenceExpression) parent).getQualifier()) {
                            qualifier = ((GrReferenceExpression) parent).getQualifier();
                            usage = parent;
                        }
                    }
                    if (qualifier != null) {
                        newRefText.append(qualifier.getText()).append('.');
                        ((GrReferenceExpression) usage).setQualifier(null);
                    } else {
                        newRefText.append("this.");
                    }
                    newRefText.append('&').append(usage.getText());
                }
                usage.replace(factory.createReferenceExpressionFromText(newRefText.toString()));
            }
        }
    });
}
Also used : GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrModifierList(org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)

Example 93 with GrMethod

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

the class GroovyShellLanguageConsoleView method processCode.

protected void processCode() {
    GroovyShellCodeFragment groovyFile = getGroovyFile();
    for (GrTopStatement statement : groovyFile.getTopStatements()) {
        if (statement instanceof GrImportStatement) {
            groovyFile.addImportsFromString(importToString((GrImportStatement) statement));
        } else if (statement instanceof GrMethod) {
            groovyFile.addVariable(((GrMethod) statement).getName(), generateClosure((GrMethod) statement));
        } else if (statement instanceof GrAssignmentExpression) {
            GrAssignmentExpression assignment = (GrAssignmentExpression) statement;
            GrExpression left = assignment.getLValue();
            if (left instanceof GrReferenceExpression && !((GrReferenceExpression) left).isQualified()) {
                groovyFile.addVariable(((GrReferenceExpression) left).getReferenceName(), assignment.getRValue());
            }
        } else if (statement instanceof GrTypeDefinition) {
            groovyFile.addTypeDefinition(prepareTypeDefinition((GrTypeDefinition) statement));
        }
    }
    PsiType scriptType = groovyFile.getInferredScriptReturnType();
    if (scriptType != null) {
        groovyFile.addVariable("_", scriptType);
    }
}
Also used : GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition) GrAssignmentExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) GrTopStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.GrTopStatement) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) PsiType(com.intellij.psi.PsiType)

Example 94 with GrMethod

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

the class GrPullUpHelper method doMoveMethod.

private void doMoveMethod(PsiSubstitutor substitutor, MemberInfo info) {
    GroovyPsiElementFactory elementFactory = GroovyPsiElementFactory.getInstance(myProject);
    GrMethod method = (GrMethod) info.getMember();
    PsiMethod sibling = method;
    PsiMethod anchor = null;
    while (sibling != null) {
        sibling = PsiTreeUtil.getNextSiblingOfType(sibling, PsiMethod.class);
        if (sibling != null) {
            anchor = MethodSignatureUtil.findMethodInSuperClassBySignatureInDerived(method.getContainingClass(), myTargetSuperClass, sibling.getSignature(PsiSubstitutor.EMPTY), false);
            if (anchor != null) {
                break;
            }
        }
    }
    GrMethod methodCopy = (GrMethod) method.copy();
    if (method.findSuperMethods(myTargetSuperClass).length == 0) {
        deleteOverrideAnnotationIfFound(methodCopy);
    }
    final boolean isOriginalMethodAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT) || method.hasModifierProperty(PsiModifier.DEFAULT);
    if (myTargetSuperClass.isInterface() || info.isToAbstract()) {
        GroovyChangeContextUtil.clearContextInfo(method);
        RefactoringUtil.makeMethodAbstract(myTargetSuperClass, methodCopy);
        if (myTargetSuperClass.isInterface()) {
            PsiUtil.setModifierProperty(methodCopy, PsiModifier.ABSTRACT, false);
        }
        replaceMovedMemberTypeParameters(methodCopy, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
        final GrMethod movedElement = anchor != null ? (GrMethod) myTargetSuperClass.addBefore(methodCopy, anchor) : (GrMethod) myTargetSuperClass.add(methodCopy);
        CodeStyleSettings styleSettings = CodeStyleSettingsManager.getSettings(method.getProject());
        if (styleSettings.INSERT_OVERRIDE_ANNOTATION) {
            if (PsiUtil.isLanguageLevel5OrHigher(mySourceClass) && !myTargetSuperClass.isInterface() || PsiUtil.isLanguageLevel6OrHigher(mySourceClass)) {
                new AddAnnotationFix(CommonClassNames.JAVA_LANG_OVERRIDE, method).invoke(method.getProject(), null, mySourceClass.getContainingFile());
            }
        }
        GrDocComment oldDoc = method.getDocComment();
        if (oldDoc != null) {
            GrDocCommentUtil.setDocComment(movedElement, oldDoc);
        }
        myDocCommentPolicy.processCopiedJavaDoc(methodCopy.getDocComment(), oldDoc, isOriginalMethodAbstract);
        myMembersAfterMove.add(movedElement);
        if (isOriginalMethodAbstract) {
            deleteMemberWithDocComment(method);
        }
    } else {
        if (isOriginalMethodAbstract) {
            PsiUtil.setModifierProperty(myTargetSuperClass, PsiModifier.ABSTRACT, true);
        }
        fixReferencesToStatic(methodCopy);
        replaceMovedMemberTypeParameters(methodCopy, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
        final PsiMethod superClassMethod = myTargetSuperClass.findMethodBySignature(methodCopy, false);
        Language language = myTargetSuperClass.getLanguage();
        final PsiMethod movedElement;
        if (superClassMethod != null && superClassMethod.hasModifierProperty(PsiModifier.ABSTRACT)) {
            movedElement = (PsiMethod) superClassMethod.replace(convertMethodToLanguage(methodCopy, language));
        } else {
            movedElement = anchor != null ? (PsiMethod) myTargetSuperClass.addBefore(convertMethodToLanguage(methodCopy, language), anchor) : (PsiMethod) myTargetSuperClass.add(convertMethodToLanguage(methodCopy, language));
            myMembersAfterMove.add(movedElement);
        }
        if (movedElement instanceof GrMethod) {
            GrDocCommentUtil.setDocComment((GrDocCommentOwner) movedElement, method.getDocComment());
        }
        deleteMemberWithDocComment(method);
    }
}
Also used : GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) CodeStyleSettings(com.intellij.psi.codeStyle.CodeStyleSettings) Language(com.intellij.lang.Language) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) AddAnnotationFix(com.intellij.codeInsight.intention.AddAnnotationFix) GrDocComment(org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GrDocComment)

Example 95 with GrMethod

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

the class MethodOrClosureScopeChooser method updateView.

public static void updateView(GrParametersOwner selectedMethod, Editor editor, TextAttributes attributes, List<RangeHighlighter> highlighters, JCheckBox superMethod) {
    final MarkupModel markupModel = editor.getMarkupModel();
    final TextRange textRange = selectedMethod.getTextRange();
    final RangeHighlighter rangeHighlighter = markupModel.addRangeHighlighter(textRange.getStartOffset(), textRange.getEndOffset(), HighlighterLayer.SELECTION - 1, attributes, HighlighterTargetArea.EXACT_RANGE);
    highlighters.add(rangeHighlighter);
    if (selectedMethod instanceof GrMethod) {
        superMethod.setText(USE_SUPER_METHOD_OF);
        superMethod.setEnabled(((GrMethod) selectedMethod).findDeepestSuperMethod() != null);
    } else {
        superMethod.setText(CHANGE_USAGES_OF);
        superMethod.setEnabled(findVariableToUse(selectedMethod) != null);
    }
}
Also used : GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) TextRange(com.intellij.openapi.util.TextRange)

Aggregations

GrMethod (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)134 GrOpenBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock)24 PsiElement (com.intellij.psi.PsiElement)22 NotNull (org.jetbrains.annotations.NotNull)21 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)19 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)18 GrParameter (org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)17 GrField (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField)16 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)16 ArrayList (java.util.ArrayList)15 GrTypeDefinition (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition)15 Nullable (org.jetbrains.annotations.Nullable)12 GrStatement (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement)12 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)12 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)12 IncorrectOperationException (com.intellij.util.IncorrectOperationException)10 GrCodeBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock)10 Project (com.intellij.openapi.project.Project)9 GrVariable (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable)8 GrReturnStatement (org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement)8