Search in sources :

Example 21 with ExpectedTypeInfo

use of com.intellij.codeInsight.ExpectedTypeInfo in project intellij-community by JetBrains.

the class AbstractExpectedTypeSkipper method getSkippingStatus.

private static Result getSkippingStatus(final LookupElement item, final CompletionLocation location) {
    if (location.getCompletionType() != CompletionType.SMART)
        return Result.ACCEPT;
    final PsiExpression expression = PsiTreeUtil.getParentOfType(location.getCompletionParameters().getPosition(), PsiExpression.class);
    if (!(expression instanceof PsiNewExpression))
        return Result.ACCEPT;
    final Object object = item.getObject();
    if (!(object instanceof PsiClass))
        return Result.ACCEPT;
    if (StatisticsManager.getInstance().getUseCount(StatisticsWeigher.getBaseStatisticsInfo(item, location)) > 1)
        return Result.ACCEPT;
    PsiClass psiClass = (PsiClass) object;
    int toImplement = 0;
    for (final PsiMethod method : psiClass.getMethods()) {
        if (method.hasModifierProperty(PsiModifier.ABSTRACT)) {
            toImplement++;
            if (toImplement > 2)
                return Result.ABSTRACT;
        }
    }
    toImplement += OverrideImplementUtil.getMethodSignaturesToImplement(psiClass).size();
    if (toImplement > 2)
        return Result.ABSTRACT;
    final ExpectedTypeInfo[] infos = JavaCompletionUtil.EXPECTED_TYPES.getValue(location);
    boolean isDefaultType = false;
    if (infos != null) {
        final PsiType type = JavaPsiFacade.getInstance(psiClass.getProject()).getElementFactory().createType(psiClass);
        for (final ExpectedTypeInfo info : infos) {
            final PsiType infoType = TypeConversionUtil.erasure(info.getType().getDeepComponentType());
            final PsiType defaultType = TypeConversionUtil.erasure(info.getDefaultType().getDeepComponentType());
            if (!defaultType.equals(infoType) && infoType.isAssignableFrom(type)) {
                if (!defaultType.isAssignableFrom(type))
                    return Result.NON_DEFAULT;
                isDefaultType = true;
            }
        }
    }
    if (toImplement > 0)
        return Result.ACCEPT;
    if (psiClass.hasModifierProperty(PsiModifier.ABSTRACT))
        return Result.ABSTRACT;
    if (!isDefaultType && CommonClassNames.JAVA_LANG_STRING.equals(psiClass.getQualifiedName()))
        return Result.STRING;
    if (CommonClassNames.JAVA_LANG_OBJECT.equals(psiClass.getQualifiedName()))
        return Result.NON_DEFAULT;
    return Result.ACCEPT;
}
Also used : ExpectedTypeInfo(com.intellij.codeInsight.ExpectedTypeInfo)

Example 22 with ExpectedTypeInfo

use of com.intellij.codeInsight.ExpectedTypeInfo in project intellij-community by JetBrains.

the class CollectConversion method addCollectConversion.

