Search in sources :

Example 21 with GrReferenceExpression

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

the class ConvertClosureToMethodIntention method processIntention.

@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException {
    final GrField field;
    if (element.getParent() instanceof GrField) {
        field = (GrField) element.getParent();
    } else {
        final PsiReference ref = element.getReference();
        LOG.assertTrue(ref != null);
        PsiElement resolved = ref.resolve();
        if (resolved instanceof GrAccessorMethod) {
            resolved = ((GrAccessorMethod) resolved).getProperty();
        }
        LOG.assertTrue(resolved instanceof GrField);
        field = (GrField) resolved;
    }
    final HashSet<PsiReference> usages = new HashSet<>();
    usages.addAll(ReferencesSearch.search(field).findAll());
    final GrAccessorMethod[] getters = field.getGetters();
    for (GrAccessorMethod getter : getters) {
        usages.addAll(MethodReferencesSearch.search(getter).findAll());
    }
    final GrAccessorMethod setter = field.getSetter();
    if (setter != null) {
        usages.addAll(MethodReferencesSearch.search(setter).findAll());
    }
    final String fieldName = field.getName();
    LOG.assertTrue(fieldName != null);
    final Collection<PsiElement> fieldUsages = new HashSet<>();
    MultiMap<PsiElement, String> conflicts = new MultiMap<>();
    for (PsiReference usage : usages) {
        final PsiElement psiElement = usage.getElement();
        if (PsiUtil.isMethodUsage(psiElement))
            continue;
        if (!GroovyLanguage.INSTANCE.equals(psiElement.getLanguage())) {
            conflicts.putValue(psiElement, GroovyIntentionsBundle.message("closure.is.accessed.outside.of.groovy", fieldName));
        } else {
            if (psiElement instanceof GrReferenceExpression) {
                fieldUsages.add(psiElement);
                if (PsiUtil.isAccessedForWriting((GrExpression) psiElement)) {
                    conflicts.putValue(psiElement, GroovyIntentionsBundle.message("write.access.to.closure.variable", fieldName));
                }
            } else if (psiElement instanceof GrArgumentLabel) {
                conflicts.putValue(psiElement, GroovyIntentionsBundle.message("field.is.used.in.argument.label", fieldName));
            }
        }
    }
    final PsiClass containingClass = field.getContainingClass();
    final GrExpression initializer = field.getInitializerGroovy();
    LOG.assertTrue(initializer != null);
    final PsiType type = initializer.getType();
    LOG.assertTrue(type instanceof GrClosureType);
    final GrSignature signature = ((GrClosureType) type).getSignature();
    final List<MethodSignature> signatures = GrClosureSignatureUtil.generateAllMethodSignaturesBySignature(fieldName, signature);
    for (MethodSignature s : signatures) {
        final PsiMethod method = MethodSignatureUtil.findMethodBySignature(containingClass, s, true);
        if (method != null) {
            conflicts.putValue(method, GroovyIntentionsBundle.message("method.with.signature.already.exists", GroovyPresentationUtil.getSignaturePresentation(s)));
        }
    }
    if (!conflicts.isEmpty()) {
        final ConflictsDialog conflictsDialog = new ConflictsDialog(project, conflicts, () -> execute(field, fieldUsages));
        conflictsDialog.show();
        if (conflictsDialog.getExitCode() != DialogWrapper.OK_EXIT_CODE)
            return;
    }
    execute(field, fieldUsages);
}
Also used : GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) MethodSignature(com.intellij.psi.util.MethodSignature) GrArgumentLabel(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) GrAccessorMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod) MultiMap(com.intellij.util.containers.MultiMap) ConflictsDialog(com.intellij.refactoring.ui.ConflictsDialog) GrSignature(org.jetbrains.plugins.groovy.lang.psi.api.signatures.GrSignature) HashSet(com.intellij.util.containers.HashSet) GrClosureType(org.jetbrains.plugins.groovy.lang.psi.impl.GrClosureType)

Example 22 with GrReferenceExpression

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

the class IndexingMethodConversionPredicate method satisfiedBy.

@Override
public boolean satisfiedBy(PsiElement element) {
    if (!(element instanceof GrMethodCallExpression)) {
        return false;
    }
    if (ErrorUtil.containsError(element)) {
        return false;
    }
    final GrMethodCallExpression callExpression = (GrMethodCallExpression) element;
    final GrArgumentList argList = callExpression.getArgumentList();
    final GrExpression[] arguments = argList.getExpressionArguments();
    final GrExpression invokedExpression = callExpression.getInvokedExpression();
    if (!(invokedExpression instanceof GrReferenceExpression)) {
        return false;
    }
    final GrReferenceExpression referenceExpression = (GrReferenceExpression) invokedExpression;
    final GrExpression qualifier = referenceExpression.getQualifierExpression();
    if (qualifier == null) {
        return false;
    }
    final IElementType referenceType = referenceExpression.getDotTokenType();
    if (!GroovyTokenTypes.mDOT.equals(referenceType)) {
        return false;
    }
    final String methodName = referenceExpression.getReferenceName();
    if ("getAt".equals(methodName)) {
        return arguments.length == 1;
    }
    if ("get".equals(methodName)) {
        final PsiType qualifierType = qualifier.getType();
        if (!isMap(qualifierType)) {
            return false;
        }
        return arguments.length == 1;
    } else if ("setAt".equals(methodName)) {
        return arguments.length == 2;
    } else if ("put".equals(methodName)) {
        final PsiType qualifierType = qualifier.getType();
        if (!isMap(qualifierType)) {
            return false;
        }
        return arguments.length == 2;
    }
    return false;
}
Also used : IElementType(com.intellij.psi.tree.IElementType) GrMethodCallExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression) GrArgumentList(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) PsiType(com.intellij.psi.PsiType)

