Search in sources :

Example 11 with TypeConstraint

use of org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint in project intellij-community by JetBrains.

the class ExpressionGenerator method visitLiteralExpression.

@Override
public //doesn't visit GrString and regexps
void visitLiteralExpression(@NotNull GrLiteral literal) {
    final TypeConstraint[] constraints = GroovyExpectedTypesProvider.calculateTypeConstraints(literal);
    boolean isChar = false;
    for (TypeConstraint constraint : constraints) {
        if (constraint instanceof SubtypeConstraint && PsiType.CHAR.equals(TypesUtil.unboxPrimitiveTypeWrapper(constraint.getDefaultType()))) {
            isChar = true;
        }
    }
    final String text = literal.getText();
    if (text.startsWith("'''") || text.startsWith("\"\"\"")) {
        String string = GrStringUtil.removeQuotes(text).replace("\n", "\\n").replace("\r", "\\r");
        builder.append('"').append(string).append('"');
    } else if (text.startsWith("'")) {
        if (isChar) {
            builder.append(text);
        } else {
            builder.append('"').append(StringUtil.escapeQuotes(StringUtil.trimEnd(text.substring(1, text.length()), "'"))).append('"');
        }
    } else if (text.startsWith("\"")) {
        if (isChar) {
            builder.append('\'').append(StringUtil.escapeQuotes(StringUtil.trimEnd(text.substring(1, text.length()), "\""))).append('\'');
        } else {
            builder.append(text);
        }
    } else {
        builder.append(text);
    }
}
Also used : SubtypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.SubtypeConstraint) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint) GrString(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString)

Example 12 with TypeConstraint

use of org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint 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)

Example 13 with TypeConstraint

use of org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint in project intellij-community by JetBrains.

the class ChooseTypeExpression method createItems.

@NotNull
private static List<SmartTypePointer> createItems(@NotNull TypeConstraint[] constraints, @NotNull SmartTypePointerManager typePointerManager) {
    List<SmartTypePointer> result = ContainerUtil.newArrayList();
    for (TypeConstraint constraint : constraints) {
        if (constraint instanceof SubtypeConstraint) {
            PsiType type = constraint.getDefaultType();
            result.add(typePointerManager.createSmartTypePointer(type));
        } else if (constraint instanceof SupertypeConstraint) {
            processSuperTypes(constraint.getType(), result, typePointerManager);
        }
    }
    return result;
}
Also used : SubtypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.SubtypeConstraint) SupertypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.SupertypeConstraint) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint) NotNull(org.jetbrains.annotations.NotNull)

Example 14 with TypeConstraint

use of org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint in project intellij-community by JetBrains.

the class GrSetStrongTypeIntention method processIntention.

