Search in sources :

Example 1 with ParameterNameExpression

use of org.jetbrains.plugins.groovy.template.expressions.ParameterNameExpression 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 2 with ParameterNameExpression

use of org.jetbrains.plugins.groovy.template.expressions.ParameterNameExpression in project intellij-community by JetBrains.

the class IntentionUtils method createTemplateForMethod.

public static void createTemplateForMethod(PsiType[] argTypes, ChooseTypeExpression[] paramTypesExpressions, PsiMethod method, PsiClass owner, TypeConstraint[] constraints, boolean isConstructor, @NotNull final PsiElement context) {
    final Project project = owner.getProject();
    PsiTypeElement typeElement = method.getReturnTypeElement();
    ChooseTypeExpression expr = new ChooseTypeExpression(constraints, PsiManager.getInstance(project), context.getResolveScope(), method.getLanguage() == GroovyLanguage.INSTANCE);
    TemplateBuilderImpl builder = new TemplateBuilderImpl(method);
    if (!isConstructor) {
        assert typeElement != null;
        builder.replaceElement(typeElement, expr);
    }
    PsiParameter[] parameters = method.getParameterList().getParameters();
    assert parameters.length == argTypes.length;
    for (int i = 0; i < parameters.length; i++) {
        PsiParameter parameter = parameters[i];
        PsiTypeElement parameterTypeElement = parameter.getTypeElement();
        builder.replaceElement(parameterTypeElement, paramTypesExpressions[i]);
        builder.replaceElement(parameter.getNameIdentifier(), new ParameterNameExpression(null));
    }
    PsiCodeBlock body = method.getBody();
    if (body != null) {
        PsiElement lbrace = body.getLBrace();
        assert lbrace != null;
        builder.setEndVariableAfter(lbrace);
    } else {
        builder.setEndVariableAfter(method.getParameterList());
    }
    method = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(method);
    Template template = builder.buildTemplate();
    final PsiFile targetFile = owner.getContainingFile();
    final Editor newEditor = positionCursor(project, targetFile, method);
    TextRange range = method.getTextRange();
    newEditor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
    TemplateManager manager = TemplateManager.getInstance(project);
    TemplateEditingListener templateListener = new TemplateEditingAdapter() {

        @Override
        public void templateFinished(Template template, boolean brokenOff) {
            ApplicationManager.getApplication().runWriteAction(() -> {
                PsiDocumentManager.getInstance(project).commitDocument(newEditor.getDocument());
                final int offset = newEditor.getCaretModel().getOffset();
                PsiMethod method1 = PsiTreeUtil.findElementOfClassAtOffset(targetFile, offset - 1, PsiMethod.class, false);
                if (context instanceof PsiMethod) {
                    final PsiTypeParameter[] typeParameters = ((PsiMethod) context).getTypeParameters();
                    if (typeParameters.length > 0) {
                        for (PsiTypeParameter typeParameter : typeParameters) {
                            if (CreateMethodFromUsageFix.checkTypeParam(method1, typeParameter)) {
                                final JVMElementFactory factory = JVMElementFactories.getFactory(method1.getLanguage(), method1.getProject());
                                PsiTypeParameterList list = method1.getTypeParameterList();
                                if (list == null) {
                                    PsiTypeParameterList newList = factory.createTypeParameterList();
                                    list = (PsiTypeParameterList) method1.addAfter(newList, method1.getModifierList());
                                }
                                list.add(factory.createTypeParameter(typeParameter.getName(), typeParameter.getExtendsList().getReferencedTypes()));
                            }
                        }
                    }
                }
                if (method1 != null) {
                    try {
                        final boolean hasNoReturnType = method1.getReturnTypeElement() == null && method1 instanceof GrMethod;
                        if (hasNoReturnType) {
                            ((GrMethod) method1).setReturnType(PsiType.VOID);
                        }
                        if (method1.getBody() != null) {
                            FileTemplateManager templateManager = FileTemplateManager.getInstance(project);
                            FileTemplate fileTemplate = templateManager.getCodeTemplate(GroovyTemplates.GROOVY_FROM_USAGE_METHOD_BODY);
                            PsiClass containingClass = method1.getContainingClass();
                            LOG.assertTrue(!containingClass.isInterface() || GrTraitUtil.isTrait(containingClass), "Interface bodies should be already set up");
                            CreateFromUsageUtils.setupMethodBody(method1, containingClass, fileTemplate);
                        }
                        if (hasNoReturnType) {
                            ((GrMethod) method1).setReturnType(null);
                        }
                    } catch (IncorrectOperationException e) {
                        LOG.error(e);
                    }
                    CreateFromUsageUtils.setupEditor(method1, newEditor);
                }
            });
        }
    };
    manager.startTemplate(newEditor, template, templateListener);
}
Also used : FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) ChooseTypeExpression(org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression) FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) FileTemplateManager(com.intellij.ide.fileTemplates.FileTemplateManager) FileTemplateManager(com.intellij.ide.fileTemplates.FileTemplateManager) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) TextRange(com.intellij.openapi.util.TextRange) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint) Project(com.intellij.openapi.project.Project) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Editor(com.intellij.openapi.editor.Editor) ParameterNameExpression(org.jetbrains.plugins.groovy.template.expressions.ParameterNameExpression)

Aggregations

TextRange (com.intellij.openapi.util.TextRange)2 TypeConstraint (org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint)2 ChooseTypeExpression (org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression)2 ParameterNameExpression (org.jetbrains.plugins.groovy.template.expressions.ParameterNameExpression)2 FileTemplate (com.intellij.ide.fileTemplates.FileTemplate)1 FileTemplateManager (com.intellij.ide.fileTemplates.FileTemplateManager)1 CaretModel (com.intellij.openapi.editor.CaretModel)1 Document (com.intellij.openapi.editor.Document)1 Editor (com.intellij.openapi.editor.Editor)1 Project (com.intellij.openapi.project.Project)1 ClsMethodImpl (com.intellij.psi.impl.compiled.ClsMethodImpl)1 IncorrectOperationException (com.intellij.util.IncorrectOperationException)1 ClosureParameterInfo (org.jetbrains.plugins.groovy.lang.completion.closureParameters.ClosureParameterInfo)1 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)1 GrParameter (org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)1 GrMethod (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)1 GrTypeElement (org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement)1 SupertypeConstraint (org.jetbrains.plugins.groovy.lang.psi.expectedTypes.SupertypeConstraint)1