diff --git a/packages/pyright-internal/src/analyzer/checker.ts b/packages/pyright-internal/src/analyzer/checker.ts index 67e61b6ab949..1fc5947f6e8e 100644 --- a/packages/pyright-internal/src/analyzer/checker.ts +++ b/packages/pyright-internal/src/analyzer/checker.ts @@ -6112,6 +6112,33 @@ export class Checker extends ParseTreeWalker { const childClassSelf = ClassType.cloneAsInstance( selfSpecializeClass(childClassType, { useBoundTypeVars: true }) ); + + let baseClassSelf = ClassType.isProtocolClass(overriddenClassAndSymbol.classType) + ? childClassSelf + : ClassType.cloneAsInstance( + selfSpecializeClass(overriddenClassAndSymbol.classType, { useBoundTypeVars: true }) + ); + + overriddenType = partiallySpecializeType( + overriddenType, + overriddenClassAndSymbol.classType, + this._evaluator.getTypeClassType(), + baseClassSelf + ); + + overrideType = partiallySpecializeType( + overrideType, + overrideClassAndSymbol.classType, + this._evaluator.getTypeClassType(), + childClassSelf + ) as FunctionType | OverloadedType; + + if (childClassType.shared.typeVarScopeId) { + overriddenType = makeTypeVarsBound(overriddenType, [childClassType.shared.typeVarScopeId]); + overrideType = makeTypeVarsBound(overrideType, [childClassType.shared.typeVarScopeId]); + baseClassSelf = makeTypeVarsBound(baseClassSelf, [childClassType.shared.typeVarScopeId]); + } + const { baseType: overriddenTypeForComparison, overrideType: overrideTypeForComparison } = this._getCallableVariableOverrideComparison( overriddenClassAndSymbol.symbol, @@ -6126,9 +6153,11 @@ export class Checker extends ParseTreeWalker { !this._evaluator.validateOverrideMethod( overriddenTypeForComparison, overrideTypeForComparison, - /* baseClass */ undefined, + childClassType, diagAddendum, - /* enforceParamNameMatch */ true + /* enforceParamNameMatch */ true, + baseClassSelf, + childClassSelf ) ) { if (overrideDecl && overrideDecl.type === DeclarationType.Function) { @@ -6955,7 +6984,7 @@ export class Checker extends ParseTreeWalker { // The "Self" value for the base class depends on whether it's a // protocol or not. It's not clear from the typing spec whether // this is the correct behavior. - const baseClassSelf = ClassType.isProtocolClass(baseClass) + let baseClassSelf = ClassType.isProtocolClass(baseClass) ? childClassSelf : ClassType.cloneAsInstance(selfSpecializeClass(baseClass, { useBoundTypeVars: true })); @@ -6976,6 +7005,7 @@ export class Checker extends ParseTreeWalker { if (childClassType.shared.typeVarScopeId) { overrideType = makeTypeVarsBound(overrideType, [childClassType.shared.typeVarScopeId]); baseType = makeTypeVarsBound(baseType, [childClassType.shared.typeVarScopeId]); + baseClassSelf = makeTypeVarsBound(baseClassSelf, [childClassType.shared.typeVarScopeId]); } // Determine whether this is an attempt to override a method marked @final. @@ -7042,7 +7072,9 @@ export class Checker extends ParseTreeWalker { overrideTypeForComparison, childClassType, diagAddendum, - enforceParamNameMatch + enforceParamNameMatch, + baseClassSelf, + childClassSelf ) ) { return; diff --git a/packages/pyright-internal/src/analyzer/typeEvaluator.ts b/packages/pyright-internal/src/analyzer/typeEvaluator.ts index 0b56dfe057aa..348414fabf86 100644 --- a/packages/pyright-internal/src/analyzer/typeEvaluator.ts +++ b/packages/pyright-internal/src/analyzer/typeEvaluator.ts @@ -18594,14 +18594,18 @@ export function createTypeEvaluator( overrideMethod: FunctionType | OverloadedType, baseClass: ClassType | undefined, diag: DiagnosticAddendum, - enforceParamNames = true + enforceParamNames = true, + baseClassSelf?: ClassType, + childClassSelf?: ClassType ): boolean { return overrideValidation.validateOverrideMethod( baseMethod, overrideMethod, baseClass, diag, - enforceParamNames + enforceParamNames, + baseClassSelf, + childClassSelf ); } diff --git a/packages/pyright-internal/src/analyzer/typeEvaluator/overrideValidation.ts b/packages/pyright-internal/src/analyzer/typeEvaluator/overrideValidation.ts index 098c00d8b2ef..92a99ee45bb2 100644 --- a/packages/pyright-internal/src/analyzer/typeEvaluator/overrideValidation.ts +++ b/packages/pyright-internal/src/analyzer/typeEvaluator/overrideValidation.ts @@ -21,10 +21,12 @@ import { isFunction, isFunctionOrOverloaded, isTypeVar, + isUnion, OverloadedType, Type, + TypeVarType, } from '../types'; -import { ApplyTypeVarOptions } from '../typeUtils'; +import { ApplyTypeVarOptions, getTypeVarScopeIds, mapSubtypes } from '../typeUtils'; interface Context { readonly assignType: TypeEvaluator['assignType']; @@ -47,7 +49,9 @@ export function createOverrideValidation(context: Context) { overrideMethod: FunctionType | OverloadedType, baseClass: ClassType | undefined, diag: DiagnosticAddendum, - enforceParamNames = true + enforceParamNames = true, + baseClassSelf?: ClassType, + childClassSelf?: ClassType ): boolean { // If we're overriding a non-method with a method, report it as an error. // This occurs when a non-property overrides a property. @@ -57,9 +61,16 @@ export function createOverrideValidation(context: Context) { } if (isFunction(baseMethod)) { + const specializedBaseMethod = partiallySpecializeOverrideMethod(baseMethod, baseClassSelf); + // Handle the easy case - a simple function overriding another simple function. if (isFunction(overrideMethod)) { - return validateOverrideMethodInternal(baseMethod, overrideMethod, diag, enforceParamNames); + return validateOverrideMethodInternal( + specializedBaseMethod, + partiallySpecializeOverrideMethod(overrideMethod, childClassSelf), + diag, + enforceParamNames + ); } const overloadsAndImpl = [...OverloadedType.getOverloads(overrideMethod)]; @@ -73,8 +84,8 @@ export function createOverrideValidation(context: Context) { if ( overloadsAndImpl.some((overrideOverload) => { return validateOverrideMethodInternal( - baseMethod, - overrideOverload, + specializedBaseMethod, + partiallySpecializeOverrideMethod(overrideOverload, childClassSelf), /* diag */ undefined, enforceParamNames ); @@ -90,6 +101,8 @@ export function createOverrideValidation(context: Context) { // For a non-overloaded method overriding an overloaded method, the // override must match all of the overloads. if (isFunction(overrideMethod)) { + const specializedOverrideMethod = partiallySpecializeOverrideMethod(overrideMethod, childClassSelf); + return OverloadedType.getOverloads(baseMethod).every((overload) => { // If the override isn't applicable for this base class, skip the check. if (baseClass && !isOverrideMethodApplicable(overload, baseClass)) { @@ -97,81 +110,107 @@ export function createOverrideValidation(context: Context) { } return validateOverrideMethodInternal( - overload, - overrideMethod, + partiallySpecializeOverrideMethod(overload, baseClassSelf), + specializedOverrideMethod, diag?.createAddendum(), enforceParamNames ); }); } - // For an overloaded method overriding an overloaded method, the overrides - // must all match and be in the correct order. It is OK if the base method - // has additional overloads that are not present in the override. + // For an overloaded method overriding an overloaded method, each base + // overload must be matched by an override overload, and the matches must + // be in the same order. It is OK if the override has additional overloads + // that are not present in the base method. let previousMatchIndex = -1; - const baseOverloads = OverloadedType.getOverloads(baseMethod); + const overrideOverloads = OverloadedType.getOverloads(overrideMethod).map((overrideOverload) => { + return partiallySpecializeOverrideMethod(overrideOverload, childClassSelf); + }); + + for (let baseOverload of OverloadedType.getOverloads(baseMethod)) { + // If the override isn't applicable for this base class, skip the check. + if (baseClass && !isOverrideMethodApplicable(baseOverload, baseClass)) { + continue; + } - for (const overrideOverload of OverloadedType.getOverloads(overrideMethod)) { - let possibleMatchIndex: number | undefined; + baseOverload = partiallySpecializeOverrideMethod(baseOverload, baseClassSelf); - let matchIndex = baseOverloads.findIndex((baseOverload, index) => { - // If the override isn't applicable for this base class, skip the check. - if (baseClass && !isOverrideMethodApplicable(baseOverload, baseClass)) { - return false; - } - - const isCompatible = validateOverrideMethodInternal( + const isCompatible = (overrideOverload: FunctionType) => { + return validateOverrideMethodInternal( baseOverload, overrideOverload, /* diag */ undefined, enforceParamNames ); + }; - // If the override is compatible but the match is one that is below the previous - // matched index, keep looking for additional matches. Record the fact that - // we found at least one match. - if (isCompatible && index <= previousMatchIndex && possibleMatchIndex === undefined) { - possibleMatchIndex = index; - return false; - } - - return isCompatible; + const matchIndex = overrideOverloads.findIndex((overrideOverload, index) => { + return index >= previousMatchIndex && isCompatible(overrideOverload); }); - if (matchIndex < 0 && possibleMatchIndex !== undefined) { - matchIndex = possibleMatchIndex; - } - if (matchIndex < 0) { - break; + if (overrideOverloads.some((overrideOverload) => isCompatible(overrideOverload))) { + diag.addMessage(LocAddendum.overrideOverloadOrder()); + } else { + diag.addMessage(LocAddendum.overrideOverloadNoMatch()); + } + return false; } - if (matchIndex < previousMatchIndex) { - diag.addMessage(LocAddendum.overrideOverloadOrder()); + // An additional overload ahead of the match must not overlap the + // base overload and return an incompatible type. + const isOverlapping = overrideOverloads.some((overrideOverload, index) => { + return index < matchIndex && isOverrideMethodOverlapping(baseOverload, overrideOverload); + }); + + if (isOverlapping) { + diag.addMessage(LocAddendum.overrideOverloadNoMatch()); return false; } previousMatchIndex = matchIndex; } - if (previousMatchIndex < baseOverloads.length - 1) { - const unmatchedOverloads = baseOverloads.slice(previousMatchIndex + 1); + return true; + } - // See if all of the remaining overrides are nonapplicable. - if ( - !baseClass || - unmatchedOverloads.some((overload) => { - return isOverrideMethodApplicable(overload, baseClass); - }) - ) { - // We didn't find matches for all of the base overloads. - diag.addMessage(LocAddendum.overrideOverloadNoMatch()); + function isOverrideMethodOverlapping(baseOverload: FunctionType, overrideOverload: FunctionType): boolean { + if ( + FunctionType.isInstanceMethod(overrideOverload) || + FunctionType.isClassMethod(overrideOverload) || + FunctionType.isConstructorMethod(overrideOverload) + ) { + baseOverload = FunctionType.clone(baseOverload, /* stripFirstParam */ true); + overrideOverload = FunctionType.clone(overrideOverload, /* stripFirstParam */ true); + } + + const flags = AssignTypeFlags.SkipReturnTypeCheck; + const partialOverlapFlags = + flags | + AssignTypeFlags.OverloadOverlap | + AssignTypeFlags.PartialOverloadOverlap | + AssignTypeFlags.IncludeOverlapByOmission; + + const checks: [FunctionType, FunctionType, AssignTypeFlags][] = [ + [baseOverload, overrideOverload, flags], + [overrideOverload, baseOverload, flags], + [overrideOverload, baseOverload, partialOverlapFlags], + ]; + + // Compare the return types with the TypeVars solved by the + // parameters the two overloads share. + return checks.some(([destType, srcType, checkFlags]) => { + const constraints = new ConstraintTracker(); + if (!assignType(destType, srcType, /* diag */ undefined, constraints, checkFlags)) { return false; } - } - return true; + return !assignType( + solveAndApplyConstraints(getEffectiveReturnType(baseOverload), constraints), + solveAndApplyConstraints(getEffectiveReturnType(overrideOverload), constraints) + ); + }); } function isOverrideMethodApplicable(baseMethod: FunctionType, childClass: ClassType): boolean { @@ -212,6 +251,33 @@ export function createOverrideValidation(context: Context) { ); } + // Solves the TypeVars in an annotated "self" or "cls" parameter against + // the class that "self" refers to, as is done when the method is bound. + function partiallySpecializeOverrideMethod(method: FunctionType, selfClass: ClassType | undefined): FunctionType { + if ( + !selfClass || + method.shared.parameters.length === 0 || + !FunctionParam.isTypeDeclared(method.shared.parameters[0]) || + !( + FunctionType.isInstanceMethod(method) || + FunctionType.isClassMethod(method) || + FunctionType.isConstructorMethod(method) + ) + ) { + return method; + } + + const constraints = new ConstraintTracker(); + const selfType = FunctionType.isInstanceMethod(method) ? selfClass : ClassType.cloneAsInstantiable(selfClass); + + if (!assignType(FunctionType.getParamType(method, 0), selfType, /* diag */ undefined, constraints)) { + return method; + } + + const specializedFunction = solveAndApplyConstraints(method, constraints); + return isFunction(specializedFunction) ? specializedFunction : method; + } + function validateOverrideMethodInternal( baseMethod: FunctionType, overrideMethod: FunctionType, @@ -609,7 +675,30 @@ export function createOverrideValidation(context: Context) { // Now check the return type. const baseReturnType = getEffectiveReturnType(baseMethod); - const overrideReturnType = solveAndApplyConstraints(getEffectiveReturnType(overrideMethod), constraints); + let overrideReturnType = solveAndApplyConstraints(getEffectiveReturnType(overrideMethod), constraints); + + // Replace unsolved TypeVars of the override in a union with their + // default, or eliminate them if they have no default, as is done for + // call return types. + const overrideScopeIds = getTypeVarScopeIds(overrideMethod); + const isUnsolvedTypeVar = (subtype: Type): subtype is TypeVarType => { + return isTypeVar(subtype) && !!subtype.priv.scopeId && overrideScopeIds.includes(subtype.priv.scopeId); + }; + if ( + isUnion(overrideReturnType) && + !overrideReturnType.priv.subtypes.every((subtype) => { + return isUnsolvedTypeVar(subtype) && !subtype.shared.isDefaultExplicit; + }) + ) { + overrideReturnType = mapSubtypes(overrideReturnType, (subtype) => { + if (isUnsolvedTypeVar(subtype)) { + return subtype.shared.isDefaultExplicit + ? solveAndApplyConstraints(subtype.shared.defaultType, constraints) + : undefined; + } + return subtype; + }); + } if ( !assignType( diff --git a/packages/pyright-internal/src/analyzer/typeEvaluator/typeCompatibility.ts b/packages/pyright-internal/src/analyzer/typeEvaluator/typeCompatibility.ts index 6f3ef41fe8c4..cb67044773aa 100644 --- a/packages/pyright-internal/src/analyzer/typeEvaluator/typeCompatibility.ts +++ b/packages/pyright-internal/src/analyzer/typeEvaluator/typeCompatibility.ts @@ -1277,6 +1277,7 @@ export function createTypeCompatibility(context: Context) { if ((flags & AssignTypeFlags.PartialOverloadOverlap) !== 0) { if (srcParam.defaultType) { if ( + (flags & AssignTypeFlags.IncludeOverlapByOmission) === 0 && isOverlapOnlyByOmission(destParamType, destParam.defaultType, srcParamType) && checkParamListOmission() ) { @@ -1716,6 +1717,7 @@ export function createTypeCompatibility(context: Context) { if (srcParamInfo.defaultType && destParamInfo.defaultType) { if ((flags & AssignTypeFlags.PartialOverloadOverlap) !== 0) { if ( + (flags & AssignTypeFlags.IncludeOverlapByOmission) === 0 && isOverlapOnlyByOmission(destParamInfo.type, destParamInfo.defaultType, srcParamType) && checkParamListOmission() ) { diff --git a/packages/pyright-internal/src/analyzer/typeEvaluatorTypes.ts b/packages/pyright-internal/src/analyzer/typeEvaluatorTypes.ts index ecfbf0c1b945..a55ef28acb80 100644 --- a/packages/pyright-internal/src/analyzer/typeEvaluatorTypes.ts +++ b/packages/pyright-internal/src/analyzer/typeEvaluatorTypes.ts @@ -684,6 +684,11 @@ export const enum AssignTypeFlags { // records it. Overload consistency validation uses this when comparing // return types. RejectCyclicLowerBound = 1 << 18, + + // When used in conjunction with PartialOverloadOverlap, treat two + // parameters with defaults as overlapping even if they overlap only + // when the argument is omitted. Override validation uses this. + IncludeOverlapByOmission = 1 << 19, } export interface TypeEvaluator { @@ -857,7 +862,9 @@ export interface TypeEvaluator { overrideMethod: FunctionType | OverloadedType, baseClass: ClassType | undefined, diag: DiagnosticAddendum, - enforceParamNames?: boolean + enforceParamNames?: boolean, + baseClassSelf?: ClassType, + childClassSelf?: ClassType ) => boolean; validateCallArgs: ( errorNode: ExpressionNode, diff --git a/packages/pyright-internal/src/tests/samples/methodOverride4.py b/packages/pyright-internal/src/tests/samples/methodOverride4.py index 1902c2257adb..d516d936425c 100644 --- a/packages/pyright-internal/src/tests/samples/methodOverride4.py +++ b/packages/pyright-internal/src/tests/samples/methodOverride4.py @@ -4,7 +4,7 @@ # pyright: strict from abc import abstractmethod -from typing import Callable, Generic, TypeVar +from typing import Any, Callable, Generic, Protocol, Self, TypeVar, overload _TSource = TypeVar("_TSource") _TResult = TypeVar("_TResult") @@ -51,3 +51,175 @@ def method1[T: BaseC](self, x: T) -> T: ... class SubclassC(BaseC): # This should generate an error because of the upper bound. def method1[T: SubclassC](self, x: T) -> T: ... + + +class BaseD: + def method1(self) -> int: ... + + +class SubclassD[T](BaseD): + # This should generate an error. + def method1[S](self: "SubclassD[S]") -> S | int: ... + + +class BaseE: + def method1(self) -> object: ... + + +class SubclassE[T](BaseE): + def method1[S](self: "SubclassE[S]") -> S | int: ... + + +class BaseF: + def method1(self, x: int) -> int: ... + + +class SubclassF1(BaseF): + def method1[T](self, x: int | T) -> T | int: ... + + +class SubclassF2(BaseF): + def method1[T: str](self, x: int | T) -> T | int: ... + + +class SubclassF3(BaseF): + def method1[T: (str, bytes)](self, x: int | T) -> T | int: ... + + +class SubclassF4[T](BaseF): + # This should generate an error because of a parameter type mismatch. + def method1[S](self: "SubclassF4[S]", x: S) -> int: ... + + +class SubclassF5(BaseF): + # This should generate an error because of a return type mismatch. + def method1[T = str](self, x: int | T) -> T | int: ... + + +class SubclassF6(BaseF): + def method1[T = int](self, x: int | T) -> T | int: ... + + +class BaseG: + @classmethod + def method1(cls, x: int) -> int: ... + + +class SubclassG[T](BaseG): + # This should generate an error because of a parameter type mismatch. + @classmethod + def method1[S](cls: "type[SubclassG[S]]", x: S) -> int: ... + + +class BaseH[T]: + def method1[S](self: "BaseH[S]", x: S) -> S: ... + + +class SubclassH(BaseH[int]): + def method1(self, x: int) -> int: ... + + +class BaseI[T]: + def method1[S](self: "BaseI[S]", x: S) -> int: ... + + +# This should generate an error because the base classes define +# method1 in an incompatible way. +class SubclassI(BaseI[str], BaseF): ... + + +class BaseJ: + def method1[T: BaseJ](self: T, x: T) -> None: ... + + +class SubclassJ1(BaseJ): + # This should generate an error because of a parameter type mismatch. + def method1[T: SubclassJ1](self: T, x: T) -> None: ... + + +class SubclassJ2(BaseJ): + # This should generate an error because of a parameter type mismatch. + def method1(self, x: "SubclassJ2") -> None: ... + + +class BaseK[T]: + def method1[S](self: "BaseK[S]", x: S) -> S: ... + + +class BaseL[T]: + def method1(self, x: T) -> T: ... + + +class SubclassK1[T](BaseK[T], BaseL[T]): ... + + +# This should generate an error because the base classes define +# method1 in an incompatible way. +class SubclassK2[T](BaseK[T], BaseF): ... + + +class BaseM[T]: + def method1[S](self: "BaseM[S]", x: "BaseM[S]") -> None: ... + + +class BaseN[T]: + def method1(self, x: BaseM[T]) -> None: ... + + +class SubclassM1[T](BaseM[T]): + def method1(self, x: BaseM[T]) -> None: ... + + +class SubclassM2[T](BaseM[T]): + def method1[S](self: "SubclassM2[S]", x: BaseM[S]) -> None: ... + + +# This should generate an error because the base classes define +# method1 in an incompatible way. +class SubclassM3[T](BaseM[int], BaseN[T]): ... + + +class BaseO[T]: + @overload + def method1(self: "BaseO[int]", x: int) -> int: ... + @overload + def method1(self, x: str) -> str: ... + @overload + def method1(self, x: bytes) -> bytes: ... + def method1(self, x: Any) -> Any: ... + + +class BaseP: + @overload + def method1(self, x: str) -> str: ... + @overload + def method1(self, x: bytes) -> bytes: ... + def method1(self, x: str | bytes) -> str | bytes: ... + + +class SubclassO1(BaseP, BaseO[str]): ... + + +# This should generate an error because the base classes define +# method1 in an incompatible way. +class SubclassO2(BaseP, BaseO[int]): ... + + +class BaseQ(Protocol): + def method1[T: BaseQ](self: T) -> T: ... + + +class BaseR: + def method1(self) -> Self: ... + + +class BaseS: + def method1(self) -> "BaseS": ... + + +class SubclassQ1(BaseR, BaseQ): ... + + +# This should generate an error because the base classes define +# method1 in an incompatible way. +class SubclassQ2(BaseS, BaseQ): ... diff --git a/packages/pyright-internal/src/tests/samples/methodOverride6.py b/packages/pyright-internal/src/tests/samples/methodOverride6.py index 20b2bdbfc689..ca0ae2ebc9db 100644 --- a/packages/pyright-internal/src/tests/samples/methodOverride6.py +++ b/packages/pyright-internal/src/tests/samples/methodOverride6.py @@ -3,6 +3,7 @@ from typing import Any, Generic, Literal, TypeVar, overload _T = TypeVar("_T") +_S = TypeVar("_S") class Parent1(Generic[_T]): @@ -238,3 +239,331 @@ def m1(self, x: str) -> str: ... # This should generate an error because the overloads are # incompatible def m1(self, x: bytes | str) -> bytes | str: ... + + +class Parent6: + @overload + def m1(self, a: int, /) -> int: ... + + @overload + def m1(self, a: int, b: int, c: int, /) -> int: ... + + def m1(self, *args: int) -> int: + return 0 + + +class Child6_1(Parent6): + @overload + def m1(self) -> int: ... + + @overload + def m1(self, a: int, /) -> int: ... + + @overload + def m1(self, a: int, b: int, c: int, /) -> int: ... + + def m1(self, *args: int) -> int: + return 0 + + +class Child6_2(Parent6): + @overload + def m1(self, a: int, /) -> int: ... + + @overload + def m1(self, a: int, b: int, /) -> int: ... + + @overload + def m1(self, a: int, b: int, c: int, /) -> int: ... + + def m1(self, *args: int) -> int: + return 0 + + +class Child6_3(Parent6): + @overload + def m1(self, a: int, b: int, c: int, /) -> int: ... + + @overload + def m1(self) -> int: ... + + @overload + def m1(self, a: int, /) -> int: ... + + # This should generate an error because the overloads are + # in the wrong order. + def m1(self, *args: int) -> int: + return 0 + + +class Child6_4(Parent6): + @overload + def m1(self, a: int, b: int, c: int, /) -> int: ... + + @overload + def m1(self) -> int: ... + + # This should generate an error because the override does not + # handle all overloads of the base method. + def m1(self, *args: int) -> int: + return 0 + + +class Parent7: + @overload + def m1(self, x: int) -> int: ... + + @overload + def m1(self, x: str) -> str: ... + + @overload + def m1(self, x: bytes) -> bytes: ... + + def m1(self, x: int | str | bytes) -> int | str | bytes: ... + + +class Child7_1(Parent7): + @overload + def m1(self, x: int) -> int: ... + + @overload + def m1(self, x: bytes) -> bytes: ... + + # This should generate an error because the override does not + # handle all overloads of the base method. + def m1(self, x: int | bytes) -> int | bytes: ... + + +class Parent8: + @overload + def m1(self, x: int, *, flag: bool) -> int: ... + + @overload + def m1(self, x: str) -> str: ... + + def m1(self, x: int | str, **kwargs: Any) -> int | str: ... + + +class Child8_1(Parent8): + @overload + def m1(self, x: int, *, flag: bool) -> int: ... + + @overload + def m1(self, x: str) -> str: ... + + @overload + def m1(self, x: bytes) -> bytes: ... + + @overload + def m1(self, x: int, *, flag: bool = False) -> int: ... + + def m1(self, x: int | str | bytes, **kwargs: Any) -> int | str | bytes: ... + + +class Child8_2(Parent8): + @overload + def m1(self, x: object, *, flag: bool) -> bytes: ... + + @overload + def m1(self, x: int, *, flag: bool) -> int: ... # pyright: ignore[reportOverlappingOverload] + + @overload + def m1(self, x: str) -> str: ... + + # This should generate an error because the override does not + # handle all overloads of the base method. + def m1(self, x: object, **kwargs: Any) -> int | str | bytes: ... + + +class Parent9: + @overload + def m1(self, x: int | str) -> str: ... + + @overload + def m1(self, x: object) -> object: ... + + def m1(self, x: object) -> object: ... + + +class Child9_1(Parent9): + @overload + def m1(self, x: int | str) -> str: ... + + @overload + def m1(self, x: str | bytes) -> str: ... + + @overload + def m1(self, x: object) -> object: ... + + def m1(self, x: object) -> object: ... + + +class Child9_2(Parent9): + @overload + def m1(self, x: str | bytes) -> bytes: ... # pyright: ignore[reportOverlappingOverload] + + @overload + def m1(self, x: int | str) -> str: ... + + @overload + def m1(self, x: object) -> object: ... + + # This should generate an error because the override does not + # handle all overloads of the base method. + def m1(self, x: object) -> object: ... + + +class Parent10(Generic[_T]): + @overload + def m1(self, x: int, /) -> _T | None: ... + + @overload + def m1(self, x: int, default: _T, /) -> _T: ... + + @overload + def m1(self, x: int, default: _S, /) -> _T | _S: ... + + def m1(self, x: int, default: object = None, /) -> object: ... + + +class Child10_1(Parent10[_T]): + @overload + def m1(self, x: int, /) -> _T | None: ... + + @overload + def m1(self, x: int, default: _T | _S, /) -> _T | _S: ... + + def m1(self, x: int, default: object = None, /) -> object: ... + + +class Child10_2(Parent10[str]): + @overload + def m1(self, x: int, /) -> str | None: ... + + @overload + def m1(self, x: int, default: str | _S, /) -> bytes | _S: ... + + # This should generate an error. + def m1(self, x: int, default: object = None, /) -> object: ... + + +class Child10_3(Parent10[str]): + @overload + def m1(self, x: int, /) -> str | None: ... + + @overload + def m1(self, x: int, default: str | _S, /) -> _S: ... + + # This should generate an error because the override does not + # handle all overloads of the base method. + def m1(self, x: int, default: object = None, /) -> object: ... + + +class Parent11(Generic[_T]): + @overload + def m1(self: "Parent11[_S]", x: int) -> _S: ... + + @overload + def m1(self, x: str) -> str: ... + + def m1(self, x: object) -> Any: ... + + +class Child11_1(Parent11[int]): + @overload + def m1(self, x: bool) -> int: ... + + @overload + def m1(self, x: int) -> int: ... + + @overload + def m1(self, x: str) -> str: ... + + def m1(self, x: object) -> Any: ... + + +class Child11_2(Parent11[int]): + @overload + def m1(self, x: bool) -> str: ... # pyright: ignore[reportOverlappingOverload] + + @overload + def m1(self, x: int) -> int: ... + + @overload + def m1(self, x: str) -> str: ... + + # This should generate an error because the override does not + # handle all overloads of the base method. + def m1(self, x: object) -> Any: ... + + +class Parent12: + @overload + def m1(self, x: int) -> int: ... + + @overload + def m1(self, x: str) -> str: ... + + def m1(self, x: int | str) -> int | str: ... + + +class Child12_1(Parent12): + @overload + def m1(self, x: int | str) -> int: ... + + @overload + def m1(self, x: str) -> str: ... # pyright: ignore[reportOverlappingOverload] + + # This should generate an error because the override does not + # handle all overloads of the base method. + def m1(self, x: int | str) -> int | str: ... + + +class Parent13: + @overload + def m1(self, x: int, mode: Literal[False] = False) -> int: ... + + @overload + def m1(self, x: str, mode: Literal[False] = False) -> str: ... + + def m1(self, x: int | str, mode: bool = False) -> int | str: ... + + +class Child13_1(Parent13): + @overload + def m1(self, x: int, mode: Literal[True] = True) -> bytes: ... + + @overload + def m1(self, x: int, mode: Literal[False] = False) -> int: ... + + @overload + def m1(self, x: str, mode: Literal[False] = False) -> str: ... + + # This should generate an error because the override does not + # handle all overloads of the base method. + def m1(self, x: int | str, mode: bool = True) -> int | str | bytes: ... + + +class Parent14: + @overload + def m1[T](self, x: T, /) -> T: ... + + @overload + def m1(self, x: int, y: int, /) -> int: ... + + def m1(self, x: object, y: int = 0, /) -> object: ... + + +class Child14_1(Parent14): + @overload + def m1(self, x: int, /) -> bytes: ... + + @overload + def m1[T](self, x: T, /) -> T: ... + + @overload + def m1(self, x: int, y: int, /) -> int: ... + + # This should generate an error because the override does not + # handle all overloads of the base method. + def m1(self, x: object, y: int = 0, /) -> object: ... diff --git a/packages/pyright-internal/src/tests/samples/protocol53.py b/packages/pyright-internal/src/tests/samples/protocol53.py index c3cec83203eb..e614d5cc189a 100644 --- a/packages/pyright-internal/src/tests/samples/protocol53.py +++ b/packages/pyright-internal/src/tests/samples/protocol53.py @@ -78,8 +78,7 @@ def m[T: Impl_CoGenericExplicit3](self: T) -> T: ... class Impl_CoOtherExplicit3(Proto_CoGeneric): - # This should generate a reportIncompatibleMethodOverride error - # but does not currently. + # This should generate a reportIncompatibleMethodOverride error. def m(self) -> Impl_CoSelf: ... @@ -167,26 +166,19 @@ def m(self, x: Impl_ContraSelf) -> None: ... class Impl_ContraRecursExplicit3(Proto_ContraGeneric): - # This should not generate a reportIncompatibleMethodOverride error - # but does currently. def m(self, x: "Impl_ContraRecursExplicit3") -> None: ... class Impl_ContraSelfExplicit3(Proto_ContraGeneric): - # This should not generate a reportIncompatibleMethodOverride error - # but does currently. def m(self, x: Self) -> None: ... class Impl_ContraGenericExplicit3(Proto_ContraGeneric): - # This should not generate a reportIncompatibleMethodOverride error - # but does currently. def m[T: Impl_ContraGenericExplicit3](self: T, x: T) -> None: ... class Impl_ContraOtherExplicit3(Proto_ContraGeneric): - # This should not generate a reportIncompatibleMethodOverride error - # but does currently. + # This should generate a reportIncompatibleMethodOverride error. def m(self, x: Impl_ContraSelf) -> None: ... diff --git a/packages/pyright-internal/src/tests/typeEvaluator3.test.ts b/packages/pyright-internal/src/tests/typeEvaluator3.test.ts index 448cbe0d7df0..5bd704356530 100644 --- a/packages/pyright-internal/src/tests/typeEvaluator3.test.ts +++ b/packages/pyright-internal/src/tests/typeEvaluator3.test.ts @@ -1036,7 +1036,7 @@ test('MethodOverride3', () => { test('MethodOverride4', () => { const analysisResults = TestUtils.typeAnalyzeSampleFiles(['methodOverride4.py']); - TestUtils.validateResults(analysisResults, 1); + TestUtils.validateResults(analysisResults, 12); }); test('MethodOverride5', () => { @@ -1056,7 +1056,7 @@ test('MethodOverride6', () => { configOptions.diagnosticRuleSet.reportIncompatibleMethodOverride = 'error'; const analysisResults2 = TestUtils.typeAnalyzeSampleFiles(['methodOverride6.py'], configOptions); - TestUtils.validateResults(analysisResults2, 3); + TestUtils.validateResults(analysisResults2, 14); }); test('MethodOverride7', () => { diff --git a/packages/pyright-internal/src/tests/typeEvaluator7.test.ts b/packages/pyright-internal/src/tests/typeEvaluator7.test.ts index 105ee26d28b3..4912b440316b 100644 --- a/packages/pyright-internal/src/tests/typeEvaluator7.test.ts +++ b/packages/pyright-internal/src/tests/typeEvaluator7.test.ts @@ -1059,12 +1059,10 @@ test('Protocol52', () => { test('Protocol53', () => { const configOptions = new ConfigOptions(Uri.empty()); - // Note: This test exposes some inconsistencies between override checks - // and protocol matching. Both of these should generate 8 errors. configOptions.diagnosticRuleSet.reportAssignmentType = 'none'; configOptions.diagnosticRuleSet.reportIncompatibleMethodOverride = 'error'; const analysisResults1 = TestUtils.typeAnalyzeSampleFiles(['protocol53.py'], configOptions); - TestUtils.validateResults(analysisResults1, 10); + TestUtils.validateResults(analysisResults1, 8); configOptions.diagnosticRuleSet.reportAssignmentType = 'error'; configOptions.diagnosticRuleSet.reportIncompatibleMethodOverride = 'none';