static void addCollectConversion(PsiReferenceExpression ref, Collection<ExpectedTypeInfo> expectedTypes, Consumer<LookupElement> consumer) {
    final PsiExpression qualifier = ref.getQualifierExpression();
    PsiType component = qualifier == null ? null : PsiUtil.substituteTypeParameter(qualifier.getType(), JAVA_UTIL_STREAM_STREAM, 0, true);
    if (component == null)
        return;
    JavaPsiFacade facade = JavaPsiFacade.getInstance(ref.getProject());
    PsiElementFactory factory = facade.getElementFactory();
    GlobalSearchScope scope = ref.getResolveScope();
    PsiClass list = facade.findClass(JAVA_UTIL_LIST, scope);
    PsiClass set = facade.findClass(JAVA_UTIL_SET, scope);
    PsiClass collection = facade.findClass(JAVA_UTIL_COLLECTION, scope);
    if (facade.findClass(JAVA_UTIL_STREAM_COLLECTORS, scope) == null || list == null || set == null || collection == null)
        return;
    PsiType listType = null;
    PsiType setType = null;
    boolean hasIterable = false;
    for (ExpectedTypeInfo info : expectedTypes) {
        PsiType type = info.getDefaultType();
        PsiClass expectedClass = PsiUtil.resolveClassInClassTypeOnly(type);
        PsiType expectedComponent = PsiUtil.extractIterableTypeParameter(type, true);
        if (expectedClass == null || expectedComponent == null || !TypeConversionUtil.isAssignable(expectedComponent, component))
            continue;
        hasIterable = true;
        if (InheritanceUtil.isInheritorOrSelf(list, expectedClass, true)) {
            listType = type;
        }
        if (InheritanceUtil.isInheritorOrSelf(set, expectedClass, true)) {
            setType = type;
        }
    }
    if (expectedTypes.isEmpty()) {
        listType = factory.createType(list, component);
        setType = factory.createType(set, component);
    }
    if (listType != null) {
        consumer.consume(new MyLookupElement("toList", listType, ref));
    }
    if (setType != null) {
        consumer.consume(new MyLookupElement("toSet", setType, ref));
    }
    if (expectedTypes.isEmpty() || hasIterable) {
        consumer.consume(new MyLookupElement("toCollection", factory.createType(collection, component), ref));
    }
}
Also used : ExpectedTypeInfo(com.intellij.codeInsight.ExpectedTypeInfo) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope)

Example 23 with ExpectedTypeInfo

use of com.intellij.codeInsight.ExpectedTypeInfo in project intellij-community by JetBrains.

the class MagicCompletionContributor method addCompletionVariants.

private static void addCompletionVariants(@NotNull final CompletionParameters parameters, @NotNull final CompletionResultSet result, PsiElement pos, MagicConstantInspection.AllowedValues allowedValues) {
    final Set<PsiElement> allowed = new THashSet<>(new TObjectHashingStrategy<PsiElement>() {

        @Override
        public int computeHashCode(PsiElement object) {
            return 0;
        }

        @Override
        public boolean equals(PsiElement o1, PsiElement o2) {
            return parameters.getOriginalFile().getManager().areElementsEquivalent(o1, o2);
        }
    });
    if (allowedValues.canBeOred) {
        PsiElementFactory factory = JavaPsiFacade.getElementFactory(pos.getProject());
        PsiExpression zero = factory.createExpressionFromText("0", pos);
        result.addElement(PrioritizedLookupElement.withPriority(LookupElementBuilder.create(zero, "0"), PRIORITY - 1));
        PsiExpression minusOne = factory.createExpressionFromText("-1", pos);
        result.addElement(PrioritizedLookupElement.withPriority(LookupElementBuilder.create(minusOne, "-1"), PRIORITY - 1));
        allowed.add(zero);
        allowed.add(minusOne);
    }
    List<ExpectedTypeInfo> types = Arrays.asList(JavaSmartCompletionContributor.getExpectedTypes(parameters));
    for (PsiAnnotationMemberValue value : allowedValues.values) {
        if (value instanceof PsiReference) {
            PsiElement resolved = ((PsiReference) value).resolve();
            if (resolved instanceof PsiNamedElement) {
                LookupElement lookupElement = LookupItemUtil.objectToLookupItem(resolved);
                if (lookupElement instanceof VariableLookupItem) {
                    ((VariableLookupItem) lookupElement).setSubstitutor(PsiSubstitutor.EMPTY);
                }
                LookupElement element = PrioritizedLookupElement.withPriority(lookupElement, PRIORITY);
                element = decorate(parameters, types, element);
                result.addElement(element);
                allowed.add(resolved);
                continue;
            }
        }
        LookupElement element = LookupElementBuilder.create(value, value.getText());
        element = decorate(parameters, types, element);
        result.addElement(element);
        allowed.add(value);
    }
    result.runRemainingContributors(parameters, completionResult -> {
        LookupElement element = completionResult.getLookupElement();
        Object object = element.getObject();
        if (object instanceof PsiElement && allowed.contains(object)) {
            return;
        }
        result.passResult(completionResult);
    });
}
Also used : LookupElement(com.intellij.codeInsight.lookup.LookupElement) THashSet(gnu.trove.THashSet) ExpectedTypeInfo(com.intellij.codeInsight.ExpectedTypeInfo) VariableLookupItem(com.intellij.codeInsight.lookup.VariableLookupItem)

