Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 19 additions & 15 deletions packages/pyright-internal/src/analyzer/constructors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -510,30 +510,34 @@ function validateInitMethod(
inferenceContext ? { ...inferenceContext, returnTypeOverride } : undefined
);

let adjustedClassType = type;

// Overload evaluation keeps the ordinary __init__ return as a placeholder
// and carries argument-dependent constructed types through this separate field,
// including when union-expanded argument lists are combined.
if (
callResult.specializedInitSelfType &&
isClassInstance(callResult.specializedInitSelfType) &&
ClassType.isSameGenericClass(callResult.specializedInitSelfType, adjustedClassType)
) {
adjustedClassType = ClassType.cloneAsInstantiable(callResult.specializedInitSelfType);
}
const returnType = callResult.specializedInitSelfType
? mapSubtypes(callResult.specializedInitSelfType, (specializedInitSelfSubtype) => {
let adjustedClassType = type;
if (
isClassInstance(specializedInitSelfSubtype) &&
ClassType.isSameGenericClass(specializedInitSelfSubtype, adjustedClassType)
) {
adjustedClassType = ClassType.cloneAsInstantiable(specializedInitSelfSubtype);
}

if (
!type.priv.isTypeArgExplicit &&
(isAny(specializedInitSelfSubtype) || isUnknown(specializedInitSelfSubtype))
) {
return specializedInitSelfSubtype;
}

const returnType =
callResult.specializedInitSelfType &&
!type.priv.isTypeArgExplicit &&
(isAny(callResult.specializedInitSelfType) || isUnknown(callResult.specializedInitSelfType))
? callResult.specializedInitSelfType
: applyExpectedTypeForConstructor(
return applyExpectedTypeForConstructor(
evaluator,
adjustedClassType,
/* inferenceContext */ undefined,
constraints
);
})
: applyExpectedTypeForConstructor(evaluator, type, /* inferenceContext */ undefined, constraints);

if (callResult.isTypeIncomplete) {
isTypeIncomplete = true;
Expand Down
44 changes: 40 additions & 4 deletions packages/pyright-internal/src/analyzer/typeEvaluator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9947,11 +9947,14 @@ export function createTypeEvaluator(
let isTypeIncomplete = false;
const overloadsUsedForCall: FunctionType[] = [];
let isDefinitiveMatchFound = false;
let hasInitSelfMaterializationAmbiguity = false;
let hasEffectiveInitSelfType = false;
const speculativeNode = getSpeculativeNodeForCall(errorNode);

for (let expandedTypesIndex = 0; expandedTypesIndex < expandedArgTypes.length; expandedTypesIndex++) {
const overloadsUsedStartIndex = overloadsUsedForCall.length;
let matchedOverload: FunctionType | undefined;
let effectiveInitSelfType: Type | undefined;
const argTypeOverride = expandedArgTypes[expandedTypesIndex];
const hasArgTypeOverride = argTypeOverride.some((a) => a !== undefined);
let possibleMatchResults: MatchedOverloadInfo[] = [];
Expand Down Expand Up @@ -10021,6 +10024,7 @@ export function createTypeEvaluator(
}
} else {
returnTypes.push(callResult.returnType);
effectiveInitSelfType = getEffectiveInitSelfType(matchedOverloadInfo);
isDefinitiveMatchFound = true;
break;
}
Expand Down Expand Up @@ -10048,6 +10052,7 @@ export function createTypeEvaluator(
// Did the filtering produce a single result? If so, we're done.
if (possibleMatchResults.length === 1) {
returnTypes.push(possibleMatchResults[0].returnType);
effectiveInitSelfType = getEffectiveInitSelfType(possibleMatchResults[0]);
matchedOverloads = [possibleMatchResults[0]];
} else {
const firstArgParamPairs = getOverloadArgParamPairs(possibleMatchResults[0]);
Expand Down Expand Up @@ -10150,19 +10155,31 @@ export function createTypeEvaluator(
// combined, and carry the effective constructed types separately.
// validateInitMethod consumes specializedInitSelfType to reconstruct
// the constructor result after call validation is complete.
specializedInitSelfTypes.push(returnType);
effectiveInitSelfType = returnType;
hasInitSelfMaterializationAmbiguity = true;
returnTypes.push(possibleMatchResults[0].returnType);
} else {
returnTypes.push(returnType);
}
}
}

if (effectiveInitSelfType) {
specializedInitSelfTypes.push(effectiveInitSelfType);
hasEffectiveInitSelfType = true;
}

if (!matchedOverload) {
return { argumentErrors: true, isTypeIncomplete, overloadsUsedForCall };
}
}

// Union expansion requires one constructor handoff per expanded argument list.
// Materialization ambiguity requires a combined handoff even when there is only
// one argument list because multiple overload candidates contribute to its result.
const shouldCombineInitSelfTypes =
hasInitSelfMaterializationAmbiguity || (expandedArgTypes.length > 1 && hasEffectiveInitSelfType);

// We found a match for all of the expanded argument lists. Copy the
// resulting type var context back into the caller's type var context.
// Use the type var context from the last matched overload because it
Expand All @@ -10173,7 +10190,9 @@ export function createTypeEvaluator(

// And run through the first expanded argument list one more time to
// populate the type cache.
const finalConstraints = constraints ?? matchedOverloads[0].constraints;
const finalConstraints = shouldCombineInitSelfTypes
? matchedOverloads[0].constraints
: constraints ?? matchedOverloads[0].constraints;
const finalCallResult = validateArgTypesWithContext(
errorNode,
matchedOverloads[0].matchResults,
Expand All @@ -10192,7 +10211,7 @@ export function createTypeEvaluator(
returnType: combineTypes(returnTypes),
isTypeIncomplete,
specializedInitSelfType:
specializedInitSelfTypes.length > 0
specializedInitSelfTypes.length > 0 && shouldCombineInitSelfTypes
? combineTypes(specializedInitSelfTypes)
: finalCallResult.specializedInitSelfType,
overloadsUsedForCall,
Expand Down Expand Up @@ -10272,7 +10291,24 @@ export function createTypeEvaluator(
}

function getEffectiveOverloadReturnType(match: MatchedOverloadInfo): Type {
return match.specializedInitSelfType ?? match.returnType;
return getEffectiveInitSelfType(match) ?? match.returnType;
}

function getEffectiveInitSelfType(match: MatchedOverloadInfo): Type | undefined {
if (match.specializedInitSelfType) {
return match.specializedInitSelfType;
}
const boundToType = match.overload.priv.boundToType;
if (match.overload.shared.name === '__init__' && boundToType && isClassInstance(boundToType)) {
return solveAndApplyConstraints(boundToType, match.constraints, {
replaceUnsolved: {
scopeIds: getTypeVarScopeIds(boundToType),
tupleClassType: getTupleClassType(),
},
});
}

return undefined;
}

function getOverloadArgParamPairs(match: MatchedOverloadInfo): { argType: Type; paramType: Type }[] {
Expand Down
63 changes: 60 additions & 3 deletions packages/pyright-internal/src/tests/samples/overloadCall12.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,48 @@ def __init__(self, values: list[Any] | bytes) -> None:
pass


class AmbiguousTable(Generic[_T]):
@overload
def __init__(self: "AmbiguousTable[int]", values: list[int]) -> None: ...

@overload
def __init__(self: "AmbiguousTable[str]", values: list[str]) -> None: ...

@overload
def __init__(self: "AmbiguousTable[int]", values: set[int]) -> None: ...

@overload
def __init__(self: "AmbiguousTable[str]", values: set[str]) -> None: ...

def __init__(self, values: list[Any] | set[Any]) -> None:
pass


class PartiallySpecializedTable(Generic[_T]):
@overload
def __init__(self: "PartiallySpecializedTable[int]", values: list[int]) -> None: ...

@overload
def __init__(self: "PartiallySpecializedTable[str]", values: list[str]) -> None: ...

@overload
def __init__(self, values: set[_T]) -> None: ...

def __init__(self, values: list[Any] | set[Any]) -> None:
pass


class InferredTable(Generic[_T]):
@overload
def __init__(self, values: list[_T]) -> None: ...

@overload
def __init__(self, values: set[_T]) -> None: ...

def __init__(self, values: list[Any] | set[Any]) -> None:
pass


def check_constructors(values_any: list[Any], values_unknown: list, values_int: list[int]) -> None:
reveal_type(Table(values_any), expected_text="Any")
reveal_type(Table(values_unknown), expected_text="Unknown")
Expand All @@ -171,9 +213,24 @@ def check_constructors(values_any: list[Any], values_unknown: list, values_int:
Table[int](["bad"])


def check_constructor_union(values_any: list[Any] | bytes, values_unknown: list | bytes) -> None:
reveal_type(Table(values_any), expected_text="Any")
reveal_type(Table(values_unknown), expected_text="Unknown")
def check_constructor_union(
table: Table[Any],
values_any: list[Any] | bytes,
values_unknown: list | bytes,
values_int: list[int] | bytes,
values_gradual: list[Any] | set,
values_partially_specialized: list[Any] | set[float],
values_inferred: list[int] | set[str],
) -> None:
reveal_type(Table(values_any), expected_text="Any | Table[bytes]")
reveal_type(Table(values_unknown), expected_text="Unknown | Table[bytes]")
reveal_type(Table(values_int), expected_text="Table[int] | Table[bytes]")
reveal_type(AmbiguousTable(values_gradual), expected_text="Any | Unknown")
reveal_type(
PartiallySpecializedTable(values_partially_specialized), expected_text="Any | PartiallySpecializedTable[float]"
)
reveal_type(InferredTable(values_inferred), expected_text="InferredTable[int] | InferredTable[str]")
reveal_type(table.__init__(values_any), expected_text="None")
Comment thread
rchiodo marked this conversation as resolved.
Resolved


@overload
Expand Down
Loading