Search in sources :

Example 11 with GrClosableBlock

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

the class GroovyIntroduceParameterUtil method generateDelegate.

public static GrMethod generateDelegate(PsiMethod prototype, IntroduceParameterData.ExpressionWrapper initializer, Project project) {
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
    GrMethod result;
    if (prototype instanceof GrMethod) {
        result = (GrMethod) prototype.copy();
    } else {
        StringBuilder builder = new StringBuilder();
        builder.append(prototype.getModifierList().getText()).append(' ');
        if (prototype.getReturnTypeElement() != null) {
            builder.append(prototype.getReturnTypeElement().getText());
        }
        builder.append(' ').append(prototype.getName());
        builder.append(prototype.getParameterList().getText());
        builder.append("{}");
        result = factory.createMethodFromText(builder.toString());
    }
    StringBuilder call = new StringBuilder();
    call.append("def foo(){\n");
    final GrParameter[] parameters = result.getParameters();
    call.append(prototype.getName());
    if (initializer.getExpression() instanceof GrClosableBlock) {
        if (parameters.length > 0) {
            call.append('(');
            for (GrParameter parameter : parameters) {
                call.append(parameter.getName()).append(", ");
            }
            call.replace(call.length() - 2, call.length(), ")");
        }
        call.append(initializer.getText());
    } else {
        call.append('(');
        for (GrParameter parameter : parameters) {
            call.append(parameter.getName()).append(", ");
        }
        call.append(initializer.getText());
        call.append(")");
    }
    call.append("\n}");
    final GrOpenBlock block = factory.createMethodFromText(call.toString()).getBlock();
    result.getBlock().replace(block);
    final PsiElement parent = prototype.getParent();
    final GrMethod method = (GrMethod) parent.addBefore(result, prototype);
    JavaCodeStyleManager.getInstance(method.getProject()).shortenClassReferences(method);
    return method;
}
Also used : GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GrOpenBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)

Example 12 with GrClosableBlock

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

the class ClosureCompleter method runClosureTemplate.

private static boolean runClosureTemplate(InsertionContext context, Document document, int offset, PsiSubstitutor substitutor, PsiMethod method, final List<ClosureParameterInfo> parameters) {
    document.insertString(offset, "{\n}");
    PsiDocumentManager.getInstance(context.getProject()).commitDocument(document);
    final GrClosableBlock closure = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), offset + 1, GrClosableBlock.class, false);
    if (closure == null)
        return false;
    runTemplate(parameters, closure, substitutor, method, context.getProject(), context.getEditor());
    return true;
}
Also used : GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)

Example 13 with GrClosableBlock

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

the class ClosureCompleter method runTemplate.

public static void runTemplate(List<ClosureParameterInfo> parameters, GrClosableBlock block, PsiSubstitutor substitutor, PsiMethod method, final Project project, final Editor editor) {
    if (method instanceof ClsMethodImpl)
        method = ((ClsMethodImpl) method).getSourceMirrorMethod();
    assert block.getArrow() == null;
    if (parameters.isEmpty())
        return;
    StringBuilder buffer = new StringBuilder();
    buffer.append("{");
    List<PsiType> paramTypes = ContainerUtil.newArrayList();
    for (ClosureParameterInfo parameter : parameters) {
        final String type = parameter.getType();
        final String name = parameter.getName();
        if (type != null) {
            final PsiType fromText = JavaPsiFacade.getElementFactory(project).createTypeFromText(type, method);
            final PsiType substituted = substitutor.substitute(fromText);
            paramTypes.add(substituted);
            buffer.append(substituted.getCanonicalText()).append(" ");
        } else {
            buffer.append("def ");
        }
        buffer.append(name);
        buffer.append(", ");
    }
    buffer.replace(buffer.length() - 2, buffer.length(), " ->}");
    final Document document = editor.getDocument();
    final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
    assert file != null;
    final GrClosableBlock closure = GroovyPsiElementFactory.getInstance(project).createClosureFromText(buffer.toString());
    final GrClosableBlock templateClosure = (GrClosableBlock) block.replaceWithExpression(closure, false);
    final TemplateBuilderImpl builder = new TemplateBuilderImpl(templateClosure);
    int i = 0;
    for (GrParameter p : templateClosure.getParameters()) {
        final GrTypeElement typeElement = p.getTypeElementGroovy();
        final PsiElement nameIdentifier = p.getNameIdentifierGroovy();
        if (typeElement != null) {
            final TypeConstraint[] typeConstraints = { SupertypeConstraint.create(paramTypes.get(i++)) };
            final ChooseTypeExpression expression = new ChooseTypeExpression(typeConstraints, PsiManager.getInstance(project), nameIdentifier.getResolveScope());
            builder.replaceElement(typeElement, expression);
        } else {
            final ChooseTypeExpression expression = new ChooseTypeExpression(TypeConstraint.EMPTY_ARRAY, PsiManager.getInstance(project), nameIdentifier.getResolveScope());
            builder.replaceElement(p.getModifierList(), expression);
        }
        builder.replaceElement(nameIdentifier, new ParameterNameExpression(nameIdentifier.getText()));
    }
    final GrClosableBlock afterPostprocess = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(templateClosure);
    final Template template = builder.buildTemplate();
    TextRange range = afterPostprocess.getTextRange();
    document.deleteString(range.getStartOffset(), range.getEndOffset());
    TemplateEditingListener templateListener = new TemplateEditingAdapter() {

        @Override
        public void templateFinished(Template template, boolean brokenOff) {
            ApplicationManager.getApplication().runWriteAction(() -> {
                PsiDocumentManager.getInstance(project).commitDocument(document);
                final CaretModel caretModel = editor.getCaretModel();
                final int offset = caretModel.getOffset();
                GrClosableBlock block1 = PsiTreeUtil.findElementOfClassAtOffset(file, offset - 1, GrClosableBlock.class, false);
                if (block1 != null) {
                    final PsiElement arrow = block1.getArrow();
                    if (arrow != null) {
                        caretModel.moveToOffset(arrow.getTextRange().getEndOffset());
                    }
                    // fix space before closure lbrace
                    final TextRange range1 = block1.getTextRange();
                    CodeStyleManager.getInstance(project).reformatRange(block1.getParent(), range1.getStartOffset() - 1, range1.getEndOffset(), true);
                }
            });
        }
    };
    TemplateManager manager = TemplateManager.getInstance(project);
    manager.startTemplate(editor, template, templateListener);
}
Also used : GrTypeElement(org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement) CaretModel(com.intellij.openapi.editor.CaretModel) ClsMethodImpl(com.intellij.psi.impl.compiled.ClsMethodImpl) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) TextRange(com.intellij.openapi.util.TextRange) Document(com.intellij.openapi.editor.Document) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) SupertypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.SupertypeConstraint) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint) ChooseTypeExpression(org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression) ClosureParameterInfo(org.jetbrains.plugins.groovy.lang.completion.closureParameters.ClosureParameterInfo) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint) ParameterNameExpression(org.jetbrains.plugins.groovy.template.expressions.ParameterNameExpression)

