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));
}
}
}
}
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));
}
}
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()));
}
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);
}
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));
}
Aggregations