Search in sources :

Example 96 with GrStatement

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

the class GroovyIntroduceParameterMethodUsagesProcessor method processAddSuperCall.

@Override
public boolean processAddSuperCall(IntroduceParameterData data, UsageInfo usage, UsageInfo[] usages) throws IncorrectOperationException {
    if (!(usage.getElement() instanceof GrMethod) || !isGroovyUsage(usage))
        return true;
    GrMethod constructor = (GrMethod) usage.getElement();
    if (!constructor.isConstructor())
        return true;
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(data.getProject());
    GrConstructorInvocation superCall = factory.createConstructorInvocation("super();");
    GrOpenBlock body = constructor.getBlock();
    final GrStatement[] statements = body.getStatements();
    if (statements.length > 0) {
        superCall = (GrConstructorInvocation) body.addStatementBefore(superCall, statements[0]);
    } else {
        superCall = (GrConstructorInvocation) body.addStatementBefore(superCall, null);
    }
    processChangeMethodUsage(data, new UsageInfo(superCall), usages);
    return false;
}
Also used : GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrConstructorInvocation(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrConstructorInvocation) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrOpenBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock) UsageInfo(com.intellij.usageView.UsageInfo) GrStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement)

Example 97 with GrStatement

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

the class GroovyInlineMethodUtil method hasBadReturns.

private static boolean hasBadReturns(GrMethod method) {
    Collection<GrStatement> returnStatements = ControlFlowUtils.collectReturns(method.getBlock());
    GrOpenBlock block = method.getBlock();
    if (block == null || returnStatements.isEmpty())
        return false;
    boolean checked = checkTailOpenBlock(block, returnStatements);
    return !(checked && returnStatements.isEmpty());
}
Also used : GrOpenBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock) GrStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement)

Example 98 with GrStatement

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

the class GroovyMethodInliner method inlineReferenceImpl.

