Search in sources :

Example 86 with GrClosableBlock

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock 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 87 with GrClosableBlock

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

the class EachToForIntention method updateReturnStatements.

private static GrForStatement updateReturnStatements(GrForStatement forStatement) {
    GrStatement body = forStatement.getBody();
    assert body != null;
    final Set<String> usedLabels = ContainerUtil.newHashSet();
    final Ref<Boolean> needLabel = Ref.create(false);
    body.accept(new GroovyRecursiveElementVisitor() {

        private int myLoops = 0;

        @Override
        public void visitReturnStatement(@NotNull GrReturnStatement returnStatement) {
            if (returnStatement.getReturnValue() != null)
                return;
            if (myLoops > 0)
                needLabel.set(true);
        }

        @Override
        public void visitLabeledStatement(@NotNull GrLabeledStatement labeledStatement) {
            super.visitLabeledStatement(labeledStatement);
            usedLabels.add(labeledStatement.getName());
        }

        @Override
        public void visitForStatement(@NotNull GrForStatement forStatement) {
            myLoops++;
            super.visitForStatement(forStatement);
            myLoops--;
        }

        @Override
        public void visitWhileStatement(@NotNull GrWhileStatement whileStatement) {
            myLoops++;
            super.visitWhileStatement(whileStatement);
            myLoops--;
        }

        @Override
        public void visitClosure(@NotNull GrClosableBlock closure) {
        //don't go into closures
        }

        @Override
        public void visitAnonymousClassDefinition(@NotNull GrAnonymousClassDefinition anonymousClassDefinition) {
        //don't go into anonymous
        }
    });
    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(forStatement.getProject());
    final String continueText;
    if (needLabel.get()) {
        int i = 0;
        String label = OUTER;
        while (usedLabels.contains(label)) {
            label = OUTER + i;
            i++;
        }
        continueText = "continue " + label;
        GrLabeledStatement labeled = (GrLabeledStatement) factory.createStatementFromText(label + ": while (true){}");
        labeled.getStatement().replaceWithStatement(forStatement);
        labeled = forStatement.replaceWithStatement(labeled);
        forStatement = (GrForStatement) labeled.getStatement();
        body = forStatement.getBody();
        assert body != null;
    } else {
        continueText = "continue";
    }
    final GrStatement continueStatement = factory.createStatementFromText(continueText);
    body.accept(new GroovyRecursiveElementVisitor() {

        @Override
        public void visitReturnStatement(@NotNull GrReturnStatement returnStatement) {
            if (returnStatement.getReturnValue() == null) {
                returnStatement.replaceWithStatement(continueStatement);
            }
        }

        @Override
        public void visitClosure(@NotNull GrClosableBlock closure) {
        //don't go into closures
        }

        @Override
        public void visitAnonymousClassDefinition(@NotNull GrAnonymousClassDefinition anonymousClassDefinition) {
        //don't go into anonymous
        }
    });
    return forStatement;
}
Also used : GrAnonymousClassDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) GrReturnStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)

Example 88 with GrClosableBlock

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

the class EachToForIntention method processIntention.

@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException {
    final GrMethodCallExpression expression = (GrMethodCallExpression) element;
    final GrClosableBlock block = expression.getClosureArguments()[0];
    final GrParameterList parameterList = block.getParameterList();
    final GrParameter[] parameters = parameterList.getParameters();
    String var;
    if (parameters.length == 1) {
        var = parameters[0].getText();
        var = StringUtil.replace(var, GrModifier.DEF, "");
    } else {
        var = "it";
    }
    final GrExpression invokedExpression = expression.getInvokedExpression();
    GrExpression qualifier = ((GrReferenceExpression) invokedExpression).getQualifierExpression();
    final GroovyPsiElementFactory elementFactory = GroovyPsiElementFactory.getInstance(element.getProject());
    if (qualifier == null) {
        qualifier = elementFactory.createExpressionFromText("this");
    }
    StringBuilder builder = new StringBuilder();
    builder.append("for (").append(var).append(" in ").append(qualifier.getText()).append(") {\n");
    String text = block.getText();
    final PsiElement blockArrow = block.getArrow();
    int index;
    if (blockArrow != null) {
        index = blockArrow.getStartOffsetInParent() + blockArrow.getTextLength();
    } else {
        index = 1;
    }
    while (index < text.length() && Character.isWhitespace(text.charAt(index))) index++;
    text = text.substring(index, text.length() - 1);
    builder.append(text);
    builder.append("}");
    final GrStatement statement = elementFactory.createStatementFromText(builder.toString());
    GrForStatement forStatement = (GrForStatement) expression.replaceWithStatement(statement);
    final GrForClause clause = forStatement.getClause();
    GrVariable variable = clause.getDeclaredVariable();
    forStatement = updateReturnStatements(forStatement);
    if (variable == null)
        return;
    if (ApplicationManager.getApplication().isUnitTestMode())
        return;
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    final Document doc = documentManager.getDocument(element.getContainingFile());
    if (doc == null)
        return;
    documentManager.doPostponedOperationsAndUnblockDocument(doc);
    editor.getCaretModel().moveToOffset(variable.getTextOffset());
    new VariableInplaceRenamer(variable, editor).performInplaceRename();
}
Also used : GrParameterList(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) Document(com.intellij.openapi.editor.Document) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrMethodCallExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression) GrForClause(org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForClause) VariableInplaceRenamer(com.intellij.refactoring.rename.inplace.VariableInplaceRenamer) PsiElement(com.intellij.psi.PsiElement) PsiDocumentManager(com.intellij.psi.PsiDocumentManager)

Example 89 with GrClosableBlock

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

the class MakeClosureCallImplicitIntention method processIntention.

@Override
public void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException {
    final GrMethodCallExpression expression = (GrMethodCallExpression) element;
    final GrReferenceExpression invokedExpression = (GrReferenceExpression) expression.getInvokedExpression();
    final GrExpression qualifier = invokedExpression.getQualifierExpression();
    final GrArgumentList argList = expression.getArgumentList();
    final GrClosableBlock[] closureArgs = expression.getClosureArguments();
    final StringBuilder newExpression = new StringBuilder();
    newExpression.append(qualifier.getText());
    newExpression.append(argList.getText());
    for (GrClosableBlock closureArg : closureArgs) {
        newExpression.append(closureArg.getText());
    }
    PsiImplUtil.replaceExpression(newExpression.toString(), expression);
}
Also used : GrMethodCallExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression) GrArgumentList(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)

Example 90 with GrClosableBlock

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

Aggregations

GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)116 PsiElement (com.intellij.psi.PsiElement)32 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)31 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)26 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)26 Nullable (org.jetbrains.annotations.Nullable)23 GrParameter (org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)23 GrMethod (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)18 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)17 GrArgumentList (org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList)15 GrMethodCallExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression)15 GrNamedArgument (org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument)14 GrMethodCall (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall)13 GrField (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField)12 ArrayList (java.util.ArrayList)11 NotNull (org.jetbrains.annotations.NotNull)10 GroovyRecursiveElementVisitor (org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor)10 GroovyResolveResult (org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult)10 GrOpenBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock)10 GroovyFile (org.jetbrains.plugins.groovy.lang.psi.GroovyFile)9