Search in sources :

Example 1 with TypeConstraint

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

the class GrInplaceVariableIntroducer method addAdditionalVariables.

@Override
protected void addAdditionalVariables(TemplateBuilderImpl builder) {
    GrVariable variable = getVariable();
    assert variable != null && variable.getInitializerGroovy() != null;
    final PsiType initializerType = variable.getInitializerGroovy().getType();
    TypeConstraint[] constraints = initializerType != null && !initializerType.equals(PsiType.NULL) ? new SupertypeConstraint[] { SupertypeConstraint.create(initializerType) } : TypeConstraint.EMPTY_ARRAY;
    ChooseTypeExpression typeExpression = new ChooseTypeExpression(constraints, variable.getManager(), variable.getResolveScope(), true, GroovyApplicationSettings.getInstance().INTRODUCE_LOCAL_SELECT_DEF);
    PsiElement element = getTypeELementOrDef(variable);
    if (element == null)
        return;
    builder.replaceElement(element, "Variable_type", typeExpression, true, true);
}
Also used : GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint) ChooseTypeExpression(org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression) PsiElement(com.intellij.psi.PsiElement) PsiType(com.intellij.psi.PsiType)

Example 2 with TypeConstraint

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

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

the class CreateMethodFromUsageFix method setupParams.

@NotNull
private ChooseTypeExpression[] setupParams(@NotNull PsiMethod method, @NotNull PsiType[] argTypes, @NotNull JVMElementFactory factory) {
    final PsiParameterList parameterList = method.getParameterList();
    ChooseTypeExpression[] paramTypesExpressions = new ChooseTypeExpression[argTypes.length];
    for (int i = 0; i < argTypes.length; i++) {
        PsiType argType = TypesUtil.unboxPrimitiveTypeWrapper(argTypes[i]);
        if (argType == null || argType == PsiType.NULL)
            argType = TypesUtil.getJavaLangObject(getRefExpr());
        final PsiParameter p = factory.createParameter("o", argType);
        parameterList.add(p);
        TypeConstraint[] constraints = { SupertypeConstraint.create(argType) };
        boolean isGroovy = method.getLanguage() == GroovyLanguage.INSTANCE;
        paramTypesExpressions[i] = new ChooseTypeExpression(constraints, method.getManager(), method.getResolveScope(), isGroovy);
    }
    return paramTypesExpressions;
}
Also used : TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint) ChooseTypeExpression(org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint) SupertypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.SupertypeConstraint) NotNull(org.jetbrains.annotations.NotNull)

Example 4 with TypeConstraint

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

the class CreateMethodFromUsageFix method invokeImpl.

@Override
protected void invokeImpl(Project project, @NotNull PsiClass targetClass) {
    final JVMElementFactory factory = JVMElementFactories.getFactory(targetClass.getLanguage(), targetClass.getProject());
    assert factory != null;
    PsiMethod method = factory.createMethod(getMethodName(), PsiType.VOID);
    final GrReferenceExpression ref = getRefExpr();
    if (GrStaticChecker.isInStaticContext(ref, targetClass)) {
        method.getModifierList().setModifierProperty(PsiModifier.STATIC, true);
    }
    PsiType[] argTypes = getArgumentTypes();
    assert argTypes != null;
    ChooseTypeExpression[] paramTypesExpressions = setupParams(method, argTypes, factory);
    TypeConstraint[] constraints = getReturnTypeConstraints();
    final PsiGenerationInfo<PsiMethod> info = OverrideImplementUtil.createGenerationInfo(method);
    info.insert(targetClass, findInsertionAnchor(info, targetClass), false);
    method = info.getPsiMember();
    if (shouldBeAbstract(targetClass)) {
        method.getBody().delete();
        if (!targetClass.isInterface()) {
            method.getModifierList().setModifierProperty(PsiModifier.ABSTRACT, true);
        }
    }
    final PsiElement context = PsiTreeUtil.getParentOfType(ref, PsiClass.class, PsiMethod.class, PsiFile.class);
    IntentionUtils.createTemplateForMethod(argTypes, paramTypesExpressions, method, targetClass, constraints, false, context);
}
Also used : TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint) ChooseTypeExpression(org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)

Example 5 with TypeConstraint

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

the class GroovySmartCompletionContributor method addExpectedClassMembers.

static void addExpectedClassMembers(CompletionParameters params, final CompletionResultSet result) {
    for (final TypeConstraint info : getExpectedTypeInfos(params)) {
        Consumer<LookupElement> consumer = element -> result.addElement(element);
        PsiType type = info.getType();
        PsiType defType = info.getDefaultType();
        boolean searchInheritors = params.getInvocationCount() > 1;
        if (type instanceof PsiClassType) {
            new GroovyMembersGetter((PsiClassType) type, params).processMembers(searchInheritors, consumer);
        }
        if (!defType.equals(type) && defType instanceof PsiClassType) {
            new GroovyMembersGetter((PsiClassType) defType, params).processMembers(searchInheritors, consumer);
        }
    }
}
Also used : TypeConversionUtil(com.intellij.psi.util.TypeConversionUtil) Arrays(java.util.Arrays) IElementType(com.intellij.psi.tree.IElementType) Document(com.intellij.openapi.editor.Document) THashSet(gnu.trove.THashSet) GrReferenceElement(org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement) GrLiteral(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral) AfterNewClassInsertHandler(org.jetbrains.plugins.groovy.lang.completion.handlers.AfterNewClassInsertHandler) TailType(com.intellij.codeInsight.TailType) PlatformPatterns(com.intellij.patterns.PlatformPatterns) TObjectHashingStrategy(gnu.trove.TObjectHashingStrategy) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) ScrollType(com.intellij.openapi.editor.ScrollType) SmartList(com.intellij.util.SmartList) TypeInferenceHelper(org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeInferenceHelper) FeatureUsageTracker(com.intellij.featureStatistics.FeatureUsageTracker) GrStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement) GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) CodeStyleSettings(com.intellij.psi.codeStyle.CodeStyleSettings) PsiTypeLookupItem(com.intellij.codeInsight.lookup.PsiTypeLookupItem) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GroovyTokenTypes(org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes) ProcessingContext(com.intellij.util.ProcessingContext) GrAnnotationNameValuePair(org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair) GroovyConfigUtils(org.jetbrains.plugins.groovy.config.GroovyConfigUtils) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint) LookupElement(com.intellij.codeInsight.lookup.LookupElement) ChooseTypeExpression(org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) Set(java.util.Set) StandardPatterns(com.intellij.patterns.StandardPatterns) GrVariableDeclaration(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration) CodeStyleSettingsManager(com.intellij.psi.codeStyle.CodeStyleSettingsManager) Editor(com.intellij.openapi.editor.Editor) ElementPattern(com.intellij.patterns.ElementPattern) GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) com.intellij.codeInsight.completion(com.intellij.codeInsight.completion) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) GrAnnotation(org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation) org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions) com.intellij.psi(com.intellij.psi) GroovyExpectedTypesProvider(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider) NotNull(org.jetbrains.annotations.NotNull) Consumer(com.intellij.util.Consumer) PsiUtil(org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint) LookupElement(com.intellij.codeInsight.lookup.LookupElement)

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