@Nullable
static RangeMarker inlineReferenceImpl(@NotNull GrCallExpression call, @NotNull GrMethod method, boolean resultOfCallExplicitlyUsed, boolean isTailMethodCall, @Nullable Editor editor) {
    try {
        GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(call.getProject());
        final Project project = call.getProject();
        // Variable declaration for qualifier expression
        GrVariableDeclaration qualifierDeclaration = null;
        GrReferenceExpression innerQualifier = null;
        GrExpression qualifier = null;
        if (call instanceof GrMethodCallExpression && ((GrMethodCallExpression) call).getInvokedExpression() != null) {
            GrExpression invoked = ((GrMethodCallExpression) call).getInvokedExpression();
            if (invoked instanceof GrReferenceExpression && ((GrReferenceExpression) invoked).getQualifierExpression() != null) {
                qualifier = ((GrReferenceExpression) invoked).getQualifierExpression();
                if (PsiUtil.isSuperReference(qualifier)) {
                    qualifier = null;
                } else if (!GroovyInlineMethodUtil.isSimpleReference(qualifier)) {
                    String qualName = generateQualifierName(call, method, project, qualifier);
                    qualifier = (GrExpression) PsiUtil.skipParentheses(qualifier, false);
                    qualifierDeclaration = factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, qualifier, null, qualName);
                    innerQualifier = (GrReferenceExpression) factory.createExpressionFromText(qualName);
                } else {
                    innerQualifier = (GrReferenceExpression) qualifier;
                }
            }
        }
        GrMethod _method = prepareNewMethod(call, method, qualifier);
        GrExpression result = getAloneResultExpression(_method);
        if (result != null) {
            GrExpression expression = call.replaceWithExpression(result, false);
            TextRange range = expression.getTextRange();
            return editor != null ? editor.getDocument().createRangeMarker(range.getStartOffset(), range.getEndOffset(), true) : null;
        }
        GrMethod newMethod = prepareNewMethod(call, method, innerQualifier);
        String resultName = InlineMethodConflictSolver.suggestNewName("result", newMethod, call);
        // Add variable for method result
        Collection<GrStatement> returnStatements = ControlFlowUtils.collectReturns(newMethod.getBlock());
        final int returnCount = returnStatements.size();
        PsiType methodType = method.getInferredReturnType();
        GrOpenBlock body = newMethod.getBlock();
        assert body != null;
        GrExpression replaced;
        if (resultOfCallExplicitlyUsed && !isTailMethodCall) {
            GrExpression resultExpr = null;
            if (PsiType.VOID.equals(methodType)) {
                resultExpr = factory.createExpressionFromText("null");
            } else if (returnCount == 1) {
                final GrExpression returnExpression = ControlFlowUtils.extractReturnExpression(returnStatements.iterator().next());
                if (returnExpression != null) {
                    resultExpr = factory.createExpressionFromText(returnExpression.getText());
                }
            } else if (returnCount > 1) {
                resultExpr = factory.createExpressionFromText(resultName);
            }
            if (resultExpr == null) {
                resultExpr = factory.createExpressionFromText("null");
            }
            replaced = call.replaceWithExpression(resultExpr, false);
        } else {
            replaced = call;
        }
        // Calculate anchor to insert before
        GrExpression enclosingExpr = GroovyRefactoringUtil.addBlockIntoParent(replaced);
        GrVariableDeclarationOwner owner = PsiTreeUtil.getParentOfType(enclosingExpr, GrVariableDeclarationOwner.class);
        assert owner != null;
        PsiElement element = enclosingExpr;
        while (element != null && element.getParent() != owner) {
            element = element.getParent();
        }
        assert element != null && element instanceof GrStatement;
        GrStatement anchor = (GrStatement) element;
        if (!resultOfCallExplicitlyUsed) {
            assert anchor == enclosingExpr;
        }
        // add qualifier reference declaration
        if (qualifierDeclaration != null) {
            owner.addVariableDeclarationBefore(qualifierDeclaration, anchor);
        }
        // Process method return statements
        if (returnCount > 1 && !PsiType.VOID.equals(methodType) && !isTailMethodCall) {
            PsiType type = methodType != null && methodType.equalsToText(CommonClassNames.JAVA_LANG_OBJECT) ? null : methodType;
            GrVariableDeclaration resultDecl = factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, "", type, resultName);
            GrStatement statement = ((GrStatementOwner) owner).addStatementBefore(resultDecl, anchor);
            JavaCodeStyleManager.getInstance(statement.getProject()).shortenClassReferences(statement);
            // Replace all return statements with assignments to 'result' variable
            for (GrStatement returnStatement : returnStatements) {
                GrExpression value = ControlFlowUtils.extractReturnExpression(returnStatement);
                if (value != null) {
                    GrExpression assignment = factory.createExpressionFromText(resultName + " = " + value.getText());
                    returnStatement.replaceWithStatement(assignment);
                } else {
                    returnStatement.replaceWithStatement(factory.createExpressionFromText(resultName + " = null"));
                }
            }
        }
        if (!isTailMethodCall && resultOfCallExplicitlyUsed && returnCount == 1) {
            returnStatements.iterator().next().removeStatement();
        } else if (!isTailMethodCall && (PsiType.VOID.equals(methodType) || returnCount == 1)) {
            for (GrStatement returnStatement : returnStatements) {
                if (returnStatement instanceof GrReturnStatement) {
                    final GrExpression returnValue = ((GrReturnStatement) returnStatement).getReturnValue();
                    if (returnValue != null && GroovyRefactoringUtil.hasSideEffect(returnValue)) {
                        returnStatement.replaceWithStatement(returnValue);
                        continue;
                    }
                } else if (GroovyRefactoringUtil.hasSideEffect(returnStatement)) {
                    continue;
                }
                returnStatement.removeStatement();
            }
        }
        // Add all method statements
        GrStatement[] statements = body.getStatements();
        for (GrStatement statement : statements) {
            ((GrStatementOwner) owner).addStatementBefore(statement, anchor);
        }
        if (resultOfCallExplicitlyUsed && !isTailMethodCall) {
            TextRange range = replaced.getTextRange();
            RangeMarker marker = editor != null ? editor.getDocument().createRangeMarker(range.getStartOffset(), range.getEndOffset(), true) : null;
            reformatOwner(owner);
            return marker;
        } else {
            GrStatement stmt;
            if (isTailMethodCall && enclosingExpr.getParent() instanceof GrReturnStatement) {
                stmt = (GrReturnStatement) enclosingExpr.getParent();
            } else {
                stmt = enclosingExpr;
            }
            stmt.removeStatement();
            reformatOwner(owner);
            return null;
        }
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
    return null;
}
Also used : GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrStatementOwner(org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) TextRange(com.intellij.openapi.util.TextRange) RangeMarker(com.intellij.openapi.editor.RangeMarker) GrReturnStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement) GrVariableDeclarationOwner(org.jetbrains.plugins.groovy.lang.psi.api.util.GrVariableDeclarationOwner) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) GrStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) Project(com.intellij.openapi.project.Project) GrVariableDeclaration(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration) GrMethodCallExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression) IncorrectOperationException(com.intellij.util.IncorrectOperationException) GrOpenBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock) Nullable(org.jetbrains.annotations.Nullable)

Example 99 with GrStatement

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

the class AddGradleDslPluginActionHandler method invoke.