Example 23 with GrReferenceExpression

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

the class GroovyInsertHandler method handleInsert.

@Override
public void handleInsert(InsertionContext context, LookupElement item) {
    @NonNls Object obj = item.getObject();
    PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
    if (obj instanceof GroovyResolveResult) {
        substitutor = ((GroovyResolveResult) obj).getSubstitutor();
        obj = ((GroovyResolveResult) obj).getElement();
    }
    if (obj instanceof PsiMethod) {
        final PsiMethod method = (PsiMethod) obj;
        PsiParameter[] parameters = method.getParameterList().getParameters();
        Editor editor = context.getEditor();
        Document document = editor.getDocument();
        if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
            handleOverwrite(editor.getCaretModel().getOffset(), document);
        }
        CaretModel caretModel = editor.getCaretModel();
        int offset = context.getTailOffset();
        PsiFile file = context.getFile();
        PsiElement elementAt = file.findElementAt(context.getStartOffset());
        assert elementAt != null;
        PsiElement parent = elementAt.getParent();
        if (parent instanceof GrReferenceExpression && ((GrReferenceExpression) parent).getDotTokenType() == GroovyTokenTypes.mMEMBER_POINTER) {
            return;
        }
        CharSequence charsSequence = document.getCharsSequence();
        if (isAnnotationNameValuePair(obj, parent)) {
            int endOffset = offset;
            if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
                endOffset = CharArrayUtil.shiftForward(charsSequence, offset, " \t");
                if (charsSequence.length() > endOffset && charsSequence.charAt(endOffset) == '=') {
                    endOffset++;
                    endOffset = CharArrayUtil.shiftForward(charsSequence, endOffset, " \t");
                }
            }
            document.replaceString(offset, endOffset, " = ");
            caretModel.moveToOffset(offset + 3);
            return;
        }
        if (PsiTreeUtil.getParentOfType(elementAt, GrImportStatement.class) != null)
            return;
        if (parameters.length == 1) {
            if ((context.getCompletionChar() != '(' && context.getCompletionChar() != ' ') && TypesUtil.isClassType(parameters[0].getType(), GroovyCommonClassNames.GROOVY_LANG_CLOSURE)) {
                int afterBrace;
                final int nonWs = CharArrayUtil.shiftForward(charsSequence, offset, " \t");
                if (nonWs < document.getTextLength() && charsSequence.charAt(nonWs) == '{') {
                    afterBrace = nonWs + 1;
                } else {
                    if (isSpaceBeforeClosure(file)) {
                        document.insertString(offset, " ");
                        offset++;
                    }
                    if (ClosureCompleter.runClosureCompletion(context, method, substitutor, document, offset, parent))
                        return;
                    if (context.getCompletionChar() == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) {
                        //smart enter invoked
                        document.insertString(offset, "{\n}");
                        //position caret before '{' for smart enter
                        afterBrace = offset + 1;
                        context.setTailOffset(afterBrace);
                    } else {
                        document.insertString(offset, "{}");
                        afterBrace = offset + 1;
                    }
                }
                caretModel.moveToOffset(afterBrace);
                return;
            }
        }
        context.commitDocument();
        if (context.getCompletionChar() == ' ' && MethodParenthesesHandler.hasParams(item, context.getElements(), true, method)) {
            return;
        }
        CommonCodeStyleSettings settings = context.getCodeStyleSettings();
        ParenthesesInsertHandler.getInstance(MethodParenthesesHandler.hasParams(item, context.getElements(), true, method), settings.SPACE_BEFORE_METHOD_CALL_PARENTHESES, settings.SPACE_WITHIN_METHOD_CALL_PARENTHESES, true, true).handleInsert(context, item);
        AutoPopupController.getInstance(context.getProject()).autoPopupParameterInfo(editor, method);
        return;
    }
    if (obj instanceof PsiClass) {
        final PsiClass clazz = (PsiClass) obj;
        Editor editor = context.getEditor();
        Document document = editor.getDocument();
        PsiFile file = PsiDocumentManager.getInstance(clazz.getProject()).getPsiFile(document);
        assert file != null;
        PsiElement elementAt = file.findElementAt(context.getStartOffset());
        assert elementAt != null;
        CaretModel caretModel = editor.getCaretModel();
        int offset = context.getStartOffset() + elementAt.getTextLength();
        final String text = document.getText();
        final PsiElement parent = elementAt.getParent();
        if (parent instanceof GrCodeReferenceElement && parent.getParent() instanceof GrNewExpression && (offset == text.length() || !text.substring(offset).trim().startsWith("("))) {
            document.insertString(offset, "()");
            if (GroovyCompletionUtil.hasConstructorParameters(clazz, parent)) {
                caretModel.moveToOffset(offset + 1);
                return;
            }
            caretModel.moveToOffset(offset + 2);
            return;
        }
    }
    if (context.getCompletionChar() == '=') {
        context.setAddCompletionChar(false);
        TailType.EQ.processTail(context.getEditor(), context.getTailOffset());
        return;
    }
    if (obj instanceof PsiPackage) {
        AutoPopupController.getInstance(context.getProject()).scheduleAutoPopup(context.getEditor());
    }
}
Also used : NonNls(org.jetbrains.annotations.NonNls) CaretModel(com.intellij.openapi.editor.CaretModel) Document(com.intellij.openapi.editor.Document) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) GrNewExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression) GrCodeReferenceElement(org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement) GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) CommonCodeStyleSettings(com.intellij.psi.codeStyle.CommonCodeStyleSettings) Editor(com.intellij.openapi.editor.Editor)

