Search in sources :

Example 6 with ExpectedTypeInfo

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

the class FunctionalExpressionCompletionProvider method addFunctionalVariants.

static void addFunctionalVariants(@NotNull CompletionParameters parameters, boolean smart, boolean addInheritors, CompletionResultSet result) {
    if (!PsiUtil.isLanguageLevel8OrHigher(parameters.getOriginalFile()) || !isLambdaContext(parameters.getPosition()))
        return;
    ExpectedTypeInfo[] expectedTypes = JavaSmartCompletionContributor.getExpectedTypes(parameters);
    for (ExpectedTypeInfo expectedType : expectedTypes) {
        final PsiType defaultType = expectedType.getDefaultType();
        if (LambdaUtil.isFunctionalType(defaultType)) {
            final PsiType functionalInterfaceType = FunctionalInterfaceParameterizationUtil.getGroundTargetType(defaultType);
            final PsiMethod functionalInterfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(functionalInterfaceType);
            if (functionalInterfaceMethod != null) {
                PsiParameter[] params = PsiParameter.EMPTY_ARRAY;
                final PsiElement originalPosition = parameters.getPosition();
                final PsiSubstitutor substitutor = LambdaUtil.getSubstitutor(functionalInterfaceMethod, PsiUtil.resolveGenericsClassInType(functionalInterfaceType));
                if (!functionalInterfaceMethod.hasTypeParameters()) {
                    params = functionalInterfaceMethod.getParameterList().getParameters();
                    final Project project = functionalInterfaceMethod.getProject();
                    final JVMElementFactory jvmElementFactory = JVMElementFactories.getFactory(originalPosition.getLanguage(), project);
                    final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
                    if (jvmElementFactory != null) {
                        params = GenerateMembersUtil.overriddenParameters(params, jvmElementFactory, javaCodeStyleManager, substitutor, originalPosition);
                    }
                    String paramsString = params.length == 1 ? getParamName(params[0], originalPosition) : "(" + StringUtil.join(params, parameter -> getParamName(parameter, originalPosition), ",") + ")";
                    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
                    PsiLambdaExpression lambdaExpression = (PsiLambdaExpression) JavaPsiFacade.getElementFactory(project).createExpressionFromText(paramsString + " -> {}", null);
                    lambdaExpression = (PsiLambdaExpression) codeStyleManager.reformat(lambdaExpression);
                    paramsString = lambdaExpression.getParameterList().getText();
                    final LookupElementBuilder builder = LookupElementBuilder.create(functionalInterfaceMethod, paramsString + " -> ").withPresentableText(paramsString + " -> {}").withTypeText(functionalInterfaceType.getPresentableText()).withIcon(AllIcons.Nodes.Function);
                    LookupElement lambdaElement = builder.withAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
                    result.addElement(smart ? lambdaElement : PrioritizedLookupElement.withPriority(lambdaElement, 1));
                }
                addMethodReferenceVariants(smart, addInheritors, parameters, result.getPrefixMatcher(), functionalInterfaceType, functionalInterfaceMethod, params, originalPosition, substitutor, element -> result.addElement(smart ? JavaSmartCompletionContributor.decorate(element, Arrays.asList(expectedTypes)) : element));
            }
        }
    }
}
Also used : TypeConversionUtil(com.intellij.psi.util.TypeConversionUtil) java.util(java.util) AllIcons(com.intellij.icons.AllIcons) JBIterable(com.intellij.util.containers.JBIterable) ExpectedTypeInfo(com.intellij.codeInsight.ExpectedTypeInfo) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) Comparing(com.intellij.openapi.util.Comparing) Project(com.intellij.openapi.project.Project) JavaResolveUtil(com.intellij.psi.impl.source.resolve.JavaResolveUtil) PsiUtil(com.intellij.psi.util.PsiUtil) ProcessingContext(com.intellij.util.ProcessingContext) LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder) LookupElement(com.intellij.codeInsight.lookup.LookupElement) StringUtil(com.intellij.openapi.util.text.StringUtil) GenerateMembersUtil(com.intellij.codeInsight.generation.GenerateMembersUtil) AutoCompletionPolicy(com.intellij.codeInsight.lookup.AutoCompletionPolicy) MethodReferenceResolver(com.intellij.psi.impl.source.tree.java.MethodReferenceResolver) Nullable(org.jetbrains.annotations.Nullable) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) FunctionalInterfaceParameterizationUtil(com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil) ObjectUtils(com.intellij.util.ObjectUtils) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) Consumer(com.intellij.util.Consumer) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) LookupElement(com.intellij.codeInsight.lookup.LookupElement) Project(com.intellij.openapi.project.Project) ExpectedTypeInfo(com.intellij.codeInsight.ExpectedTypeInfo) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder)

Example 7 with ExpectedTypeInfo

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

the class SmartCastProvider method addCastVariants.

