From 75065536608b91ae06ec3eb34500ea43e625c8bf Mon Sep 17 00:00:00 2001 From: Miguel Melon <73828966+miguelmeloninnatial@users.noreply.github.com> Date: Wed, 23 Sep 2026 13:07:24 +0200 Subject: [PATCH 1/3] Read a class name in the parameterization a class-string implies A class name carries no type arguments. `ConstantStringType::isSuperTypeOf()` and `GenericClassStringType::isSuperTypeOf()` compared it as a bare `ObjectType` with the generic type of a class-string, and `Box` is only maybe a supertype of a bare `Box`. So with a final `Box`, `$c === Box::class` did not narrow a `class-string>` to never in the else branch, and a `match` over it reported the class as unhandled. The class name now gets the type arguments that the generic type implies for it, through the new `GenericObjectType::specializeSubclass()`. A class that is not generic, such as one that implements `Option`, is still not a value of `class-string>`. Amp-Thread-ID: https://ampcode.com/threads/T-01a196f7-a83c-7170-a45b-f1d9db4220df --- phpstan-baseline.neon | 2 +- src/Type/Constant/ConstantStringType.php | 8 ++ src/Type/Generic/GenericClassStringType.php | 7 ++ src/Type/Generic/GenericObjectType.php | 51 ++++++++ .../nsrt/class-string-of-generic-class.php | 51 ++++++++ .../Comparison/MatchExpressionRuleTest.php | 6 + turbo-ext/src/ConstantStringType.cpp | 29 +++-- turbo-ext/src/GenericClassStringType.cpp | 21 +++- turbo-ext/src/GenericObjectType.cpp | 113 ++++++++++++++++++ turbo-ext/src/TypeTraits.h | 4 + turbo-ext/src/generated/GenericObjectType.h | 19 ++- 11 files changed, 292 insertions(+), 19 deletions(-) create mode 100644 tests/PHPStan/Analyser/nsrt/class-string-of-generic-class.php diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 898b4143837..a0072520473 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -1096,7 +1096,7 @@ parameters: - rawMessage: Doing instanceof PHPStan\Type\Generic\GenericObjectType is error-prone and deprecated. identifier: phpstanApi.instanceofType - count: 4 + count: 5 path: src/Type/Generic/GenericObjectType.php - diff --git a/src/Type/Constant/ConstantStringType.php b/src/Type/Constant/ConstantStringType.php index 6f1ab225393..0786a83cf74 100644 --- a/src/Type/Constant/ConstantStringType.php +++ b/src/Type/Constant/ConstantStringType.php @@ -33,6 +33,7 @@ use PHPStan\Type\ErrorType; use PHPStan\Type\GeneralizePrecision; use PHPStan\Type\Generic\GenericClassStringType; +use PHPStan\Type\Generic\GenericObjectType; use PHPStan\Type\Generic\TemplateType; use PHPStan\Type\InstanceofDeprecated; use PHPStan\Type\IntegerRangeType; @@ -178,6 +179,13 @@ public function isSuperTypeOf(Type $type): IsSuperTypeOfResult // an uncertainty originating in possible ObjectType's class subtypes. $objectType = $this->getObjectType(); + // A class name carries no type arguments, so it is compared in the + // parameterization the generic type implies for its class. + $objectType = GenericObjectType::specializeSubclass( + $genericType instanceof TemplateType ? $genericType->getBound() : $genericType, + $objectType, + ); + // Do not use TemplateType's isSuperTypeOf handling directly because it takes ObjectType // uncertainty into account. if ($genericType instanceof TemplateType) { diff --git a/src/Type/Generic/GenericClassStringType.php b/src/Type/Generic/GenericClassStringType.php index 5bc5216e5a8..5209425e47a 100644 --- a/src/Type/Generic/GenericClassStringType.php +++ b/src/Type/Generic/GenericClassStringType.php @@ -131,6 +131,13 @@ public function isSuperTypeOf(Type $type): IsSuperTypeOfResult // an uncertainty originating in possible ObjectType's class subtypes. $objectType = new ObjectType($type->getValue()); + // A class name carries no type arguments, so it is compared in the + // parameterization the generic type implies for its class. + $objectType = GenericObjectType::specializeSubclass( + $genericType instanceof TemplateType ? $genericType->getBound() : $genericType, + $objectType, + ); + // Do not use TemplateType's isSuperTypeOf handling directly because it takes ObjectType // uncertainty into account. if ($genericType instanceof TemplateType) { diff --git a/src/Type/Generic/GenericObjectType.php b/src/Type/Generic/GenericObjectType.php index a870460d2a4..acdc7740588 100644 --- a/src/Type/Generic/GenericObjectType.php +++ b/src/Type/Generic/GenericObjectType.php @@ -26,8 +26,10 @@ use PHPStan\Type\TypeWithClassName; use PHPStan\Type\UnionType; use PHPStan\Type\VerbosityLevel; +use function array_keys; use function array_map; use function count; +use function get_class; use function implode; use function sprintf; @@ -452,6 +454,55 @@ public function changeSubtractedType(?Type $subtractedType): Type return new self($this->getClassName(), $this->types, $subtractedType, null, $this->variances); } + /** + * Gives $subclass, a class written without type arguments, the ones + * $supertype implies for it through the class's `@extends` and + * `@implements` tags: Some with Option is Some, Err with + * Result is Err. + * + * Returns $subclass unchanged unless $supertype is a generic object type + * without call-site variance, $subclass is a generic subtype of its class, + * and $supertype determines every type argument of $subclass - an explicit + * argument would claim more than is known. + */ + public static function specializeSubclass(Type $supertype, Type $subclass): Type + { + if (!$supertype instanceof self || get_class($subclass) !== ObjectType::class) { + return $subclass; + } + + foreach ($supertype->variances as $variance) { + if (!$variance->invariant()) { + return $subclass; + } + } + + $classReflection = $subclass->getClassReflection(); + if ($classReflection === null || !$classReflection->isGeneric()) { + return $subclass; + } + + $templateTypeMap = $classReflection->getTemplateTypeMap(); + $ancestor = (new self($classReflection->getName(), $classReflection->typeMapToList($templateTypeMap))) + ->getAncestorWithClassName($supertype->getClassName()); + if ($ancestor === null) { + return $subclass; + } + + $inferredTypeMap = $ancestor->inferTemplateTypes($supertype); + foreach (array_keys($templateTypeMap->getTypes()) as $templateName) { + if (!$inferredTypeMap->hasType($templateName)) { + return $subclass; + } + } + + return new self( + $classReflection->getName(), + $classReflection->typeMapToList($inferredTypeMap), + $subclass->getSubtractedType(), + ); + } + public function toPhpDocNode(): TypeNode { /** @var FullyQualifiedNameNode $parent */ diff --git a/tests/PHPStan/Analyser/nsrt/class-string-of-generic-class.php b/tests/PHPStan/Analyser/nsrt/class-string-of-generic-class.php new file mode 100644 index 00000000000..b02dfd0f06a --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/class-string-of-generic-class.php @@ -0,0 +1,51 @@ += 8.0 + +namespace ClassStringOfGenericClass; + +use function PHPStan\Testing\assertType; + +/** @template-covariant T */ +final class Box {} + +/** @template-covariant T */ +interface Option {} + +/** + * @template-covariant T + * @implements Option + */ +final class Some implements Option {} + +/** @implements Option */ +final class StringOption implements Option {} + +/** @param class-string> $c */ +function finalClass(string $c): void +{ + if ($c === Box::class) { + assertType("'ClassStringOfGenericClass\\\\Box'", $c); + return; + } + + assertType('*NEVER*', $c); +} + +/** @param class-string> $c */ +function subclass(string $c): void +{ + if ($c === Some::class) { + assertType("'ClassStringOfGenericClass\\\\Some'", $c); + } + + if ($c === StringOption::class) { + assertType('*NEVER*', $c); + } +} + +/** @param class-string> $c */ +function exhaustiveMatch(string $c): int +{ + return match ($c) { + Box::class => 1, + }; +} diff --git a/tests/PHPStan/Rules/Comparison/MatchExpressionRuleTest.php b/tests/PHPStan/Rules/Comparison/MatchExpressionRuleTest.php index e216d084f33..98057be93c7 100644 --- a/tests/PHPStan/Rules/Comparison/MatchExpressionRuleTest.php +++ b/tests/PHPStan/Rules/Comparison/MatchExpressionRuleTest.php @@ -508,6 +508,12 @@ public function testBug14412(): void $this->analyse([__DIR__ . '/data/bug-14412.php'], []); } + #[RequiresPhp('>= 8.0.0')] + public function testClassStringOfGenericClass(): void + { + $this->analyse([__DIR__ . '/../../Analyser/nsrt/class-string-of-generic-class.php'], []); + } + #[RequiresPhp('>= 8.0.0')] public function testBug13029(): void { diff --git a/turbo-ext/src/ConstantStringType.cpp b/turbo-ext/src/ConstantStringType.cpp index 14bfcd82d84..5e3ac89aef6 100644 --- a/turbo-ext/src/ConstantStringType.cpp +++ b/turbo-ext/src/ConstantStringType.cpp @@ -279,20 +279,33 @@ class ConstantStringType /* We are transforming constant class-string to ObjectType. But * we need to filter out an uncertainty originating in possible * ObjectType's class subtypes. */ - zval *objectType = getObjectType(); - if (UNEXPECTED(objectType == NULL)) return zv::Val(); + zval *classObjectType = getObjectType(); + if (UNEXPECTED(classObjectType == NULL)) return zv::Val(); - /* Do not use TemplateType's isSuperTypeOf handling directly - * because it takes ObjectType uncertainty into account. */ bool isTemplate; if (UNEXPECTED(!pt_type_instanceof(genericType.raw(), PT_CLASS_TEMPLATE_TYPE, isTemplate))) return zv::Val(); - zv::Val isSuperType; + zv::Val bound; if (isTemplate) { - zv::Val bound = pt_type_call(Z_OBJ_P(genericType.raw()), PT_LC("getbound"), 0, NULL); + bound = pt_type_call(Z_OBJ_P(genericType.raw()), PT_LC("getbound"), 0, NULL); if (UNEXPECTED(bound.isUndef())) return zv::Val(); - isSuperType = pt_type_op(Z_OBJ_P(bound.raw()), PT_OP_IS_SUPER_TYPE_OF, 1, objectType); + if (UNEXPECTED(!zv::Ref(bound.raw()).isObject())) { + zend_type_error("phpstan_turbo: getBound() must return %s", ptcls::type); + return zv::Val(); + } + } + + /* A class name carries no type arguments, so it is compared in + * the parameterization the generic type implies for its class. */ + zv::Val objectType = pt_generic_object_type_specialize_subclass(isTemplate ? bound.raw() : genericType.raw(), classObjectType); + if (UNEXPECTED(objectType.isUndef())) return zv::Val(); + + /* Do not use TemplateType's isSuperTypeOf handling directly + * because it takes ObjectType uncertainty into account. */ + zv::Val isSuperType; + if (isTemplate) { + isSuperType = pt_type_op(Z_OBJ_P(bound.raw()), PT_OP_IS_SUPER_TYPE_OF, 1, objectType.raw()); } else { - isSuperType = pt_type_op(Z_OBJ_P(genericType.raw()), PT_OP_IS_SUPER_TYPE_OF, 1, objectType); + isSuperType = pt_type_op(Z_OBJ_P(genericType.raw()), PT_OP_IS_SUPER_TYPE_OF, 1, objectType.raw()); } if (UNEXPECTED(isSuperType.isUndef())) return zv::Val(); zend_long verdict = pt_type_result_trinary(isSuperType.raw()); diff --git a/turbo-ext/src/GenericClassStringType.cpp b/turbo-ext/src/GenericClassStringType.cpp index db25bca8779..2ed8bcea4ba 100644 --- a/turbo-ext/src/GenericClassStringType.cpp +++ b/turbo-ext/src/GenericClassStringType.cpp @@ -189,14 +189,27 @@ class GenericClassStringType zv::Val objectType = objectTypeOfConstantString(Z_OBJ_P(type)); if (UNEXPECTED(objectType.isUndef())) return zv::Val(); - /* Do not use TemplateType's isSuperTypeOf handling directly - * because it takes ObjectType uncertainty into account. */ bool isTemplate; if (UNEXPECTED(!pt_type_instanceof(genericType.raw(), PT_CLASS_TEMPLATE_TYPE, isTemplate))) return zv::Val(); - zv::Val isSuperType; + zv::Val bound; if (isTemplate) { - zv::Val bound = pt_type_call(Z_OBJ_P(genericType.raw()), PT_LC("getbound"), 0, NULL); + bound = pt_type_call(Z_OBJ_P(genericType.raw()), PT_LC("getbound"), 0, NULL); if (UNEXPECTED(bound.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(bound.raw()).isObject())) { + zend_type_error("phpstan_turbo: getBound() must return %s", ptcls::type); + return zv::Val(); + } + } + + /* A class name carries no type arguments, so it is compared in + * the parameterization the generic type implies for its class. */ + objectType = pt_generic_object_type_specialize_subclass(isTemplate ? bound.raw() : genericType.raw(), objectType.raw()); + if (UNEXPECTED(objectType.isUndef())) return zv::Val(); + + /* Do not use TemplateType's isSuperTypeOf handling directly + * because it takes ObjectType uncertainty into account. */ + zv::Val isSuperType; + if (isTemplate) { isSuperType = pt_type_op(Z_OBJ_P(bound.raw()), PT_OP_IS_SUPER_TYPE_OF, 1, objectType.raw()); } else { isSuperType = pt_type_op(Z_OBJ_P(genericType.raw()), PT_OP_IS_SUPER_TYPE_OF, 1, objectType.raw()); diff --git a/turbo-ext/src/GenericObjectType.cpp b/turbo-ext/src/GenericObjectType.cpp index 97b108ecc76..67b2eae3fe0 100644 --- a/turbo-ext/src/GenericObjectType.cpp +++ b/turbo-ext/src/GenericObjectType.cpp @@ -787,6 +787,109 @@ class GenericObjectType return create(name.get(), types, Z_TYPE_P(subtractedType) == IS_NULL ? NULL : subtractedType, NULL, variances); } + /* Gives $subclass, a class written without type arguments, the ones + * $supertype implies for it through the class's `@extends` and + * `@implements` tags: Some with Option is Some, Err with + * Result is Err. + * + * Returns $subclass unchanged (the same object) unless $supertype is a + * generic object type without call-site variance, $subclass is a + * generic subtype of its class, and $supertype determines every type + * argument of $subclass - an explicit argument would claim more than is + * known. UNDEF = pending exception */ + static zv::Val specializeSubclass(zval *supertype, zval *subclass) + { + /* $subclass is exactly an ObjectType: the shadowing class carries + * the twin's name, so get_class() === ObjectType::class is the + * class entry */ + if (!zv::Ref(supertype).instanceOf(pt_ce_generic_object_type) || Z_OBJCE_P(subclass) != pt_ce_object_type) return zv::Val::copyOf(zv::Ref(subclass)); + zend_object *supertypeObject = Z_OBJ_P(supertype); + + zval *variances = variancesOf(supertypeObject); + if (UNEXPECTED(variances == NULL)) return zv::Val(); + for (zv::ArrayEntry entry : zv::ArrRef(variances)) { + zv::Ref variance = entry.value().deref(); + if (UNEXPECTED(!variance.isObject())) { + zend_type_error("phpstan_turbo: a variance must be %s", ptcls::templateTypeVariance); + return zv::Val(); + } + bool invariant; + if (UNEXPECTED(!pt_type_call_bool(variance.asObject(), PT_LC("invariant"), 0, NULL, invariant))) return zv::Val(); + if (!invariant) return zv::Val::copyOf(zv::Ref(subclass)); + } + + /* $subclass->getClassReflection() — the native body, the object is + * exactly the native class */ + zv::Val classReflection = pt_object_type_get_class_reflection(Z_OBJ_P(subclass)); + if (UNEXPECTED(classReflection.isUndef())) return zv::Val(); + if (classReflection.isNull()) return zv::Val::copyOf(zv::Ref(subclass)); + if (UNEXPECTED(!zv::Ref(classReflection.raw()).isObject())) { + zend_type_error("phpstan_turbo: getClassReflection() must return an object or null"); + return zv::Val(); + } + zend_object *reflection = Z_OBJ_P(classReflection.raw()); + bool generic; + if (UNEXPECTED(!pt_class_reflection_is_generic(reflection, generic))) return zv::Val(); + if (!generic) return zv::Val::copyOf(zv::Ref(subclass)); + + zv::Val templateTypeMap = pt_class_reflection_get_template_type_map(reflection); + if (UNEXPECTED(templateTypeMap.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(templateTypeMap.raw()).isObject())) { + zend_type_error("phpstan_turbo: getTemplateTypeMap() must return an object"); + return zv::Val(); + } + zv::Val reflectionName = pt_class_reflection_get_name(reflection); + if (UNEXPECTED(reflectionName.isUndef())) return zv::Val(); + zv::Str name = zv::Str::adopt(zval_get_string(reflectionName.raw())); + zv::Val templateTypeList = pt_class_reflection_type_map_to_list(reflection, templateTypeMap.raw()); + if (UNEXPECTED(templateTypeList.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(templateTypeList.raw()).isArray())) { + zend_type_error("phpstan_turbo: typeMapToList() must return array"); + return zv::Val(); + } + zv::Val bare = create(name.get(), templateTypeList.raw(), NULL, NULL, NULL); + if (UNEXPECTED(bare.isUndef())) return zv::Val(); + zv::Val supertypeClassName = pt_type_call(supertypeObject, PT_LC("getclassname"), 0, NULL); + if (UNEXPECTED(supertypeClassName.isUndef())) return zv::Val(); + zv::Val ancestor = pt_type_call(Z_OBJ_P(bare.raw()), PT_LC("getancestorwithclassname"), 1, supertypeClassName.raw()); + if (UNEXPECTED(ancestor.isUndef())) return zv::Val(); + if (ancestor.isNull()) return zv::Val::copyOf(zv::Ref(subclass)); + if (UNEXPECTED(!zv::Ref(ancestor.raw()).isObject())) { + zend_type_error("phpstan_turbo: getAncestorWithClassName() must return an object or null"); + return zv::Val(); + } + + zv::Val inferredTypeMap = pt_type_call(Z_OBJ_P(ancestor.raw()), PT_LC("infertemplatetypes"), 1, supertype); + if (UNEXPECTED(inferredTypeMap.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(inferredTypeMap.raw()).isObject())) { + zend_type_error("phpstan_turbo: inferTemplateTypes() must return an object"); + return zv::Val(); + } + zv::Val templateTypes = pt_template_type_map_get_types(templateTypeMap.raw()); + if (UNEXPECTED(templateTypes.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(templateTypes.raw()).isArray())) { + zend_type_error("phpstan_turbo: getTypes() must return array"); + return zv::Val(); + } + for (zv::ArrayEntry entry : zv::ArrRef(templateTypes.raw())) { + /* template names are identifiers, never integer keys */ + zv::Val templateName = entry.hasStringKey() ? zv::Val::string(entry.stringKey()) : zv::Val::adoptString(zend_long_to_str((zend_long) entry.indexKey())); + bool hasType; + if (UNEXPECTED(!pt_type_call_bool(Z_OBJ_P(inferredTypeMap.raw()), PT_LC("hastype"), 1, templateName.raw(), hasType))) return zv::Val(); + if (!hasType) return zv::Val::copyOf(zv::Ref(subclass)); + } + + zv::Val inferredTypeList = pt_class_reflection_type_map_to_list(reflection, inferredTypeMap.raw()); + if (UNEXPECTED(inferredTypeList.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(inferredTypeList.raw()).isArray())) { + zend_type_error("phpstan_turbo: typeMapToList() must return array"); + return zv::Val(); + } + zval *subtractedType = pt_object_type_subtracted_type(Z_OBJ_P(subclass)); + if (UNEXPECTED(subtractedType == NULL)) return zv::Val(); + return create(name.get(), inferredTypeList.raw(), Z_TYPE_P(subtractedType) == IS_NULL ? NULL : subtractedType, NULL, NULL); + } + /* new GenericTypeNode(parent::toPhpDocNode(), the arguments' nodes, the * variances' nodes); UNDEF = pending exception */ zv::Val toPhpDocNode() const @@ -1001,6 +1104,11 @@ bool pt_generic_object_type_new(zval *out, zend_string *mainType, zval *types, z return pt_val_into(GenericObjectType::create(mainType, types, subtractedType, classReflection, variances), out); } +zv::Val pt_generic_object_type_specialize_subclass(zval *supertype, zval *subclass) +{ + return GenericObjectType::specializeSubclass(supertype, subclass); +} + /* {{{ engine ABI glue: parameter parsing + registration */ #define PT_THIS GenericObjectType(Z_OBJ_P(ZEND_THIS)) @@ -1160,6 +1268,11 @@ PT_MINIT_REGISTRATION(pt_register_generic_object_type) } PT_RETURN_VAL(PT_THIS.changeSubtractedType(subtractedType)); }); + cls.method(sigs::specializeSubclass, [](INTERNAL_FUNCTION_PARAMETERS) { + zval *supertype, *subclass; + if (!zp::parse(execute_data, supertype, subclass)) RETURN_THROWS(); + PT_RETURN_VAL(GenericObjectType::specializeSubclass(supertype, subclass)); + }); cls.method(sigs::toPhpDocNode, [](INTERNAL_FUNCTION_PARAMETERS) { pt_got_value(INTERNAL_FUNCTION_PARAM_PASSTHRU, &GenericObjectType::toPhpDocNode); }); diff --git a/turbo-ext/src/TypeTraits.h b/turbo-ext/src/TypeTraits.h index e29e21d15d4..748ba323d01 100644 --- a/turbo-ext/src/TypeTraits.h +++ b/turbo-ext/src/TypeTraits.h @@ -724,6 +724,10 @@ zv::Val pt_object_type_to_php_doc_node(zend_object *self); * object family's internal callback holder, for * RecursionGuard::runOnObjectIdentity(); UNDEF = pending exception */ zv::Val pt_object_type_referenced_classes_callback(zval *type); +/* GenericObjectType::specializeSubclass($supertype, $subclass) (both + * borrowed objects; $subclass itself when unchanged); UNDEF = pending + * exception */ +zv::Val pt_generic_object_type_specialize_subclass(zval *supertype, zval *subclass); /* merged from the parallel port branch */ diff --git a/turbo-ext/src/generated/GenericObjectType.h b/turbo-ext/src/generated/GenericObjectType.h index f5061196f3a..6419aa47bbd 100644 --- a/turbo-ext/src/generated/GenericObjectType.h +++ b/turbo-ext/src/generated/GenericObjectType.h @@ -90,9 +90,12 @@ inline constexpr char strings[] = "changeVariances\0" /* 1115 */ "withoutFinalByKeywordOverride\0" /* 1131 */ "changeSubtractedType\0" /* 1161 */ - "PHPStan\\PhpDocParser\\Ast\\Type\\TypeNode\0" /* 1182 */ - "toPhpDocNode\0" /* 1221 */ - "hasTemplateOrLateResolvableType"; /* 1234 */ + "supertype\0" /* 1182 */ + "subclass\0" /* 1192 */ + "specializeSubclass\0" /* 1201 */ + "PHPStan\\PhpDocParser\\Ast\\Type\\TypeNode\0" /* 1220 */ + "toPhpDocNode\0" /* 1259 */ + "hasTemplateOrLateResolvableType"; /* 1272 */ inline constexpr reg::PackedArg args[] = { reg::packed(0, MAY_BE_STRING), /* __construct $mainType */ reg::packed(9, MAY_BE_ARRAY), /* __construct $types */ @@ -158,7 +161,10 @@ inline constexpr reg::PackedArg args[] = { reg::packed(163, 0, 30), /* withoutFinalByKeywordOverride return */ reg::packed(15, MAY_BE_NULL, 30), /* changeSubtractedType $subtractedType */ reg::packed(163, 0, 30), /* changeSubtractedType return */ - reg::packed(163, 0, 1182), /* toPhpDocNode return */ + reg::packed(1182, 0, 30), /* specializeSubclass $supertype */ + reg::packed(1192, 0, 30), /* specializeSubclass $subclass */ + reg::packed(163, 0, 30), /* specializeSubclass return */ + reg::packed(163, 0, 1220), /* toPhpDocNode return */ reg::packed(163, MAY_BE_BOOL), /* hasTemplateOrLateResolvableType return */ }; using Sig = reg::Sig; @@ -192,8 +198,9 @@ inline constexpr sigtab::Sig recreate = { { 1106 /* recreate */, 3, 54, 4, 58, Z inline constexpr sigtab::Sig changeVariances = { { 1115 /* changeVariances */, 1, 59, 1, 60, ZEND_ACC_PUBLIC } }; inline constexpr sigtab::Sig withoutFinalByKeywordOverride = { { 1131 /* withoutFinalByKeywordOverride */, 0, 61, 0, 61, ZEND_ACC_PUBLIC } }; inline constexpr sigtab::Sig changeSubtractedType = { { 1161 /* changeSubtractedType */, 1, 62, 1, 63, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig toPhpDocNode = { { 1221 /* toPhpDocNode */, 0, 64, 0, 64, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig hasTemplateOrLateResolvableType = { { 1234 /* hasTemplateOrLateResolvableType */, 0, 65, 0, 65, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig specializeSubclass = { { 1201 /* specializeSubclass */, 2, 64, 2, 66, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } }; +inline constexpr sigtab::Sig toPhpDocNode = { { 1259 /* toPhpDocNode */, 0, 67, 0, 67, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig hasTemplateOrLateResolvableType = { { 1272 /* hasTemplateOrLateResolvableType */, 0, 68, 0, 68, ZEND_ACC_PUBLIC } }; } // namespace sig } // namespace ptdecl::GenericObjectType From fd9f45a9d765aa56bbaf66cf3ec95f6f7cdbb86c Mon Sep 17 00:00:00 2001 From: Miguel Melon <73828966+miguelmeloninnatial@users.noreply.github.com> Date: Wed, 23 Sep 2026 13:11:52 +0200 Subject: [PATCH 2/3] Keep type arguments when narrowing a generic type to a subclass A generic class written without type arguments is a subtype of every parameterization of its ancestors, so `TypeCombinator::intersect()` kept the bare subclass and dropped the arguments: `instanceof Some` narrowed an `Option` to `Some`, and so did `is_a()`, `@phpstan-assert` and `$o::class` comparisons. Since `GenericObjectType::changeSubtractedType()` returns the lone remaining subtype of a sealed hierarchy (#5369), that subtype lost its arguments too: `Result` without `Ok` became `Err`. The merge after the branch no longer hid the loss, so a wrong return type was accepted. Both now take the arguments that the generic type implies for the subclass. A subclass stays bare when the generic type does not determine all of its arguments or has call-site variance. In a union, a bare subtracted subclass is read within its type: `Option~Some` together with `Some` gives `Option`. Amp-Thread-ID: https://ampcode.com/threads/T-01a196f7-a83c-7170-a45b-f1d9db4220df --- phpstan-baseline.neon | 6 + src/Type/Generic/GenericObjectType.php | 8 +- src/Type/TypeCombinator.php | 41 ++- tests/PHPStan/Analyser/nsrt/bug-15289.php | 241 ++++++++++++++++++ .../Comparison/MatchExpressionRuleTest.php | 6 + .../Rules/Functions/ReturnTypeRuleTest.php | 25 ++ turbo-ext/src/GenericObjectType.cpp | 14 +- turbo-ext/src/TypeCombinator.cpp | 50 +++- 8 files changed, 377 insertions(+), 14 deletions(-) create mode 100644 tests/PHPStan/Analyser/nsrt/bug-15289.php diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index a0072520473..543bc7ca0e8 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -1615,6 +1615,12 @@ parameters: count: 2 path: src/Type/TypeCombinator.php + - + rawMessage: Doing instanceof PHPStan\Type\Generic\GenericObjectType is error-prone and deprecated. + identifier: phpstanApi.instanceofType + count: 3 + path: src/Type/TypeCombinator.php + - rawMessage: Doing instanceof PHPStan\Type\IntersectionType is error-prone and deprecated. identifier: phpstanApi.instanceofType diff --git a/src/Type/Generic/GenericObjectType.php b/src/Type/Generic/GenericObjectType.php index acdc7740588..5ca514011bc 100644 --- a/src/Type/Generic/GenericObjectType.php +++ b/src/Type/Generic/GenericObjectType.php @@ -447,10 +447,16 @@ public function changeSubtractedType(?Type $subtractedType): Type // Parent handles sealed type exhaustiveness (returning NeverType when all // allowed subtypes are subtracted, or a single remaining subtype). - if (!$result instanceof ObjectType || $result->getClassName() !== $this->getClassName()) { + if (!$result instanceof ObjectType) { return $result; } + // The remaining subtype comes back as the sealed tag names it, without + // type arguments, and takes the ones this type implies for it. + if ($result->getClassName() !== $this->getClassName()) { + return self::specializeSubclass($this, $result); + } + return new self($this->getClassName(), $this->types, $subtractedType, null, $this->variances); } diff --git a/src/Type/TypeCombinator.php b/src/Type/TypeCombinator.php index 426964dc43f..37b1d04d8f6 100644 --- a/src/Type/TypeCombinator.php +++ b/src/Type/TypeCombinator.php @@ -24,6 +24,7 @@ use PHPStan\Type\Constant\ConstantIntegerType; use PHPStan\Type\Constant\ConstantStringType; use PHPStan\Type\Generic\GenericClassStringType; +use PHPStan\Type\Generic\GenericObjectType; use PHPStan\Type\Generic\TemplateArrayType; use PHPStan\Type\Generic\TemplateBenevolentUnionType; use PHPStan\Type\Generic\TemplateMixedType; @@ -1236,6 +1237,23 @@ private static function intersectWithSubtractedType( } elseif ($isBAlreadySubtracted->yes()) { $subtractedType = self::remove($a->getSubtractedType(), $b); + // The subtracted type counts only within $a, where a class written + // without type arguments has the ones $a implies: in Option, + // a subtracted Some is used up by Some. + // instanceof and not a Type method, as in intersect(): only a + // GenericObjectType instance can specialize, and skipping the static + // call keeps an analysis without generics from loading GenericObjectType + // (AnalysisBench, bug-4300.php). + $subtractedWithinA = $a instanceof GenericObjectType + ? GenericObjectType::specializeSubclass($a->getTypeWithoutSubtractedType(), $a->getSubtractedType()) + : $a->getSubtractedType(); + if ( + $subtractedWithinA !== $a->getSubtractedType() + && self::remove($subtractedWithinA, $b) instanceof NeverType + ) { + $subtractedType = new NeverType(); + } + if ( $subtractedType instanceof NeverType || !$subtractedType->isSuperTypeOf($b)->no() @@ -2574,6 +2592,7 @@ public static function doIntersect(Type ...$types): Type // transform IntegerType & ConstantIntegerType to ConstantIntegerType // transform Child & Parent to Child + // transform Child & Parent to Child // transform Object & ~null to Object // transform A & A to A // transform int[] & string to never @@ -2591,7 +2610,19 @@ public static function doIntersect(Type ...$types): Type $isSuperTypeSubtractableA = $typeWithoutSubtractedTypeA->isSuperTypeOf($types[$i]); } if ($isSuperTypeSubtractableA->yes()) { - $types[$i] = self::unionWithSubtractedType($types[$i], $types[$j]->getSubtractedType()); + // A generic class written without type arguments is a subtype of + // every parameterization of its generic ancestors, so it is kept - + // with the arguments the dropped ancestor implies for it. + // instanceof and not a Type method: specializeSubclass() acts only on a + // GenericObjectType instance and returns anything else unchanged, so the + // check skips a no-op call on the hot path of every intersection + // (TypeSpecifierBench::benchSpecifyShortTernary). + $types[$i] = self::unionWithSubtractedType( + $typeWithoutSubtractedTypeA instanceof GenericObjectType + ? GenericObjectType::specializeSubclass($typeWithoutSubtractedTypeA, $types[$i]) + : $types[$i], + $types[$j]->getSubtractedType(), + ); array_splice($types, $j--, 1); $typesCount--; continue 1; @@ -2607,7 +2638,13 @@ public static function doIntersect(Type ...$types): Type $isSuperTypeSubtractableB = $typeWithoutSubtractedTypeB->isSuperTypeOf($types[$j]); } if ($isSuperTypeSubtractableB->yes()) { - $types[$j] = self::unionWithSubtractedType($types[$j], $types[$i]->getSubtractedType()); + // The same guard as for $types[$i] above: no call for a non-generic type. + $types[$j] = self::unionWithSubtractedType( + $typeWithoutSubtractedTypeB instanceof GenericObjectType + ? GenericObjectType::specializeSubclass($typeWithoutSubtractedTypeB, $types[$j]) + : $types[$j], + $types[$i]->getSubtractedType(), + ); array_splice($types, $i--, 1); $typesCount--; continue 2; diff --git a/tests/PHPStan/Analyser/nsrt/bug-15289.php b/tests/PHPStan/Analyser/nsrt/bug-15289.php new file mode 100644 index 00000000000..d5effe7d220 --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/bug-15289.php @@ -0,0 +1,241 @@ += 8.0 + +namespace Bug15289; + +use LogicException; +use function PHPStan\Testing\assertType; + +/** + * @template-covariant T + * @phpstan-sealed Some|None + */ +interface Option {} + +/** + * @template-covariant T + * @implements Option + */ +final class Some implements Option {} + +/** @implements Option */ +final class None implements Option {} + +/** + * @template-covariant T + * @template-covariant E + * @phpstan-sealed Ok|Err + */ +interface Result {} + +/** + * @template-covariant T + * @implements Result + */ +final class Ok implements Result {} + +/** + * @template-covariant E + * @implements Result + */ +final class Err implements Result {} + +/** + * @param Option $o + * @return Option + */ +function afterEmptyBranch(Option $o): Option +{ + if ($o instanceof Some) { + } + assertType('Bug15289\None|Bug15289\Some', $o); + + return $o; // should be reported +} + +/** + * @param Option $o + * @return Option + */ +function inTheBranch(Option $o): Option +{ + if ($o instanceof Some) { + assertType('Bug15289\Some', $o); + + return $o; // should be reported + } + + return $o; // correctly not reported: $o is None here +} + +/** + * @param Result $r + * @return Err + */ +function elseBranch(Result $r): Err +{ + if ($r instanceof Ok) { + throw new LogicException(); + } + assertType('Bug15289\Err', $r); + + return $r; // should be reported +} + +/** @param Option $o */ +function exhaustiveMatch(Option $o): int +{ + return match (true) { + $o instanceof Some => 1, + $o instanceof None => 2, + }; +} + +/** @template-covariant T */ +interface UnsealedOption {} + +/** + * @template-covariant T + * @implements UnsealedOption + */ +final class UnsealedSome implements UnsealedOption {} + +/** + * @param UnsealedOption $o + * @return UnsealedOption + */ +function unsealedControl(UnsealedOption $o): UnsealedOption +{ + if ($o instanceof UnsealedSome) { + assertType('Bug15289\UnsealedSome', $o); + } + assertType('Bug15289\UnsealedOption', $o); + + return $o; // reported +} + +/** @param Result $r */ +function truthyBranchOfEachVariant(Result $r): void +{ + if ($r instanceof Err) { + assertType('Bug15289\Err', $r); + } else { + assertType('Bug15289\Ok', $r); + } +} + +/** + * @template T + * @param Option $o + */ +function templateArgument(Option $o): void +{ + assertType('Bug15289\Option', $o); + if ($o instanceof Some) { + assertType('Bug15289\Some', $o); + } + assertType('Bug15289\None|Bug15289\Some', $o); +} + +/** @template T */ +interface Invariant {} + +/** + * @template T + * @implements Invariant + */ +final class InvariantImpl implements Invariant {} + +/** @param Invariant $i */ +function callSiteVariance(Invariant $i): void +{ + if ($i instanceof InvariantImpl) { + assertType('Bug15289\InvariantImpl', $i); + } +} + +/** @phpstan-assert Some $o */ +function assertSome(Option $o): void +{ +} + +/** @param Option|null $o */ +function otherNarrowings(?Option $o): void +{ + if ($o instanceof Some) { + assertType('Bug15289\Some', $o); + } + + if ($o === null) { + return; + } + + if (is_a($o, Some::class)) { + assertType('Bug15289\Some', $o); + } + + if ($o::class === Some::class) { + assertType('Bug15289\Some', $o); + } + + assertSome($o); + assertType('Bug15289\Some', $o); +} + +/** + * @template-covariant T + * @phpstan-sealed Plain|Tagged + */ +interface Wrapped {} + +/** + * @template-covariant T + * @implements Wrapped + */ +final class Plain implements Wrapped {} + +/** + * @template-covariant T + * @template-covariant Tag + * @implements Wrapped + */ +final class Tagged implements Wrapped {} + +/** @param Wrapped $w */ +function undeterminedArgument(Wrapped $w): void +{ + if ($w instanceof Tagged) { + assertType('Bug15289\Tagged', $w); + } +} + +/** @param Wrapped $w */ +function undeterminedRemainder(Wrapped $w): void +{ + if ($w instanceof Plain) { + assertType('Bug15289\Plain', $w); + return; + } + + assertType('Bug15289\Tagged', $w); +} + +function bareSupertype(UnsealedOption $o): void +{ + assertType('Bug15289\UnsealedOption', $o); + if ($o instanceof UnsealedSome) { + assertType('Bug15289\UnsealedSome', $o); + } +} + +/** + * @template O of Option + * @param O $o + */ +function templateRemainder(Option $o): void +{ + if ($o instanceof None) { + return; + } + + assertType('O of Bug15289\Some (function Bug15289\templateRemainder(), argument)', $o); +} diff --git a/tests/PHPStan/Rules/Comparison/MatchExpressionRuleTest.php b/tests/PHPStan/Rules/Comparison/MatchExpressionRuleTest.php index 98057be93c7..656fbc99123 100644 --- a/tests/PHPStan/Rules/Comparison/MatchExpressionRuleTest.php +++ b/tests/PHPStan/Rules/Comparison/MatchExpressionRuleTest.php @@ -508,6 +508,12 @@ public function testBug14412(): void $this->analyse([__DIR__ . '/data/bug-14412.php'], []); } + #[RequiresPhp('>= 8.0.0')] + public function testBug15289(): void + { + $this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-15289.php'], []); + } + #[RequiresPhp('>= 8.0.0')] public function testClassStringOfGenericClass(): void { diff --git a/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php b/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php index 55f68eca67d..da8ea2c54a8 100644 --- a/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php +++ b/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php @@ -583,6 +583,31 @@ public function testBug15245(): void ]); } + #[RequiresPhp('>= 8.0.0')] + public function testBug15289(): void + { + $this->checkNullables = true; + $this->checkExplicitMixed = false; + $this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-15289.php'], [ + [ + 'Function Bug15289\afterEmptyBranch() should return Bug15289\Option but returns Bug15289\None|Bug15289\Some.', + 52, + ], + [ + 'Function Bug15289\inTheBranch() should return Bug15289\Option but returns Bug15289\Some.', + 64, + ], + [ + 'Function Bug15289\elseBranch() should return Bug15289\Err but returns Bug15289\Err.', + 81, + ], + [ + 'Function Bug15289\unsealedControl() should return Bug15289\UnsealedOption but returns Bug15289\UnsealedOption.', + 113, + ], + ]); + } + public function testBug15714(): void { $this->checkNullables = true; diff --git a/turbo-ext/src/GenericObjectType.cpp b/turbo-ext/src/GenericObjectType.cpp index 67b2eae3fe0..25fc3dd0ff7 100644 --- a/turbo-ext/src/GenericObjectType.cpp +++ b/turbo-ext/src/GenericObjectType.cpp @@ -762,8 +762,9 @@ class GenericObjectType return create(name.get(), types, subtractedType.isNull() ? NULL : subtractedType.raw(), withoutOverride.raw(), variances); } - /* the parent's sealed-hierarchy verdict when it changes the class, a - * new self with the type arguments otherwise; $subtractedType IS_NULL + /* the parent's sealed-hierarchy verdict when it changes the class (a + * remaining subtype given the type arguments this type implies for it), + * a new self with the type arguments otherwise; $subtractedType IS_NULL * for null; UNDEF = pending exception */ zv::Val changeSubtractedType(zval *subtractedType) const { @@ -773,11 +774,18 @@ class GenericObjectType // Parent handles sealed type exhaustiveness (returning NeverType when all // allowed subtypes are subtracted, or a single remaining subtype). if (!zv::Ref(result.raw()).instanceOf(pt_ce_object_type)) return result; + + // The remaining subtype comes back as the sealed tag names it, without + // type arguments, and takes the ones this type implies for it. zv::Val resultClassName = pt_type_call(Z_OBJ_P(result.raw()), PT_LC("getclassname"), 0, NULL); if (UNEXPECTED(resultClassName.isUndef())) return zv::Val(); zv::Val className = thisGetClassName(); if (UNEXPECTED(className.isUndef())) return zv::Val(); - if (!zend_is_identical(resultClassName.raw(), className.raw())) return result; + if (!zend_is_identical(resultClassName.raw(), className.raw())) { + zval selfZv; + ZVAL_OBJ(&selfZv, self); + return specializeSubclass(&selfZv, result.raw()); + } zval *types = this->types(); if (UNEXPECTED(types == NULL)) return zv::Val(); diff --git a/turbo-ext/src/TypeCombinator.cpp b/turbo-ext/src/TypeCombinator.cpp index a63def8d15a..39c47c19463 100644 --- a/turbo-ext/src/TypeCombinator.cpp +++ b/turbo-ext/src/TypeCombinator.cpp @@ -1732,7 +1732,14 @@ class TypeCombinator * exception */ static int subtractableCovers(zval *a, zval *b) { - zv::Val withoutSubtracted = call(a, PT_LC("gettypewithoutsubtractedtype")); + zv::Val withoutSubtracted; + return subtractableCovers(a, b, withoutSubtracted); + } + + /* the same, handing out $a->getTypeWithoutSubtractedType() */ + static int subtractableCovers(zval *a, zval *b, zv::Val &withoutSubtracted) + { + withoutSubtracted = call(a, PT_LC("gettypewithoutsubtractedtype")); if (UNEXPECTED(withoutSubtracted.isUndef())) return -1; zend_long isSuperType; if (isInstance(withoutSubtracted.raw(), pt_ce_mixed_type) && isInstance(b, pt_ce_mixed_type)) { @@ -1991,6 +1998,22 @@ class TypeCombinator zv::Val subtracted = remove(aSubtracted.raw(), b); PT_FAIL_IF_UNDEF(subtracted); + /* The subtracted type counts only within $a, where a class + * written without type arguments has the ones $a implies: in + * Option, a subtracted Some is used up by Some. */ + zv::Val withoutSubtracted = call(a, PT_LC("gettypewithoutsubtractedtype")); + PT_FAIL_IF_UNDEF(withoutSubtracted); + zv::Val subtractedWithinA = pt_generic_object_type_specialize_subclass(withoutSubtracted.raw(), aSubtracted.raw()); + PT_FAIL_IF_UNDEF(subtractedWithinA); + if (Z_OBJ_P(subtractedWithinA.raw()) != Z_OBJ_P(aSubtracted.raw())) { + zv::Val removedWithinA = remove(subtractedWithinA.raw(), b); + PT_FAIL_IF_UNDEF(removedWithinA); + if (isInstance(removedWithinA.raw(), pt_ce_never_type)) { + subtracted = neverType(); + PT_FAIL_IF_UNDEF(subtracted); + } + } + if (isInstance(subtracted.raw(), pt_ce_never_type)) { subtracted = zv::Val::null(); } else { @@ -3769,10 +3792,10 @@ class TypeCombinator /* the SubtractableType arm of doIntersect()'s reduction: whether the * subtractable's type without its subtracted type is a super type of - * $other; -1 = pending exception */ - static int subtractableCoversInIntersect(zval *subtractable, zval *other) + * $other, handing out that type; -1 = pending exception */ + static int subtractableCoversInIntersect(zval *subtractable, zval *other, zv::Val &withoutSubtracted) { - return subtractableCovers(subtractable, other); + return subtractableCovers(subtractable, other, withoutSubtracted); } /* $constantArray->makeOffsetRequired($constantArray->getKeyTypes()[0]) @@ -4136,6 +4159,7 @@ class TypeCombinator /* transform IntegerType & ConstantIntegerType to ConstantIntegerType * transform Child & Parent to Child + * transform Child & Parent to Child * transform Object & ~null to Object * transform A & A to A * transform int[] & string to never @@ -4147,12 +4171,19 @@ class TypeCombinator int jSubtractable = isInstanceMap(types[j].raw(), PT_CLASS_SUBTRACTABLE_TYPE); PT_FAIL_IF_NEG(jSubtractable); if (jSubtractable) { - int covers = subtractableCoversInIntersect(types[j].raw(), types[i].raw()); + zv::Val typeWithoutSubtractedTypeA; + int covers = subtractableCoversInIntersect(types[j].raw(), types[i].raw(), typeWithoutSubtractedTypeA); PT_FAIL_IF_NEG(covers); if (covers) { + /* A generic class written without type arguments is a + * subtype of every parameterization of its generic + * ancestors, so it is kept - with the arguments the + * dropped ancestor implies for it. */ + zv::Val specialized = pt_generic_object_type_specialize_subclass(typeWithoutSubtractedTypeA.raw(), types[i].raw()); + PT_FAIL_IF_UNDEF(specialized); zv::Val subtracted = call(types[j].raw(), PT_LC("getsubtractedtype")); PT_FAIL_IF_UNDEF(subtracted); - zv::Val unioned = unionWithSubtractedType(types[i].raw(), subtracted.raw()); + zv::Val unioned = unionWithSubtractedType(specialized.raw(), subtracted.raw()); PT_FAIL_IF_UNDEF(unioned); types[i] = std::move(unioned); types.erase(types.begin() + (ptrdiff_t) j); @@ -4165,12 +4196,15 @@ class TypeCombinator int iSubtractable = isInstanceMap(types[i].raw(), PT_CLASS_SUBTRACTABLE_TYPE); PT_FAIL_IF_NEG(iSubtractable); if (iSubtractable) { - int covers = subtractableCoversInIntersect(types[i].raw(), types[j].raw()); + zv::Val typeWithoutSubtractedTypeB; + int covers = subtractableCoversInIntersect(types[i].raw(), types[j].raw(), typeWithoutSubtractedTypeB); PT_FAIL_IF_NEG(covers); if (covers) { + zv::Val specialized = pt_generic_object_type_specialize_subclass(typeWithoutSubtractedTypeB.raw(), types[j].raw()); + PT_FAIL_IF_UNDEF(specialized); zv::Val subtracted = call(types[i].raw(), PT_LC("getsubtractedtype")); PT_FAIL_IF_UNDEF(subtracted); - zv::Val unioned = unionWithSubtractedType(types[j].raw(), subtracted.raw()); + zv::Val unioned = unionWithSubtractedType(specialized.raw(), subtracted.raw()); PT_FAIL_IF_UNDEF(unioned); types[j] = std::move(unioned); types.erase(types.begin() + (ptrdiff_t) i); From beeb28bba58d5527aebe0a741a881c5e421afc61 Mon Sep 17 00:00:00 2001 From: Miguel Melon <73828966+miguelmeloninnatial@users.noreply.github.com> Date: Wed, 23 Sep 2026 16:20:46 +0200 Subject: [PATCH 3/3] Narrow a class-string with call-site variance by its class name A class name compared with a class-string of its own generic class now takes the type arguments and the call-site variance of that class-string as they are written: `X::class` read against `class-string>` is `X<*>`. So `$class !== X::class` narrows `class-string>|class-string>` to `class-string>`. Before, a class-string with call-site variance left the class name bare, which is only maybe an `X<*>`, and nothing narrowed. A subclass still stays bare when the class-string has call-site variance. --- src/Type/Generic/GenericObjectType.php | 21 ++++++++-- tests/PHPStan/Analyser/nsrt/bug-15266.php | 50 +++++++++++++++++++++++ turbo-ext/src/GenericObjectType.cpp | 30 ++++++++++---- 3 files changed, 90 insertions(+), 11 deletions(-) create mode 100644 tests/PHPStan/Analyser/nsrt/bug-15266.php diff --git a/src/Type/Generic/GenericObjectType.php b/src/Type/Generic/GenericObjectType.php index 5ca514011bc..3d939df4428 100644 --- a/src/Type/Generic/GenericObjectType.php +++ b/src/Type/Generic/GenericObjectType.php @@ -464,12 +464,15 @@ public function changeSubtractedType(?Type $subtractedType): Type * Gives $subclass, a class written without type arguments, the ones * $supertype implies for it through the class's `@extends` and * `@implements` tags: Some with Option is Some, Err with - * Result is Err. + * Result is Err. The class of $supertype itself + * takes its arguments and call-site variance as written: X with X<*> is + * X<*>. * * Returns $subclass unchanged unless $supertype is a generic object type - * without call-site variance, $subclass is a generic subtype of its class, - * and $supertype determines every type argument of $subclass - an explicit - * argument would claim more than is known. + * and $subclass is its class or a generic subtype of it. A subtype also + * stays unchanged when $supertype has call-site variance or does not + * determine every type argument of the subtype - an explicit argument + * would claim more than is known. */ public static function specializeSubclass(Type $supertype, Type $subclass): Type { @@ -477,6 +480,16 @@ public static function specializeSubclass(Type $supertype, Type $subclass): Type return $subclass; } + if ($subclass->getClassName() === $supertype->getClassName()) { + return new self( + $supertype->getClassName(), + $supertype->types, + $subclass->getSubtractedType(), + null, + $supertype->variances, + ); + } + foreach ($supertype->variances as $variance) { if (!$variance->invariant()) { return $subclass; diff --git a/tests/PHPStan/Analyser/nsrt/bug-15266.php b/tests/PHPStan/Analyser/nsrt/bug-15266.php new file mode 100644 index 00000000000..b3180360f70 --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/bug-15266.php @@ -0,0 +1,50 @@ +> | class-string> $class + * @return class-string> | class-string> + */ +function parametrized(string $class): string +{ + if ($class !== X::class) { + assertType('class-string>', $class); + } + + return $class; +} + +/** + * @param class-string> | class-string> $class + * @return class-string> | class-string> + */ +function star(string $class): string +{ + if ($class !== X::class) { + assertType('class-string>', $class); + } + + return $class; +} + +/** + * @param class-string | class-string $class + * @return class-string | class-string + */ +function raw(string $class): string +{ + if ($class !== X::class) { + assertType('class-string', $class); + } + + return $class; +} diff --git a/turbo-ext/src/GenericObjectType.cpp b/turbo-ext/src/GenericObjectType.cpp index 25fc3dd0ff7..b2bff536ad5 100644 --- a/turbo-ext/src/GenericObjectType.cpp +++ b/turbo-ext/src/GenericObjectType.cpp @@ -798,13 +798,16 @@ class GenericObjectType /* Gives $subclass, a class written without type arguments, the ones * $supertype implies for it through the class's `@extends` and * `@implements` tags: Some with Option is Some, Err with - * Result is Err. + * Result is Err. The class of $supertype itself + * takes its arguments and call-site variance as written: X with X<*> is + * X<*>. * * Returns $subclass unchanged (the same object) unless $supertype is a - * generic object type without call-site variance, $subclass is a - * generic subtype of its class, and $supertype determines every type - * argument of $subclass - an explicit argument would claim more than is - * known. UNDEF = pending exception */ + * generic object type and $subclass is its class or a generic subtype + * of it. A subtype also stays unchanged when $supertype has call-site + * variance or does not determine every type argument of the subtype - + * an explicit argument would claim more than is known. UNDEF = pending + * exception */ static zv::Val specializeSubclass(zval *supertype, zval *subclass) { /* $subclass is exactly an ObjectType: the shadowing class carries @@ -813,8 +816,23 @@ class GenericObjectType if (!zv::Ref(supertype).instanceOf(pt_ce_generic_object_type) || Z_OBJCE_P(subclass) != pt_ce_object_type) return zv::Val::copyOf(zv::Ref(subclass)); zend_object *supertypeObject = Z_OBJ_P(supertype); + /* $subclass->getClassName() — the slot, the object is exactly the + * native class */ + zend_string *subclassName = pt_object_type_class_name(Z_OBJ_P(subclass)); + if (UNEXPECTED(subclassName == NULL)) return zv::Val(); + zv::Val supertypeClassName = pt_type_call(supertypeObject, PT_LC("getclassname"), 0, NULL); + if (UNEXPECTED(supertypeClassName.isUndef())) return zv::Val(); zval *variances = variancesOf(supertypeObject); if (UNEXPECTED(variances == NULL)) return zv::Val(); + if (zv::Ref(supertypeClassName.raw()).isString() && zend_string_equals(subclassName, Z_STR_P(supertypeClassName.raw()))) { + zval *types = typesOf(supertypeObject); + if (UNEXPECTED(types == NULL)) return zv::Val(); + zval *subtractedType = pt_object_type_subtracted_type(Z_OBJ_P(subclass)); + if (UNEXPECTED(subtractedType == NULL)) return zv::Val(); + zend_string *supertypeName = Z_STR_P(supertypeClassName.raw()); + return create(supertypeName, types, Z_TYPE_P(subtractedType) == IS_NULL ? NULL : subtractedType, NULL, variances); + } + for (zv::ArrayEntry entry : zv::ArrRef(variances)) { zv::Ref variance = entry.value().deref(); if (UNEXPECTED(!variance.isObject())) { @@ -857,8 +875,6 @@ class GenericObjectType } zv::Val bare = create(name.get(), templateTypeList.raw(), NULL, NULL, NULL); if (UNEXPECTED(bare.isUndef())) return zv::Val(); - zv::Val supertypeClassName = pt_type_call(supertypeObject, PT_LC("getclassname"), 0, NULL); - if (UNEXPECTED(supertypeClassName.isUndef())) return zv::Val(); zv::Val ancestor = pt_type_call(Z_OBJ_P(bare.raw()), PT_LC("getancestorwithclassname"), 1, supertypeClassName.raw()); if (UNEXPECTED(ancestor.isUndef())) return zv::Val(); if (ancestor.isNull()) return zv::Val::copyOf(zv::Ref(subclass));