Example 24 with GrReferenceExpression

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

the class GroovyExtractMethodHandler method renameParameterOccurrences.

private static void renameParameterOccurrences(GrMethod method, ExtractMethodInfoHelper helper) throws IncorrectOperationException {
    GrOpenBlock block = method.getBlock();
    if (block == null)
        return;
    GrStatement[] statements = block.getStatements();
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(helper.getProject());
    for (ParameterInfo info : helper.getParameterInfos()) {
        final String oldName = info.getOriginalName();
        final String newName = info.getName();
        final ArrayList<GrExpression> result = new ArrayList<>();
        if (!oldName.equals(newName)) {
            for (final GrStatement statement : statements) {
                statement.accept(new PsiRecursiveElementVisitor() {

                    @Override
                    public void visitElement(final PsiElement element) {
                        super.visitElement(element);
                        if (element instanceof GrReferenceExpression) {
                            GrReferenceExpression expr = (GrReferenceExpression) element;
                            if (!expr.isQualified() && oldName.equals(expr.getReferenceName())) {
                                result.add(expr);
                            }
                        }
                    }
                });
                for (GrExpression expr : result) {
                    expr.replaceWithExpression(factory.createExpressionFromText(newName), false);
                }
            }
        }
    }
}
Also used : ArrayList(java.util.ArrayList) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) ParameterInfo(org.jetbrains.plugins.groovy.refactoring.extract.ParameterInfo) GrStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrOpenBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock)

Example 25 with GrReferenceExpression

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

the class GrVariableInliner method inlineReference.

static void inlineReference(UsageInfo usage, PsiElement referenced, GrExpression initializer) {
    if (initializer == null)
        return;
    GrExpression exprToBeReplaced = (GrExpression) usage.getElement();
    if (exprToBeReplaced == null)
        return;
    if ((referenced instanceof GrAccessorMethod || referenced instanceof GrField) && exprToBeReplaced instanceof GrReferenceExpression) {
        final GroovyResolveResult resolveResult = ((GrReferenceExpression) exprToBeReplaced).advancedResolve();
        if (resolveResult.getElement() instanceof GrAccessorMethod && !resolveResult.isInvokedOnProperty()) {
            final PsiElement parent = exprToBeReplaced.getParent();
            if (parent instanceof GrCall && parent instanceof GrExpression) {
                exprToBeReplaced = (GrExpression) parent;
            } else {
                return;
            }
        }
    }
    GrExpression newExpr = exprToBeReplaced.replaceWithExpression((GrExpression) initializer.copy(), true);
    final Project project = usage.getProject();
    JavaCodeStyleManager.getInstance(project).shortenClassReferences(newExpr);
    Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
    GroovyRefactoringUtil.highlightOccurrences(project, editor, new PsiElement[] { newExpr });
    WindowManager.getInstance().getStatusBar(project).setInfo(GroovyRefactoringBundle.message("press.escape.to.remove.the.highlighting"));
}
Also used : GrAccessorMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod) GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) Project(com.intellij.openapi.project.Project) GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) GrCall(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) Editor(com.intellij.openapi.editor.Editor) PsiElement(com.intellij.psi.PsiElement) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)

Aggregations

GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)177 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)92 PsiElement (com.intellij.psi.PsiElement)56 Nullable (org.jetbrains.annotations.Nullable)28 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)27 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)26 NotNull (org.jetbrains.annotations.NotNull)25 GroovyResolveResult (org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult)22 GrMethodCall (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall)22 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)21 GrArgumentList (org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList)17 GrParameter (org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)16 GrField (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField)15 GroovyRecursiveElementVisitor (org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor)14 GrVariable (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable)14 PsiType (com.intellij.psi.PsiType)13 GrAssignmentExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression)12 Project (com.intellij.openapi.project.Project)11 ArrayList (java.util.ArrayList)11 GrMethodCallExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression)11