static void addCastVariants(@NotNull CompletionParameters parameters, PrefixMatcher matcher, @NotNull Consumer<LookupElement> result) {
    if (!shouldSuggestCast(parameters))
        return;
    PsiElement position = parameters.getPosition();
    PsiElement parenthesisOwner = getParenthesisOwner(position);
    final boolean insideCast = parenthesisOwner instanceof PsiTypeCastExpression;
    if (insideCast) {
        PsiElement parent = parenthesisOwner.getParent();
        if (parent instanceof PsiParenthesizedExpression) {
            if (parent.getParent() instanceof PsiReferenceExpression) {
                for (ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes((PsiParenthesizedExpression) parent, false)) {
                    result.consume(PsiTypeLookupItem.createLookupItem(info.getType(), parent));
                }
            }
            ExpectedTypeInfo info = getParenthesizedCastExpectationByOperandType(position);
            if (info != null) {
                addHierarchyTypes(parameters, matcher, info, type -> result.consume(PsiTypeLookupItem.createLookupItem(type, parent)));
            }
            return;
        }
    }
    for (final ExpectedTypeInfo info : JavaSmartCompletionContributor.getExpectedTypes(parameters)) {
        PsiType type = info.getDefaultType();
        if (type instanceof PsiWildcardType) {
            type = ((PsiWildcardType) type).getBound();
        }
        if (type == null || PsiType.VOID.equals(type)) {
            continue;
        }
        if (type instanceof PsiPrimitiveType) {
            final PsiType castedType = getCastedExpressionType(parenthesisOwner);
            if (castedType != null && !(castedType instanceof PsiPrimitiveType)) {
                final PsiClassType boxedType = ((PsiPrimitiveType) type).getBoxedType(position);
                if (boxedType != null) {
                    type = boxedType;
                }
            }
        }
        result.consume(createSmartCastElement(parameters, insideCast, type));
    }
}
Also used : ExpectedTypeInfo(com.intellij.codeInsight.ExpectedTypeInfo)

Example 8 with ExpectedTypeInfo

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

the class TypeSelectorManagerImpl method getTypesForAll.

protected PsiType[] getTypesForAll(final boolean areTypesDirected) {
    final ArrayList<ExpectedTypeInfo[]> expectedTypesFromAll = new ArrayList<>();
    for (PsiExpression occurrence : myOccurrences) {
        final ExpectedTypeInfo[] expectedTypes = ExpectedTypesProvider.getExpectedTypes(occurrence, false, myOccurrenceClassProvider, isUsedAfter());
        if (expectedTypes.length > 0) {
            expectedTypesFromAll.add(expectedTypes);
        }
    }
    final ArrayList<PsiType> allowedTypes = new ArrayList<>();
    RefactoringHierarchyUtil.processSuperTypes(getDefaultType(), new RefactoringHierarchyUtil.SuperTypeVisitor() {

        @Override
        public void visitType(PsiType aType) {
            checkIfAllowed(aType);
        }

        @Override
        public void visitClass(PsiClass aClass) {
            checkIfAllowed(myFactory.createType(aClass));
        }

        private void checkIfAllowed(PsiType type) {
            NextInfo: for (ExpectedTypeInfo[] expectedTypes : expectedTypesFromAll) {
                for (final ExpectedTypeInfo info : expectedTypes) {
                    if (ExpectedTypeUtil.matches(type, info))
                        continue NextInfo;
                }
                return;
            }
            allowedTypes.add(type);
        }
    });
    for (ExpectedTypeInfo[] typeInfos : expectedTypesFromAll) {
        collectAllSameShapedTypes(typeInfos, allowedTypes);
    }
    final ArrayList<PsiType> result = normalizeTypeList(allowedTypes);
    if (!areTypesDirected) {
        Collections.reverse(result);
    }
    return result.toArray(PsiType.createArray(result.size()));
}
Also used : ExpectedTypeInfo(com.intellij.codeInsight.ExpectedTypeInfo) RefactoringHierarchyUtil(com.intellij.refactoring.util.RefactoringHierarchyUtil)

Example 9 with ExpectedTypeInfo

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

the class CreateFieldFromUsageFix method invokeImpl.