@Override
public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) {
    if (!EditorModificationUtil.checkModificationAllowed(editor))
        return;
    if (!FileModificationService.getInstance().preparePsiElementsForWrite(file))
        return;
    final JBList list = new JBList(myPlugins);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setCellRenderer(new MyListCellRenderer());
    Runnable runnable = () -> {
        final Pair selected = (Pair) list.getSelectedValue();
        new WriteCommandAction.Simple(project, GradleBundle.message("gradle.codeInsight.action.apply_plugin.text"), file) {

            @Override
            protected void run() {
                if (selected == null)
                    return;
                GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
                GrStatement grStatement = factory.createStatementFromText(String.format("apply plugin: '%s'", selected.first), null);
                PsiElement anchor = file.findElementAt(editor.getCaretModel().getOffset());
                PsiElement currentElement = PsiTreeUtil.getParentOfType(anchor, GrClosableBlock.class, GroovyFile.class);
                if (currentElement != null) {
                    currentElement.addAfter(grStatement, anchor);
                } else {
                    file.addAfter(grStatement, file.findElementAt(editor.getCaretModel().getOffset() - 1));
                }
                PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
                Document document = documentManager.getDocument(file);
                if (document != null) {
                    documentManager.commitDocument(document);
                }
            }
        }.execute();
    };
    if (ApplicationManager.getApplication().isUnitTestMode()) {
        Pair<String, String> descriptor = ContainerUtil.find(myPlugins, value -> value.first.equals(AddGradleDslPluginAction.TEST_THREAD_LOCAL.get()));
        list.setSelectedValue(descriptor, false);
        runnable.run();
    } else {
        JBPopupFactory.getInstance().createListPopupBuilder(list).setTitle(GradleBundle.message("gradle.codeInsight.action.apply_plugin.popup.title")).setItemChoosenCallback(runnable).setFilteringEnabled(o -> String.valueOf(((Pair) o).first)).createPopup().showInBestPositionFor(editor);
    }
}
Also used : GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) JBList(com.intellij.ui.components.JBList) Document(com.intellij.openapi.editor.Document) PsiElement(com.intellij.psi.PsiElement) Pair(com.intellij.openapi.util.Pair) GrStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement) PsiDocumentManager(com.intellij.psi.PsiDocumentManager)

Example 100 with GrStatement

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

the class CreateLocalVariableFromUsageFix method processIntention.

@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException {
    final PsiFile file = element.getContainingFile();
    PsiClassType type = JavaPsiFacade.getInstance(project).getElementFactory().createTypeByFQClassName("Object", GlobalSearchScope.allScope(project));
    GrVariableDeclaration decl = GroovyPsiElementFactory.getInstance(project).createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, "", type, myRefExpression.getReferenceName());
    int offset = myRefExpression.getTextRange().getStartOffset();
    GrStatement anchor = findAnchor(file, offset);
    TypeConstraint[] constraints = GroovyExpectedTypesProvider.calculateTypeConstraints(myRefExpression);
    if (myRefExpression.equals(anchor)) {
        decl = myRefExpression.replaceWithStatement(decl);
    } else {
        decl = myOwner.addVariableDeclarationBefore(decl, anchor);
    }
    GrTypeElement typeElement = decl.getTypeElementGroovy();
    assert typeElement != null;
    ChooseTypeExpression expr = new ChooseTypeExpression(constraints, PsiManager.getInstance(project), typeElement.getResolveScope());
    TemplateBuilderImpl builder = new TemplateBuilderImpl(decl);
    builder.replaceElement(typeElement, expr);
    decl = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(decl);
    Template template = builder.buildTemplate();
    Editor newEditor = positionCursor(project, myOwner.getContainingFile(), decl);
    TextRange range = decl.getTextRange();
    newEditor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
    TemplateManager manager = TemplateManager.getInstance(project);
    manager.startTemplate(newEditor, template);
}
Also used : GrTypeElement(org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement) TextRange(com.intellij.openapi.util.TextRange) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint) ChooseTypeExpression(org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression) GrStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement) Template(com.intellij.codeInsight.template.Template) GrVariableDeclaration(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint) TemplateManager(com.intellij.codeInsight.template.TemplateManager) Editor(com.intellij.openapi.editor.Editor)

Aggregations

GrStatement (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement)113 PsiElement (com.intellij.psi.PsiElement)36 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)26 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)22 GrOpenBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock)21 GrIfStatement (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrIfStatement)17 TextRange (com.intellij.openapi.util.TextRange)14 Nullable (org.jetbrains.annotations.Nullable)14 GrBlockStatement (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrBlockStatement)13 NotNull (org.jetbrains.annotations.NotNull)12 GrReturnStatement (org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement)12 GrMethod (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)12 GrStatementOwner (org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner)11 GrVariable (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable)10 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)10 GrVariableDeclaration (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration)9 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)9 GrAssignmentExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression)8 GrMethodCallExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression)8 Document (com.intellij.openapi.editor.Document)6