@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, final Editor editor) throws IncorrectOperationException {
    PsiElement parent = element.getParent();
    PsiElement elementToBuildTemplate;
    GrVariable[] variables;
    if (parent instanceof GrVariable && parent.getParent() instanceof GrVariableDeclaration) {
        variables = ((GrVariableDeclaration) parent.getParent()).getVariables();
        elementToBuildTemplate = parent.getParent();
    } else if (parent instanceof GrVariable && parent.getParent() instanceof GrForInClause) {
        variables = new GrVariable[] { (GrVariable) parent };
        elementToBuildTemplate = parent.getParent().getParent();
    } else if (parent instanceof GrVariableDeclaration) {
        variables = ((GrVariableDeclaration) parent).getVariables();
        elementToBuildTemplate = parent;
    } else if (parent instanceof GrParameter && parent.getParent() instanceof GrParameterList) {
        variables = new GrVariable[] { (GrVariable) parent };
        elementToBuildTemplate = parent.getParent().getParent();
    } else if (parent instanceof GrVariable) {
        variables = new GrVariable[] { ((GrVariable) parent) };
        elementToBuildTemplate = parent;
    } else {
        return;
    }
    ArrayList<TypeConstraint> types = new ArrayList<>();
    if (parent.getParent() instanceof GrForInClause) {
        types.add(SupertypeConstraint.create(PsiUtil.extractIteratedType((GrForInClause) parent.getParent())));
    } else {
        for (GrVariable variable : variables) {
            GrExpression initializer = variable.getInitializerGroovy();
            if (initializer != null) {
                PsiType type = initializer.getType();
                if (type != null) {
                    types.add(SupertypeConstraint.create(type));
                }
            }
            if (variable instanceof GrParameter) {
                final PsiParameter parameter = (PsiParameter) variable;
                final PsiType type = getClosureParameterType(parameter);
                if (type != null) {
                    types.add(SupertypeConstraint.create(type));
                }
            }
        }
    }
    final String originalText = elementToBuildTemplate.getText();
    final TypeInfo typeInfo = getOrCreateTypeElement(parent, elementToBuildTemplate);
    final PsiElement replaceElement = typeInfo.elementToReplace;
    TypeConstraint[] constraints = types.toArray(new TypeConstraint[types.size()]);
    ChooseTypeExpression chooseTypeExpression = new ChooseTypeExpression(constraints, element.getManager(), replaceElement.getResolveScope());
    TemplateBuilderImpl builder = new TemplateBuilderImpl(elementToBuildTemplate);
    builder.replaceElement(replaceElement, chooseTypeExpression);
    final Document document = editor.getDocument();
    final RangeMarker rangeMarker = document.createRangeMarker(elementToBuildTemplate.getTextRange());
    rangeMarker.setGreedyToRight(true);
    rangeMarker.setGreedyToLeft(true);
    final PsiElement afterPostprocess = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(elementToBuildTemplate);
    final Template template = builder.buildTemplate();
    TextRange range = afterPostprocess.getTextRange();
    document.deleteString(range.getStartOffset(), range.getEndOffset());
    TemplateManager templateManager = TemplateManager.getInstance(project);
    templateManager.startTemplate(editor, template, new TemplateEditingAdapter() {

        @Override
        public void templateFinished(Template template, boolean brokenOff) {
            if (brokenOff) {
                ApplicationManager.getApplication().runWriteAction(() -> {
                    if (rangeMarker.isValid()) {
                        document.replaceString(rangeMarker.getStartOffset(), rangeMarker.getEndOffset(), originalText);
                        editor.getCaretModel().moveToOffset(rangeMarker.getStartOffset() + typeInfo.originalOffset);
                    }
                });
            }
        }
    });
}
Also used : GrParameterList(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList) ArrayList(java.util.ArrayList) GrParameter(org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter) Document(com.intellij.openapi.editor.Document) ChooseTypeExpression(org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression) Template(com.intellij.codeInsight.template.Template) GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) TemplateManager(com.intellij.codeInsight.template.TemplateManager) PsiElement(com.intellij.psi.PsiElement) PsiType(com.intellij.psi.PsiType) TemplateEditingAdapter(com.intellij.codeInsight.template.TemplateEditingAdapter) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) TextRange(com.intellij.openapi.util.TextRange) RangeMarker(com.intellij.openapi.editor.RangeMarker) GrVariableDeclaration(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration) PsiParameter(com.intellij.psi.PsiParameter) GrForInClause(org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForInClause) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint)

Aggregations

TypeConstraint (org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint)14 ChooseTypeExpression (org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression)10 TextRange (com.intellij.openapi.util.TextRange)5 NotNull (org.jetbrains.annotations.NotNull)4 SupertypeConstraint (org.jetbrains.plugins.groovy.lang.psi.expectedTypes.SupertypeConstraint)4 Template (com.intellij.codeInsight.template.Template)3 TemplateBuilderImpl (com.intellij.codeInsight.template.TemplateBuilderImpl)3 Document (com.intellij.openapi.editor.Document)3 Editor (com.intellij.openapi.editor.Editor)3 PsiType (com.intellij.psi.PsiType)3 GrVariable (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable)3 GrVariableDeclaration (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration)3 TemplateManager (com.intellij.codeInsight.template.TemplateManager)2 Project (com.intellij.openapi.project.Project)2 com.intellij.psi (com.intellij.psi)2 PsiElement (com.intellij.psi.PsiElement)2 List (java.util.List)2 GroovyResolveResult (org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult)2 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)2 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)2