@Override
protected void invokeImpl(final PsiClass targetClass) {
    final Project project = myReferenceExpression.getProject();
    JVMElementFactory factory = JVMElementFactories.getFactory(targetClass.getLanguage(), project);
    if (factory == null)
        factory = JavaPsiFacade.getElementFactory(project);
    PsiMember enclosingContext = null;
    PsiClass parentClass;
    do {
        enclosingContext = PsiTreeUtil.getParentOfType(enclosingContext == null ? myReferenceExpression : enclosingContext, PsiMethod.class, PsiField.class, PsiClassInitializer.class);
        parentClass = enclosingContext == null ? null : enclosingContext.getContainingClass();
    } while (parentClass instanceof PsiAnonymousClass);
    ExpectedTypeInfo[] expectedTypes = CreateFromUsageUtils.guessExpectedTypes(myReferenceExpression, false);
    String fieldName = myReferenceExpression.getReferenceName();
    assert fieldName != null;
    PsiField field = factory.createField(fieldName, PsiType.INT);
    if (createConstantField()) {
        PsiUtil.setModifierProperty(field, PsiModifier.FINAL, true);
    }
    if (createConstantField()) {
        PsiUtil.setModifierProperty(field, PsiModifier.STATIC, true);
        PsiUtil.setModifierProperty(field, PsiModifier.FINAL, true);
    } else {
        if (!targetClass.isInterface() && shouldCreateStaticMember(myReferenceExpression, targetClass)) {
            PsiUtil.setModifierProperty(field, PsiModifier.STATIC, true);
        }
        if (shouldCreateFinalMember(myReferenceExpression, targetClass)) {
            PsiUtil.setModifierProperty(field, PsiModifier.FINAL, true);
        }
    }
    field = CreateFieldFromUsageHelper.insertField(targetClass, field, myReferenceExpression);
    setupVisibility(parentClass, targetClass, field.getModifierList());
    createFieldFromUsageTemplate(targetClass, project, expectedTypes, field, createConstantField(), myReferenceExpression);
}
Also used : Project(com.intellij.openapi.project.Project) ExpectedTypeInfo(com.intellij.codeInsight.ExpectedTypeInfo)

Example 10 with ExpectedTypeInfo

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

the class GuessTypeParameters method setupTypeElement.

public void setupTypeElement(PsiTypeElement typeElement, ExpectedTypeInfo[] infos, PsiSubstitutor substitutor, TemplateBuilder builder, @Nullable PsiElement context, PsiClass targetClass) {
    LOG.assertTrue(typeElement.isValid());
    ApplicationManager.getApplication().assertWriteAccessAllowed();
    PsiManager manager = typeElement.getManager();
    GlobalSearchScope scope = typeElement.getResolveScope();
    Project project = manager.getProject();
    if (infos.length == 1 && substitutor != null && substitutor != PsiSubstitutor.EMPTY) {
        ExpectedTypeInfo info = infos[0];
        Map<PsiTypeParameter, PsiType> map = substitutor.getSubstitutionMap();
        PsiType[] vals = map.values().toArray(PsiType.createArray(map.size()));
        PsiTypeParameter[] params = map.keySet().toArray(new PsiTypeParameter[map.size()]);
        List<PsiType> types = matchingTypeParameters(vals, params, info);
        if (!types.isEmpty()) {
            ContainerUtil.addAll(types, ExpectedTypesProvider.processExpectedTypes(infos, new MyTypeVisitor(manager, scope), project));
            builder.replaceElement(typeElement, new TypeExpression(project, types.toArray(PsiType.createArray(types.size()))));
            return;
        } else {
            PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
            PsiType type = info.getType();
            PsiType defaultType = info.getDefaultType();
            try {
                PsiTypeElement inplaceTypeElement = ((PsiVariable) factory.createVariableDeclarationStatement("foo", type, null).getDeclaredElements()[0]).getTypeElement();
                PsiSubstitutor rawingSubstitutor = getRawingSubstitutor(context, targetClass);
                int substitionResult = substituteToTypeParameters(typeElement, inplaceTypeElement, vals, params, builder, rawingSubstitutor, true);
                if (substitionResult != SUBSTITUTED_NONE) {
                    if (substitionResult == SUBSTITUTED_IN_PARAMETERS) {
                        PsiJavaCodeReferenceElement refElement = typeElement.getInnermostComponentReferenceElement();
                        LOG.assertTrue(refElement != null && refElement.getReferenceNameElement() != null);
                        type = getComponentType(type);
                        LOG.assertTrue(type != null);
                        defaultType = getComponentType(defaultType);
                        LOG.assertTrue(defaultType != null);
                        ExpectedTypeInfo info1 = ExpectedTypesProvider.createInfo(((PsiClassType) defaultType).rawType(), ExpectedTypeInfo.TYPE_STRICTLY, ((PsiClassType) defaultType).rawType(), info.getTailType());
                        MyTypeVisitor visitor = new MyTypeVisitor(manager, scope);
                        builder.replaceElement(refElement.getReferenceNameElement(), new TypeExpression(project, ExpectedTypesProvider.processExpectedTypes(new ExpectedTypeInfo[] { info1 }, visitor, project)));
                    }
                    return;
                }
            } catch (IncorrectOperationException e) {
                LOG.error(e);
            }
        }
    }
    PsiType[] types = infos.length == 0 ? new PsiType[] { typeElement.getType() } : ExpectedTypesProvider.processExpectedTypes(infos, new MyTypeVisitor(manager, scope), project);
    builder.replaceElement(typeElement, new TypeExpression(project, types));
}
Also used : TypeExpression(com.intellij.codeInsight.intention.impl.TypeExpression) Project(com.intellij.openapi.project.Project) ExpectedTypeInfo(com.intellij.codeInsight.ExpectedTypeInfo) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

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