Example 24 with ExpectedTypeInfo

use of com.intellij.codeInsight.ExpectedTypeInfo in project intellij-community by JetBrains.

the class GroovyCreateFieldFromUsageHelper method setupTemplateImpl.

@Override
public Template setupTemplateImpl(PsiField f, Object expectedTypes, PsiClass targetClass, Editor editor, PsiElement context, boolean createConstantField, PsiSubstitutor substitutor) {
    GrVariableDeclaration fieldDecl = (GrVariableDeclaration) f.getParent();
    GrField field = (GrField) fieldDecl.getVariables()[0];
    TemplateBuilderImpl builder = new TemplateBuilderImpl(fieldDecl);
    Project project = context.getProject();
    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
    if (expectedTypes instanceof TypeConstraint[]) {
        GrTypeElement typeElement = fieldDecl.getTypeElementGroovy();
        assert typeElement != null;
        ChooseTypeExpression expr = new ChooseTypeExpression((TypeConstraint[]) expectedTypes, PsiManager.getInstance(project), typeElement.getResolveScope());
        builder.replaceElement(typeElement, expr);
    } else if (expectedTypes instanceof ExpectedTypeInfo[]) {
        new GuessTypeParameters(factory).setupTypeElement(field.getTypeElement(), (ExpectedTypeInfo[]) expectedTypes, substitutor, builder, context, targetClass);
    }
    if (createConstantField) {
        field.setInitializerGroovy(factory.createExpressionFromText("0", null));
        builder.replaceElement(field.getInitializerGroovy(), new EmptyExpression());
    }
    fieldDecl = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(fieldDecl);
    Template template = builder.buildTemplate();
    TextRange range = fieldDecl.getTextRange();
    editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
    if (expectedTypes instanceof ExpectedTypeInfo[]) {
        if (((ExpectedTypeInfo[]) expectedTypes).length > 1)
            template.setToShortenLongNames(false);
    }
    return template;
}
Also used : GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) GrTypeElement(org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement) GuessTypeParameters(com.intellij.codeInsight.daemon.impl.quickfix.GuessTypeParameters) TextRange(com.intellij.openapi.util.TextRange) ChooseTypeExpression(org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression) EmptyExpression(com.intellij.codeInsight.daemon.impl.quickfix.EmptyExpression) Template(com.intellij.codeInsight.template.Template) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrVariableDeclaration(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration) Project(com.intellij.openapi.project.Project) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) ExpectedTypeInfo(com.intellij.codeInsight.ExpectedTypeInfo) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint)

Aggregations

ExpectedTypeInfo (com.intellij.codeInsight.ExpectedTypeInfo)24 Project (com.intellij.openapi.project.Project)6 NotNull (org.jetbrains.annotations.NotNull)5 ExpectedTypeInfoImpl (com.intellij.codeInsight.ExpectedTypeInfoImpl)4 LookupElement (com.intellij.codeInsight.lookup.LookupElement)4 THashSet (gnu.trove.THashSet)3 Nullable (org.jetbrains.annotations.Nullable)3 TailType (com.intellij.codeInsight.TailType)2 Template (com.intellij.codeInsight.template.Template)2 TemplateBuilderImpl (com.intellij.codeInsight.template.TemplateBuilderImpl)2 com.intellij.psi (com.intellij.psi)2 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)2 PsiTreeUtil (com.intellij.psi.util.PsiTreeUtil)2 PsiUtil (com.intellij.psi.util.PsiUtil)2 Consumer (com.intellij.util.Consumer)2 ProcessingContext (com.intellij.util.ProcessingContext)2 QuickFixBundle (com.intellij.codeInsight.daemon.QuickFixBundle)1 EmptyExpression (com.intellij.codeInsight.daemon.impl.quickfix.EmptyExpression)1 GuessTypeParameters (com.intellij.codeInsight.daemon.impl.quickfix.GuessTypeParameters)1 GenerateMembersUtil (com.intellij.codeInsight.generation.GenerateMembersUtil)1