[FE 1.0] Resolve constructor calls through the new type inference infra

^KT-48961 In progress
This commit is contained in:
Victor Petukhov
2022-06-01 12:37:11 +02:00
committed by teamcity
parent e66cc9a639
commit 0070c234ce
4 changed files with 95 additions and 102 deletions
@@ -6,7 +6,6 @@
package org.jetbrains.kotlin.resolve.calls;
import com.intellij.psi.PsiElement;
import kotlin.Pair;
import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -17,7 +16,6 @@ import org.jetbrains.kotlin.config.LanguageFeature;
import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl;
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory0;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.progress.ProgressIndicatorAndCompilationCanceledStatus;
@@ -309,7 +307,8 @@ public class CallResolver {
callResolutionContext,
Collections.singletonList(descriptor),
tracingStrategy,
substitutor
substitutor,
null
);
}
@@ -354,7 +353,7 @@ public class CallResolver {
NewResolutionOldInference.ResolutionKind.Function.INSTANCE);
}
else if (calleeExpression instanceof KtConstructorCalleeExpression) {
return (OverloadResolutionResults) resolveCallForConstructor(context, (KtConstructorCalleeExpression) calleeExpression);
return (OverloadResolutionResults) resolveConstructorCall(context, (KtConstructorCalleeExpression) calleeExpression);
}
else if (calleeExpression instanceof KtConstructorDelegationReferenceExpression) {
KtConstructorDelegationCall delegationCall = (KtConstructorDelegationCall) context.call.getCallElement();
@@ -393,7 +392,7 @@ public class CallResolver {
return resolveCallForInvoke(context.replaceCall(call), tracingForInvoke);
}
private OverloadResolutionResults<ConstructorDescriptor> resolveCallForConstructor(
public OverloadResolutionResults<ConstructorDescriptor> resolveConstructorCall(
@NotNull BasicCallResolutionContext context,
@NotNull KtConstructorCalleeExpression expression
) {
@@ -427,22 +426,27 @@ public class CallResolver {
return checkArgumentTypesAndFail(context);
}
return resolveConstructorCall(context, functionReference, constructedType);
return resolveTypeParametersAwaringConstructorCall(context, constructedType, TracingStrategyImpl.create(functionReference, context.call));
}
@NotNull
public OverloadResolutionResults<ConstructorDescriptor> resolveConstructorCall(
public OverloadResolutionResults<ConstructorDescriptor> resolveTypeParametersAwaringConstructorCall(
@NotNull BasicCallResolutionContext context,
@NotNull KtReferenceExpression functionReference,
@NotNull KotlinType constructedType
@NotNull KotlinType constructedType,
@NotNull TracingStrategy tracingStrategy
) {
Pair<Collection<OldResolutionCandidate<ConstructorDescriptor>>, BasicCallResolutionContext> candidatesAndContext =
prepareCandidatesAndContextForConstructorCall(constructedType, context, syntheticScopes);
// If any constructor has type parameter (currently it only can be true for ones from Java), try to infer arguments for them
// Otherwise use NO_EXPECTED_TYPE and known type substitutor
boolean anyConstructorHasDeclaredTypeParameters =
anyConstructorHasDeclaredTypeParameters(constructedType.getConstructor().getDeclarationDescriptor());
Collection<OldResolutionCandidate<ConstructorDescriptor>> candidates = candidatesAndContext.getFirst();
context = candidatesAndContext.getSecond();
if (anyConstructorHasDeclaredTypeParameters) {
context = context.replaceExpectedType(constructedType);
}
return computeTasksFromCandidatesAndResolvedCall(context, functionReference, candidates);
return CallResolverUtilKt.resolveConstructorCallWithGivenDescriptors(
PSICallResolver, context, constructedType, !anyConstructorHasDeclaredTypeParameters, syntheticScopes, tracingStrategy
);
}
@Nullable
@@ -492,11 +496,11 @@ public class CallResolver {
@NotNull
private OverloadResolutionResults<ConstructorDescriptor> resolveConstructorDelegationCall(
@NotNull BasicCallResolutionContext context,
@NotNull KtConstructorDelegationCall call,
@NotNull KtConstructorDelegationCall callElement,
@NotNull KtConstructorDelegationReferenceExpression calleeExpression,
@NotNull ClassDescriptor currentClassDescriptor
) {
context.trace.record(BindingContext.LEXICAL_SCOPE, call, context.scope);
context.trace.record(BindingContext.LEXICAL_SCOPE, callElement, context.scope);
boolean isThisCall = calleeExpression.isThis();
if (currentClassDescriptor.getKind() == ClassKind.ENUM_CLASS && !isThisCall) {
@@ -514,7 +518,7 @@ public class CallResolver {
PsiElement reportOn = calcReportOn(calleeExpression);
context.trace.report(PRIMARY_CONSTRUCTOR_DELEGATION_CALL_EXPECTED.on(reportOn));
}
if (call.isImplicit()) return OverloadResolutionResultsImpl.nameNotFound();
if (callElement.isImplicit()) return OverloadResolutionResultsImpl.nameNotFound();
}
if (constructors.isEmpty()) {
@@ -526,16 +530,14 @@ public class CallResolver {
KotlinType superType =
isThisCall ? currentClassDescriptor.getDefaultType() : DescriptorUtils.getSuperClassType(currentClassDescriptor);
Pair<Collection<OldResolutionCandidate<ConstructorDescriptor>>, BasicCallResolutionContext> candidatesAndContext =
prepareCandidatesAndContextForConstructorCall(superType, context, syntheticScopes);
Collection<OldResolutionCandidate<ConstructorDescriptor>> candidates = candidatesAndContext.getFirst();
context = candidatesAndContext.getSecond();
TracingStrategy tracing = call.isImplicit() ?
new TracingStrategyForImplicitConstructorDelegationCall(call, context.call) :
TracingStrategy tracingStrategy = callElement.isImplicit() ?
new TracingStrategyForImplicitConstructorDelegationCall(callElement, context.call) :
TracingStrategyImpl.create(calleeExpression, context.call);
PsiElement reportOn = call.isImplicit() ? call : calleeExpression;
OverloadResolutionResults<ConstructorDescriptor> resolutionResults =
resolveTypeParametersAwaringConstructorCall(context, superType, tracingStrategy);
PsiElement reportOn = callElement.isImplicit() ? callElement : calleeExpression;
if (delegateClassDescriptor.isInner()
&& !DescriptorResolver.checkHasOuterClassInstance(context.scope, context.trace, reportOn,
@@ -543,7 +545,7 @@ public class CallResolver {
return checkArgumentTypesAndFail(context);
}
return computeTasksFromCandidatesAndResolvedCall(context, candidates, tracing);
return resolutionResults;
}
@Nullable
@@ -552,33 +554,6 @@ public class CallResolver {
return CallResolverUtilKt.reportOnElement(delegationCall);
}
@NotNull
private static Pair<Collection<OldResolutionCandidate<ConstructorDescriptor>>, BasicCallResolutionContext> prepareCandidatesAndContextForConstructorCall(
@NotNull KotlinType superType,
@NotNull BasicCallResolutionContext context,
@NotNull SyntheticScopes syntheticScopes
) {
if (!(superType.getConstructor().getDeclarationDescriptor() instanceof ClassDescriptor)) {
return new Pair<>(Collections.<OldResolutionCandidate<ConstructorDescriptor>>emptyList(), context);
}
// If any constructor has type parameter (currently it only can be true for ones from Java), try to infer arguments for them
// Otherwise use NO_EXPECTED_TYPE and known type substitutor
boolean anyConstructorHasDeclaredTypeParameters =
anyConstructorHasDeclaredTypeParameters(superType.getConstructor().getDeclarationDescriptor());
if (anyConstructorHasDeclaredTypeParameters) {
context = context.replaceExpectedType(superType);
}
List<OldResolutionCandidate<ConstructorDescriptor>> candidates =
CallResolverUtilKt.createResolutionCandidatesForConstructors(
context.scope, context.call, superType, !anyConstructorHasDeclaredTypeParameters, syntheticScopes
);
return new Pair<>(candidates, context);
}
private static boolean anyConstructorHasDeclaredTypeParameters(@Nullable ClassifierDescriptor classDescriptor) {
if (!(classDescriptor instanceof ClassDescriptor)) return false;
for (ConstructorDescriptor constructor : ((ClassDescriptor) classDescriptor).getConstructors()) {
@@ -147,18 +147,19 @@ class PSICallResolver(
context: BasicCallResolutionContext,
descriptors: Collection<CallableDescriptor>,
tracingStrategy: TracingStrategy,
substitutor: TypeSubstitutor? = null
substitutor: TypeSubstitutor? = null,
receiver: ReceiverValueWithSmartCastInfo? = null
): OverloadResolutionResults<D> {
val isSpecialFunction = descriptors.any { it.name in SPECIAL_FUNCTION_NAMES }
val kotlinCall = toKotlinCall(
context, KotlinCallKind.FUNCTION, context.call, givenCandidatesName, tracingStrategy, isSpecialFunction, null
context, KotlinCallKind.FUNCTION, context.call, givenCandidatesName, tracingStrategy, isSpecialFunction, receiver?.receiverValue
)
val scopeTower = ASTScopeTower(context)
val resolutionCallbacks = createResolutionCallbacks(context)
val givenCandidates = descriptors.map {
GivenCandidate(
it,
dispatchReceiver = null,
dispatchReceiver = receiver,
knownTypeParametersResultingSubstitutor = substitutor
)
}
@@ -18,6 +18,7 @@ import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.lexer.KtToken
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.calls.CallTransformer
import org.jetbrains.kotlin.resolve.calls.components.KotlinResolutionCallbacks
@@ -31,8 +32,8 @@ import org.jetbrains.kotlin.resolve.calls.inference.components.NewTypeSubstituto
import org.jetbrains.kotlin.resolve.calls.inference.constraintPosition.ConstraintPositionKind.EXPECTED_TYPE_POSITION
import org.jetbrains.kotlin.resolve.calls.inference.getNestedTypeVariables
import org.jetbrains.kotlin.resolve.calls.model.*
import org.jetbrains.kotlin.resolve.calls.tasks.ExplicitReceiverKind
import org.jetbrains.kotlin.resolve.calls.tasks.OldResolutionCandidate
import org.jetbrains.kotlin.resolve.calls.results.OverloadResolutionResults
import org.jetbrains.kotlin.resolve.calls.tasks.TracingStrategy
import org.jetbrains.kotlin.resolve.calls.tower.*
import org.jetbrains.kotlin.resolve.descriptorUtil.isParameterOfAnnotation
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
@@ -43,10 +44,10 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValueWithSmartCastInfo
import org.jetbrains.kotlin.resolve.scopes.utils.getImplicitReceiversHierarchy
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.types.TypeUtils.DONT_CARE
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.error.ErrorScopeKind
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.types.typeUtil.contains
import org.jetbrains.kotlin.util.buildNotFixedVariablesToPossibleResultType
@@ -282,57 +283,73 @@ fun isArrayOrArrayLiteral(argument: ValueArgument, trace: BindingTrace): Boolean
return KotlinBuiltIns.isArrayOrPrimitiveArray(type)
}
fun createResolutionCandidatesForConstructors(
lexicalScope: LexicalScope,
call: Call,
typeWithConstructors: KotlinType,
useKnownTypeSubstitutor: Boolean,
private fun computeConstructorDescriptorsToResolveAndReceiver(
constructors: Collection<ConstructorDescriptor>,
containingClass: ClassDescriptor,
scope: LexicalScope,
substitutor: TypeSubstitutor?,
syntheticScopes: SyntheticScopes
): List<OldResolutionCandidate<ConstructorDescriptor>> {
val classWithConstructors = typeWithConstructors.constructor.declarationDescriptor as ClassDescriptor
val unwrappedType = typeWithConstructors.unwrap()
val knownSubstitutor =
if (useKnownTypeSubstitutor)
TypeSubstitutor.create(
(unwrappedType as? AbbreviatedType)?.abbreviation ?: unwrappedType
)
else null
val typeAliasDescriptor =
if (unwrappedType is AbbreviatedType)
unwrappedType.abbreviation.constructor.declarationDescriptor as? TypeAliasDescriptor
else
null
val constructors = typeAliasDescriptor?.constructors?.mapNotNull(TypeAliasConstructorDescriptor::withDispatchReceiver)
?: classWithConstructors.constructors
if (constructors.isEmpty()) return emptyList()
val receiverKind: ExplicitReceiverKind
val dispatchReceiver: ReceiverValue?
if (classWithConstructors.isInner) {
val outerClassType = (classWithConstructors.containingDeclaration as? ClassDescriptor)?.defaultType ?: return emptyList()
val substitutedOuterClassType = knownSubstitutor?.substitute(outerClassType, Variance.INVARIANT) ?: outerClassType
val receiver = lexicalScope.getImplicitReceiversHierarchy().firstOrNull {
): Pair<Collection<ConstructorDescriptor>, ReceiverValue?>? {
val dispatchReceiver: ReceiverValue? = if (containingClass.isInner) {
val outerClassType = (containingClass.containingDeclaration as? ClassDescriptor)?.defaultType ?: return null
val substitutedOuterClassType = substitutor?.substitute(outerClassType, Variance.INVARIANT) ?: outerClassType
val receiver = scope.getImplicitReceiversHierarchy().firstOrNull {
KotlinTypeChecker.DEFAULT.isSubtypeOf(it.type, substitutedOuterClassType)
} ?: return emptyList()
} ?: return null
receiverKind = ExplicitReceiverKind.DISPATCH_RECEIVER
dispatchReceiver = receiver.value
receiver.value
} else {
receiverKind = ExplicitReceiverKind.NO_EXPLICIT_RECEIVER
dispatchReceiver = null
null
}
val syntheticConstructors = constructors.flatMap { syntheticScopes.collectSyntheticConstructors(it) }
return (constructors + syntheticConstructors).map {
OldResolutionCandidate.create(call, it, dispatchReceiver, receiverKind, knownSubstitutor)
return constructors + syntheticConstructors to dispatchReceiver
}
fun resolveConstructorCallWithGivenDescriptors(
PSICallResolver: PSICallResolver,
context: BasicCallResolutionContext,
constructorType: KotlinType,
useKnownTypeSubstitutor: Boolean,
syntheticScopes: SyntheticScopes,
tracingStrategy: TracingStrategy
): OverloadResolutionResults<ConstructorDescriptor> {
val containingClass = constructorType.constructor.declarationDescriptor as ClassDescriptor
@Suppress("NAME_SHADOWING")
val constructorType = constructorType.unwrap()
val knownSubstitutor = if (useKnownTypeSubstitutor) {
TypeSubstitutor.create((constructorType as? AbbreviatedType)?.abbreviation ?: constructorType)
} else null
val typeAliasDescriptor = if (constructorType is AbbreviatedType) {
constructorType.abbreviation.constructor.declarationDescriptor as? TypeAliasDescriptor
} else null
val (constructors, receiver) = computeConstructorDescriptorsToResolveAndReceiver(
constructors = typeAliasDescriptor?.constructors?.mapNotNull(TypeAliasConstructorDescriptor::withDispatchReceiver)
?: containingClass.constructors,
containingClass,
context.scope,
knownSubstitutor,
syntheticScopes
) ?: (emptyList<ConstructorDescriptor>() to null)
val resolutionResults = PSICallResolver.runResolutionAndInferenceForGivenDescriptors<ConstructorDescriptor>(
context,
constructors,
tracingStrategy,
knownSubstitutor,
receiver?.let { context.transformToReceiverWithSmartCastInfo(it) }
)
if (resolutionResults.isSingleResult) {
context.trace.record(BindingContext.RESOLVED_CALL, context.call, resolutionResults.resultingCall)
context.trace.record(BindingContext.CALL, context.call.calleeExpression ?: context.call.callElement, context.call)
}
return resolutionResults
}
internal fun PsiElement.reportOnElement() =
@@ -2,6 +2,6 @@ class A {
open inner class Inner
class Nested : Inner {
<!INACCESSIBLE_OUTER_CLASS_EXPRESSION!>constructor()<!>
<!INACCESSIBLE_OUTER_CLASS_EXPRESSION!>constructor()<!><!UNRESOLVED_REFERENCE!><!>
}
}