Example 14 with GrClosableBlock

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

the class GdslClosureCompleter method getParameterInfos.

@Override
protected List<ClosureParameterInfo> getParameterInfos(InsertionContext context, PsiMethod method, PsiSubstitutor substitutor, PsiElement place) {
    final ArrayList<ClosureDescriptor> descriptors = new ArrayList<>();
    GrReferenceExpression ref = (GrReferenceExpression) place;
    PsiType qtype = PsiImplUtil.getQualifierType(ref);
    if (qtype == null)
        return null;
    GrExpression qualifier = ref.getQualifier();
    if (qualifier != null) {
        PsiType type = qualifier.getType();
        if (type == null)
            return null;
        processExecutors(qtype, ref, descriptors);
    } else {
        PsiElementFactory factory = JavaPsiFacade.getElementFactory(context.getProject());
        for (PsiElement parent = ref.getParent(); parent != null; parent = parent.getParent()) {
            if (parent instanceof GrClosableBlock) {
                processExecutors(TypesUtil.createTypeByFQClassName(GroovyCommonClassNames.GROOVY_LANG_CLOSURE, ref), ref, descriptors);
            } else if (parent instanceof GrTypeDefinition) {
                processExecutors(factory.createType(((GrTypeDefinition) parent), PsiType.EMPTY_ARRAY), ref, descriptors);
            }
        }
    }
    for (ClosureDescriptor descriptor : descriptors) {
        if (descriptor.isMethodApplicable(method, ref)) {
            return descriptor.getParameters();
        }
    }
    return null;
}
Also used : GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition) ArrayList(java.util.ArrayList) ClosureDescriptor(org.jetbrains.plugins.groovy.lang.completion.closureParameters.ClosureDescriptor) 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 15 with GrClosableBlock

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

the class ConvertClosureArgToItIntention method processIntention.

@Override
public void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException {
    final GrClosableBlock closure = (GrClosableBlock) element;
    final GrParameterList parameterList = closure.getParameterList();
    final GrParameter parameter = parameterList.getParameters()[0];
    final Set<GrReferenceExpression> referencesToChange = new HashSet<>();
    final GroovyRecursiveElementVisitor visitor = new GroovyRecursiveElementVisitor() {

        @Override
        public void visitReferenceExpression(@NotNull GrReferenceExpression referenceExpression) {
            super.visitReferenceExpression(referenceExpression);
            if (!referenceExpression.getText().equals(parameter.getName())) {
                return;
            }
            final PsiElement referent = referenceExpression.resolve();
            if (parameter.equals(referent)) {
                referencesToChange.add(referenceExpression);
            }
        }
    };
    closure.accept(visitor);
    parameter.delete();
    for (GrReferenceExpression referenceExpression : referencesToChange) {
        PsiImplUtil.replaceExpression("it", referenceExpression);
    }
}
Also used : GrParameterList(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) NotNull(org.jetbrains.annotations.NotNull) PsiElement(com.intellij.psi.PsiElement) HashSet(java.util.HashSet) 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