From aa88f7674aae67fd0a3503f5b157a4f900892763 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Mon, 30 Nov 2026 05:59:35 +0000 Subject: [PATCH 1/7] =?UTF-8?q?Keep=20static<=E2=80=A6>=20on=20the=20class?= =?UTF-8?q?=20when=20a=20subclass=20cannot=20hold=20its=20type=20arguments?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `static` called on a subclass becomes the subclass with the type arguments passed on to its own templates, but a subclass that does not pass them, like `IntVec implements Coll`, holds only ints whatever U is: `$intVec->map(fn (int $i): string => …)` was IntVec. Such a type now stays `Coll`, which is all that is known. The class's own templates stand for what the subclass passes to them, so `static` on IntVec is still IntVec, while `static` on `IntStringPair extends Pair` is `Pair`. Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7 --- src/Type/Generic/GenericStaticType.php | 49 ++++++- .../nsrt/class-constant-static-type.php | 2 +- .../generic-static-subclass-arguments.php | 121 +++++++++++++++++ .../Rules/Functions/ReturnTypeRuleTest.php | 16 +++ .../generic-static-subclass-arguments.php | 63 +++++++++ turbo-ext/src/GenericStaticType.cpp | 128 +++++++++++++++++- turbo-ext/src/generated/GenericStaticType.h | 77 ++++++----- 7 files changed, 415 insertions(+), 41 deletions(-) create mode 100644 tests/PHPStan/Analyser/nsrt/generic-static-subclass-arguments.php create mode 100644 tests/PHPStan/Rules/Functions/data/generic-static-subclass-arguments.php diff --git a/src/Type/Generic/GenericStaticType.php b/src/Type/Generic/GenericStaticType.php index 70b80143e19..b4893ab96c0 100644 --- a/src/Type/Generic/GenericStaticType.php +++ b/src/Type/Generic/GenericStaticType.php @@ -19,6 +19,7 @@ use function array_key_exists; use function array_keys; use function array_map; +use function array_search; use function count; /** @api */ @@ -122,7 +123,7 @@ public function changeBaseClass(ClassReflection $classReflection): StaticType } if (!$classReflection->isGeneric()) { - return new StaticType($classReflection); + return $this->keepingTypeArguments(new StaticType($classReflection)); } $templateTags = $this->getClassReflection()->getTemplateTags(); @@ -177,7 +178,51 @@ public function changeBaseClass(ClassReflection $classReflection): StaticType $newClassVariances[$templateType->getName()] = $indexedVariances[$typeName]; } - return new self($classReflection, $classReflection->typeMapToList(new TemplateTypeMap($newClassTypes)), $this->subtractedType, $classReflection->varianceMapToList(new TemplateTypeVarianceMap($newClassVariances))); + return $this->keepingTypeArguments(new self($classReflection, $classReflection->typeMapToList(new TemplateTypeMap($newClassTypes)), $this->subtractedType, $classReflection->varianceMapToList(new TemplateTypeVarianceMap($newClassVariances)))); + } + + /** + * A subclass that does not pass the type arguments on to the class, like + * `IntList implements Collection` for `static`, cannot hold them, + * so the type stays on the class: `Collection` is all that is known. + */ + private function keepingTypeArguments(StaticType $changed): StaticType + { + $ancestor = $changed->getStaticObjectType()->getAncestorWithClassName($this->getClassName()); + if ($ancestor === null) { + return $changed; + } + + $ancestorReflection = $ancestor->getClassReflection(); + if ($ancestorReflection === null || !$ancestorReflection->isGeneric()) { + return $changed; + } + + // the class's own templates stand for what the subclass passes to them, + // and so do the arguments left out + $ancestorTypes = $ancestorReflection->typeMapToList($ancestorReflection->getActiveTemplateTypeMap()); + $templateNames = array_keys($this->getClassReflection()->getTemplateTags()); + $types = $ancestorTypes; + foreach ($this->types as $i => $type) { + if ( + $type instanceof TemplateType + && $type->getScope()->getClassName() === $this->getClassName() + && $type->getScope()->getFunctionName() === null + ) { + $index = array_search($type->getName(), $templateNames, true); + if ($index !== false && array_key_exists($index, $ancestorTypes)) { + $type = $ancestorTypes[$index]; + } + } + $types[$i] = $type; + } + + $requested = new GenericObjectType($this->getClassName(), $types, variances: $this->variances); + if ($requested->isSuperTypeOf($ancestor)->yes()) { + return $changed; + } + + return $this; } public function isSuperTypeOf(Type $type): IsSuperTypeOfResult diff --git a/tests/PHPStan/Analyser/nsrt/class-constant-static-type.php b/tests/PHPStan/Analyser/nsrt/class-constant-static-type.php index 4b42b3fda67..b7bdf602840 100644 --- a/tests/PHPStan/Analyser/nsrt/class-constant-static-type.php +++ b/tests/PHPStan/Analyser/nsrt/class-constant-static-type.php @@ -60,5 +60,5 @@ function test(Base $base, Child $child, GenericBase $genericBase, GenericChild $ assertType('class-string', $child::IMPL); assertType('list>', $child::IMPLS); assertType('class-string>', $genericBase::IMPL); - assertType('class-string', $genericChild::IMPL); + assertType('class-string>', $genericChild::IMPL); } diff --git a/tests/PHPStan/Analyser/nsrt/generic-static-subclass-arguments.php b/tests/PHPStan/Analyser/nsrt/generic-static-subclass-arguments.php new file mode 100644 index 00000000000..27dc71cf6c2 --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/generic-static-subclass-arguments.php @@ -0,0 +1,121 @@ + */ + public function filter(); + + /** + * @template U + * @param callable(T): U $f + * @return static + */ + public function map(callable $f); + +} + +/** @implements Coll */ +final class IntVec implements Coll +{ + + public function filter() + { + return $this; + } + + public function map(callable $f) + { + throw new \Exception(); + } + +} + +/** + * @template-covariant T + * @implements Coll + */ +final class Vec implements Coll +{ + + public function filter() + { + return $this; + } + + public function map(callable $f) + { + throw new \Exception(); + } + +} + +/** + * @template K + * @template-covariant V + * @implements Coll + */ +final class Dict implements Coll +{ + + public function filter() + { + return $this; + } + + public function map(callable $f) + { + throw new \Exception(); + } + +} + +/** + * @template K + * @template V + */ +class Pair +{ + + /** @return static */ + public function same() + { + return $this; + } + + /** @return static */ + public function flip() + { + throw new \Exception(); + } + +} + +/** @extends Pair */ +final class IntStringPair extends Pair +{ + +} + +/** + * @param Vec $vec + * @param Dict $dict + */ +function test(IntVec $intVec, Vec $vec, Dict $dict, IntStringPair $pair): void +{ + // an IntVec holds only ints, the strings are in some Coll + assertType('GenericStaticSubclassArguments\Coll<\'a\'>', $intVec->map(static fn (int $i): string => 'a')); + // an IntVec holds any int, not only 1 + assertType('GenericStaticSubclassArguments\Coll<1>', $intVec->map(static fn (int $i): int => 1)); + assertType('GenericStaticSubclassArguments\IntVec', $intVec->filter()); + assertType('GenericStaticSubclassArguments\Vec<\'a\'>', $vec->map(static fn (int $i): string => 'a')); + assertType('GenericStaticSubclassArguments\Vec', $vec->filter()); + assertType('GenericStaticSubclassArguments\Dict', $dict->map(static fn (int $i): string => 'a')); + assertType('GenericStaticSubclassArguments\IntStringPair', $pair->same()); + assertType('GenericStaticSubclassArguments\Pair', $pair->flip()); +} diff --git a/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php b/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php index 9f5d379f659..cdad750ba22 100644 --- a/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php +++ b/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php @@ -46,6 +46,22 @@ public function testArrayObjectObjectInput(): void $this->analyse([__DIR__ . '/../../Analyser/nsrt/array-object-object-input.php'], []); } + public function testGenericStaticSubclassArguments(): void + { + $this->checkNullables = true; + $this->checkExplicitMixed = false; + $this->analyse([__DIR__ . '/data/generic-static-subclass-arguments.php'], [ + [ + 'Function GenericStaticSubclassArgumentsRules\\mapToString() should return GenericStaticSubclassArgumentsRules\\IntVec but returns GenericStaticSubclassArgumentsRules\\Coll.', + 51, + ], + [ + 'Function GenericStaticSubclassArgumentsRules\\positives() should return GenericStaticSubclassArgumentsRules\\IntVec but returns GenericStaticSubclassArgumentsRules\\Coll>.', + 57, + ], + ]); + } + public function testTemplateBoundedByTemplate(): void { $this->checkNullables = true; diff --git a/tests/PHPStan/Rules/Functions/data/generic-static-subclass-arguments.php b/tests/PHPStan/Rules/Functions/data/generic-static-subclass-arguments.php new file mode 100644 index 00000000000..9e96c15b6d7 --- /dev/null +++ b/tests/PHPStan/Rules/Functions/data/generic-static-subclass-arguments.php @@ -0,0 +1,63 @@ + */ + public function filter(); + + /** @return static */ + public function positives(); + + /** + * @template U + * @param callable(T): U $f + * @return static + */ + public function map(callable $f); + +} + +/** @implements Coll */ +final class IntVec implements Coll +{ + + public function filter() + { + return $this; + } + + public function positives() + { + throw new \Exception(); + } + + public function map(callable $f) + { + throw new \Exception(); + } + +} + +/** + * an IntVec holds only ints, the strings are in some Coll + * @param callable(int): string $f + */ +function mapToString(IntVec $intVec, callable $f): IntVec +{ + return $intVec->map($f); +} + +// an IntVec holds any int, not only positive ones +function positives(IntVec $intVec): IntVec +{ + return $intVec->positives(); +} + +function filter(IntVec $intVec): IntVec +{ + return $intVec->filter(); +} diff --git a/turbo-ext/src/GenericStaticType.cpp b/turbo-ext/src/GenericStaticType.cpp index 7269ddd303f..8197a8e1f7c 100644 --- a/turbo-ext/src/GenericStaticType.cpp +++ b/turbo-ext/src/GenericStaticType.cpp @@ -239,7 +239,7 @@ class GenericStaticType if (!generic) { zval result; if (UNEXPECTED(!pt_static_type_new(&result, classReflection))) return zv::Val(); - return zv::Val::adopt(result); + return keepingTypeArguments(zv::Val::adopt(result), ownClassName); } /* $templateTags = $this->getClassReflection()->getTemplateTags() */ @@ -348,7 +348,131 @@ class GenericStaticType zend_type_error("phpstan_turbo: typeMapToList()/varianceMapToList() must return array"); return zv::Val(); } - return create(classReflection, listTypes.raw(), subtracted, listVariances.raw()); + return keepingTypeArguments(create(classReflection, listTypes.raw(), subtracted, listVariances.raw()), ownClassName); + } + + /* $changed when its static object type's ancestor with the own class name + * is none, not generic, or certainly within the own type arguments, with + * the own class templates and the arguments left out taken from that + * ancestor; $this otherwise; UNDEF = pending exception */ + zv::Val keepingTypeArguments(zv::Val changed, zv::Val &ownClassName) const + { + if (UNEXPECTED(changed.isUndef())) return zv::Val(); + zv::Val changedObject = pt_type_call(Z_OBJ_P(changed.raw()), PT_LC("getstaticobjecttype"), 0, NULL); + if (UNEXPECTED(changedObject.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(changedObject.raw()).isObject())) { + zend_type_error("phpstan_turbo: getStaticObjectType() must return an object"); + return zv::Val(); + } + zv::Val ancestor = pt_type_call(Z_OBJ_P(changedObject.raw()), PT_LC("getancestorwithclassname"), 1, ownClassName.raw()); + if (UNEXPECTED(ancestor.isUndef())) return zv::Val(); + if (ancestor.isNull()) return changed; + if (UNEXPECTED(!zv::Ref(ancestor.raw()).isObject())) { + zend_type_error("phpstan_turbo: getAncestorWithClassName() must return an object or null"); + return zv::Val(); + } + zv::Val ancestorReflection = pt_type_call(Z_OBJ_P(ancestor.raw()), PT_LC("getclassreflection"), 0, NULL); + if (UNEXPECTED(ancestorReflection.isUndef())) return zv::Val(); + if (ancestorReflection.isNull()) return changed; + if (UNEXPECTED(!zv::Ref(ancestorReflection.raw()).isObject())) { + zend_type_error("phpstan_turbo: getClassReflection() must return an object or null"); + return zv::Val(); + } + bool ancestorGeneric; + if (UNEXPECTED(!pt_class_reflection_is_generic(Z_OBJ_P(ancestorReflection.raw()), ancestorGeneric))) return zv::Val(); + if (!ancestorGeneric) return changed; + + /* the class's own templates stand for what the subclass passes to them, + * and so do the arguments left out: + * $ancestorReflection->typeMapToList($ancestorReflection->getActiveTemplateTypeMap()) */ + zv::Val ancestorTypeMap = pt_class_reflection_get_active_template_type_map(Z_OBJ_P(ancestorReflection.raw())); + if (UNEXPECTED(ancestorTypeMap.isUndef())) return zv::Val(); + zv::Val ancestorTypes = pt_class_reflection_type_map_to_list(Z_OBJ_P(ancestorReflection.raw()), ancestorTypeMap.raw()); + if (UNEXPECTED(ancestorTypes.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(ancestorTypes.raw()).isArray())) { + zend_type_error("phpstan_turbo: typeMapToList() must return array"); + return zv::Val(); + } + zv::Val ownReflection = pt_static_type_this_class_reflection(self); + if (UNEXPECTED(ownReflection.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(ownReflection.raw()).isObject())) { + zend_type_error("phpstan_turbo: getClassReflection() must return an object"); + return zv::Val(); + } + zv::Val templateTags = pt_type_call(Z_OBJ_P(ownReflection.raw()), PT_LC("gettemplatetags"), 0, NULL); + if (UNEXPECTED(templateTags.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(templateTags.raw()).isArray())) { + zend_type_error("phpstan_turbo: getTemplateTags() must return array"); + return zv::Val(); + } + zval *ownTypes = types(); + zval *ownVariances = ownTypes != NULL ? variances() : NULL; + if (UNEXPECTED(ownVariances == NULL)) return zv::Val(); + zval requestedTypes; + ZVAL_ARR(&requestedTypes, zend_array_dup(Z_ARRVAL_P(ancestorTypes.raw()))); + zv::Val requestedTypesVal = zv::Val::adopt(requestedTypes); + zend_ulong i; + zval *type; + ZEND_HASH_FOREACH_NUM_KEY_VAL(Z_ARRVAL_P(ownTypes), i, type) { + zval *requested = type; + bool isTemplate; + if (UNEXPECTED(!pt_type_instanceof(type, PT_CLASS_TEMPLATE_TYPE, isTemplate))) return zv::Val(); + if (isTemplate) { + zv::Val scope = pt_type_call(Z_OBJ_P(type), PT_LC("getscope"), 0, NULL); + if (UNEXPECTED(scope.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(scope.raw()).isObject())) { + zend_type_error("phpstan_turbo: getScope() must return an object"); + return zv::Val(); + } + zv::Val scopeClassName = pt_type_call(Z_OBJ_P(scope.raw()), PT_LC("getclassname"), 0, NULL); + if (UNEXPECTED(scopeClassName.isUndef())) return zv::Val(); + bool ownTemplate = zend_is_identical(scopeClassName.raw(), ownClassName.raw()); + if (ownTemplate) { + zv::Val scopeFunctionName = pt_type_call(Z_OBJ_P(scope.raw()), PT_LC("getfunctionname"), 0, NULL); + if (UNEXPECTED(scopeFunctionName.isUndef())) return zv::Val(); + ownTemplate = scopeFunctionName.isNull(); + } + if (ownTemplate) { + zv::Val name = pt_type_call(Z_OBJ_P(type), PT_LC("getname"), 0, NULL); + if (UNEXPECTED(name.isUndef())) return zv::Val(); + /* array_search($type->getName(), $templateNames, true) */ + zend_long index = -1; + zend_long position = 0; + zend_string *tagName; + zend_ulong tagIndex; + ZEND_HASH_FOREACH_KEY(Z_ARRVAL_P(templateTags.raw()), tagIndex, tagName) { + zval key; + if (tagName != NULL) { + ZVAL_STR(&key, tagName); + } else { + ZVAL_LONG(&key, (zend_long) tagIndex); + } + if (zend_is_identical(&key, name.raw())) { + index = position; + break; + } + position++; + } ZEND_HASH_FOREACH_END(); + if (index >= 0) { + zval *ancestorType = zend_hash_index_find(Z_ARRVAL_P(ancestorTypes.raw()), (zend_ulong) index); + if (ancestorType != NULL) requested = ancestorType; + } + } + } + Z_TRY_ADDREF_P(requested); + zend_hash_index_update(Z_ARRVAL_P(requestedTypesVal.raw()), i, requested); + } ZEND_HASH_FOREACH_END(); + + /* new GenericObjectType($this->getClassName(), $types, null, null, $this->variances) */ + zval requestedRaw; + if (UNEXPECTED(!pt_generic_object_type_new(&requestedRaw, Z_STR_P(ownClassName.raw()), requestedTypesVal.raw(), NULL, NULL, ownVariances))) return zv::Val(); + zv::Val requestedType = zv::Val::adopt(requestedRaw); + zv::Val result = pt_type_op(Z_OBJ_P(requestedType.raw()), PT_OP_IS_SUPER_TYPE_OF, 1, ancestor.raw()); + if (UNEXPECTED(result.isUndef())) return zv::Val(); + zend_long value = pt_type_result_trinary(result.raw()); + if (UNEXPECTED(value < 0)) return zv::Val(); + if (value == PT_TRI_YES) return changed; + return thisValue(); } /* the CompoundType callback; the static object types' answer for diff --git a/turbo-ext/src/generated/GenericStaticType.h b/turbo-ext/src/generated/GenericStaticType.h index ade11b4c9e4..fa9e08c3e72 100644 --- a/turbo-ext/src/generated/GenericStaticType.h +++ b/turbo-ext/src/generated/GenericStaticType.h @@ -55,24 +55,26 @@ inline constexpr char strings[] = "getAncestorWithClassName\0" /* 239 */ "PHPStan\\Type\\StaticType\0" /* 264 */ "changeBaseClass\0" /* 288 */ - "type\0" /* 304 */ - "PHPStan\\Type\\IsSuperTypeOfResult\0" /* 309 */ - "isSuperTypeOf\0" /* 342 */ - "cb\0" /* 356 */ - "traverse\0" /* 359 */ - "right\0" /* 368 */ - "traverseSimultaneously\0" /* 374 */ - "changeSubtractedType\0" /* 397 */ - "receivedType\0" /* 418 */ - "PHPStan\\Type\\Generic\\TemplateTypeMap\0" /* 431 */ - "inferTemplateTypes\0" /* 468 */ - "positionVariance\0" /* 487 */ - "PHPStan\\Type\\Generic\\TemplateTypeVariance\0" /* 504 */ - "getReferencedTemplateTypes\0" /* 546 */ - "PHPStan\\PhpDocParser\\Ast\\Type\\TypeNode\0" /* 573 */ - "toPhpDocNode\0" /* 612 */ - "hasTemplateOrLateResolvableType\0" /* 625 */ - "hasUnresolvedTemplateArgumentType"; /* 657 */ + "changed\0" /* 304 */ + "keepingTypeArguments\0" /* 312 */ + "type\0" /* 333 */ + "PHPStan\\Type\\IsSuperTypeOfResult\0" /* 338 */ + "isSuperTypeOf\0" /* 371 */ + "cb\0" /* 385 */ + "traverse\0" /* 388 */ + "right\0" /* 397 */ + "traverseSimultaneously\0" /* 403 */ + "changeSubtractedType\0" /* 426 */ + "receivedType\0" /* 447 */ + "PHPStan\\Type\\Generic\\TemplateTypeMap\0" /* 460 */ + "inferTemplateTypes\0" /* 497 */ + "positionVariance\0" /* 516 */ + "PHPStan\\Type\\Generic\\TemplateTypeVariance\0" /* 533 */ + "getReferencedTemplateTypes\0" /* 575 */ + "PHPStan\\PhpDocParser\\Ast\\Type\\TypeNode\0" /* 602 */ + "toPhpDocNode\0" /* 641 */ + "hasTemplateOrLateResolvableType\0" /* 654 */ + "hasUnresolvedTemplateArgumentType"; /* 686 */ inline constexpr reg::PackedArg args[] = { reg::packed(0, 0, 16), /* __construct $classReflection */ reg::packed(51, MAY_BE_ARRAY), /* __construct $types */ @@ -86,20 +88,22 @@ inline constexpr reg::PackedArg args[] = { reg::packed(112, MAY_BE_NULL, 208), /* getAncestorWithClassName return */ reg::packed(0, 0, 16), /* changeBaseClass $classReflection */ reg::packed(112, 0, 264), /* changeBaseClass return */ - reg::packed(304, 0, 72), /* isSuperTypeOf $type */ - reg::packed(112, 0, 309), /* isSuperTypeOf return */ - reg::packed(356, MAY_BE_CALLABLE), /* traverse $cb */ + reg::packed(304, 0, 264), /* keepingTypeArguments $changed */ + reg::packed(112, 0, 264), /* keepingTypeArguments return */ + reg::packed(333, 0, 72), /* isSuperTypeOf $type */ + reg::packed(112, 0, 338), /* isSuperTypeOf return */ + reg::packed(385, MAY_BE_CALLABLE), /* traverse $cb */ reg::packed(112, 0, 72), /* traverse return */ - reg::packed(368, 0, 72), /* traverseSimultaneously $right */ - reg::packed(356, MAY_BE_CALLABLE), /* traverseSimultaneously $cb */ + reg::packed(397, 0, 72), /* traverseSimultaneously $right */ + reg::packed(385, MAY_BE_CALLABLE), /* traverseSimultaneously $cb */ reg::packed(112, 0, 72), /* traverseSimultaneously return */ reg::packed(57, MAY_BE_NULL, 72), /* changeSubtractedType $subtractedType */ reg::packed(112, 0, 72), /* changeSubtractedType return */ - reg::packed(418, 0, 72), /* inferTemplateTypes $receivedType */ - reg::packed(112, 0, 431), /* inferTemplateTypes return */ - reg::packed(487, 0, 504), /* getReferencedTemplateTypes $positionVariance */ + reg::packed(447, 0, 72), /* inferTemplateTypes $receivedType */ + reg::packed(112, 0, 460), /* inferTemplateTypes return */ + reg::packed(516, 0, 533), /* getReferencedTemplateTypes $positionVariance */ reg::packed(112, MAY_BE_ARRAY), /* getReferencedTemplateTypes return */ - reg::packed(112, 0, 573), /* toPhpDocNode return */ + reg::packed(112, 0, 602), /* toPhpDocNode return */ reg::packed(112, MAY_BE_BOOL), /* hasTemplateOrLateResolvableType return */ reg::packed(112, MAY_BE_BOOL), /* hasUnresolvedTemplateArgumentType return */ }; @@ -115,15 +119,16 @@ inline constexpr sigtab::Sig getClassReflection = { { 135 /* getClassReflection inline constexpr sigtab::Sig getStaticObjectType = { { 178 /* getStaticObjectType */, 0, 7, 0, 7, ZEND_ACC_PUBLIC } }; inline constexpr sigtab::Sig getAncestorWithClassName = { { 239 /* getAncestorWithClassName */, 1, 8, 1, 9, ZEND_ACC_PUBLIC } }; inline constexpr sigtab::Sig changeBaseClass = { { 288 /* changeBaseClass */, 1, 10, 1, 11, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isSuperTypeOf = { { 342 /* isSuperTypeOf */, 1, 12, 1, 13, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig traverse = { { 359 /* traverse */, 1, 14, 1, 15, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig traverseSimultaneously = { { 374 /* traverseSimultaneously */, 2, 16, 2, 18, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig changeSubtractedType = { { 397 /* changeSubtractedType */, 1, 19, 1, 20, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig inferTemplateTypes = { { 468 /* inferTemplateTypes */, 1, 21, 1, 22, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getReferencedTemplateTypes = { { 546 /* getReferencedTemplateTypes */, 1, 23, 1, 24, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig toPhpDocNode = { { 612 /* toPhpDocNode */, 0, 25, 0, 25, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig hasTemplateOrLateResolvableType = { { 625 /* hasTemplateOrLateResolvableType */, 0, 26, 0, 26, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig hasUnresolvedTemplateArgumentType = { { 657 /* hasUnresolvedTemplateArgumentType */, 0, 27, 0, 27, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig keepingTypeArguments = { { 312 /* keepingTypeArguments */, 1, 12, 1, 13, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig isSuperTypeOf = { { 371 /* isSuperTypeOf */, 1, 14, 1, 15, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig traverse = { { 388 /* traverse */, 1, 16, 1, 17, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig traverseSimultaneously = { { 403 /* traverseSimultaneously */, 2, 18, 2, 20, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig changeSubtractedType = { { 426 /* changeSubtractedType */, 1, 21, 1, 22, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig inferTemplateTypes = { { 497 /* inferTemplateTypes */, 1, 23, 1, 24, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getReferencedTemplateTypes = { { 575 /* getReferencedTemplateTypes */, 1, 25, 1, 26, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig toPhpDocNode = { { 641 /* toPhpDocNode */, 0, 27, 0, 27, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig hasTemplateOrLateResolvableType = { { 654 /* hasTemplateOrLateResolvableType */, 0, 28, 0, 28, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig hasUnresolvedTemplateArgumentType = { { 686 /* hasUnresolvedTemplateArgumentType */, 0, 29, 0, 29, ZEND_ACC_PUBLIC } }; } // namespace sig } // namespace ptdecl::GenericStaticType From d2028fe68ba85edbbe2502cf5060a03bc808c232 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Mon, 30 Nov 2026 06:00:10 +0000 Subject: [PATCH 2/7] Add @phpstan-consistent-templates A class or an interface with @phpstan-consistent-templates, or @psalm-consistent-templates, makes the classes below it declare the same template types, pass them on in the order they declare them and bound them at most as tightly, so that the class of an object with other type arguments is a type. The rule checking them reports generics.inconsistentTemplates under bleeding edge (checkConsistentTemplates). Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7 --- conf/bleedingEdge.neon | 1 + conf/config.neon | 1 + conf/parametersSchema.neon | 1 + src/PhpDoc/PhpDocNodeResolver.php | 11 ++ src/PhpDoc/ResolvedPhpDocBlock.php | 11 ++ src/Reflection/ConsistentTemplatesHelper.php | 49 ++++++ .../Generics/ConsistentTemplatesRule.php | 163 +++++++++++++++++ src/Rules/PhpDoc/InvalidPHPStanDocTagRule.php | 1 + .../Generics/ConsistentTemplatesRuleTest.php | 62 +++++++ .../Generics/data/consistent-templates.php | 165 ++++++++++++++++++ 10 files changed, 465 insertions(+) create mode 100644 src/Reflection/ConsistentTemplatesHelper.php create mode 100644 src/Rules/Generics/ConsistentTemplatesRule.php create mode 100644 tests/PHPStan/Rules/Generics/ConsistentTemplatesRuleTest.php create mode 100644 tests/PHPStan/Rules/Generics/data/consistent-templates.php diff --git a/conf/bleedingEdge.neon b/conf/bleedingEdge.neon index d82b36a0599..ee3e7f6b91b 100644 --- a/conf/bleedingEdge.neon +++ b/conf/bleedingEdge.neon @@ -42,3 +42,4 @@ parameters: checkConditionalParameterTypes: true checkMixedWitnessTypes: true recursiveLoopTypes: true + checkConsistentTemplates: true diff --git a/conf/config.neon b/conf/config.neon index 2a9f2e621ae..44fe68ef960 100644 --- a/conf/config.neon +++ b/conf/config.neon @@ -74,6 +74,7 @@ parameters: checkConditionalParameterTypes: false checkMixedWitnessTypes: false recursiveLoopTypes: false + checkConsistentTemplates: false fileExtensions: - php checkAdvancedIsset: false diff --git a/conf/parametersSchema.neon b/conf/parametersSchema.neon index eb2014cf8eb..6b046a7619f 100644 --- a/conf/parametersSchema.neon +++ b/conf/parametersSchema.neon @@ -71,6 +71,7 @@ parametersSchema: checkConditionalParameterTypes: bool() checkMixedWitnessTypes: bool() recursiveLoopTypes: bool() + checkConsistentTemplates: bool() ]) fileExtensions: listOf(string()) checkAdvancedIsset: bool() diff --git a/src/PhpDoc/PhpDocNodeResolver.php b/src/PhpDoc/PhpDocNodeResolver.php index 962f9fb079a..32187964cf2 100644 --- a/src/PhpDoc/PhpDocNodeResolver.php +++ b/src/PhpDoc/PhpDocNodeResolver.php @@ -742,6 +742,17 @@ public function resolveHasConsistentConstructor(PhpDocNode $phpDocNode): bool return false; } + public function resolveHasConsistentTemplates(PhpDocNode $phpDocNode): bool + { + foreach (['@phpstan-consistent-templates', '@psalm-consistent-templates'] as $tagName) { + if (count($phpDocNode->getTagsByName($tagName)) > 0) { + return true; + } + } + + return false; + } + public function resolveAcceptsNamedArguments(PhpDocNode $phpDocNode): bool { return count($phpDocNode->getTagsByName('@no-named-arguments')) === 0; diff --git a/src/PhpDoc/ResolvedPhpDocBlock.php b/src/PhpDoc/ResolvedPhpDocBlock.php index e1026770cef..9fa44dcf79b 100644 --- a/src/PhpDoc/ResolvedPhpDocBlock.php +++ b/src/PhpDoc/ResolvedPhpDocBlock.php @@ -160,6 +160,8 @@ final class ResolvedPhpDocBlock private ?bool $hasConsistentConstructor = null; + private ?bool $hasConsistentTemplates = null; + private ?bool $acceptsNamedArguments = null; private function __construct() @@ -254,6 +256,7 @@ public static function createEmpty(): self $self->isImmutable = false; $self->isAllowedPrivateMutation = false; $self->hasConsistentConstructor = false; + $self->hasConsistentTemplates = false; $self->acceptsNamedArguments = true; return $self; @@ -312,6 +315,7 @@ public function merge(ResolvedPhpDocBlock $parent, InheritedPhpDocParameterMappi $result->isImmutable = $this->isImmutable(); $result->isAllowedPrivateMutation = $this->isAllowedPrivateMutation(); $result->hasConsistentConstructor = $this->hasConsistentConstructor(); + $result->hasConsistentTemplates = $this->hasConsistentTemplates(); $result->acceptsNamedArguments = $acceptsNamedArguments; return $result; @@ -828,6 +832,13 @@ public function hasConsistentConstructor(): bool ); } + public function hasConsistentTemplates(): bool + { + return $this->hasConsistentTemplates ??= $this->phpDocNodeResolver->resolveHasConsistentTemplates( + $this->phpDocNode, + ); + } + public function acceptsNamedArguments(): bool { return $this->acceptsNamedArguments ??= $this->phpDocNodeResolver->resolveAcceptsNamedArguments( diff --git a/src/Reflection/ConsistentTemplatesHelper.php b/src/Reflection/ConsistentTemplatesHelper.php new file mode 100644 index 00000000000..3f01aa9ba03 --- /dev/null +++ b/src/Reflection/ConsistentTemplatesHelper.php @@ -0,0 +1,49 @@ +`. + */ +#[AutowiredService] +final class ConsistentTemplatesHelper +{ + + /** + * The class itself or the ancestor with `@phpstan-consistent-templates`, the nearest one first. + * Breadth-first, each ancestor once: interfaces that extend each other form diamonds. + */ + public function findConsistentTemplatesClass(ClassReflection $classReflection): ?ClassReflection + { + $queue = [$classReflection]; + $visited = []; + while ($queue !== []) { + $current = array_shift($queue); + if (isset($visited[$current->getName()])) { + continue; + } + $visited[$current->getName()] = true; + + $resolvedPhpDoc = $current->getResolvedPhpDoc(); + if ($resolvedPhpDoc !== null && $resolvedPhpDoc->hasConsistentTemplates()) { + return $current; + } + + $parent = $current->getParentClass(); + if ($parent !== null) { + $queue[] = $parent; + } + foreach ($current->getImmediateInterfaces() as $interface) { + $queue[] = $interface; + } + } + + return null; + } + +} diff --git a/src/Rules/Generics/ConsistentTemplatesRule.php b/src/Rules/Generics/ConsistentTemplatesRule.php new file mode 100644 index 00000000000..c2e4f1db6e9 --- /dev/null +++ b/src/Rules/Generics/ConsistentTemplatesRule.php @@ -0,0 +1,163 @@ + + */ +#[RegisteredRule(level: 2)] +final class ConsistentTemplatesRule implements Rule +{ + + public function __construct( + private ConsistentTemplatesHelper $consistentTemplatesHelper, + #[AutowiredParameter(ref: '%featureToggles.checkConsistentTemplates%')] + private bool $checkConsistentTemplates, + ) + { + } + + public function getNodeType(): string + { + return InClassNode::class; + } + + public function processNode(Node $node, Scope $scope): array + { + if (!$this->checkConsistentTemplates) { + return []; + } + + $classReflection = $node->getClassReflection(); + if ($classReflection->isAnonymous()) { + return []; + } + + $ancestors = array_values($classReflection->getImmediateInterfaces()); + $parent = $classReflection->getParentClass(); + if ($parent !== null) { + $ancestors = [$parent, ...$ancestors]; + } + + $errors = []; + foreach ($ancestors as $ancestor) { + $consistentClass = $this->consistentTemplatesHelper->findConsistentTemplatesClass($ancestor); + if ($consistentClass === null) { + continue; + } + + foreach ($this->check($classReflection, $ancestor, $consistentClass) as $message) { + $errors[] = RuleErrorBuilder::message($message) + ->identifier('generics.inconsistentTemplates') + ->build(); + } + } + + return $errors; + } + + /** + * @return list + */ + private function check(ClassReflection $classReflection, ClassReflection $ancestor, ClassReflection $consistentClass): array + { + $classDescription = sprintf('%s %s', strtolower($classReflection->getClassTypeDescription()), $classReflection->getDisplayName(false)); + $ancestorDescription = sprintf('%s %s with @phpstan-consistent-templates', strtolower($ancestor->getClassTypeDescription()), $ancestor->getDisplayName(false)); + if ($consistentClass->getName() !== $ancestor->getName()) { + $ancestorDescription .= sprintf(' from %s %s', strtolower($consistentClass->getClassTypeDescription()), $consistentClass->getDisplayName(false)); + } + + $ownNames = array_keys($classReflection->getTemplateTags()); + $ancestorNames = array_keys($ancestor->getTemplateTags()); + if (count($ownNames) !== count($ancestorNames)) { + return [sprintf( + '%s declares %d template %s, but %s declares %d.', + ucfirst($classDescription), + count($ownNames), + count($ownNames) === 1 ? 'type' : 'types', + $ancestorDescription, + count($ancestorNames), + )]; + } + + $passed = $classReflection->getAncestorWithClassName($ancestor->getName()); + if ($passed === null) { + return []; + } + + $passedTypes = $passed->getActiveTemplateTypeMap(); + $ownTypes = $classReflection->getTemplateTypeMap(); + $ancestorTypes = $ancestor->getTemplateTypeMap(); + $messages = []; + foreach ($ancestorNames as $i => $ancestorName) { + $ownName = $ownNames[$i]; + $passedType = $passedTypes->getType($ancestorName); + if ( + !$passedType instanceof TemplateType + || $passedType->getName() !== $ownName + || $passedType->getScope()->getClassName() !== $classReflection->getName() + || $passedType->getScope()->getFunctionName() !== null + ) { + return [sprintf( + '%s does not pass its template types to %s in the order it declares them.', + ucfirst($classDescription), + $ancestorDescription, + )]; + } + + $ownType = $ownTypes->getType($ownName); + $ancestorType = $ancestorTypes->getType($ancestorName); + if (!$ownType instanceof TemplateType || !$ancestorType instanceof TemplateType) { + continue; + } + + // the ancestor's bound in terms of the own template types + $ancestorBound = TemplateTypeHelper::resolveTemplateTypes( + $ancestorType->getBound(), + $passedTypes, + TemplateTypeVarianceMap::createEmpty(), + TemplateTypeVariance::createInvariant(), + ); + if ($ownType->getBound()->isSuperTypeOf($ancestorBound)->yes()) { + continue; + } + + $messages[] = sprintf( + 'Bound type %s of template type %s of %s is narrower than bound type %s of template type %s of %s.', + $ownType->getBound()->describe(VerbosityLevel::typeOnly()), + $ownName, + $classDescription, + $ancestorBound->describe(VerbosityLevel::typeOnly()), + $ancestorName, + $ancestorDescription, + ); + } + + return $messages; + } + +} diff --git a/src/Rules/PhpDoc/InvalidPHPStanDocTagRule.php b/src/Rules/PhpDoc/InvalidPHPStanDocTagRule.php index 9600a7907b0..8f7025fc30a 100644 --- a/src/Rules/PhpDoc/InvalidPHPStanDocTagRule.php +++ b/src/Rules/PhpDoc/InvalidPHPStanDocTagRule.php @@ -48,6 +48,7 @@ final class InvalidPHPStanDocTagRule implements MultipleNodeTypesRule '@phpstan-property-read', '@phpstan-property-write', '@phpstan-consistent-constructor', + '@phpstan-consistent-templates', '@phpstan-assert', '@phpstan-assert-if-true', '@phpstan-assert-if-false', diff --git a/tests/PHPStan/Rules/Generics/ConsistentTemplatesRuleTest.php b/tests/PHPStan/Rules/Generics/ConsistentTemplatesRuleTest.php new file mode 100644 index 00000000000..0977f1bea04 --- /dev/null +++ b/tests/PHPStan/Rules/Generics/ConsistentTemplatesRuleTest.php @@ -0,0 +1,62 @@ + + */ +class ConsistentTemplatesRuleTest extends RuleTestCase +{ + + protected function getRule(): Rule + { + return new ConsistentTemplatesRule(new ConsistentTemplatesHelper(), true); + } + + public function testRule(): void + { + $this->analyse([__DIR__ . '/data/consistent-templates.php'], [ + [ + 'Bound type int of template type T of class ConsistentTemplates\IntBoundVec is narrower than bound type mixed of template type T of interface ConsistentTemplates\Coll with @phpstan-consistent-templates.', + 27, + ], + [ + 'Class ConsistentTemplates\IntVec declares 0 template types, but interface ConsistentTemplates\Coll with @phpstan-consistent-templates declares 1.', + 35, + ], + [ + 'Class ConsistentTemplates\Dict declares 2 template types, but interface ConsistentTemplates\Coll with @phpstan-consistent-templates declares 1.', + 45, + ], + [ + 'Class ConsistentTemplates\Wrapped does not pass its template types to interface ConsistentTemplates\Coll with @phpstan-consistent-templates in the order it declares them.', + 54, + ], + [ + 'Bound type object of template type T of class ConsistentTemplates\ObjVec is narrower than bound type mixed of template type T of class ConsistentTemplates\Vec with @phpstan-consistent-templates from interface ConsistentTemplates\Coll.', + 72, + ], + [ + 'Class ConsistentTemplates\Flipped does not pass its template types to interface ConsistentTemplates\Pair with @phpstan-consistent-templates in the order it declares them.', + 110, + ], + [ + 'Class ConsistentTemplates\PsalmIntVec declares 0 template types, but interface ConsistentTemplates\PsalmColl with @phpstan-consistent-templates declares 1.', + 137, + ], + [ + 'Interface ConsistentTemplates\IntSequence declares 0 template types, but interface ConsistentTemplates\Coll with @phpstan-consistent-templates declares 1.', + 154, + ], + [ + 'Class ConsistentTemplates\NoTag does not pass its template types to interface ConsistentTemplates\Sequence with @phpstan-consistent-templates from interface ConsistentTemplates\Coll in the order it declares them.', + 162, + ], + ]); + } + +} diff --git a/tests/PHPStan/Rules/Generics/data/consistent-templates.php b/tests/PHPStan/Rules/Generics/data/consistent-templates.php new file mode 100644 index 00000000000..27ac7efe5af --- /dev/null +++ b/tests/PHPStan/Rules/Generics/data/consistent-templates.php @@ -0,0 +1,165 @@ + + */ +class Vec implements Coll +{ + +} + +/** + * @template T of int + * @implements Coll + */ +class IntBoundVec implements Coll +{ + +} + +/** + * @implements Coll + */ +final class IntVec implements Coll +{ + +} + +/** + * @template K + * @template V + * @implements Coll + */ +final class Dict implements Coll +{ + +} + +/** + * @template T + * @implements Coll> + */ +final class Wrapped implements Coll +{ + +} + +/** + * @template-covariant U + * @extends Vec + */ +final class RenamedVec extends Vec +{ + +} + +/** + * @template-covariant T of object + * @extends Vec + */ +final class ObjVec extends Vec +{ + +} + +/** + * @template-covariant T of int + * @phpstan-consistent-templates + */ +interface IntColl +{ + +} + +/** + * @template-covariant T of int + * @implements IntColl + */ +final class IntCollImpl implements IntColl +{ + +} + +/** + * @template K + * @template V + * @phpstan-consistent-templates + */ +interface Pair +{ + +} + +/** + * @template K + * @template V + * @implements Pair + */ +final class Flipped implements Pair +{ + +} + +/** @template T */ +interface NotConsistent +{ + +} + +/** @implements NotConsistent */ +final class IntNotConsistent implements NotConsistent +{ + +} + +/** + * @template T + * @psalm-consistent-templates + */ +interface PsalmColl +{ + +} + +/** @implements PsalmColl */ +final class PsalmIntVec implements PsalmColl +{ + +} + +/** + * @template-covariant T + * @extends Coll + */ +interface Sequence extends Coll +{ + +} + +/** + * @extends Coll + */ +interface IntSequence extends Coll +{ + +} + +/** + * @template-covariant T + */ +final class NoTag implements Sequence +{ + +} From 7f7282acd7fcf988f7260a65948a6dc95ab0bf56 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Mon, 30 Nov 2026 06:32:23 +0000 Subject: [PATCH 3/7] Support type arguments on a template type bound by a class with consistent templates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `@template TColl of Coll` with `@param TColl $c` and `@return TColl` is the class TColl is with other type arguments when Coll has @phpstan-consistent-templates: called with a Vec, the function returns a Vec. The template is inferred from the class of the argument, together with the templates in the type arguments, and the type arguments are carried down to that class the way `static<…>` does. Until TColl is known, `TColl` is a Coll that only another `TColl<…>` is known to be, so returning any Coll is reported. Without the tag, the type stays the bound with the type arguments, which bleeding edge reports (generics.inconsistentTemplates). Ported to turbo-ext. Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7 --- .../ValidateIgnoredErrorsExtension.php | 3 + src/PhpDoc/TypeNodeResolver.php | 35 + src/Rules/Generics/GenericObjectTypeCheck.php | 34 +- src/Type/Generic/TemplateTypeApplication.php | 226 +++++++ .../Traverser/LateResolvableTraverser.php | 10 +- .../nsrt/template-type-application.php | 134 ++++ .../CallToFunctionParametersRuleTest.php | 19 + .../Rules/Functions/ReturnTypeRuleTest.php | 16 + .../data/template-type-application.php | 61 ++ .../PhpDoc/IncompatiblePhpDocTypeRuleTest.php | 8 +- turbo-ext/src/TemplateTypeApplication.cpp | 599 ++++++++++++++++++ .../src/generated/TemplateTypeApplication.h | 144 +++++ turbo-ext/tests/smoke.php | 3 +- turbo-ext/tests/type-family.php | 10 +- 14 files changed, 1295 insertions(+), 7 deletions(-) create mode 100644 src/Type/Generic/TemplateTypeApplication.php create mode 100644 tests/PHPStan/Analyser/nsrt/template-type-application.php create mode 100644 tests/PHPStan/Rules/Functions/data/template-type-application.php create mode 100644 turbo-ext/src/TemplateTypeApplication.cpp create mode 100644 turbo-ext/src/generated/TemplateTypeApplication.h diff --git a/src/DependencyInjection/ValidateIgnoredErrorsExtension.php b/src/DependencyInjection/ValidateIgnoredErrorsExtension.php index 3164e532acd..53b8825829c 100644 --- a/src/DependencyInjection/ValidateIgnoredErrorsExtension.php +++ b/src/DependencyInjection/ValidateIgnoredErrorsExtension.php @@ -23,6 +23,7 @@ use PHPStan\PhpDocParser\Parser\ConstExprParser; use PHPStan\PhpDocParser\Parser\TypeParser; use PHPStan\PhpDocParser\ParserConfig; +use PHPStan\Reflection\ConsistentTemplatesHelper; use PHPStan\Reflection\InitializerExprTypeResolver; use PHPStan\Reflection\MissingStaticAccessorInstanceException; use PHPStan\Reflection\PhpVersionStaticAccessor; @@ -134,6 +135,8 @@ public function resolveTypeAliasWithArguments(string $aliasName, array $argument new InitializerExprTypeResolver($constantResolver, $reflectionProviderProvider, new PhpVersion(PHP_VERSION_ID), new OperatorTypeSpecifyingExtensionRegistry(new DirectExtensionsCollection([])), new UnaryOperatorTypeSpecifyingExtensionRegistry(new DirectExtensionsCollection([])), new OversizedArrayBuilder(), true, $valueDependencyCollector), reportUnsafeArrayStringKeyCasting: null, valueDependencyCollector: $valueDependencyCollector, + consistentTemplatesHelper: new ConsistentTemplatesHelper(), + checkConsistentTemplates: false, ), ), ); diff --git a/src/PhpDoc/TypeNodeResolver.php b/src/PhpDoc/TypeNodeResolver.php index dfb86c31fdc..52f7a6c82f7 100644 --- a/src/PhpDoc/TypeNodeResolver.php +++ b/src/PhpDoc/TypeNodeResolver.php @@ -46,6 +46,7 @@ use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use PHPStan\Reflection\Assertions; use PHPStan\Reflection\Callables\SimpleImpurePoint; +use PHPStan\Reflection\ConsistentTemplatesHelper; use PHPStan\Reflection\InitializerExprContext; use PHPStan\Reflection\InitializerExprTypeResolver; use PHPStan\Reflection\Native\NativeParameterReflection; @@ -87,6 +88,7 @@ use PHPStan\Type\Generic\GenericStaticType; use PHPStan\Type\Generic\TemplateSelfReferenceTarget; use PHPStan\Type\Generic\TemplateType; +use PHPStan\Type\Generic\TemplateTypeApplication; use PHPStan\Type\Generic\TemplateTypeFactory; use PHPStan\Type\Generic\TemplateTypeMap; use PHPStan\Type\Generic\TemplateTypeScope; @@ -177,6 +179,9 @@ public function __construct( #[AutowiredParameter] private ?string $reportUnsafeArrayStringKeyCasting, private ValueDependencyCollector $valueDependencyCollector, + private ConsistentTemplatesHelper $consistentTemplatesHelper, + #[AutowiredParameter(ref: '%featureToggles.checkConsistentTemplates%')] + private bool $checkConsistentTemplates, ) { } @@ -1029,6 +1034,12 @@ static function (string $variance): TemplateTypeVariance { $mainType = $typeNode->type instanceof NameNode ? $this->resolveNameNode($typeNode->type, $nameScope) : $this->resolveIdentifierTypeNode($typeNode->type, $nameScope); + if ($mainType instanceof TemplateType) { + $application = $this->resolveTemplateTypeApplication($mainType, $genericTypes, $variances); + if ($application !== null) { + return $application; + } + } $mainTypeObjectClassNames = $mainType->getObjectClassNames(); if (count($mainTypeObjectClassNames) > 1) { if ($mainType instanceof TemplateType) { @@ -1448,6 +1459,30 @@ private function resolveTemplateTagsInDeclaration(array $valueNodes, NameScope $ return $tags; } + /** + * `TColl` for `@template TColl of Coll`: the class TColl is with other type + * arguments, which only a class with @phpstan-consistent-templates guarantees exists. + * Without it, the type is the bound with the arguments, as it always was. + * + * @param array $genericTypes + * @param array $variances + */ + private function resolveTemplateTypeApplication(TemplateType $templateType, array $genericTypes, array $variances): ?Type + { + $classReflections = $templateType->getBound()->getObjectClassReflections(); + if (count($classReflections) !== 1 || !$classReflections[0]->isGeneric()) { + return null; + } + + $consistent = $this->consistentTemplatesHelper->findConsistentTemplatesClass($classReflections[0]) !== null; + if (!$consistent && !$this->checkConsistentTemplates) { + return null; + } + + // the bound with the type arguments for a class without the tag, which the PHPDoc checks report + return new TemplateTypeApplication($templateType, new GenericStaticType($classReflections[0], $genericTypes, null, $variances), $consistent); + } + private function resolveCallableTypeNode(CallableTypeNode $typeNode, NameScope $nameScope): Type { $templateTags = []; diff --git a/src/Rules/Generics/GenericObjectTypeCheck.php b/src/Rules/Generics/GenericObjectTypeCheck.php index e9fd3969b1a..d904d19e1cc 100644 --- a/src/Rules/Generics/GenericObjectTypeCheck.php +++ b/src/Rules/Generics/GenericObjectTypeCheck.php @@ -9,6 +9,7 @@ use PHPStan\Type\Generic\GenericObjectType; use PHPStan\Type\Generic\GenericStaticType; use PHPStan\Type\Generic\TemplateType; +use PHPStan\Type\Generic\TemplateTypeApplication; use PHPStan\Type\Generic\TemplateTypeHelper; use PHPStan\Type\Generic\TemplateTypeMap; use PHPStan\Type\Generic\TemplateTypeVariance; @@ -43,8 +44,32 @@ public function check( string $typeProjectionIsRedundantMessage, ): array { - $genericTypes = $this->getGenericTypes($phpDocType); $messages = []; + $genericTypes = []; + foreach ($this->getGenericTypes($phpDocType) as $genericType) { + if (!$genericType instanceof TemplateTypeApplication) { + $genericTypes[] = $genericType; + continue; + } + + $application = $genericType; + $constructor = $application->getConstructor(); + if (!$constructor instanceof TemplateType) { + continue; + } + + $classReflection = $application->getApplication()->getClassReflection(); + $classDescription = sprintf('%s %s', strtolower($classReflection->getClassTypeDescription()), $classReflection->getDisplayName(false)); + $messages[] = RuleErrorBuilder::message(sprintf( + 'PHPDoc type %s applies type arguments to template type %s, but its bound %s does not have @phpstan-consistent-templates.', + (string) $application->toPhpDocNode(), + $constructor->getName(), + $classDescription, + )) + ->identifier('generics.inconsistentTemplates') + ->tip(sprintf('Add @phpstan-consistent-templates to the PHPDoc of %s.', $classDescription)) + ->build(); + } foreach ($genericTypes as $genericType) { $classReflection = $genericType->getClassReflection(); if ($classReflection === null) { @@ -187,7 +212,9 @@ public function check( } /** - * @return list + * The generic types, and the applications of template types to type arguments without consistent templates. + * + * @return list */ private function getGenericTypes(Type $phpDocType): array { @@ -198,6 +225,9 @@ private function getGenericTypes(Type $phpDocType): array $genericObjectTypes = []; TypeTraverser::map($phpDocType, static function (Type $type, callable $traverse) use (&$genericObjectTypes): Type { + if ($type instanceof TemplateTypeApplication && !$type->isConsistent()) { + $genericObjectTypes[] = $type; + } if ($type instanceof GenericObjectType || $type instanceof GenericStaticType) { $resolvedType = TemplateTypeHelper::resolveToBounds($type); if (!$resolvedType instanceof GenericObjectType && !$resolvedType instanceof GenericStaticType) { diff --git a/src/Type/Generic/TemplateTypeApplication.php b/src/Type/Generic/TemplateTypeApplication.php new file mode 100644 index 00000000000..87ae8b411e6 --- /dev/null +++ b/src/Type/Generic/TemplateTypeApplication.php @@ -0,0 +1,226 @@ +` for `@template TColl of Coll` where Coll has `@phpstan-consistent-templates`: + * the class TColl is with other type arguments. Once TColl is known, like `Vec`, the type + * is that class with these arguments, `Vec`. Until then it is a `Coll`, and + * only another `TColl<…>` is known to be the same class. + * + * The application is a `static<…>` of the bound's class, so a class below it gets the type + * arguments the way `static<…>` called on it does. + */ +#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/TemplateTypeApplication.cpp')] +final class TemplateTypeApplication implements CompoundType, LateResolvableType +{ + + use LateResolvableTypeTrait; + use NonGeneralizableTypeTrait; + + /** + * @param bool $consistent Whether the bound's class has `@phpstan-consistent-templates`; + * without it, the type is the bound with the type arguments. + */ + public function __construct( + private Type $constructor, + private GenericStaticType $application, + private bool $consistent, + ) + { + } + + public function isConsistent(): bool + { + return $this->consistent; + } + + public function getConstructor(): Type + { + return $this->constructor; + } + + public function getApplication(): GenericStaticType + { + return $this->application; + } + + public function getReferencedClasses(): array + { + return array_merge($this->constructor->getReferencedClasses(), $this->application->getReferencedClasses()); + } + + public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array + { + return array_merge( + $this->constructor->getReferencedTemplateTypes($positionVariance), + $this->application->getReferencedTemplateTypes($positionVariance), + ); + } + + public function equals(Type $type): bool + { + return $type instanceof self + && $this->constructor->equals($type->constructor) + && $this->application->equals($type->application); + } + + public function describe(VerbosityLevel $level): string + { + if ($this->isResolvable() || !$this->constructor instanceof TemplateType) { + return $this->resolve()->describe($level); + } + + $constructor = $this->constructor; + $arguments = implode(', ', array_map(static fn (Type $type): string => $type->describe($level), $this->application->getTypes())); + + // written as in the PHPDoc, but the cache keys tell apart the templates of the same name + return $level->handle( + static fn (): string => sprintf('%s<%s>', $constructor->getName(), $arguments), + static fn (): string => sprintf('%s<%s>', $constructor->getName(), $arguments), + static fn (): string => sprintf('%s<%s>', $constructor->getName(), $arguments), + static fn (): string => sprintf('%s<%s>', $constructor->describe(VerbosityLevel::cache()), $arguments), + ); + } + + public function isResolvable(): bool + { + return !$this->consistent || !$this->constructor instanceof TemplateType; + } + + protected function getResult(): Type + { + if (!$this->consistent) { + return $this->application->getStaticObjectType(); + } + + $applicationClassReflection = $this->application->getClassReflection(); + $results = []; + foreach ($this->constructor->getObjectClassReflections() as $classReflection) { + if ($classReflection->getName() !== $applicationClassReflection->getName() && !$classReflection->isSubclassOfClass($applicationClassReflection)) { + continue; + } + + $results[] = $this->application->changeBaseClass($classReflection)->getStaticObjectType(); + } + + if ($results === []) { + return $this->application->getStaticObjectType(); + } + + return TypeCombinator::union(...$results); + } + + public function isSuperTypeOf(Type $type): IsSuperTypeOfResult + { + if ($this->isSameUnresolvedClass($type)) { + return $this->application->getStaticObjectType()->isSuperTypeOf($type->application->getStaticObjectType()); + } + + return $this->isSuperTypeOfDefault($type); + } + + public function accepts(Type $type, bool $strictTypes): AcceptsResult + { + if ($this->isSameUnresolvedClass($type)) { + return $this->application->getStaticObjectType()->accepts($type->application->getStaticObjectType(), $strictTypes); + } + + $accepts = $this->resolve()->accepts($type, $strictTypes); + if (!$this->isResolvable()) { + // like a template, an unknown class is the same as another one only maybe + return $accepts->and(AcceptsResult::createMaybe()); + } + + return $accepts; + } + + public function inferTemplateTypes(Type $receivedType): TemplateTypeMap + { + // the received object is the class the constructor stands for, + // and its type arguments are what the application has + return $this->constructor->inferTemplateTypes($receivedType) + ->union($this->application->getStaticObjectType()->inferTemplateTypes($receivedType)); + } + + /** @phpstan-assert-if-true self $type */ + private function isSameUnresolvedClass(Type $type): bool + { + return $type instanceof self + && !$this->isResolvable() + && $this->constructor->equals($type->constructor); + } + + /** + * @param callable(Type): Type $cb + */ + public function traverse(callable $cb): Type + { + $constructor = $cb($this->constructor); + $application = $this->application->traverse($cb); + + if ($this->constructor === $constructor && $this->application === $application) { + return $this; + } + + return $this->create($constructor, $application); + } + + public function traverseSimultaneously(Type $right, callable $cb): Type + { + if (!$right instanceof self) { + return $this; + } + + $constructor = $cb($this->constructor, $right->constructor); + $application = $this->application->traverseSimultaneously($right->application, $cb); + + if ($this->constructor === $constructor && $this->application === $application) { + return $this; + } + + return $this->create($constructor, $application); + } + + /** A traversal may turn the application into anything, which then stands on its own. */ + private function create(Type $constructor, Type $application): Type + { + if (!$application instanceof GenericStaticType) { + return $application; + } + + return new self($constructor, $application, $this->consistent); + } + + public function toPhpDocNode(): TypeNode + { + $constructor = $this->constructor->toPhpDocNode(); + if (!$constructor instanceof IdentifierTypeNode) { + return $this->resolve()->toPhpDocNode(); + } + + return new GenericTypeNode( + $constructor, + array_map(static fn (Type $type): TypeNode => $type->toPhpDocNode(), $this->application->getTypes()), + ); + } + +} diff --git a/src/Type/Traverser/LateResolvableTraverser.php b/src/Type/Traverser/LateResolvableTraverser.php index 79ac770a44b..125bc842078 100644 --- a/src/Type/Traverser/LateResolvableTraverser.php +++ b/src/Type/Traverser/LateResolvableTraverser.php @@ -6,6 +6,7 @@ use PHPStan\Type\ArrayType; use PHPStan\Type\CallableType; use PHPStan\Type\ClosureType; +use PHPStan\Type\Generic\TemplateTypeApplication; use PHPStan\Type\LateResolvableType; use PHPStan\Type\Type; use PHPStan\Type\TypeTraverserCallable; @@ -28,7 +29,14 @@ public function __construct( */ public function traverse(Type $type, callable $traverse): Type { - while ($type instanceof LateResolvableType && (($this->resolveUnresolvableTypes && $this->ignoreResolveUnresolvableTypesLevel === 0) || $type->isResolvable())) { + // TColl<…> of a TColl not known yet is not some Coll<…>, it is the class TColl will be + while ( + $type instanceof LateResolvableType + && ( + ($this->resolveUnresolvableTypes && $this->ignoreResolveUnresolvableTypesLevel === 0 && !$type instanceof TemplateTypeApplication) + || $type->isResolvable() + ) + ) { $type = $type->resolve(); } diff --git a/tests/PHPStan/Analyser/nsrt/template-type-application.php b/tests/PHPStan/Analyser/nsrt/template-type-application.php new file mode 100644 index 00000000000..286dacf8b02 --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/template-type-application.php @@ -0,0 +1,134 @@ + + */ +final class Vec implements Coll +{ + +} + +/** + * @template-covariant T + * @implements Coll + */ +final class Set implements Coll +{ + +} + +/** + * @template K + * @template-covariant V + * @phpstan-consistent-templates + */ +interface Dict +{ + +} + +/** + * @template K + * @template-covariant V + * @implements Dict + */ +final class HashMap implements Dict +{ + +} + +/** @template-covariant T */ +interface Loose +{ + +} + +/** + * @template-covariant T + * @implements Loose + */ +final class LooseVec implements Loose +{ + +} + +/** + * @template TColl of Coll + * @param TColl $c + * @return TColl + */ +function stringify(Coll $c): Coll +{ + assertType('TColl', $c); + throw new \Exception(); +} + +/** + * @template TColl of Coll + * @template T + * @param TColl $c + * @return TColl> + */ +function wrap(Coll $c): Coll +{ + throw new \Exception(); +} + +/** + * @template TDict of Dict + * @template K + * @template V + * @param TDict $dict + * @return TDict + */ +function flip(Dict $dict): Dict +{ + throw new \Exception(); +} + +/** + * @template TColl of Loose + * @param TColl $c + * @return TColl + */ +function loose(Loose $c): Loose +{ + // without @phpstan-consistent-templates a LooseVec is not known to exist, + // so TColl is the bound with the type argument + assertType('TemplateTypeApplication\Loose', $c); + throw new \Exception(); +} + +/** + * @param Vec $vec + * @param Set $set + * @param Coll $coll + * @param Vec|Set $vecOrSet + * @param HashMap $hashMap + * @param LooseVec $looseVec + */ +function test(Vec $vec, Set $set, Coll $coll, $vecOrSet, HashMap $hashMap, LooseVec $looseVec): void +{ + assertType('TemplateTypeApplication\Vec', stringify($vec)); + assertType('TemplateTypeApplication\Set', stringify($set)); + assertType('TemplateTypeApplication\Coll', stringify($coll)); + assertType('TemplateTypeApplication\Set|TemplateTypeApplication\Vec', stringify($vecOrSet)); + assertType('TemplateTypeApplication\Vec>', wrap($vec)); + assertType('TemplateTypeApplication\Set>', wrap($set)); + assertType('TemplateTypeApplication\HashMap', flip($hashMap)); + assertType('TemplateTypeApplication\Loose', loose($looseVec)); +} diff --git a/tests/PHPStan/Rules/Functions/CallToFunctionParametersRuleTest.php b/tests/PHPStan/Rules/Functions/CallToFunctionParametersRuleTest.php index a043b865ba6..55699b9299a 100644 --- a/tests/PHPStan/Rules/Functions/CallToFunctionParametersRuleTest.php +++ b/tests/PHPStan/Rules/Functions/CallToFunctionParametersRuleTest.php @@ -4024,4 +4024,23 @@ public function testRecursiveBuiltinParameters(): void $this->analyse([__DIR__ . '/data/recursive-builtin-parameters.php'], $errors); } + public function testTemplateTypeApplication(): void + { + $this->analyse([__DIR__ . '/data/template-type-application.php'], [ + [ + 'Parameter #1 $c of function TemplateTypeApplicationRules\\ints expects TemplateTypeApplicationRules\\Vec, TemplateTypeApplicationRules\\Vec given.', + 59, + ], + [ + 'Parameter #1 $c of function TemplateTypeApplicationRules\\ints expects TemplateTypeApplicationRules\\Coll, stdClass given.', + 60, + ], + [ + 'Unable to resolve the template type TColl in call to function TemplateTypeApplicationRules\\ints', + 60, + 'See: https://phpstan.org/blog/solving-phpstan-error-unable-to-resolve-template-type', + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php b/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php index cdad750ba22..4d623e535ad 100644 --- a/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php +++ b/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php @@ -693,4 +693,20 @@ public function testFBound(): void $this->analyse([__DIR__ . '/../../Analyser/nsrt/template-f-bound.php'], []); } + public function testTemplateTypeApplication(): void + { + $this->checkNullables = true; + $this->checkExplicitMixed = true; + $this->analyse([__DIR__ . '/data/template-type-application.php'], [ + [ + 'Function TemplateTypeApplicationRules\\same() should return TColl but returns TemplateTypeApplicationRules\\Coll.', + 33, + ], + [ + 'Function TemplateTypeApplicationRules\\same() should return TColl but returns TColl.', + 36, + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/Functions/data/template-type-application.php b/tests/PHPStan/Rules/Functions/data/template-type-application.php new file mode 100644 index 00000000000..32d73eefbec --- /dev/null +++ b/tests/PHPStan/Rules/Functions/data/template-type-application.php @@ -0,0 +1,61 @@ + + */ +final class Vec implements Coll +{ + +} + +/** + * @template TColl of Coll + * @param TColl $c + * @param Coll $other + * @param TColl $ints + * @return TColl + */ +function same(Coll $c, Coll $other, Coll $ints, bool $b): Coll +{ + if ($b) { + return $other; + } + if (rand(0, 1) === 0) { + return $ints; + } + + return $c; +} + +/** + * @template TColl of Coll + * @param TColl $c + * @return TColl + */ +function ints(Coll $c): Coll +{ + return $c; +} + +/** + * @param Vec $strings + * @param Vec $ints + */ +function test(Vec $strings, Vec $ints): void +{ + ints($ints); + ints($strings); + ints(new \stdClass()); +} diff --git a/tests/PHPStan/Rules/PhpDoc/IncompatiblePhpDocTypeRuleTest.php b/tests/PHPStan/Rules/PhpDoc/IncompatiblePhpDocTypeRuleTest.php index 1b7f433bb97..a598c482809 100644 --- a/tests/PHPStan/Rules/PhpDoc/IncompatiblePhpDocTypeRuleTest.php +++ b/tests/PHPStan/Rules/PhpDoc/IncompatiblePhpDocTypeRuleTest.php @@ -562,7 +562,13 @@ public function testBug13652(): void public function testBug9708(): void { - $this->analyse([__DIR__ . '/data/bug-9708.php'], []); + $this->analyse([__DIR__ . '/data/bug-9708.php'], [ + [ + 'PHPDoc type TEventType applies type arguments to template type TEventType, but its bound interface Bug9708\\EventType does not have @phpstan-consistent-templates.', + 74, + 'Add @phpstan-consistent-templates to the PHPDoc of interface Bug9708\\EventType.', + ], + ]); } public function testBug11463(): void diff --git a/turbo-ext/src/TemplateTypeApplication.cpp b/turbo-ext/src/TemplateTypeApplication.cpp new file mode 100644 index 00000000000..71a232d62f5 --- /dev/null +++ b/turbo-ext/src/TemplateTypeApplication.cpp @@ -0,0 +1,599 @@ +/* + * PHPStanTurbo\TemplateTypeApplication — native implementation of + * PHPStan\Type\Generic\TemplateTypeApplication. + * + * Declared as PHPStan\Type\Generic\TemplateTypeApplication itself at + * activation: final, implementing PHPStan\Type\CompoundType and + * PHPStan\Type\LateResolvableType. State is the twin's promoted + * `private Type $constructor`, `private GenericStaticType $application` and + * `private bool $consistent` in slots 0 to 2; LateResolvableTypeTrait's `private ?Type $result` + * follows them, declared by the shared registrar in TypeTraits.cpp that also + * supplies the trait's forwards; NonGeneralizableTypeTrait's generalize() + * comes from its registrar. + * + * The class is final, so the twin's $this-calls (isResolvable(), resolve(), + * the trait's private isSuperTypeOfDefault(), the private + * isSameUnresolvedClass() and create()) are direct C++ calls; another + * instance's private slots are read directly, as the twin does from inside + * the class. + */ + +#include "TypeTraits.h" +#include "generated/TemplateTypeApplication.h" + +namespace slots = ptdecl::TemplateTypeApplication::slot; +namespace sigs = ptdecl::TemplateTypeApplication::sig; + +zend_class_entry *pt_ce_template_type_application = nullptr; + +namespace phpstanturbo { + +/* Mirrors PHPStan\Type\Generic\TemplateTypeApplication. State lives in the + * PHP object's slots. */ +class TemplateTypeApplication +{ +public: + explicit TemplateTypeApplication(zend_object *self) : self(self) {} + + /* __construct(private Type $constructor, private GenericStaticType $application, + * private bool $consistent); borrowed */ + void construct(zval *constructor, zval *application, bool consistent) + { + assign(slots::constructor, constructor); + assign(slots::application, application); + zval flag; + ZVAL_BOOL(&flag, consistent); + assign(slots::consistent, &flag); + } + + /* new self($constructor, $application, $consistent); UNDEF = pending exception */ + static zv::Val createInstance(zval *constructor, zval *application, bool consistent) + { + zval object; + if (UNEXPECTED(object_init_ex(&object, pt_ce_template_type_application) != SUCCESS)) return zv::Val(); + TemplateTypeApplication(Z_OBJ(object)).construct(constructor, application, consistent); + return zv::Val::adopt(object); + } + + /* the slots (borrowed); NULL with an Error pending when the constructor + * never ran — the twin's typed-property read raises the same */ + [[nodiscard]] zval *constructor() const { return slot(self, slots::constructor, "constructor"); } + [[nodiscard]] zval *application() const { return slot(self, slots::application, "application"); } + + static zval *slot(zend_object *object, uint32_t index, const char *name) + { + zval *p = OBJ_PROP_NUM(object, index); + if (UNEXPECTED(Z_TYPE_P(p) == IS_UNDEF)) { + zend_throw_error(NULL, "Typed property %s::$%s must not be accessed before initialization", ZSTR_VAL(pt_ce_template_type_application->name), name); + return NULL; + } + return p; + } + + /* the flag slot; false with an Error pending when the constructor never ran */ + [[nodiscard]] bool consistent(bool &out) const + { + zval *p = slot(self, slots::consistent, "consistent"); + if (UNEXPECTED(p == NULL)) return false; + out = Z_TYPE_P(p) == IS_TRUE; + return true; + } + + [[nodiscard]] bool isConsistent(bool &out) const { return consistent(out); } + + zv::Val getConstructor() const { return copied(constructor()); } + + zv::Val getApplication() const { return copied(application()); } + + /* array_merge() of the constructor's and the application's getReferencedClasses() */ + zv::Val getReferencedClasses() const { return mergedOfParts(PT_LC("getreferencedclasses"), 0, NULL); } + + /* array_merge() of the constructor's and the application's getReferencedTemplateTypes($positionVariance) */ + zv::Val getReferencedTemplateTypes(zval *positionVariance) const { return mergedOfParts(PT_LC("getreferencedtemplatetypes"), 1, positionVariance); } + + /* $type instanceof self && equal constructors && equal applications; + * false with an exception pending */ + [[nodiscard]] bool equals(zval *type, bool &out) const + { + out = false; + if (!instanceof_function(Z_OBJCE_P(type), pt_ce_template_type_application)) return true; + static const uint32_t parts[2] = { slots::constructor, slots::application }; + static const char *const names[2] = { "constructor", "application" }; + for (int i = 0; i < 2; i++) { + zval *mine = slot(self, parts[i], names[i]); + if (UNEXPECTED(mine == NULL)) return false; + zval *theirs = slot(Z_OBJ_P(type), parts[i], names[i]); + if (UNEXPECTED(theirs == NULL)) return false; + bool equal; + if (UNEXPECTED(!pt_type_call_bool(Z_OBJ_P(mine), PT_LC("equals"), 1, theirs, equal))) return false; + if (!equal) return true; + } + out = true; + return true; + } + + /* the resolved type's description for a known class; else + * ```, the constructor's cache description in + * place of the name at the cache level; UNDEF = pending exception */ + zv::Val describe(zval *level) const + { + bool resolvable; + if (UNEXPECTED(!isResolvable(resolvable))) return zv::Val(); + if (resolvable) { + zv::Val resolved = resolve(); + if (UNEXPECTED(resolved.isUndef())) return zv::Val(); + return pt_type_call(Z_OBJ_P(resolved.raw()), PT_LC("describe"), 1, level); + } + + zval *app = application(); + if (UNEXPECTED(app == NULL)) return zv::Val(); + zv::Val types = pt_type_call(Z_OBJ_P(app), PT_LC("gettypes"), 0, NULL); + if (UNEXPECTED(types.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(types.raw()).isArray())) { + zend_type_error("phpstan_turbo: getTypes() must return array"); + return zv::Val(); + } + /* implode(', ', array_map(fn (Type $type): string => $type->describe($level), ...)) */ + smart_str arguments = {}; + bool first = true; + for (zv::ArrayEntry entry : zv::ArrRef(types.raw())) { + zv::Ref type = entry.value().deref(); + if (UNEXPECTED(!type.isObject())) { + smart_str_free(&arguments); + zend_type_error("phpstan_turbo: a type argument must be %s", ptcls::type); + return zv::Val(); + } + zv::Val description = pt_type_call(type.asObject(), PT_LC("describe"), 1, level); + if (UNEXPECTED(description.isUndef() || !zv::Ref(description.raw()).isString())) { + smart_str_free(&arguments); + if (!description.isUndef()) zend_type_error("phpstan_turbo: describe() must return string"); + return zv::Val(); + } + if (!first) smart_str_appendl(&arguments, ", ", 2); + first = false; + smart_str_append(&arguments, Z_STR_P(description.raw())); + } + smart_str_0(&arguments); + + zval *ctor = constructor(); + zend_long levelValue; + zv::Val name = ctor == NULL || !pt_verbosity_level_value_of(level, levelValue) + ? zv::Val() + : (levelValue == PT_VERBOSITY_LEVEL_CACHE + ? pt_type_call(Z_OBJ_P(ctor), PT_LC("describe"), 1, pt_verbosity_level_singleton(PT_VERBOSITY_LEVEL_CACHE)) + : pt_type_call(Z_OBJ_P(ctor), PT_LC("getname"), 0, NULL)); + if (UNEXPECTED(name.isUndef() || !zv::Ref(name.raw()).isString())) { + smart_str_free(&arguments); + if (!name.isUndef()) zend_type_error("phpstan_turbo: the name must be string"); + return zv::Val(); + } + zend_string *result = zend_strpprintf(0, "%s<%s>", Z_STRVAL_P(name.raw()), arguments.s != NULL ? ZSTR_VAL(arguments.s) : ""); + smart_str_free(&arguments); + zval out; + ZVAL_STR(&out, result); + return zv::Val::adopt(out); + } + + /* !$this->consistent || !$this->constructor instanceof TemplateType; + * false = pending exception */ + [[nodiscard]] bool isResolvable(bool &out) const + { + bool isConsistent; + if (UNEXPECTED(!consistent(isConsistent))) return false; + if (!isConsistent) { + out = true; + return true; + } + zval *ctor = constructor(); + if (UNEXPECTED(ctor == NULL)) return false; + bool isTemplate; + if (UNEXPECTED(!pt_type_instanceof(ctor, PT_CLASS_TEMPLATE_TYPE, isTemplate))) return false; + out = !isTemplate; + return true; + } + + /* the application's class carried to each class below it the constructor + * is, their union; the application's static object type without one; + * UNDEF = pending exception */ + zv::Val getResult() const + { + bool isConsistent; + if (UNEXPECTED(!consistent(isConsistent))) return zv::Val(); + zval *app = application(); + if (UNEXPECTED(app == NULL)) return zv::Val(); + if (!isConsistent) return pt_type_call(Z_OBJ_P(app), PT_LC("getstaticobjecttype"), 0, NULL); + zv::Val applicationReflection = pt_type_call(Z_OBJ_P(app), PT_LC("getclassreflection"), 0, NULL); + if (UNEXPECTED(applicationReflection.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(applicationReflection.raw()).isObject())) { + zend_type_error("phpstan_turbo: getClassReflection() must return an object"); + return zv::Val(); + } + zval *ctor = constructor(); + if (UNEXPECTED(ctor == NULL)) return zv::Val(); + zv::Val reflections = pt_type_op(Z_OBJ_P(ctor), PT_OP_GET_OBJECT_CLASS_REFLECTIONS, 0, NULL); + if (UNEXPECTED(reflections.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(reflections.raw()).isArray())) { + zend_type_error("phpstan_turbo: getObjectClassReflections() must return array"); + return zv::Val(); + } + zv::Arr results = zv::Arr::create(0); + for (zv::ArrayEntry entry : zv::ArrRef(reflections.raw())) { + zv::Ref reflection = entry.value().deref(); + if (UNEXPECTED(!reflection.isObject())) { + zend_type_error("phpstan_turbo: getObjectClassReflections() must return ClassReflection objects"); + return zv::Val(); + } + zv::Val name = pt_class_reflection_get_name(reflection.asObject()); + if (UNEXPECTED(name.isUndef())) return zv::Val(); + zv::Val applicationName = pt_class_reflection_get_name(Z_OBJ_P(applicationReflection.raw())); + if (UNEXPECTED(applicationName.isUndef())) return zv::Val(); + if (!zend_is_identical(name.raw(), applicationName.raw())) { + bool subclass; + if (UNEXPECTED(!pt_class_reflection_is_subclass_of_class(reflection.asObject(), applicationReflection.raw(), subclass))) return zv::Val(); + if (!subclass) continue; + } + zv::Val changed = pt_type_call(Z_OBJ_P(app), PT_LC("changebaseclass"), 1, reflection.raw()); + if (UNEXPECTED(changed.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(changed.raw()).isObject())) { + zend_type_error("phpstan_turbo: changeBaseClass() must return an object"); + return zv::Val(); + } + zv::Val objectType = pt_type_call(Z_OBJ_P(changed.raw()), PT_LC("getstaticobjecttype"), 0, NULL); + if (UNEXPECTED(objectType.isUndef())) return zv::Val(); + results.push(std::move(objectType)); + } + if (zend_hash_num_elements(results.table()) == 0) return pt_type_call(Z_OBJ_P(app), PT_LC("getstaticobjecttype"), 0, NULL); + + + /* TypeCombinator::union(...$results), the results borrowed */ + zv::Val resultsVal(std::move(results)); + uint32_t argc = 0; + zval *argv = (zval *) safe_emalloc(zend_hash_num_elements(Z_ARRVAL_P(resultsVal.raw())), sizeof(zval), 0); + for (zv::ArrayEntry entry : zv::ArrRef(resultsVal.raw())) { + ZVAL_COPY_VALUE(&argv[argc++], entry.value().raw()); + } + zv::Val union_ = pt_type_combinator_union(argc, argv); + efree(argv); + return union_; + } + + /* the applications' static object types for the same unresolved class, + * the trait's default otherwise; UNDEF = pending exception */ + zv::Val isSuperTypeOf(zval *type) const + { + bool same; + if (UNEXPECTED(!isSameUnresolvedClass(type, same))) return zv::Val(); + if (same) return staticObjectTypesCall(PT_OP_IS_SUPER_TYPE_OF, type, NULL); + return pt_type_late_resolvable_is_super_type_of_default(self, pt_ce_template_type_application, type); + } + + /* the applications' static object types for the same unresolved class, + * else the resolved type's answer, held to maybe while the class is not + * known; UNDEF = pending exception */ + zv::Val accepts(zval *type, bool strictTypes) const + { + bool same; + if (UNEXPECTED(!isSameUnresolvedClass(type, same))) return zv::Val(); + zval strict; + ZVAL_BOOL(&strict, strictTypes); + if (same) return staticObjectTypesCall(PT_OP_ACCEPTS, type, &strict); + + zv::Val resolved = resolve(); + if (UNEXPECTED(resolved.isUndef())) return zv::Val(); + zval args[2]; + ZVAL_COPY_VALUE(&args[0], type); + ZVAL_COPY_VALUE(&args[1], &strict); + zv::Val accepted = pt_type_op(Z_OBJ_P(resolved.raw()), PT_OP_ACCEPTS, 2, args); + if (UNEXPECTED(accepted.isUndef())) return zv::Val(); + bool resolvable; + if (UNEXPECTED(!isResolvable(resolvable))) return zv::Val(); + if (resolvable) return accepted; + zv::Val maybe = pt_type_accepts_result(PT_TRI_MAYBE); + if (UNEXPECTED(maybe.isUndef())) return zv::Val(); + zval anded; + if (UNEXPECTED(!pt_accepts_result_and(&anded, accepted.raw(), maybe.raw()))) return zv::Val(); + return zv::Val::adopt(anded); + } + + /* $this->constructor->inferTemplateTypes($receivedType) + * ->union($this->application->getStaticObjectType()->inferTemplateTypes($receivedType)); + * UNDEF = pending exception */ + zv::Val inferTemplateTypes(zval *receivedType) const + { + zval *ctor = constructor(); + if (UNEXPECTED(ctor == NULL)) return zv::Val(); + zv::Val fromConstructor = pt_type_call(Z_OBJ_P(ctor), PT_LC("infertemplatetypes"), 1, receivedType); + if (UNEXPECTED(fromConstructor.isUndef())) return zv::Val(); + zv::Val staticObject = applicationStaticObjectType(self); + if (UNEXPECTED(staticObject.isUndef())) return zv::Val(); + zv::Val fromApplication = pt_type_call(Z_OBJ_P(staticObject.raw()), PT_LC("infertemplatetypes"), 1, receivedType); + if (UNEXPECTED(fromApplication.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(fromConstructor.raw()).isObject())) { + zend_type_error("phpstan_turbo: inferTemplateTypes() must return %s", "PHPStan\\Type\\Generic\\TemplateTypeMap"); + return zv::Val(); + } + return pt_type_call(Z_OBJ_P(fromConstructor.raw()), PT_LC("union"), 1, fromApplication.raw()); + } + + /* the constructor and the application mapped by the callback, $this when + * neither changed, else create(); UNDEF = pending exception */ + zv::Val traverse(zend_fcall_info *fci, zend_fcall_info_cache *fcc) const + { + zval *ctor = constructor(); + if (UNEXPECTED(ctor == NULL)) return zv::Val(); + zv::Val newConstructor = pt_type_traverse_call(fci, fcc, ctor); + if (UNEXPECTED(newConstructor.isUndef())) return zv::Val(); + zval *app = application(); + if (UNEXPECTED(app == NULL)) return zv::Val(); + /* $this->application->traverse($cb) */ + zv::Val newApplication = pt_type_call(Z_OBJ_P(app), PT_LC("traverse"), 1, &fci->function_name); + if (UNEXPECTED(newApplication.isUndef())) return zv::Val(); + return traversed(std::move(newConstructor), std::move(newApplication)); + } + + /* $this for a $right of another class, else traverse() with $right's + * constructor and application as the callback's second arguments */ + zv::Val traverseSimultaneously(zval *right, zend_fcall_info *fci, zend_fcall_info_cache *fcc) const + { + if (!instanceof_function(Z_OBJCE_P(right), pt_ce_template_type_application)) return thisValue(); + zval *ctor = constructor(); + if (UNEXPECTED(ctor == NULL)) return zv::Val(); + zval *theirConstructor = slot(Z_OBJ_P(right), slots::constructor, "constructor"); + if (UNEXPECTED(theirConstructor == NULL)) return zv::Val(); + zv::Val newConstructor = pt_type_traverse_call(fci, fcc, ctor, theirConstructor); + if (UNEXPECTED(newConstructor.isUndef())) return zv::Val(); + zval *app = application(); + if (UNEXPECTED(app == NULL)) return zv::Val(); + zval *theirApplication = slot(Z_OBJ_P(right), slots::application, "application"); + if (UNEXPECTED(theirApplication == NULL)) return zv::Val(); + /* $this->application->traverseSimultaneously($right->application, $cb) */ + zval args[2]; + ZVAL_COPY_VALUE(&args[0], theirApplication); + ZVAL_COPY_VALUE(&args[1], &fci->function_name); + zv::Val newApplication = pt_type_call(Z_OBJ_P(app), PT_LC("traversesimultaneously"), 2, args); + if (UNEXPECTED(newApplication.isUndef())) return zv::Val(); + return traversed(std::move(newConstructor), std::move(newApplication)); + } + + /* new GenericTypeNode(, ) + * for a constructor written as a name, the resolved type's node + * otherwise; UNDEF = pending exception */ + zv::Val toPhpDocNode() const + { + zval *ctor = constructor(); + if (UNEXPECTED(ctor == NULL)) return zv::Val(); + zv::Val constructorNode = pt_type_call(Z_OBJ_P(ctor), PT_LC("tophpdocnode"), 0, NULL); + if (UNEXPECTED(constructorNode.isUndef())) return zv::Val(); + bool identifier; + if (UNEXPECTED(!pt_type_instanceof(constructorNode.raw(), PT_CLASS_IDENTIFIER_TYPE_NODE, identifier))) return zv::Val(); + if (!identifier) { + zv::Val resolved = resolve(); + if (UNEXPECTED(resolved.isUndef())) return zv::Val(); + return pt_type_call(Z_OBJ_P(resolved.raw()), PT_LC("tophpdocnode"), 0, NULL); + } + zval *app = application(); + if (UNEXPECTED(app == NULL)) return zv::Val(); + zv::Val types = pt_type_call(Z_OBJ_P(app), PT_LC("gettypes"), 0, NULL); + if (UNEXPECTED(types.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(types.raw()).isArray())) { + zend_type_error("phpstan_turbo: getTypes() must return array"); + return zv::Val(); + } + zv::Arr nodes = zv::Arr::create(zv::ArrRef(types.raw()).size()); + for (zv::ArrayEntry entry : zv::ArrRef(types.raw())) { + zv::Ref type = entry.value().deref(); + if (UNEXPECTED(!type.isObject())) { + zend_type_error("phpstan_turbo: a type argument must be %s", ptcls::type); + return zv::Val(); + } + zv::Val node = pt_type_call(type.asObject(), PT_LC("tophpdocnode"), 0, NULL); + if (UNEXPECTED(node.isUndef())) return zv::Val(); + nodes.push(std::move(node)); + } + zv::Val nodesVal(std::move(nodes)); + zval args[2]; + ZVAL_COPY_VALUE(&args[0], constructorNode.raw()); + ZVAL_COPY_VALUE(&args[1], nodesVal.raw()); + return pt_type_new(PT_CLASS_GENERIC_TYPE_NODE, 2, args); + } + + /* $this->result ??= $this->getResult() — the trait's body */ + zv::Val resolve() const { return pt_type_late_resolvable_resolve(self, pt_ce_template_type_application); } + + /* $type instanceof self && !$this->isResolvable() + * && $this->constructor->equals($type->constructor); false = pending exception */ + [[nodiscard]] bool isSameUnresolvedClass(zval *type, bool &out) const + { + out = false; + if (!instanceof_function(Z_OBJCE_P(type), pt_ce_template_type_application)) return true; + bool resolvable; + if (UNEXPECTED(!isResolvable(resolvable))) return false; + if (resolvable) return true; + zval *ctor = constructor(); + if (UNEXPECTED(ctor == NULL)) return false; + zval *theirs = slot(Z_OBJ_P(type), slots::constructor, "constructor"); + if (UNEXPECTED(theirs == NULL)) return false; + return pt_type_call_bool(Z_OBJ_P(ctor), PT_LC("equals"), 1, theirs, out); + } + + /* create(): the application a traversal turned into anything else + * stands on its own, else new self($constructor, $application, + * $this->consistent); UNDEF = pending exception */ + zv::Val create(zval *newConstructor, zval *newApplication) const + { + if (!zv::Ref(newApplication).isObject() || !instanceof_function(Z_OBJCE_P(newApplication), pt_ce_generic_static_type)) { + return zv::Val::copyOf(zv::Ref(newApplication)); + } + bool isConsistent; + if (UNEXPECTED(!consistent(isConsistent))) return zv::Val(); + return createInstance(newConstructor, newApplication, isConsistent); + } + +private: + zend_object *self; + + zv::Val thisValue() const { return pt_this_value(self); } + + static zv::Val copied(zval *value) + { + if (UNEXPECTED(value == NULL)) return zv::Val(); + return zv::Val::copyOf(zv::Ref(value)); + } + + void assign(uint32_t index, zval *value) + { + zval *p = OBJ_PROP_NUM(self, index); + /* the slot is overwritten in place: a repeated __construct() call + * would otherwise leak the first value */ + zval previous; + ZVAL_COPY_VALUE(&previous, p); + ZVAL_COPY(p, value); + Z_PROP_FLAG_P(p) = 0; /* no longer IS_PROP_UNINIT */ + if (Z_TYPE(previous) != IS_UNDEF) { + zval_ptr_dtor(&previous); + } + } + + zv::Val mergedOfParts(const char *lcname, size_t len, uint32_t argc, zval *argv) const + { + static const uint32_t parts[2] = { slots::constructor, slots::application }; + static const char *const names[2] = { "constructor", "application" }; + zv::Arr merged = zv::Arr::create(0); + for (int i = 0; i < 2; i++) { + zval *part = slot(self, parts[i], names[i]); + if (UNEXPECTED(part == NULL)) return zv::Val(); + zv::Val ofPart = pt_type_call(Z_OBJ_P(part), lcname, len, argc, argv); + if (UNEXPECTED(ofPart.isUndef() || !pt_callable_array_merge_into(merged, ofPart.raw()))) return zv::Val(); + } + return zv::Val(std::move(merged)); + } + + /* $object->application->getStaticObjectType(); UNDEF = pending exception */ + static zv::Val applicationStaticObjectType(zend_object *object) + { + zval *app = slot(object, slots::application, "application"); + if (UNEXPECTED(app == NULL)) return zv::Val(); + zv::Val staticObject = pt_type_call(Z_OBJ_P(app), PT_LC("getstaticobjecttype"), 0, NULL); + if (UNEXPECTED(staticObject.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(staticObject.raw()).isObject())) { + zend_type_error("phpstan_turbo: getStaticObjectType() must return an object"); + return zv::Val(); + } + return staticObject; + } + + /* the operation of this application's static object type on $type's, + * with $extra as the second argument; UNDEF = pending exception */ + zv::Val staticObjectTypesCall(pt_type_op_id op, zval *type, zval *extra) const + { + zv::Val mine = applicationStaticObjectType(self); + if (UNEXPECTED(mine.isUndef())) return zv::Val(); + zv::Val theirs = applicationStaticObjectType(Z_OBJ_P(type)); + if (UNEXPECTED(theirs.isUndef())) return zv::Val(); + zval args[2]; + ZVAL_COPY_VALUE(&args[0], theirs.raw()); + if (extra != NULL) ZVAL_COPY_VALUE(&args[1], extra); + return pt_type_op(Z_OBJ_P(mine.raw()), op, extra != NULL ? 2 : 1, args); + } + + /* `$this->constructor === $constructor && $this->application === $application + * ? $this : self::create($constructor, $application)` (UNDEF in = UNDEF out) */ + zv::Val traversed(zv::Val newConstructor, zv::Val newApplication) const + { + if (UNEXPECTED(newConstructor.isUndef() || newApplication.isUndef())) return zv::Val(); + zval *ctor = constructor(); + if (UNEXPECTED(ctor == NULL)) return zv::Val(); + zval *app = application(); + if (UNEXPECTED(app == NULL)) return zv::Val(); + if (pt_type_same_object(ctor, newConstructor.raw()) && pt_type_same_object(app, newApplication.raw())) return thisValue(); + return create(newConstructor.raw(), newApplication.raw()); + } +}; + +} // namespace phpstanturbo + +using phpstanturbo::TemplateTypeApplication; + +/* {{{ engine ABI glue: parameter parsing + registration */ + +#define PT_THIS TemplateTypeApplication(Z_OBJ_P(ZEND_THIS)) + +PT_MINIT_REGISTRATION(pt_register_template_type_application) +{ + reg::Class cls("PHPStan\\Type\\Generic\\TemplateTypeApplication"); + ptdecl::TemplateTypeApplication::declareClass(cls); + /* the slots must stay first (slots::constructor, slots::application, + * slots::consistent); + * the trait registrar declares $result after them */ + ptdecl::TemplateTypeApplication::declareProperties(cls); + + cls.method(sigs::__construct, [](INTERNAL_FUNCTION_PARAMETERS) { + zval *constructor; + zval *application; + bool consistent; + ZEND_PARSE_PARAMETERS_START(3, 3) + Z_PARAM_OBJECT_OF_CLASS(constructor, pt_ce_type_interface()) + Z_PARAM_OBJECT_OF_CLASS(application, pt_ce_generic_static_type) + Z_PARAM_BOOL(consistent) + ZEND_PARSE_PARAMETERS_END(); + PT_THIS.construct(constructor, application, consistent); + }); + + cls.method<&TemplateTypeApplication::isConsistent>(sigs::isConsistent); + + cls.method<&TemplateTypeApplication::getConstructor>(sigs::getConstructor); + cls.method<&TemplateTypeApplication::getApplication>(sigs::getApplication); + + cls.method<&TemplateTypeApplication::getReferencedClasses>(sigs::getReferencedClasses); + cls.op(); + + cls.method<&TemplateTypeApplication::getReferencedTemplateTypes, zp::Obj>(sigs::getReferencedTemplateTypes); + + cls.method<&TemplateTypeApplication::equals, zp::TypeObj>(sigs::equals); + + cls.method<&TemplateTypeApplication::describe, zp::Obj>(sigs::describe); + + cls.method<&TemplateTypeApplication::isResolvable>(sigs::isResolvable); + + cls.method<&TemplateTypeApplication::getResult>(sigs::getResult); + + cls.method<&TemplateTypeApplication::isSuperTypeOf, zp::TypeObj>(sigs::isSuperTypeOf); + + cls.method<&TemplateTypeApplication::accepts, zp::TypeObj, zp::Bool>(sigs::accepts); + + cls.method<&TemplateTypeApplication::inferTemplateTypes, zp::TypeObj>(sigs::inferTemplateTypes); + + cls.method(sigs::traverse, [](INTERNAL_FUNCTION_PARAMETERS) { + zend_fcall_info fci; + zend_fcall_info_cache fcc; + ZEND_PARSE_PARAMETERS_START(1, 1) + Z_PARAM_FUNC(fci, fcc) + ZEND_PARSE_PARAMETERS_END(); + PT_RETURN_VAL(PT_THIS.traverse(&fci, &fcc)); + }); + + cls.method(sigs::traverseSimultaneously, [](INTERNAL_FUNCTION_PARAMETERS) { + zval *right; + zend_fcall_info fci; + zend_fcall_info_cache fcc; + ZEND_PARSE_PARAMETERS_START(2, 2) + Z_PARAM_OBJECT(right) + Z_PARAM_FUNC(fci, fcc) + ZEND_PARSE_PARAMETERS_END(); + PT_RETURN_VAL(PT_THIS.traverseSimultaneously(right, &fci, &fcc)); + }); + + cls.method<&TemplateTypeApplication::isSameUnresolvedClass, zp::TypeObj>(sigs::isSameUnresolvedClass); + + cls.method<&TemplateTypeApplication::create, zp::TypeObj, zp::TypeObj>(sigs::create); + + cls.method<&TemplateTypeApplication::toPhpDocNode>(sigs::toPhpDocNode); + + /* the traits, in the twin's `use` order; the class body above wins over + * every name it declares */ + ptdecl::TemplateTypeApplication::registerTraits(cls); + + cls.shadow(&pt_ce_template_type_application); +} + +/* }}} */ diff --git a/turbo-ext/src/generated/TemplateTypeApplication.h b/turbo-ext/src/generated/TemplateTypeApplication.h new file mode 100644 index 00000000000..4fa191234d6 --- /dev/null +++ b/turbo-ext/src/generated/TemplateTypeApplication.h @@ -0,0 +1,144 @@ +/* Generated by turbo-ext/bin/generate-declarations.php from + * src/Type/Generic/TemplateTypeApplication.php — do not edit. */ + +#ifndef PHPSTANTURBO_GENERATED_TEMPLATE_TYPE_APPLICATION_H +#define PHPSTANTURBO_GENERATED_TEMPLATE_TYPE_APPLICATION_H + +#include "../reg.h" + +namespace ptdecl::TemplateTypeApplication { + +/* the OBJ_PROP_NUM slots of the instance properties the class declares (the inherited ones come first) */ +namespace slot { +inline constexpr uint32_t constructor = 0; +inline constexpr uint32_t application = 1; +inline constexpr uint32_t consistent = 2; +inline constexpr uint32_t result = 3; +} // namespace slot + +inline void declareClass(reg::Class &cls) +{ + cls.final(); + cls.implements({ "PHPStan\\Type\\CompoundType", "PHPStan\\Type\\LateResolvableType" }); +} + +/* the properties the class declares itself, in declaration order (a used trait's come from its registrar) */ +inline void declareProperties(reg::Class &cls) +{ + cls.property("constructor", ZEND_ACC_PRIVATE, reg::PropertyKind::Typed, 0, "PHPStan\\Type\\Type"); + cls.property("application", ZEND_ACC_PRIVATE, reg::PropertyKind::Typed, 0, "PHPStan\\Type\\Generic\\GenericStaticType"); + cls.property("consistent", ZEND_ACC_PRIVATE, reg::PropertyKind::Typed, MAY_BE_BOOL); +} + +/* the shared registrars of the traits the twin uses, in its own order (a used trait's own traits after it) */ +inline void registerTraits(reg::Class &cls) +{ + pt_type_trait_late_resolvable(cls); + pt_type_trait_delegating(cls); + pt_type_trait_operator(cls); + pt_type_trait_non_generalizable(cls); +} + +/* the string and parameter tables the signatures below index into (see reg::Sig) */ +namespace sigtab { +inline constexpr char strings[] = + "constructor\0" /* 0 */ + "PHPStan\\Type\\Type\0" /* 12 */ + "application\0" /* 30 */ + "PHPStan\\Type\\Generic\\GenericStaticType\0" /* 42 */ + "consistent\0" /* 81 */ + "__construct\0" /* 92 */ + "\0" /* 104 */ + "isConsistent\0" /* 105 */ + "getConstructor\0" /* 118 */ + "getApplication\0" /* 133 */ + "getReferencedClasses\0" /* 148 */ + "positionVariance\0" /* 169 */ + "PHPStan\\Type\\Generic\\TemplateTypeVariance\0" /* 186 */ + "getReferencedTemplateTypes\0" /* 228 */ + "type\0" /* 255 */ + "equals\0" /* 260 */ + "level\0" /* 267 */ + "PHPStan\\Type\\VerbosityLevel\0" /* 273 */ + "describe\0" /* 301 */ + "isResolvable\0" /* 310 */ + "getResult\0" /* 323 */ + "PHPStan\\Type\\IsSuperTypeOfResult\0" /* 333 */ + "isSuperTypeOf\0" /* 366 */ + "strictTypes\0" /* 380 */ + "PHPStan\\Type\\AcceptsResult\0" /* 392 */ + "accepts\0" /* 419 */ + "receivedType\0" /* 427 */ + "PHPStan\\Type\\Generic\\TemplateTypeMap\0" /* 440 */ + "inferTemplateTypes\0" /* 477 */ + "isSameUnresolvedClass\0" /* 496 */ + "cb\0" /* 518 */ + "traverse\0" /* 521 */ + "right\0" /* 530 */ + "traverseSimultaneously\0" /* 536 */ + "create\0" /* 559 */ + "PHPStan\\PhpDocParser\\Ast\\Type\\TypeNode\0" /* 566 */ + "toPhpDocNode"; /* 605 */ +inline constexpr reg::PackedArg args[] = { + reg::packed(0, 0, 12), /* __construct $constructor */ + reg::packed(30, 0, 42), /* __construct $application */ + reg::packed(81, MAY_BE_BOOL), /* __construct $consistent */ + reg::packed(104, MAY_BE_BOOL), /* isConsistent return */ + reg::packed(104, 0, 12), /* getConstructor return */ + reg::packed(104, 0, 42), /* getApplication return */ + reg::packed(104, MAY_BE_ARRAY), /* getReferencedClasses return */ + reg::packed(169, 0, 186), /* getReferencedTemplateTypes $positionVariance */ + reg::packed(104, MAY_BE_ARRAY), /* getReferencedTemplateTypes return */ + reg::packed(255, 0, 12), /* equals $type */ + reg::packed(104, MAY_BE_BOOL), /* equals return */ + reg::packed(267, 0, 273), /* describe $level */ + reg::packed(104, MAY_BE_STRING), /* describe return */ + reg::packed(104, MAY_BE_BOOL), /* isResolvable return */ + reg::packed(104, 0, 12), /* getResult return */ + reg::packed(255, 0, 12), /* isSuperTypeOf $type */ + reg::packed(104, 0, 333), /* isSuperTypeOf return */ + reg::packed(255, 0, 12), /* accepts $type */ + reg::packed(380, MAY_BE_BOOL), /* accepts $strictTypes */ + reg::packed(104, 0, 392), /* accepts return */ + reg::packed(427, 0, 12), /* inferTemplateTypes $receivedType */ + reg::packed(104, 0, 440), /* inferTemplateTypes return */ + reg::packed(255, 0, 12), /* isSameUnresolvedClass $type */ + reg::packed(104, MAY_BE_BOOL), /* isSameUnresolvedClass return */ + reg::packed(518, MAY_BE_CALLABLE), /* traverse $cb */ + reg::packed(104, 0, 12), /* traverse return */ + reg::packed(530, 0, 12), /* traverseSimultaneously $right */ + reg::packed(518, MAY_BE_CALLABLE), /* traverseSimultaneously $cb */ + reg::packed(104, 0, 12), /* traverseSimultaneously return */ + reg::packed(0, 0, 12), /* create $constructor */ + reg::packed(30, 0, 12), /* create $application */ + reg::packed(104, 0, 12), /* create return */ + reg::packed(104, 0, 566), /* toPhpDocNode return */ +}; +using Sig = reg::Sig; +} // namespace sigtab + +/* the signatures of the methods the class declares itself (a used trait's are in the trait's header) */ +namespace sig { +inline constexpr sigtab::Sig __construct = { { 92 /* __construct */, 3, 0, 3, reg::NoArg, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isConsistent = { { 105 /* isConsistent */, 0, 3, 0, 3, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getConstructor = { { 118 /* getConstructor */, 0, 4, 0, 4, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getApplication = { { 133 /* getApplication */, 0, 5, 0, 5, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getReferencedClasses = { { 148 /* getReferencedClasses */, 0, 6, 0, 6, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getReferencedTemplateTypes = { { 228 /* getReferencedTemplateTypes */, 1, 7, 1, 8, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig equals = { { 260 /* equals */, 1, 9, 1, 10, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig describe = { { 301 /* describe */, 1, 11, 1, 12, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isResolvable = { { 310 /* isResolvable */, 0, 13, 0, 13, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getResult = { { 323 /* getResult */, 0, 14, 0, 14, ZEND_ACC_PROTECTED } }; +inline constexpr sigtab::Sig isSuperTypeOf = { { 366 /* isSuperTypeOf */, 1, 15, 1, 16, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig accepts = { { 419 /* accepts */, 2, 17, 2, 19, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig inferTemplateTypes = { { 477 /* inferTemplateTypes */, 1, 20, 1, 21, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isSameUnresolvedClass = { { 496 /* isSameUnresolvedClass */, 1, 22, 1, 23, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig traverse = { { 521 /* traverse */, 1, 24, 1, 25, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig traverseSimultaneously = { { 536 /* traverseSimultaneously */, 2, 26, 2, 28, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig create = { { 559 /* create */, 2, 29, 2, 31, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig toPhpDocNode = { { 605 /* toPhpDocNode */, 0, 32, 0, 32, ZEND_ACC_PUBLIC } }; +} // namespace sig + +} // namespace ptdecl::TemplateTypeApplication + +#endif diff --git a/turbo-ext/tests/smoke.php b/turbo-ext/tests/smoke.php index c62e0783d50..b43273bade8 100644 --- a/turbo-ext/tests/smoke.php +++ b/turbo-ext/tests/smoke.php @@ -1193,7 +1193,7 @@ function observeTypeFamily(string $mode): array $typeFamilyPhp = observeTypeFamily('php'); $typeFamilyNative = observeTypeFamily('native'); -foreach ([\PHPStan\Type\BooleanType::class, \PHPStan\Type\Constant\ConstantBooleanType::class, \PHPStan\Type\IntegerType::class, \PHPStan\Type\Constant\ConstantIntegerType::class, \PHPStan\Type\IntegerRangeType::class, \PHPStan\Type\StringType::class, \PHPStan\Type\Constant\ConstantStringType::class, \PHPStan\Type\ClassStringType::class, \PHPStan\Type\Generic\GenericClassStringType::class, \PHPStan\Type\FloatType::class, \PHPStan\Type\Constant\ConstantFloatType::class, \PHPStan\Type\FloatRangeType::class, \PHPStan\Type\NullType::class, \PHPStan\Type\VoidType::class, \PHPStan\Type\NeverType::class, \PHPStan\Type\MixedType::class, \PHPStan\Type\StrictMixedType::class, \PHPStan\Type\ObjectWithoutClassType::class, \PHPStan\Type\StaticType::class, \PHPStan\Type\ThisType::class, \PHPStan\Type\Generic\GenericStaticType::class, \PHPStan\Type\ObjectShapeType::class, \PHPStan\Type\NonexistentParentClassType::class, \PHPStan\Type\ArrayType::class, \PHPStan\Type\Accessory\NonEmptyArrayType::class, \PHPStan\Type\Accessory\AccessoryArrayListType::class, \PHPStan\Type\Accessory\OversizedArrayType::class, \PHPStan\Type\Accessory\HasOffsetType::class, \PHPStan\Type\Accessory\HasOffsetValueType::class, \PHPStan\Type\Accessory\AccessoryNumericStringType::class, \PHPStan\Type\Accessory\AccessoryNonEmptyStringType::class, \PHPStan\Type\Accessory\AccessoryNonFalsyStringType::class, \PHPStan\Type\Accessory\AccessoryLiteralStringType::class, \PHPStan\Type\Accessory\AccessoryLowercaseStringType::class, \PHPStan\Type\Accessory\AccessoryUppercaseStringType::class, \PHPStan\Type\Accessory\AccessoryDecimalIntegerStringType::class, \PHPStan\Type\Accessory\HasMethodType::class, \PHPStan\Type\Accessory\HasPropertyType::class, \PHPStan\Type\ObjectType::class, \PHPStan\Type\Generic\GenericObjectType::class, \PHPStan\Type\Enum\EnumCaseObjectType::class, \PHPStan\Type\IterableType::class, \PHPStan\Type\CallableType::class, \PHPStan\Type\ClosureType::class, \PHPStan\Type\Constant\ConstantArrayType::class, \PHPStan\Type\UnionType::class, \PHPStan\Type\BenevolentUnionType::class, \PHPStan\Type\IntersectionType::class, \PHPStan\Type\ErrorType::class, \PHPStan\Type\CircularTypeAliasErrorType::class, \PHPStan\Type\Generic\AbsorbedTemplateArgumentType::class, \PHPStan\Type\NonAcceptingNeverType::class, \PHPStan\Type\StringAlwaysAcceptingObjectWithToStringType::class, \PHPStan\Type\StringNeverAcceptingObjectWithToStringType::class, \PHPStan\Type\ResourceType::class, \PHPStan\Type\TypeUtils::class, \PHPStan\Type\TypehintHelper::class, \PHPStan\Type\Generic\TemplateTypeVariance::class, \PHPStan\Type\Generic\TemplateTypeVarianceMap::class, \PHPStan\Type\Generic\TemplateTypeMap::class, \PHPStan\Type\Generic\TemplateTypeScope::class, \PHPStan\Type\Generic\TemplateTypeReference::class, \PHPStan\Type\Generic\TemplateTypeHelper::class, \PHPStan\Type\Generic\ArrayKeyTemplateHelper::class, \PHPStan\Type\KeyOfType::class, \PHPStan\Type\ValueOfType::class, \PHPStan\Type\OffsetAccessType::class, \PHPStan\Type\ClassConstantAccessType::class, \PHPStan\Type\NewObjectType::class, \PHPStan\Type\ConditionalType::class, \PHPStan\Type\ConditionalTypeForParameter::class, \PHPStan\Type\LateResolvableArrayShapeType::class, \PHPStan\Type\Generic\UnresolvedTemplateArgumentType::class, \PHPStan\Type\Generic\TemplateArrayType::class, \PHPStan\Type\Generic\TemplateBenevolentUnionType::class, \PHPStan\Type\Generic\TemplateBooleanType::class, \PHPStan\Type\Generic\TemplateConstantArrayType::class, \PHPStan\Type\Generic\TemplateConstantIntegerType::class, \PHPStan\Type\Generic\TemplateConstantStringType::class, \PHPStan\Type\Generic\TemplateFloatType::class, \PHPStan\Type\Generic\TemplateGenericObjectType::class, \PHPStan\Type\Generic\TemplateIntegerType::class, \PHPStan\Type\Generic\TemplateIntersectionType::class, \PHPStan\Type\Generic\TemplateIterableType::class, \PHPStan\Type\Generic\TemplateMixedType::class, \PHPStan\Type\Generic\TemplateNullType::class, \PHPStan\Type\Generic\TemplateObjectShapeType::class, \PHPStan\Type\Generic\TemplateObjectType::class, \PHPStan\Type\Generic\TemplateObjectWithoutClassType::class, \PHPStan\Type\Generic\TemplateStrictMixedType::class, \PHPStan\Type\Generic\TemplateStringType::class, \PHPStan\Type\Generic\TemplateUnionType::class, \PHPStan\Type\Generic\TemplateTypeArgumentStrategy::class, \PHPStan\Type\Generic\TemplateTypeParameterStrategy::class, \PHPStan\Type\Generic\TemplateTypeFactory::class, \PHPStan\Type\Generic\TypeProjectionHelper::class, \PHPStan\Type\Constant\ConstantArrayTypeBuilder::class, \PHPStan\Type\UnionTypeHelper::class, \PHPStan\Type\CallableTypeHelper::class, \PHPStan\Type\Helper\GetTemplateTypeType::class, \PHPStan\Type\Generic\TemplateKeyOfType::class, \PHPStan\Rules\PhpDoc\UnresolvableTypeHelper::class, \PHPStan\Rules\RuleLevelHelper::class, \PHPStan\Reflection\Native\NativeParameterReflection::class, \PHPStan\Reflection\Type\CalledOnTypeUnresolvedMethodPrototypeReflection::class, \PHPStan\Reflection\Type\CalledOnTypeUnresolvedPropertyPrototypeReflection::class, \PHPStan\Reflection\Type\CallbackUnresolvedMethodPrototypeReflection::class, \PHPStan\Reflection\Type\CallbackUnresolvedPropertyPrototypeReflection::class, \PHPStan\Reflection\ResolvedMethodReflection::class, \PHPStan\Reflection\Dummy\ChangedTypeMethodReflection::class, \PHPStan\Reflection\Callables\SimpleImpurePoint::class, \PHPStan\Reflection\SideEffects::class, \PHPStan\Reflection\PassedByReference::class, \PHPStan\Reflection\Php\DummyParameter::class, \PHPStan\Reflection\Php\ExtendedDummyParameter::class, \PHPStan\Analyser\ArgumentsNormalizer::class, \PHPStan\Reflection\ParametersAcceptorSelector::class, \PHPStan\Reflection\Php\PhpParameterReflection::class, \PHPStan\Reflection\Native\ExtendedNativeParameterReflection::class, \PHPStan\Reflection\FunctionVariant::class, \PHPStan\Reflection\ExtendedFunctionVariant::class, \PHPStan\Reflection\ExtendedCallableFunctionVariant::class, \PHPStan\Reflection\ResolvedFunctionVariantWithOriginal::class, \PHPStan\Reflection\TrivialParametersAcceptor::class, \PHPStan\Reflection\Assertions::class, \PHPStan\Reflection\InitializerExprTypeResolver::class, \PHPStan\Type\ValueSet::class, \PHPStan\Analyser\Generics\TemplateArgumentConstraints::class, \PHPStan\Analyser\Generics\TemplateArgumentObserver::class, \PHPStan\Analyser\Generics\TemplateArgumentResolver::class, \PHPStan\Analyser\RicherScopeGetTypeHelper::class, \PHPStan\Analyser\NullsafeOperatorHelper::class, \PHPStan\Analyser\LoopWrittenVariableNames::class, \PHPStan\Reflection\Php\PhpPropertyReflection::class, \PHPStan\Reflection\Dummy\ChangedTypePropertyReflection::class, \PHPStan\Reflection\ResolvedPropertyReflection::class, \PHPStan\Type\StringSet::class] as $typeClass) { +foreach ([\PHPStan\Type\BooleanType::class, \PHPStan\Type\Constant\ConstantBooleanType::class, \PHPStan\Type\IntegerType::class, \PHPStan\Type\Constant\ConstantIntegerType::class, \PHPStan\Type\IntegerRangeType::class, \PHPStan\Type\StringType::class, \PHPStan\Type\Constant\ConstantStringType::class, \PHPStan\Type\ClassStringType::class, \PHPStan\Type\Generic\GenericClassStringType::class, \PHPStan\Type\FloatType::class, \PHPStan\Type\Constant\ConstantFloatType::class, \PHPStan\Type\FloatRangeType::class, \PHPStan\Type\NullType::class, \PHPStan\Type\VoidType::class, \PHPStan\Type\NeverType::class, \PHPStan\Type\MixedType::class, \PHPStan\Type\StrictMixedType::class, \PHPStan\Type\ObjectWithoutClassType::class, \PHPStan\Type\StaticType::class, \PHPStan\Type\ThisType::class, \PHPStan\Type\Generic\GenericStaticType::class, \PHPStan\Type\ObjectShapeType::class, \PHPStan\Type\NonexistentParentClassType::class, \PHPStan\Type\ArrayType::class, \PHPStan\Type\Accessory\NonEmptyArrayType::class, \PHPStan\Type\Accessory\AccessoryArrayListType::class, \PHPStan\Type\Accessory\OversizedArrayType::class, \PHPStan\Type\Accessory\HasOffsetType::class, \PHPStan\Type\Accessory\HasOffsetValueType::class, \PHPStan\Type\Accessory\AccessoryNumericStringType::class, \PHPStan\Type\Accessory\AccessoryNonEmptyStringType::class, \PHPStan\Type\Accessory\AccessoryNonFalsyStringType::class, \PHPStan\Type\Accessory\AccessoryLiteralStringType::class, \PHPStan\Type\Accessory\AccessoryLowercaseStringType::class, \PHPStan\Type\Accessory\AccessoryUppercaseStringType::class, \PHPStan\Type\Accessory\AccessoryDecimalIntegerStringType::class, \PHPStan\Type\Accessory\HasMethodType::class, \PHPStan\Type\Accessory\HasPropertyType::class, \PHPStan\Type\ObjectType::class, \PHPStan\Type\Generic\GenericObjectType::class, \PHPStan\Type\Enum\EnumCaseObjectType::class, \PHPStan\Type\IterableType::class, \PHPStan\Type\CallableType::class, \PHPStan\Type\ClosureType::class, \PHPStan\Type\Constant\ConstantArrayType::class, \PHPStan\Type\UnionType::class, \PHPStan\Type\BenevolentUnionType::class, \PHPStan\Type\IntersectionType::class, \PHPStan\Type\ErrorType::class, \PHPStan\Type\CircularTypeAliasErrorType::class, \PHPStan\Type\Generic\AbsorbedTemplateArgumentType::class, \PHPStan\Type\NonAcceptingNeverType::class, \PHPStan\Type\StringAlwaysAcceptingObjectWithToStringType::class, \PHPStan\Type\StringNeverAcceptingObjectWithToStringType::class, \PHPStan\Type\ResourceType::class, \PHPStan\Type\TypeUtils::class, \PHPStan\Type\TypehintHelper::class, \PHPStan\Type\Generic\TemplateTypeVariance::class, \PHPStan\Type\Generic\TemplateTypeVarianceMap::class, \PHPStan\Type\Generic\TemplateTypeMap::class, \PHPStan\Type\Generic\TemplateTypeScope::class, \PHPStan\Type\Generic\TemplateTypeReference::class, \PHPStan\Type\Generic\TemplateTypeHelper::class, \PHPStan\Type\Generic\ArrayKeyTemplateHelper::class, \PHPStan\Type\KeyOfType::class, \PHPStan\Type\ValueOfType::class, \PHPStan\Type\OffsetAccessType::class, \PHPStan\Type\ClassConstantAccessType::class, \PHPStan\Type\NewObjectType::class, \PHPStan\Type\Generic\TemplateTypeApplication::class, \PHPStan\Type\ConditionalType::class, \PHPStan\Type\ConditionalTypeForParameter::class, \PHPStan\Type\LateResolvableArrayShapeType::class, \PHPStan\Type\Generic\UnresolvedTemplateArgumentType::class, \PHPStan\Type\Generic\TemplateArrayType::class, \PHPStan\Type\Generic\TemplateBenevolentUnionType::class, \PHPStan\Type\Generic\TemplateBooleanType::class, \PHPStan\Type\Generic\TemplateConstantArrayType::class, \PHPStan\Type\Generic\TemplateConstantIntegerType::class, \PHPStan\Type\Generic\TemplateConstantStringType::class, \PHPStan\Type\Generic\TemplateFloatType::class, \PHPStan\Type\Generic\TemplateGenericObjectType::class, \PHPStan\Type\Generic\TemplateIntegerType::class, \PHPStan\Type\Generic\TemplateIntersectionType::class, \PHPStan\Type\Generic\TemplateIterableType::class, \PHPStan\Type\Generic\TemplateMixedType::class, \PHPStan\Type\Generic\TemplateNullType::class, \PHPStan\Type\Generic\TemplateObjectShapeType::class, \PHPStan\Type\Generic\TemplateObjectType::class, \PHPStan\Type\Generic\TemplateObjectWithoutClassType::class, \PHPStan\Type\Generic\TemplateStrictMixedType::class, \PHPStan\Type\Generic\TemplateStringType::class, \PHPStan\Type\Generic\TemplateUnionType::class, \PHPStan\Type\Generic\TemplateTypeArgumentStrategy::class, \PHPStan\Type\Generic\TemplateTypeParameterStrategy::class, \PHPStan\Type\Generic\TemplateTypeFactory::class, \PHPStan\Type\Generic\TypeProjectionHelper::class, \PHPStan\Type\Constant\ConstantArrayTypeBuilder::class, \PHPStan\Type\UnionTypeHelper::class, \PHPStan\Type\CallableTypeHelper::class, \PHPStan\Type\Helper\GetTemplateTypeType::class, \PHPStan\Type\Generic\TemplateKeyOfType::class, \PHPStan\Rules\PhpDoc\UnresolvableTypeHelper::class, \PHPStan\Rules\RuleLevelHelper::class, \PHPStan\Reflection\Native\NativeParameterReflection::class, \PHPStan\Reflection\Type\CalledOnTypeUnresolvedMethodPrototypeReflection::class, \PHPStan\Reflection\Type\CalledOnTypeUnresolvedPropertyPrototypeReflection::class, \PHPStan\Reflection\Type\CallbackUnresolvedMethodPrototypeReflection::class, \PHPStan\Reflection\Type\CallbackUnresolvedPropertyPrototypeReflection::class, \PHPStan\Reflection\ResolvedMethodReflection::class, \PHPStan\Reflection\Dummy\ChangedTypeMethodReflection::class, \PHPStan\Reflection\Callables\SimpleImpurePoint::class, \PHPStan\Reflection\SideEffects::class, \PHPStan\Reflection\PassedByReference::class, \PHPStan\Reflection\Php\DummyParameter::class, \PHPStan\Reflection\Php\ExtendedDummyParameter::class, \PHPStan\Analyser\ArgumentsNormalizer::class, \PHPStan\Reflection\ParametersAcceptorSelector::class, \PHPStan\Reflection\Php\PhpParameterReflection::class, \PHPStan\Reflection\Native\ExtendedNativeParameterReflection::class, \PHPStan\Reflection\FunctionVariant::class, \PHPStan\Reflection\ExtendedFunctionVariant::class, \PHPStan\Reflection\ExtendedCallableFunctionVariant::class, \PHPStan\Reflection\ResolvedFunctionVariantWithOriginal::class, \PHPStan\Reflection\TrivialParametersAcceptor::class, \PHPStan\Reflection\Assertions::class, \PHPStan\Reflection\InitializerExprTypeResolver::class, \PHPStan\Type\ValueSet::class, \PHPStan\Analyser\Generics\TemplateArgumentConstraints::class, \PHPStan\Analyser\Generics\TemplateArgumentObserver::class, \PHPStan\Analyser\Generics\TemplateArgumentResolver::class, \PHPStan\Analyser\RicherScopeGetTypeHelper::class, \PHPStan\Analyser\NullsafeOperatorHelper::class, \PHPStan\Analyser\LoopWrittenVariableNames::class, \PHPStan\Reflection\Php\PhpPropertyReflection::class, \PHPStan\Reflection\Dummy\ChangedTypePropertyReflection::class, \PHPStan\Reflection\ResolvedPropertyReflection::class, \PHPStan\Type\StringSet::class] as $typeClass) { check(($typeFamilyPhp["native $typeClass"] ?? null) === false, "type-family.php php: $typeClass is the PHP twin"); check(($typeFamilyNative["native $typeClass"] ?? null) === true, "type-family.php native: $typeClass is the native class"); unset($typeFamilyPhp["native $typeClass"], $typeFamilyNative["native $typeClass"]); @@ -1921,6 +1921,7 @@ public function traverse(\PHPStan\Type\Type $type, callable $traverse): \PHPStan $covered[\PHPStan\Type\OffsetAccessType::class] = true; $covered[\PHPStan\Type\ClassConstantAccessType::class] = true; $covered[\PHPStan\Type\NewObjectType::class] = true; +$covered[\PHPStan\Type\Generic\TemplateTypeApplication::class] = true; $covered[\PHPStan\Type\ConditionalType::class] = true; $covered[\PHPStan\Type\ConditionalTypeForParameter::class] = true; $covered[\PHPStan\Type\LateResolvableArrayShapeType::class] = true; diff --git a/turbo-ext/tests/type-family.php b/turbo-ext/tests/type-family.php index d6fa4dd9734..a7dc04d0e1f 100644 --- a/turbo-ext/tests/type-family.php +++ b/turbo-ext/tests/type-family.php @@ -56,7 +56,7 @@ // which implementation answered: smoke.php holds the php run to false and // the native run to true, so the two sets can never be one implementation // compared against itself -foreach ([\PHPStan\Type\BooleanType::class, \PHPStan\Type\Constant\ConstantBooleanType::class, \PHPStan\Type\IntegerType::class, \PHPStan\Type\Constant\ConstantIntegerType::class, \PHPStan\Type\IntegerRangeType::class, \PHPStan\Type\StringType::class, \PHPStan\Type\Constant\ConstantStringType::class, \PHPStan\Type\ClassStringType::class, \PHPStan\Type\Generic\GenericClassStringType::class, \PHPStan\Type\FloatType::class, \PHPStan\Type\Constant\ConstantFloatType::class, \PHPStan\Type\FloatRangeType::class, \PHPStan\Type\NullType::class, \PHPStan\Type\VoidType::class, \PHPStan\Type\NeverType::class, \PHPStan\Type\MixedType::class, \PHPStan\Type\StrictMixedType::class, \PHPStan\Type\ObjectWithoutClassType::class, \PHPStan\Type\StaticType::class, \PHPStan\Type\ThisType::class, \PHPStan\Type\Generic\GenericStaticType::class, \PHPStan\Type\ObjectShapeType::class, \PHPStan\Type\NonexistentParentClassType::class, \PHPStan\Type\ArrayType::class, \PHPStan\Type\Accessory\NonEmptyArrayType::class, \PHPStan\Type\Accessory\AccessoryArrayListType::class, \PHPStan\Type\Accessory\OversizedArrayType::class, \PHPStan\Type\Accessory\HasOffsetType::class, \PHPStan\Type\Accessory\HasOffsetValueType::class, \PHPStan\Type\Accessory\AccessoryNumericStringType::class, \PHPStan\Type\Accessory\AccessoryNonEmptyStringType::class, \PHPStan\Type\Accessory\AccessoryNonFalsyStringType::class, \PHPStan\Type\Accessory\AccessoryLiteralStringType::class, \PHPStan\Type\Accessory\AccessoryLowercaseStringType::class, \PHPStan\Type\Accessory\AccessoryUppercaseStringType::class, \PHPStan\Type\Accessory\AccessoryDecimalIntegerStringType::class, \PHPStan\Type\Accessory\HasMethodType::class, \PHPStan\Type\Accessory\HasPropertyType::class, \PHPStan\Type\ObjectType::class, \PHPStan\Type\Generic\GenericObjectType::class, \PHPStan\Type\Enum\EnumCaseObjectType::class, \PHPStan\Type\IterableType::class, \PHPStan\Type\CallableType::class, \PHPStan\Type\ClosureType::class, \PHPStan\Type\Constant\ConstantArrayType::class, \PHPStan\Type\UnionType::class, \PHPStan\Type\BenevolentUnionType::class, \PHPStan\Type\IntersectionType::class, \PHPStan\Type\ErrorType::class, \PHPStan\Type\CircularTypeAliasErrorType::class, \PHPStan\Type\Generic\AbsorbedTemplateArgumentType::class, \PHPStan\Type\NonAcceptingNeverType::class, \PHPStan\Type\StringAlwaysAcceptingObjectWithToStringType::class, \PHPStan\Type\StringNeverAcceptingObjectWithToStringType::class, \PHPStan\Type\ResourceType::class, \PHPStan\Type\KeyOfType::class, \PHPStan\Type\ValueOfType::class, \PHPStan\Type\OffsetAccessType::class, \PHPStan\Type\ClassConstantAccessType::class, \PHPStan\Type\NewObjectType::class, \PHPStan\Type\ConditionalType::class, \PHPStan\Type\ConditionalTypeForParameter::class, \PHPStan\Type\LateResolvableArrayShapeType::class, \PHPStan\Type\Generic\UnresolvedTemplateArgumentType::class, \PHPStan\Type\Generic\TemplateArrayType::class, \PHPStan\Type\Generic\TemplateBenevolentUnionType::class, \PHPStan\Type\Generic\TemplateBooleanType::class, \PHPStan\Type\Generic\TemplateConstantArrayType::class, \PHPStan\Type\Generic\TemplateConstantIntegerType::class, \PHPStan\Type\Generic\TemplateConstantStringType::class, \PHPStan\Type\Generic\TemplateFloatType::class, \PHPStan\Type\Generic\TemplateGenericObjectType::class, \PHPStan\Type\Generic\TemplateIntegerType::class, \PHPStan\Type\Generic\TemplateIntersectionType::class, \PHPStan\Type\Generic\TemplateIterableType::class, \PHPStan\Type\Generic\TemplateMixedType::class, \PHPStan\Type\Generic\TemplateNullType::class, \PHPStan\Type\Generic\TemplateObjectShapeType::class, \PHPStan\Type\Generic\TemplateObjectType::class, \PHPStan\Type\Generic\TemplateObjectWithoutClassType::class, \PHPStan\Type\Generic\TemplateStrictMixedType::class, \PHPStan\Type\Generic\TemplateStringType::class, \PHPStan\Type\Generic\TemplateUnionType::class, \PHPStan\Type\Generic\TemplateKeyOfType::class] as $typeClass) { +foreach ([\PHPStan\Type\BooleanType::class, \PHPStan\Type\Constant\ConstantBooleanType::class, \PHPStan\Type\IntegerType::class, \PHPStan\Type\Constant\ConstantIntegerType::class, \PHPStan\Type\IntegerRangeType::class, \PHPStan\Type\StringType::class, \PHPStan\Type\Constant\ConstantStringType::class, \PHPStan\Type\ClassStringType::class, \PHPStan\Type\Generic\GenericClassStringType::class, \PHPStan\Type\FloatType::class, \PHPStan\Type\Constant\ConstantFloatType::class, \PHPStan\Type\FloatRangeType::class, \PHPStan\Type\NullType::class, \PHPStan\Type\VoidType::class, \PHPStan\Type\NeverType::class, \PHPStan\Type\MixedType::class, \PHPStan\Type\StrictMixedType::class, \PHPStan\Type\ObjectWithoutClassType::class, \PHPStan\Type\StaticType::class, \PHPStan\Type\ThisType::class, \PHPStan\Type\Generic\GenericStaticType::class, \PHPStan\Type\ObjectShapeType::class, \PHPStan\Type\NonexistentParentClassType::class, \PHPStan\Type\ArrayType::class, \PHPStan\Type\Accessory\NonEmptyArrayType::class, \PHPStan\Type\Accessory\AccessoryArrayListType::class, \PHPStan\Type\Accessory\OversizedArrayType::class, \PHPStan\Type\Accessory\HasOffsetType::class, \PHPStan\Type\Accessory\HasOffsetValueType::class, \PHPStan\Type\Accessory\AccessoryNumericStringType::class, \PHPStan\Type\Accessory\AccessoryNonEmptyStringType::class, \PHPStan\Type\Accessory\AccessoryNonFalsyStringType::class, \PHPStan\Type\Accessory\AccessoryLiteralStringType::class, \PHPStan\Type\Accessory\AccessoryLowercaseStringType::class, \PHPStan\Type\Accessory\AccessoryUppercaseStringType::class, \PHPStan\Type\Accessory\AccessoryDecimalIntegerStringType::class, \PHPStan\Type\Accessory\HasMethodType::class, \PHPStan\Type\Accessory\HasPropertyType::class, \PHPStan\Type\ObjectType::class, \PHPStan\Type\Generic\GenericObjectType::class, \PHPStan\Type\Enum\EnumCaseObjectType::class, \PHPStan\Type\IterableType::class, \PHPStan\Type\CallableType::class, \PHPStan\Type\ClosureType::class, \PHPStan\Type\Constant\ConstantArrayType::class, \PHPStan\Type\UnionType::class, \PHPStan\Type\BenevolentUnionType::class, \PHPStan\Type\IntersectionType::class, \PHPStan\Type\ErrorType::class, \PHPStan\Type\CircularTypeAliasErrorType::class, \PHPStan\Type\Generic\AbsorbedTemplateArgumentType::class, \PHPStan\Type\NonAcceptingNeverType::class, \PHPStan\Type\StringAlwaysAcceptingObjectWithToStringType::class, \PHPStan\Type\StringNeverAcceptingObjectWithToStringType::class, \PHPStan\Type\ResourceType::class, \PHPStan\Type\KeyOfType::class, \PHPStan\Type\ValueOfType::class, \PHPStan\Type\OffsetAccessType::class, \PHPStan\Type\ClassConstantAccessType::class, \PHPStan\Type\NewObjectType::class, \PHPStan\Type\Generic\TemplateTypeApplication::class, \PHPStan\Type\ConditionalType::class, \PHPStan\Type\ConditionalTypeForParameter::class, \PHPStan\Type\LateResolvableArrayShapeType::class, \PHPStan\Type\Generic\UnresolvedTemplateArgumentType::class, \PHPStan\Type\Generic\TemplateArrayType::class, \PHPStan\Type\Generic\TemplateBenevolentUnionType::class, \PHPStan\Type\Generic\TemplateBooleanType::class, \PHPStan\Type\Generic\TemplateConstantArrayType::class, \PHPStan\Type\Generic\TemplateConstantIntegerType::class, \PHPStan\Type\Generic\TemplateConstantStringType::class, \PHPStan\Type\Generic\TemplateFloatType::class, \PHPStan\Type\Generic\TemplateGenericObjectType::class, \PHPStan\Type\Generic\TemplateIntegerType::class, \PHPStan\Type\Generic\TemplateIntersectionType::class, \PHPStan\Type\Generic\TemplateIterableType::class, \PHPStan\Type\Generic\TemplateMixedType::class, \PHPStan\Type\Generic\TemplateNullType::class, \PHPStan\Type\Generic\TemplateObjectShapeType::class, \PHPStan\Type\Generic\TemplateObjectType::class, \PHPStan\Type\Generic\TemplateObjectWithoutClassType::class, \PHPStan\Type\Generic\TemplateStrictMixedType::class, \PHPStan\Type\Generic\TemplateStringType::class, \PHPStan\Type\Generic\TemplateUnionType::class, \PHPStan\Type\Generic\TemplateKeyOfType::class] as $typeClass) { $observations["native $typeClass"] = (new ReflectionMethod($typeClass, 'describe'))->isInternal(); } @@ -5156,6 +5156,8 @@ public function getKeyType(): \PHPStan\Type\Type $lateList = new \PHPStan\Type\IntersectionType([new \PHPStan\Type\ArrayType(new \PHPStan\Type\IntegerType(), new \PHPStan\Type\StringType()), new \PHPStan\Type\Accessory\AccessoryArrayListType()]); $lateShapeNodeStatic = new \PHPStan\Type\StaticType($stringReflectionProvider->getClass(\PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode::class)); $lateShapeNodeObject = new \PHPStan\Type\ObjectType(\PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode::class); +$lateTIterator = $lateTemplate('TIterator', new \PHPStan\Type\ObjectType(\ArrayIterator::class)); +$lateIteratorApplication = new \PHPStan\Type\Generic\GenericStaticType($stringReflectionProvider->getClass(\ArrayIterator::class), [new \PHPStan\Type\IntegerType(), new \PHPStan\Type\StringType()], null, []); $lateSiteA = new \PhpParser\Node\Expr\Variable('a'); $lateSiteB = new \PhpParser\Node\Expr\Variable('b'); $lateSubjects = static fn (): array => [ @@ -5197,6 +5199,10 @@ public function getKeyType(): \PHPStan\Type\Type 'newClassString' => new \PHPStan\Type\NewObjectType(new \PHPStan\Type\Generic\GenericClassStringType(new \PHPStan\Type\ObjectType(\Exception::class))), 'newTObject' => new \PHPStan\Type\NewObjectType($lateTObject), 'newT' => new \PHPStan\Type\NewObjectType($lateT), + 'applicationT' => new \PHPStan\Type\Generic\TemplateTypeApplication($lateTIterator, $lateIteratorApplication, true), + 'applicationRecursive' => new \PHPStan\Type\Generic\TemplateTypeApplication(new \PHPStan\Type\ObjectType(\RecursiveArrayIterator::class), $lateIteratorApplication, true), + 'applicationUnion' => new \PHPStan\Type\Generic\TemplateTypeApplication(new \PHPStan\Type\UnionType([new \PHPStan\Type\ObjectType(\RecursiveArrayIterator::class), new \PHPStan\Type\ObjectType(\Exception::class)]), $lateIteratorApplication, true), + 'applicationInconsistent' => new \PHPStan\Type\Generic\TemplateTypeApplication($lateTIterator, $lateIteratorApplication, false), 'newString' => new \PHPStan\Type\NewObjectType(new \PHPStan\Type\StringType()), 'newMixed' => new \PHPStan\Type\NewObjectType(new \PHPStan\Type\MixedType()), 'condIntIsInt' => new \PHPStan\Type\ConditionalType(new \PHPStan\Type\IntegerType(), new \PHPStan\Type\IntegerType(), new \PHPStan\Type\StringType(), new \PHPStan\Type\BooleanType(), false), @@ -5510,7 +5516,7 @@ public function getKeyType(): \PHPStan\Type\Type $subjects['shapeTKeyUnsealedTKeyBool']->traverseSimultaneously($subjects['shapeTKeyIntOptionalUnsealedMixed'], static fn ($a, $b) => $b) === $subjects['shapeTKeyUnsealedTKeyBool'], ]); // the uninitialized-slot reads the twins' typed properties raise - foreach (['keyOfArray' => \PHPStan\Type\KeyOfType::class, 'valueOfArray' => \PHPStan\Type\ValueOfType::class, 'offsetShapeA' => \PHPStan\Type\OffsetAccessType::class, 'constantMissing' => \PHPStan\Type\ClassConstantAccessType::class, 'newException' => \PHPStan\Type\NewObjectType::class, 'condIntIsInt' => \PHPStan\Type\ConditionalType::class, 'condParamIsInt' => \PHPStan\Type\ConditionalTypeForParameter::class, 'shapeTKeyInt' => \PHPStan\Type\LateResolvableArrayShapeType::class, 'unresolvedInt' => \PHPStan\Type\Generic\UnresolvedTemplateArgumentType::class] as $name => $class) { + foreach (['keyOfArray' => \PHPStan\Type\KeyOfType::class, 'valueOfArray' => \PHPStan\Type\ValueOfType::class, 'offsetShapeA' => \PHPStan\Type\OffsetAccessType::class, 'constantMissing' => \PHPStan\Type\ClassConstantAccessType::class, 'newException' => \PHPStan\Type\NewObjectType::class, 'applicationT' => \PHPStan\Type\Generic\TemplateTypeApplication::class, 'condIntIsInt' => \PHPStan\Type\ConditionalType::class, 'condParamIsInt' => \PHPStan\Type\ConditionalTypeForParameter::class, 'shapeTKeyInt' => \PHPStan\Type\LateResolvableArrayShapeType::class, 'unresolvedInt' => \PHPStan\Type\Generic\UnresolvedTemplateArgumentType::class] as $name => $class) { $uninitialized = (new ReflectionClass($class))->newInstanceWithoutConstructor(); $r["$name uninitialized describe"] = $attempt(static fn () => $uninitialized->describe(\PHPStan\Type\VerbosityLevel::precise())); $r["$name uninitialized isString"] = $attempt(static fn () => $uninitialized->isString()); From 798380bdaa04309594bd16a0a3be13c26235bca3 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Mon, 30 Nov 2026 06:48:17 +0000 Subject: [PATCH 4/7] =?UTF-8?q?Make=20static<=E2=80=A6>=20called=20on=20a?= =?UTF-8?q?=20template=20type=20of=20a=20consistent=20class=20an=20applica?= =?UTF-8?q?tion=20of=20that=20template=20type?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7 --- src/Reflection/ConsistentTemplatesHelper.php | 2 + .../ResolvedFunctionVariantWithOriginal.php | 4 +- ...ypeUnresolvedMethodPrototypeReflection.php | 8 +- ...eUnresolvedPropertyPrototypeReflection.php | 9 +- src/Type/Generic/TemplateTypeApplication.php | 98 ++++++++ .../nsrt/template-type-application-static.php | 114 ++++++++++ .../Rules/Functions/ReturnTypeRuleTest.php | 4 + .../data/template-type-application.php | 62 ++++++ ...ypeUnresolvedMethodPrototypeReflection.cpp | 9 +- ...eUnresolvedPropertyPrototypeReflection.cpp | 9 +- .../ResolvedFunctionVariantWithOriginal.cpp | 13 +- turbo-ext/src/TemplateTypeApplication.cpp | 108 +++++++++ turbo-ext/src/TypeTraits.h | 4 + .../src/generated/TemplateTypeApplication.h | 209 +++++++++++------- turbo-ext/src/support.cpp | 1 + turbo-ext/src/support.h | 3 + 16 files changed, 570 insertions(+), 87 deletions(-) create mode 100644 tests/PHPStan/Analyser/nsrt/template-type-application-static.php diff --git a/src/Reflection/ConsistentTemplatesHelper.php b/src/Reflection/ConsistentTemplatesHelper.php index 3f01aa9ba03..92cc549b6b6 100644 --- a/src/Reflection/ConsistentTemplatesHelper.php +++ b/src/Reflection/ConsistentTemplatesHelper.php @@ -3,6 +3,7 @@ namespace PHPStan\Reflection; use PHPStan\DependencyInjection\AutowiredService; +use PHPStan\Turbo\ReferencedByTurboExtension; use function array_shift; /** @@ -11,6 +12,7 @@ * class of an object together with other type arguments is a type, like `static`. */ #[AutowiredService] +#[ReferencedByTurboExtension(key: 'consistentTemplatesHelper')] final class ConsistentTemplatesHelper { diff --git a/src/Reflection/ResolvedFunctionVariantWithOriginal.php b/src/Reflection/ResolvedFunctionVariantWithOriginal.php index af85439f365..ffc913a48ec 100644 --- a/src/Reflection/ResolvedFunctionVariantWithOriginal.php +++ b/src/Reflection/ResolvedFunctionVariantWithOriginal.php @@ -11,6 +11,7 @@ use PHPStan\Type\Generic\GenericObjectType; use PHPStan\Type\Generic\GenericStaticType; use PHPStan\Type\Generic\TemplateType; +use PHPStan\Type\Generic\TemplateTypeApplication; use PHPStan\Type\Generic\TemplateTypeHelper; use PHPStan\Type\Generic\TemplateTypeMap; use PHPStan\Type\Generic\TemplateTypeVariance; @@ -337,7 +338,8 @@ private function resolveResolvableTemplateTypes(Type $type, TemplateTypeVariance }; return TypeTraverser::map($type, function (Type $type, callable $traverse) use ($references, $objectCb): Type { - if ($type instanceof GenericObjectType || $type instanceof GenericStaticType) { + // TColl<…> holds its arguments like the object it will be + if ($type instanceof GenericObjectType || $type instanceof GenericStaticType || $type instanceof TemplateTypeApplication) { return TypeTraverser::map($type, $objectCb); } diff --git a/src/Reflection/Type/CalledOnTypeUnresolvedMethodPrototypeReflection.php b/src/Reflection/Type/CalledOnTypeUnresolvedMethodPrototypeReflection.php index ba61cd9c1fc..5f4c3cc6a68 100644 --- a/src/Reflection/Type/CalledOnTypeUnresolvedMethodPrototypeReflection.php +++ b/src/Reflection/Type/CalledOnTypeUnresolvedMethodPrototypeReflection.php @@ -12,6 +12,7 @@ use PHPStan\Reflection\ResolvedMethodReflection; use PHPStan\Turbo\ShadowedByTurboExtension; use PHPStan\Type\Generic\GenericStaticType; +use PHPStan\Type\Generic\TemplateTypeApplication; use PHPStan\Type\StaticType; use PHPStan\Type\ThisType; use PHPStan\Type\Type; @@ -148,8 +149,13 @@ private function transformStaticType(Type $type): Type $calledOnTypeReflections = $this->calledOnType->getObjectClassReflections(); if (count($calledOnTypeReflections) === 1) { $calledOnTypeReflection = $calledOnTypeReflections[0]; + $changed = $type->changeBaseClass($calledOnTypeReflection); + $application = TemplateTypeApplication::ofCalledOnType($this->calledOnType, $changed); + if ($application !== null) { + return $application; + } - return $traverse($type->changeBaseClass($calledOnTypeReflection)->getStaticObjectType()); + return $traverse($changed->getStaticObjectType()); } return $this->calledOnType; diff --git a/src/Reflection/Type/CalledOnTypeUnresolvedPropertyPrototypeReflection.php b/src/Reflection/Type/CalledOnTypeUnresolvedPropertyPrototypeReflection.php index eda211fb11e..a1f4b12bbef 100644 --- a/src/Reflection/Type/CalledOnTypeUnresolvedPropertyPrototypeReflection.php +++ b/src/Reflection/Type/CalledOnTypeUnresolvedPropertyPrototypeReflection.php @@ -8,6 +8,7 @@ use PHPStan\Reflection\ResolvedPropertyReflection; use PHPStan\Turbo\ShadowedByTurboExtension; use PHPStan\Type\Generic\GenericStaticType; +use PHPStan\Type\Generic\TemplateTypeApplication; use PHPStan\Type\StaticType; use PHPStan\Type\Type; use PHPStan\Type\TypeTraverser; @@ -90,7 +91,13 @@ private function transformStaticType(Type $type): Type if ($type instanceof GenericStaticType) { $fetchedOnTypeReflections = $this->fetchedOnType->getObjectClassReflections(); if (count($fetchedOnTypeReflections) === 1) { - return $traverse($type->changeBaseClass($fetchedOnTypeReflections[0])->getStaticObjectType()); + $changed = $type->changeBaseClass($fetchedOnTypeReflections[0]); + $application = TemplateTypeApplication::ofCalledOnType($this->fetchedOnType, $changed); + if ($application !== null) { + return $application; + } + + return $traverse($changed->getStaticObjectType()); } return $this->fetchedOnType; diff --git a/src/Type/Generic/TemplateTypeApplication.php b/src/Type/Generic/TemplateTypeApplication.php index 87ae8b411e6..ab09d844751 100644 --- a/src/Type/Generic/TemplateTypeApplication.php +++ b/src/Type/Generic/TemplateTypeApplication.php @@ -5,11 +5,18 @@ use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use PHPStan\Reflection\ClassMemberAccessAnswerer; +use PHPStan\Reflection\ConsistentTemplatesHelper; +use PHPStan\Reflection\ExtendedMethodReflection; +use PHPStan\Reflection\ExtendedPropertyReflection; +use PHPStan\Reflection\Type\UnresolvedMethodPrototypeReflection; +use PHPStan\Reflection\Type\UnresolvedPropertyPrototypeReflection; use PHPStan\Turbo\ShadowedByTurboExtension; use PHPStan\Type\AcceptsResult; use PHPStan\Type\CompoundType; use PHPStan\Type\IsSuperTypeOfResult; use PHPStan\Type\LateResolvableType; +use PHPStan\Type\StaticType; use PHPStan\Type\Traits\LateResolvableTypeTrait; use PHPStan\Type\Traits\NonGeneralizableTypeTrait; use PHPStan\Type\Type; @@ -48,6 +55,35 @@ public function __construct( { } + /** + * `static` called on a TColl, or on a TColl<…> that is not known yet, is TColl + * when the class has `@phpstan-consistent-templates`. + */ + public static function ofCalledOnType(Type $calledOnType, StaticType $static): ?self + { + if (!$static instanceof GenericStaticType) { + return null; + } + + if ($calledOnType instanceof self) { + if ($calledOnType->isResolvable()) { + return null; + } + + return new self($calledOnType->constructor, $static, true); + } + + if (!$calledOnType instanceof TemplateType) { + return null; + } + + if ((new ConsistentTemplatesHelper())->findConsistentTemplatesClass($static->getClassReflection()) === null) { + return null; + } + + return new self($calledOnType, $static, true); + } + public function isConsistent(): bool { return $this->consistent; @@ -161,6 +197,68 @@ public function inferTemplateTypes(Type $receivedType): TemplateTypeMap ->union($this->application->getStaticObjectType()->inferTemplateTypes($receivedType)); } + // the methods and properties of the class TColl will be, where `static` is that class + + public function getMethod(string $methodName, ClassMemberAccessAnswerer $scope): ExtendedMethodReflection + { + return $this->getUnresolvedMethodPrototype($methodName, $scope)->getTransformedMethod(); + } + + public function getProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection + { + return $this->getUnresolvedPropertyPrototype($propertyName, $scope)->getTransformedProperty(); + } + + public function getInstanceProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection + { + return $this->getUnresolvedInstancePropertyPrototype($propertyName, $scope)->getTransformedProperty(); + } + + public function getStaticProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection + { + return $this->getUnresolvedStaticPropertyPrototype($propertyName, $scope)->getTransformedProperty(); + } + + public function getUnresolvedMethodPrototype(string $methodName, ClassMemberAccessAnswerer $scope): UnresolvedMethodPrototypeReflection + { + $prototype = $this->resolve()->getUnresolvedMethodPrototype($methodName, $scope); + if ($this->isResolvable()) { + return $prototype; + } + + return $prototype->withCalledOnType($this); + } + + public function getUnresolvedPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection + { + $prototype = $this->resolve()->getUnresolvedPropertyPrototype($propertyName, $scope); + if ($this->isResolvable()) { + return $prototype; + } + + return $prototype->withFechedOnType($this); + } + + public function getUnresolvedInstancePropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection + { + $prototype = $this->resolve()->getUnresolvedInstancePropertyPrototype($propertyName, $scope); + if ($this->isResolvable()) { + return $prototype; + } + + return $prototype->withFechedOnType($this); + } + + public function getUnresolvedStaticPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection + { + $prototype = $this->resolve()->getUnresolvedStaticPropertyPrototype($propertyName, $scope); + if ($this->isResolvable()) { + return $prototype; + } + + return $prototype->withFechedOnType($this); + } + /** @phpstan-assert-if-true self $type */ private function isSameUnresolvedClass(Type $type): bool { diff --git a/tests/PHPStan/Analyser/nsrt/template-type-application-static.php b/tests/PHPStan/Analyser/nsrt/template-type-application-static.php new file mode 100644 index 00000000000..5a8ece33e52 --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/template-type-application-static.php @@ -0,0 +1,114 @@ + + */ + public function map(callable $f); + + /** @return static */ + public function filter(); + +} + +/** + * @template-covariant T + * @implements Coll + */ +final class Vec implements Coll +{ + + /** @var static */ + public $strings; + + public function map(callable $f) + { + throw new \Exception(); + } + + public function filter() + { + return $this; + } + +} + +/** @template-covariant T */ +interface Loose +{ + + /** + * @template U + * @param callable(T): U $f + * @return static + */ + public function map(callable $f); + +} + +/** + * @template TColl of Coll + * @param TColl $c + * @return TColl + */ +function stringify(Coll $c): Coll +{ + assertType('TColl', $c->map(static fn (int $i): string => (string) $i)); + assertType('TColl', $c->filter()); + + return $c->map(static fn (int $i): string => (string) $i); +} + +/** + * @template TColl of Coll + * @param TColl $c + * @return TColl + */ +function plain(Coll $c): Coll +{ + assertType('TColl', $c->map(static fn (int $i): string => (string) $i)); + assertType('TColl of TemplateTypeApplicationStatic\Coll (function TemplateTypeApplicationStatic\plain(), argument)', $c->filter()); + + return $c->filter(); +} + +/** + * @template TVec of Vec + * @param TVec $vec + */ +function property(Vec $vec): void +{ + assertType('TVec', $vec->strings); +} + +/** + * @template TLoose of Loose + * @param TLoose $c + */ +function loose(Loose $c): void +{ + // without @phpstan-consistent-templates the class is not known to hold strings + assertType('TemplateTypeApplicationStatic\Loose', $c->map(static fn (int $i): string => (string) $i)); +} + +/** + * @param Vec $vec + */ +function test(Vec $vec): void +{ + assertType('TemplateTypeApplicationStatic\Vec', stringify($vec)); + assertType('TemplateTypeApplicationStatic\Vec', plain($vec)); + assertType('TemplateTypeApplicationStatic\Vec', $vec->map(static fn (int $i): string => (string) $i)); +} diff --git a/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php b/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php index 4d623e535ad..73bf90f7ac9 100644 --- a/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php +++ b/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php @@ -706,6 +706,10 @@ public function testTemplateTypeApplication(): void 'Function TemplateTypeApplicationRules\\same() should return TColl but returns TColl.', 36, ], + [ + 'Function TemplateTypeApplicationRules\\mappedWrongly() should return TMappable but returns TMappable.', + 96, + ], ]); } diff --git a/tests/PHPStan/Rules/Functions/data/template-type-application.php b/tests/PHPStan/Rules/Functions/data/template-type-application.php index 32d73eefbec..587aaca08b7 100644 --- a/tests/PHPStan/Rules/Functions/data/template-type-application.php +++ b/tests/PHPStan/Rules/Functions/data/template-type-application.php @@ -59,3 +59,65 @@ function test(Vec $strings, Vec $ints): void ints($strings); ints(new \stdClass()); } + +/** + * @template-covariant T + * @phpstan-consistent-templates + */ +interface Mappable +{ + + /** + * @template U + * @param callable(T): U $f + * @return static + */ + public function map(callable $f); + +} + +/** + * @template TMappable of Mappable + * @param TMappable $m + * @return TMappable + */ +function mapped(Mappable $m): Mappable +{ + return $m->map(static fn (int $i): string => (string) $i); +} + +/** + * @template TMappable of Mappable + * @param TMappable $m + * @return TMappable + */ +function mappedWrongly(Mappable $m): Mappable +{ + return $m->map(static fn (int $i): string => (string) $i); +} + +/** + * @template T + * @phpstan-consistent-templates + */ +interface InvariantMappable +{ + + /** + * @template U + * @param callable(T): U $f + * @return static + */ + public function map(callable $f); + +} + +/** + * @template TMappable of InvariantMappable + * @param TMappable $m + * @return TMappable + */ +function mappedInvariant(InvariantMappable $m): InvariantMappable +{ + return $m->map(static fn (int $i): string => (string) $i); +} diff --git a/turbo-ext/src/CalledOnTypeUnresolvedMethodPrototypeReflection.cpp b/turbo-ext/src/CalledOnTypeUnresolvedMethodPrototypeReflection.cpp index 0a1465aa224..19975f5565d 100644 --- a/turbo-ext/src/CalledOnTypeUnresolvedMethodPrototypeReflection.cpp +++ b/turbo-ext/src/CalledOnTypeUnresolvedMethodPrototypeReflection.cpp @@ -207,7 +207,7 @@ class CalledOnTypeUnresolvedMethodPrototypeReflection return; } if (zend_hash_num_elements(Z_ARRVAL_P(reflections.raw())) == 1) { - /* return $traverse($type->changeBaseClass($calledOnTypeReflections[0])->getStaticObjectType()); */ + /* $changed = $type->changeBaseClass($calledOnTypeReflections[0]); */ zval *first = zend_hash_index_find(Z_ARRVAL_P(reflections.raw()), 0); if (UNEXPECTED(first == NULL)) { zend_throw_error(NULL, "phpstan_turbo: getObjectClassReflections() must return a list"); @@ -220,6 +220,13 @@ class CalledOnTypeUnresolvedMethodPrototypeReflection zend_type_error("phpstan_turbo: changeBaseClass() must return an object"); return; } + /* $application = TemplateTypeApplication::ofCalledOnType($this->calledOnType, $changed); */ + zv::Val application = pt_template_type_application_of_called_on_type(calledOnType, changed.raw()); + if (UNEXPECTED(application.isUndef())) return; + if (Z_TYPE_P(application.raw()) != IS_NULL) { + application.intoReturnValue(return_value); + return; + } zv::Val staticObjectType = pt_type_call(Z_OBJ_P(changed.raw()), PT_LC("getstaticobjecttype"), 0, NULL); if (UNEXPECTED(staticObjectType.isUndef())) return; zv::Val traversed = pt_type_call_callable(&argv[1], 1, staticObjectType.raw()); diff --git a/turbo-ext/src/CalledOnTypeUnresolvedPropertyPrototypeReflection.cpp b/turbo-ext/src/CalledOnTypeUnresolvedPropertyPrototypeReflection.cpp index 3d1e316de07..18e055dfb5a 100644 --- a/turbo-ext/src/CalledOnTypeUnresolvedPropertyPrototypeReflection.cpp +++ b/turbo-ext/src/CalledOnTypeUnresolvedPropertyPrototypeReflection.cpp @@ -173,7 +173,7 @@ class CalledOnTypeUnresolvedPropertyPrototypeReflection return; } if (zend_hash_num_elements(Z_ARRVAL_P(reflections.raw())) == 1) { - /* return $traverse($type->changeBaseClass($fetchedOnTypeReflections[0])->getStaticObjectType()); */ + /* $changed = $type->changeBaseClass($fetchedOnTypeReflections[0]); */ zval *first = zend_hash_index_find(Z_ARRVAL_P(reflections.raw()), 0); if (UNEXPECTED(first == NULL)) { zend_throw_error(NULL, "phpstan_turbo: getObjectClassReflections() must return a list"); @@ -186,6 +186,13 @@ class CalledOnTypeUnresolvedPropertyPrototypeReflection zend_type_error("phpstan_turbo: changeBaseClass() must return an object"); return; } + /* $application = TemplateTypeApplication::ofCalledOnType($this->fetchedOnType, $changed); */ + zv::Val application = pt_template_type_application_of_called_on_type(fetchedOnType, changed.raw()); + if (UNEXPECTED(application.isUndef())) return; + if (Z_TYPE_P(application.raw()) != IS_NULL) { + application.intoReturnValue(return_value); + return; + } zv::Val staticObjectType = pt_type_call(Z_OBJ_P(changed.raw()), PT_LC("getstaticobjecttype"), 0, NULL); if (UNEXPECTED(staticObjectType.isUndef())) return; zv::Val traversed = pt_type_call_callable(&argv[1], 1, staticObjectType.raw()); diff --git a/turbo-ext/src/ResolvedFunctionVariantWithOriginal.cpp b/turbo-ext/src/ResolvedFunctionVariantWithOriginal.cpp index 1bffe1006fa..51ab859dcfa 100644 --- a/turbo-ext/src/ResolvedFunctionVariantWithOriginal.cpp +++ b/turbo-ext/src/ResolvedFunctionVariantWithOriginal.cpp @@ -133,7 +133,7 @@ zv::Val weakReferenceCreate(zval *object) #define PT_RFV_CLASS "PHPStan\\Reflection\\ResolvedFunctionVariantWithOriginal" /* the closure names differ: PHP 8.3 names a closure by its namespace alone */ #define PT_RFV_CLOSURE(method, line) PT_ABI_SINCE(80400, PT_RFV_CLASS "::{closure:" PT_RFV_CLASS "::" method "():" line "}", PT_RFV_CLASS "::PHPStan\\Reflection\\{closure}") -#define PT_RFV_PARAMETERS_CLOSURE PT_RFV_CLOSURE("getParameters", "90") +#define PT_RFV_PARAMETERS_CLOSURE PT_RFV_CLOSURE("getParameters", "91") /* }}} */ @@ -683,7 +683,7 @@ class ResolvedFunctionVariantWithOriginal static void typeCallbackBody(zval *captures, uint32_t argc, zval *argv, zval *return_value) { if (UNEXPECTED(argc < 2)) { - zend_throw_error(zend_ce_argument_count_error, "Too few arguments to function %s(), %u passed and exactly 2 expected", PT_RFV_CLOSURE("resolveResolvableTemplateTypes", "338"), argc); + zend_throw_error(zend_ce_argument_count_error, "Too few arguments to function %s(), %u passed and exactly 2 expected", PT_RFV_CLOSURE("resolveResolvableTemplateTypes", "339"), argc); return; } zend_object *self = Z_OBJ(captures[0]); @@ -695,7 +695,8 @@ class ResolvedFunctionVariantWithOriginal return; } zend_class_entry *ce = Z_OBJCE_P(type); - if (instanceof_function(ce, pt_ce_generic_object_type) || instanceof_function(ce, pt_ce_generic_static_type)) { + /* TColl<…> holds its arguments like the object it will be */ + if (instanceof_function(ce, pt_ce_generic_object_type) || instanceof_function(ce, pt_ce_generic_static_type) || instanceof_function(ce, pt_ce_template_type_application)) { (void) pt_type_traverser_map(return_value, type, &captures[2]); return; } @@ -746,7 +747,7 @@ class ResolvedFunctionVariantWithOriginal static void objectCallbackBody(zval *captures, uint32_t argc, zval *argv, zval *return_value) { if (UNEXPECTED(argc < 2)) { - zend_throw_error(zend_ce_argument_count_error, "Too few arguments to function %s(), %u passed and exactly 2 expected", PT_RFV_CLOSURE("resolveResolvableTemplateTypes", "292"), argc); + zend_throw_error(zend_ce_argument_count_error, "Too few arguments to function %s(), %u passed and exactly 2 expected", PT_RFV_CLOSURE("resolveResolvableTemplateTypes", "293"), argc); return; } zend_object *self = Z_OBJ(captures[0]); @@ -807,7 +808,7 @@ class ResolvedFunctionVariantWithOriginal static void narrowCallbackBody(zval *captures, uint32_t argc, zval *argv, zval *return_value) { if (UNEXPECTED(argc < 2)) { - zend_throw_error(zend_ce_argument_count_error, "Too few arguments to function %s(), %u passed and exactly 2 expected", PT_RFV_CLOSURE("narrowTemplateTypesInConditionalTypesForParameter", "427"), argc); + zend_throw_error(zend_ce_argument_count_error, "Too few arguments to function %s(), %u passed and exactly 2 expected", PT_RFV_CLOSURE("narrowTemplateTypesInConditionalTypesForParameter", "429"), argc); return; } zend_object *self = Z_OBJ(captures[0]); @@ -864,7 +865,7 @@ class ResolvedFunctionVariantWithOriginal static void referencesCallbackBody(zval *references, zval *templateType, uint32_t argc, zval *argv, zval *return_value) { if (UNEXPECTED(argc < 2)) { - zend_throw_error(zend_ce_argument_count_error, "Too few arguments to function %s(), %u passed and exactly 2 expected", PT_RFV_CLOSURE("referencesTemplateType", "490"), argc); + zend_throw_error(zend_ce_argument_count_error, "Too few arguments to function %s(), %u passed and exactly 2 expected", PT_RFV_CLOSURE("referencesTemplateType", "492"), argc); return; } zval *type = &argv[0]; diff --git a/turbo-ext/src/TemplateTypeApplication.cpp b/turbo-ext/src/TemplateTypeApplication.cpp index 71a232d62f5..daa43bc241a 100644 --- a/turbo-ext/src/TemplateTypeApplication.cpp +++ b/turbo-ext/src/TemplateTypeApplication.cpp @@ -55,6 +55,39 @@ class TemplateTypeApplication return zv::Val::adopt(object); } + /* ofCalledOnType(Type $calledOnType, StaticType $static): ?self — + * `static` called on a TColl, or on a TColl<…> that is not known yet, + * is TColl when the class has `@phpstan-consistent-templates`; + * IS_NULL for none, UNDEF = pending exception */ + static zv::Val ofCalledOnType(zval *calledOnType, zval *staticType) + { + if (!instanceof_function(Z_OBJCE_P(staticType), pt_ce_generic_static_type)) return zv::Val::null(); + + if (instanceof_function(Z_OBJCE_P(calledOnType), pt_ce_template_type_application)) { + TemplateTypeApplication calledOn(Z_OBJ_P(calledOnType)); + bool resolvable; + if (UNEXPECTED(!calledOn.isResolvable(resolvable))) return zv::Val(); + if (resolvable) return zv::Val::null(); + zval *ctor = calledOn.constructor(); + if (UNEXPECTED(ctor == NULL)) return zv::Val(); + return createInstance(ctor, staticType, true); + } + + bool isTemplate; + if (UNEXPECTED(!pt_type_instanceof(calledOnType, PT_CLASS_TEMPLATE_TYPE, isTemplate))) return zv::Val(); + if (!isTemplate) return zv::Val::null(); + + zv::Val classReflection = pt_type_call(Z_OBJ_P(staticType), PT_LC("getclassreflection"), 0, NULL); + if (UNEXPECTED(classReflection.isUndef())) return zv::Val(); + zv::Val helper = pt_type_new(PT_CLASS_CONSISTENT_TEMPLATES_HELPER, 0, NULL); + if (UNEXPECTED(helper.isUndef())) return zv::Val(); + zv::Val found = pt_type_call(Z_OBJ_P(helper.raw()), PT_LC("findconsistenttemplatesclass"), 1, classReflection.raw()); + if (UNEXPECTED(found.isUndef())) return zv::Val(); + if (Z_TYPE_P(found.raw()) == IS_NULL) return zv::Val::null(); + + return createInstance(calledOnType, staticType, true); + } + /* the slots (borrowed); NULL with an Error pending when the constructor * never ran — the twin's typed-property read raises the same */ [[nodiscard]] zval *constructor() const { return slot(self, slots::constructor, "constructor"); } @@ -429,9 +462,60 @@ class TemplateTypeApplication return createInstance(newConstructor, newApplication, isConsistent); } + /* the methods and properties of the class TColl will be, where `static` + * is that class: $this->getUnresolved…Prototype(…)->getTransformed…(); + * UNDEF = pending exception */ + zv::Val getMethod(zend_string *name, zval *scope) const { return transformed(PT_LC("getunresolvedmethodprototype"), name, scope, PT_LC("gettransformedmethod")); } + zv::Val getProperty(zend_string *name, zval *scope) const { return transformed(PT_LC("getunresolvedpropertyprototype"), name, scope, PT_LC("gettransformedproperty")); } + zv::Val getInstanceProperty(zend_string *name, zval *scope) const { return transformed(PT_LC("getunresolvedinstancepropertyprototype"), name, scope, PT_LC("gettransformedproperty")); } + zv::Val getStaticProperty(zend_string *name, zval *scope) const { return transformed(PT_LC("getunresolvedstaticpropertyprototype"), name, scope, PT_LC("gettransformedproperty")); } + + /* $this->resolve()->getUnresolved…Prototype($name, $scope), called on + * (fetched on) $this while the constructor is not known yet; UNDEF = + * pending exception */ + zv::Val getUnresolvedMethodPrototype(zend_string *name, zval *scope) const { return prototype(PT_LC("getunresolvedmethodprototype"), name, scope, PT_LC("withcalledontype")); } + zv::Val getUnresolvedPropertyPrototype(zend_string *name, zval *scope) const { return prototype(PT_LC("getunresolvedpropertyprototype"), name, scope, PT_LC("withfechedontype")); } + zv::Val getUnresolvedInstancePropertyPrototype(zend_string *name, zval *scope) const { return prototype(PT_LC("getunresolvedinstancepropertyprototype"), name, scope, PT_LC("withfechedontype")); } + zv::Val getUnresolvedStaticPropertyPrototype(zend_string *name, zval *scope) const { return prototype(PT_LC("getunresolvedstaticpropertyprototype"), name, scope, PT_LC("withfechedontype")); } + private: zend_object *self; + zv::Val prototype(const char *lcname, size_t len, zend_string *name, zval *scope, const char *withLcname, size_t withLen) const + { + zv::Val resolved = resolve(); + if (UNEXPECTED(resolved.isUndef())) return zv::Val(); + zval args[2]; + ZVAL_STR(&args[0], name); + ZVAL_COPY_VALUE(&args[1], scope); + zv::Val found = pt_type_call(Z_OBJ_P(resolved.raw()), lcname, len, 2, args); + if (UNEXPECTED(found.isUndef())) return zv::Val(); + bool resolvable; + if (UNEXPECTED(!isResolvable(resolvable))) return zv::Val(); + if (resolvable) return found; + if (UNEXPECTED(!zv::Ref(found.raw()).isObject())) { + zend_type_error("phpstan_turbo: an unresolved member prototype must be an object"); + return zv::Val(); + } + zv::Val thisVal = thisValue(); + return pt_type_call(Z_OBJ_P(found.raw()), withLcname, withLen, 1, thisVal.raw()); + } + + zv::Val transformed(const char *lcname, size_t len, zend_string *name, zval *scope, const char *getLcname, size_t getLen) const + { + zval args[2]; + ZVAL_STR(&args[0], name); + ZVAL_COPY_VALUE(&args[1], scope); + zv::Val thisVal = thisValue(); + zv::Val found = pt_type_call(Z_OBJ_P(thisVal.raw()), lcname, len, 2, args); + if (UNEXPECTED(found.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(found.raw()).isObject())) { + zend_type_error("phpstan_turbo: an unresolved member prototype must be an object"); + return zv::Val(); + } + return pt_type_call(Z_OBJ_P(found.raw()), getLcname, getLen, 0, NULL); + } + zv::Val thisValue() const { return pt_this_value(self); } static zv::Val copied(zval *value) @@ -539,6 +623,16 @@ PT_MINIT_REGISTRATION(pt_register_template_type_application) PT_THIS.construct(constructor, application, consistent); }); + cls.method(sigs::ofCalledOnType, [](INTERNAL_FUNCTION_PARAMETERS) { + zval *calledOnType; + zval *staticType; + ZEND_PARSE_PARAMETERS_START(2, 2) + Z_PARAM_OBJECT_OF_CLASS(calledOnType, pt_ce_type_interface()) + Z_PARAM_OBJECT_OF_CLASS(staticType, pt_ce_static_type) + ZEND_PARSE_PARAMETERS_END(); + PT_RETURN_VAL(TemplateTypeApplication::ofCalledOnType(calledOnType, staticType)); + }); + cls.method<&TemplateTypeApplication::isConsistent>(sigs::isConsistent); cls.method<&TemplateTypeApplication::getConstructor>(sigs::getConstructor); @@ -589,6 +683,15 @@ PT_MINIT_REGISTRATION(pt_register_template_type_application) cls.method<&TemplateTypeApplication::toPhpDocNode>(sigs::toPhpDocNode); + cls.method<&TemplateTypeApplication::getMethod, zp::Str, zp::Obj>(sigs::getMethod); + cls.method<&TemplateTypeApplication::getProperty, zp::Str, zp::Obj>(sigs::getProperty); + cls.method<&TemplateTypeApplication::getInstanceProperty, zp::Str, zp::Obj>(sigs::getInstanceProperty); + cls.method<&TemplateTypeApplication::getStaticProperty, zp::Str, zp::Obj>(sigs::getStaticProperty); + cls.method<&TemplateTypeApplication::getUnresolvedMethodPrototype, zp::Str, zp::Obj>(sigs::getUnresolvedMethodPrototype); + cls.method<&TemplateTypeApplication::getUnresolvedPropertyPrototype, zp::Str, zp::Obj>(sigs::getUnresolvedPropertyPrototype); + cls.method<&TemplateTypeApplication::getUnresolvedInstancePropertyPrototype, zp::Str, zp::Obj>(sigs::getUnresolvedInstancePropertyPrototype); + cls.method<&TemplateTypeApplication::getUnresolvedStaticPropertyPrototype, zp::Str, zp::Obj>(sigs::getUnresolvedStaticPropertyPrototype); + /* the traits, in the twin's `use` order; the class body above wins over * every name it declares */ ptdecl::TemplateTypeApplication::registerTraits(cls); @@ -597,3 +700,8 @@ PT_MINIT_REGISTRATION(pt_register_template_type_application) } /* }}} */ + +zv::Val pt_template_type_application_of_called_on_type(zval *calledOnType, zval *staticType) +{ + return TemplateTypeApplication::ofCalledOnType(calledOnType, staticType); +} diff --git a/turbo-ext/src/TypeTraits.h b/turbo-ext/src/TypeTraits.h index d7c57947d71..5e0008c6292 100644 --- a/turbo-ext/src/TypeTraits.h +++ b/turbo-ext/src/TypeTraits.h @@ -170,6 +170,10 @@ zv::Val pt_type_call_static(int classIdx, const char *lcname, size_t len, uint32 * declares one; UNDEF = pending exception */ zv::Val pt_type_new(int classIdx, uint32_t argc, zval *argv); +/* TemplateTypeApplication::ofCalledOnType($calledOnType, $static): the + * application, or NULL (IS_NULL) for none; UNDEF = pending exception */ +zv::Val pt_template_type_application_of_called_on_type(zval *calledOnType, zval *staticType); + /* {{{ Type::toValueSet() (ValueSet.cpp) */ /* ValueSet::(...$args); UNDEF = pending exception */ diff --git a/turbo-ext/src/generated/TemplateTypeApplication.h b/turbo-ext/src/generated/TemplateTypeApplication.h index 4fa191234d6..76395ea4df1 100644 --- a/turbo-ext/src/generated/TemplateTypeApplication.h +++ b/turbo-ext/src/generated/TemplateTypeApplication.h @@ -48,71 +48,119 @@ inline constexpr char strings[] = "PHPStan\\Type\\Generic\\GenericStaticType\0" /* 42 */ "consistent\0" /* 81 */ "__construct\0" /* 92 */ - "\0" /* 104 */ - "isConsistent\0" /* 105 */ - "getConstructor\0" /* 118 */ - "getApplication\0" /* 133 */ - "getReferencedClasses\0" /* 148 */ - "positionVariance\0" /* 169 */ - "PHPStan\\Type\\Generic\\TemplateTypeVariance\0" /* 186 */ - "getReferencedTemplateTypes\0" /* 228 */ - "type\0" /* 255 */ - "equals\0" /* 260 */ - "level\0" /* 267 */ - "PHPStan\\Type\\VerbosityLevel\0" /* 273 */ - "describe\0" /* 301 */ - "isResolvable\0" /* 310 */ - "getResult\0" /* 323 */ - "PHPStan\\Type\\IsSuperTypeOfResult\0" /* 333 */ - "isSuperTypeOf\0" /* 366 */ - "strictTypes\0" /* 380 */ - "PHPStan\\Type\\AcceptsResult\0" /* 392 */ - "accepts\0" /* 419 */ - "receivedType\0" /* 427 */ - "PHPStan\\Type\\Generic\\TemplateTypeMap\0" /* 440 */ - "inferTemplateTypes\0" /* 477 */ - "isSameUnresolvedClass\0" /* 496 */ - "cb\0" /* 518 */ - "traverse\0" /* 521 */ - "right\0" /* 530 */ - "traverseSimultaneously\0" /* 536 */ - "create\0" /* 559 */ - "PHPStan\\PhpDocParser\\Ast\\Type\\TypeNode\0" /* 566 */ - "toPhpDocNode"; /* 605 */ + "calledOnType\0" /* 104 */ + "static\0" /* 117 */ + "PHPStan\\Type\\StaticType\0" /* 124 */ + "\0" /* 148 */ + "PHPStan\\Type\\Generic\\TemplateTypeApplication\0" /* 149 */ + "ofCalledOnType\0" /* 194 */ + "isConsistent\0" /* 209 */ + "getConstructor\0" /* 222 */ + "getApplication\0" /* 237 */ + "getReferencedClasses\0" /* 252 */ + "positionVariance\0" /* 273 */ + "PHPStan\\Type\\Generic\\TemplateTypeVariance\0" /* 290 */ + "getReferencedTemplateTypes\0" /* 332 */ + "type\0" /* 359 */ + "equals\0" /* 364 */ + "level\0" /* 371 */ + "PHPStan\\Type\\VerbosityLevel\0" /* 377 */ + "describe\0" /* 405 */ + "isResolvable\0" /* 414 */ + "getResult\0" /* 427 */ + "PHPStan\\Type\\IsSuperTypeOfResult\0" /* 437 */ + "isSuperTypeOf\0" /* 470 */ + "strictTypes\0" /* 484 */ + "PHPStan\\Type\\AcceptsResult\0" /* 496 */ + "accepts\0" /* 523 */ + "receivedType\0" /* 531 */ + "PHPStan\\Type\\Generic\\TemplateTypeMap\0" /* 544 */ + "inferTemplateTypes\0" /* 581 */ + "methodName\0" /* 600 */ + "scope\0" /* 611 */ + "PHPStan\\Reflection\\ClassMemberAccessAnswerer\0" /* 617 */ + "PHPStan\\Reflection\\ExtendedMethodReflection\0" /* 662 */ + "getMethod\0" /* 706 */ + "propertyName\0" /* 716 */ + "PHPStan\\Reflection\\ExtendedPropertyReflection\0" /* 729 */ + "getProperty\0" /* 775 */ + "getInstanceProperty\0" /* 787 */ + "getStaticProperty\0" /* 807 */ + "PHPStan\\Reflection\\Type\\UnresolvedMethodPrototypeReflection\0" /* 825 */ + "getUnresolvedMethodPrototype\0" /* 885 */ + "PHPStan\\Reflection\\Type\\UnresolvedPropertyPrototypeReflection\0" /* 914 */ + "getUnresolvedPropertyPrototype\0" /* 976 */ + "getUnresolvedInstancePropertyPrototype\0" /* 1007 */ + "getUnresolvedStaticPropertyPrototype\0" /* 1046 */ + "isSameUnresolvedClass\0" /* 1083 */ + "cb\0" /* 1105 */ + "traverse\0" /* 1108 */ + "right\0" /* 1117 */ + "traverseSimultaneously\0" /* 1123 */ + "create\0" /* 1146 */ + "PHPStan\\PhpDocParser\\Ast\\Type\\TypeNode\0" /* 1153 */ + "toPhpDocNode"; /* 1192 */ inline constexpr reg::PackedArg args[] = { reg::packed(0, 0, 12), /* __construct $constructor */ reg::packed(30, 0, 42), /* __construct $application */ reg::packed(81, MAY_BE_BOOL), /* __construct $consistent */ - reg::packed(104, MAY_BE_BOOL), /* isConsistent return */ - reg::packed(104, 0, 12), /* getConstructor return */ - reg::packed(104, 0, 42), /* getApplication return */ - reg::packed(104, MAY_BE_ARRAY), /* getReferencedClasses return */ - reg::packed(169, 0, 186), /* getReferencedTemplateTypes $positionVariance */ - reg::packed(104, MAY_BE_ARRAY), /* getReferencedTemplateTypes return */ - reg::packed(255, 0, 12), /* equals $type */ - reg::packed(104, MAY_BE_BOOL), /* equals return */ - reg::packed(267, 0, 273), /* describe $level */ - reg::packed(104, MAY_BE_STRING), /* describe return */ - reg::packed(104, MAY_BE_BOOL), /* isResolvable return */ - reg::packed(104, 0, 12), /* getResult return */ - reg::packed(255, 0, 12), /* isSuperTypeOf $type */ - reg::packed(104, 0, 333), /* isSuperTypeOf return */ - reg::packed(255, 0, 12), /* accepts $type */ - reg::packed(380, MAY_BE_BOOL), /* accepts $strictTypes */ - reg::packed(104, 0, 392), /* accepts return */ - reg::packed(427, 0, 12), /* inferTemplateTypes $receivedType */ - reg::packed(104, 0, 440), /* inferTemplateTypes return */ - reg::packed(255, 0, 12), /* isSameUnresolvedClass $type */ - reg::packed(104, MAY_BE_BOOL), /* isSameUnresolvedClass return */ - reg::packed(518, MAY_BE_CALLABLE), /* traverse $cb */ - reg::packed(104, 0, 12), /* traverse return */ - reg::packed(530, 0, 12), /* traverseSimultaneously $right */ - reg::packed(518, MAY_BE_CALLABLE), /* traverseSimultaneously $cb */ - reg::packed(104, 0, 12), /* traverseSimultaneously return */ + reg::packed(104, 0, 12), /* ofCalledOnType $calledOnType */ + reg::packed(117, 0, 124), /* ofCalledOnType $static */ + reg::packed(148, MAY_BE_NULL, 149), /* ofCalledOnType return */ + reg::packed(148, MAY_BE_BOOL), /* isConsistent return */ + reg::packed(148, 0, 12), /* getConstructor return */ + reg::packed(148, 0, 42), /* getApplication return */ + reg::packed(148, MAY_BE_ARRAY), /* getReferencedClasses return */ + reg::packed(273, 0, 290), /* getReferencedTemplateTypes $positionVariance */ + reg::packed(148, MAY_BE_ARRAY), /* getReferencedTemplateTypes return */ + reg::packed(359, 0, 12), /* equals $type */ + reg::packed(148, MAY_BE_BOOL), /* equals return */ + reg::packed(371, 0, 377), /* describe $level */ + reg::packed(148, MAY_BE_STRING), /* describe return */ + reg::packed(148, MAY_BE_BOOL), /* isResolvable return */ + reg::packed(148, 0, 12), /* getResult return */ + reg::packed(359, 0, 12), /* isSuperTypeOf $type */ + reg::packed(148, 0, 437), /* isSuperTypeOf return */ + reg::packed(359, 0, 12), /* accepts $type */ + reg::packed(484, MAY_BE_BOOL), /* accepts $strictTypes */ + reg::packed(148, 0, 496), /* accepts return */ + reg::packed(531, 0, 12), /* inferTemplateTypes $receivedType */ + reg::packed(148, 0, 544), /* inferTemplateTypes return */ + reg::packed(600, MAY_BE_STRING), /* getMethod $methodName */ + reg::packed(611, 0, 617), /* getMethod $scope */ + reg::packed(148, 0, 662), /* getMethod return */ + reg::packed(716, MAY_BE_STRING), /* getProperty $propertyName */ + reg::packed(611, 0, 617), /* getProperty $scope */ + reg::packed(148, 0, 729), /* getProperty return */ + reg::packed(716, MAY_BE_STRING), /* getInstanceProperty $propertyName */ + reg::packed(611, 0, 617), /* getInstanceProperty $scope */ + reg::packed(148, 0, 729), /* getInstanceProperty return */ + reg::packed(716, MAY_BE_STRING), /* getStaticProperty $propertyName */ + reg::packed(611, 0, 617), /* getStaticProperty $scope */ + reg::packed(148, 0, 729), /* getStaticProperty return */ + reg::packed(600, MAY_BE_STRING), /* getUnresolvedMethodPrototype $methodName */ + reg::packed(611, 0, 617), /* getUnresolvedMethodPrototype $scope */ + reg::packed(148, 0, 825), /* getUnresolvedMethodPrototype return */ + reg::packed(716, MAY_BE_STRING), /* getUnresolvedPropertyPrototype $propertyName */ + reg::packed(611, 0, 617), /* getUnresolvedPropertyPrototype $scope */ + reg::packed(148, 0, 914), /* getUnresolvedPropertyPrototype return */ + reg::packed(716, MAY_BE_STRING), /* getUnresolvedInstancePropertyPrototype $propertyName */ + reg::packed(611, 0, 617), /* getUnresolvedInstancePropertyPrototype $scope */ + reg::packed(148, 0, 914), /* getUnresolvedInstancePropertyPrototype return */ + reg::packed(716, MAY_BE_STRING), /* getUnresolvedStaticPropertyPrototype $propertyName */ + reg::packed(611, 0, 617), /* getUnresolvedStaticPropertyPrototype $scope */ + reg::packed(148, 0, 914), /* getUnresolvedStaticPropertyPrototype return */ + reg::packed(359, 0, 12), /* isSameUnresolvedClass $type */ + reg::packed(148, MAY_BE_BOOL), /* isSameUnresolvedClass return */ + reg::packed(1105, MAY_BE_CALLABLE), /* traverse $cb */ + reg::packed(148, 0, 12), /* traverse return */ + reg::packed(1117, 0, 12), /* traverseSimultaneously $right */ + reg::packed(1105, MAY_BE_CALLABLE), /* traverseSimultaneously $cb */ + reg::packed(148, 0, 12), /* traverseSimultaneously return */ reg::packed(0, 0, 12), /* create $constructor */ reg::packed(30, 0, 12), /* create $application */ - reg::packed(104, 0, 12), /* create return */ - reg::packed(104, 0, 566), /* toPhpDocNode return */ + reg::packed(148, 0, 12), /* create return */ + reg::packed(148, 0, 1153), /* toPhpDocNode return */ }; using Sig = reg::Sig; } // namespace sigtab @@ -120,23 +168,32 @@ using Sig = reg::Sig; /* the signatures of the methods the class declares itself (a used trait's are in the trait's header) */ namespace sig { inline constexpr sigtab::Sig __construct = { { 92 /* __construct */, 3, 0, 3, reg::NoArg, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isConsistent = { { 105 /* isConsistent */, 0, 3, 0, 3, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getConstructor = { { 118 /* getConstructor */, 0, 4, 0, 4, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getApplication = { { 133 /* getApplication */, 0, 5, 0, 5, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getReferencedClasses = { { 148 /* getReferencedClasses */, 0, 6, 0, 6, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getReferencedTemplateTypes = { { 228 /* getReferencedTemplateTypes */, 1, 7, 1, 8, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig equals = { { 260 /* equals */, 1, 9, 1, 10, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig describe = { { 301 /* describe */, 1, 11, 1, 12, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isResolvable = { { 310 /* isResolvable */, 0, 13, 0, 13, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getResult = { { 323 /* getResult */, 0, 14, 0, 14, ZEND_ACC_PROTECTED } }; -inline constexpr sigtab::Sig isSuperTypeOf = { { 366 /* isSuperTypeOf */, 1, 15, 1, 16, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig accepts = { { 419 /* accepts */, 2, 17, 2, 19, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig inferTemplateTypes = { { 477 /* inferTemplateTypes */, 1, 20, 1, 21, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isSameUnresolvedClass = { { 496 /* isSameUnresolvedClass */, 1, 22, 1, 23, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig traverse = { { 521 /* traverse */, 1, 24, 1, 25, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig traverseSimultaneously = { { 536 /* traverseSimultaneously */, 2, 26, 2, 28, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig create = { { 559 /* create */, 2, 29, 2, 31, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig toPhpDocNode = { { 605 /* toPhpDocNode */, 0, 32, 0, 32, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig ofCalledOnType = { { 194 /* ofCalledOnType */, 2, 3, 2, 5, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } }; +inline constexpr sigtab::Sig isConsistent = { { 209 /* isConsistent */, 0, 6, 0, 6, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getConstructor = { { 222 /* getConstructor */, 0, 7, 0, 7, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getApplication = { { 237 /* getApplication */, 0, 8, 0, 8, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getReferencedClasses = { { 252 /* getReferencedClasses */, 0, 9, 0, 9, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getReferencedTemplateTypes = { { 332 /* getReferencedTemplateTypes */, 1, 10, 1, 11, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig equals = { { 364 /* equals */, 1, 12, 1, 13, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig describe = { { 405 /* describe */, 1, 14, 1, 15, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isResolvable = { { 414 /* isResolvable */, 0, 16, 0, 16, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getResult = { { 427 /* getResult */, 0, 17, 0, 17, ZEND_ACC_PROTECTED } }; +inline constexpr sigtab::Sig isSuperTypeOf = { { 470 /* isSuperTypeOf */, 1, 18, 1, 19, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig accepts = { { 523 /* accepts */, 2, 20, 2, 22, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig inferTemplateTypes = { { 581 /* inferTemplateTypes */, 1, 23, 1, 24, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getMethod = { { 706 /* getMethod */, 2, 25, 2, 27, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getProperty = { { 775 /* getProperty */, 2, 28, 2, 30, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getInstanceProperty = { { 787 /* getInstanceProperty */, 2, 31, 2, 33, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getStaticProperty = { { 807 /* getStaticProperty */, 2, 34, 2, 36, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnresolvedMethodPrototype = { { 885 /* getUnresolvedMethodPrototype */, 2, 37, 2, 39, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnresolvedPropertyPrototype = { { 976 /* getUnresolvedPropertyPrototype */, 2, 40, 2, 42, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnresolvedInstancePropertyPrototype = { { 1007 /* getUnresolvedInstancePropertyPrototype */, 2, 43, 2, 45, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnresolvedStaticPropertyPrototype = { { 1046 /* getUnresolvedStaticPropertyPrototype */, 2, 46, 2, 48, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isSameUnresolvedClass = { { 1083 /* isSameUnresolvedClass */, 1, 49, 1, 50, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig traverse = { { 1108 /* traverse */, 1, 51, 1, 52, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig traverseSimultaneously = { { 1123 /* traverseSimultaneously */, 2, 53, 2, 55, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig create = { { 1146 /* create */, 2, 56, 2, 58, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig toPhpDocNode = { { 1192 /* toPhpDocNode */, 0, 59, 0, 59, ZEND_ACC_PUBLIC } }; } // namespace sig } // namespace ptdecl::TemplateTypeApplication diff --git a/turbo-ext/src/support.cpp b/turbo-ext/src/support.cpp index 0ccef7b2f03..d57ba325999 100644 --- a/turbo-ext/src/support.cpp +++ b/turbo-ext/src/support.cpp @@ -435,6 +435,7 @@ static const pt_class_template pt_class_templates[PT_CLASS_COUNT] = { /* PT_CLASS_TEMPLATE_SELF_REFERENCE_TYPE */ {"templateSelfReferenceType", "PHPStan\\Type\\Generic\\TemplateSelfReferenceType"}, /* PT_CLASS_RECURSIVE_TYPE */ {"recursiveType", "PHPStan\\Type\\RecursiveType"}, /* PT_CLASS_RECURSIVE_TYPE_REFERENCE */ {"recursiveTypeReference", "PHPStan\\Type\\RecursiveTypeReference"}, + /* PT_CLASS_CONSISTENT_TEMPLATES_HELPER */ {"consistentTemplatesHelper", "PHPStan\\Reflection\\ConsistentTemplatesHelper"}, }; zend_class_entry *pt_class(int idx) diff --git a/turbo-ext/src/support.h b/turbo-ext/src/support.h index b1fe9f50290..dedad5ce85f 100644 --- a/turbo-ext/src/support.h +++ b/turbo-ext/src/support.h @@ -547,6 +547,8 @@ enum { PT_CLASS_TEMPLATE_SELF_REFERENCE_TYPE, PT_CLASS_RECURSIVE_TYPE, PT_CLASS_RECURSIVE_TYPE_REFERENCE, + /* the class with @phpstan-consistent-templates of a static<…> */ + PT_CLASS_CONSISTENT_TEMPLATES_HELPER, PT_CLASS_COUNT }; @@ -686,6 +688,7 @@ extern zend_class_entry *pt_ce_object_without_class_type; extern zend_class_entry *pt_ce_static_type; extern zend_class_entry *pt_ce_this_type; extern zend_class_entry *pt_ce_generic_static_type; +extern zend_class_entry *pt_ce_template_type_application; extern zend_class_entry *pt_ce_object_shape_type; extern zend_class_entry *pt_ce_nonexistent_parent_class_type; From 83669be55886eb7e1816fb5434290f6e37f256d4 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Mon, 30 Nov 2026 07:04:52 +0000 Subject: [PATCH 5/7] =?UTF-8?q?Return=20static<=E2=80=A6>=20from=20Ds\Sequ?= =?UTF-8?q?ence=20methods?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7 --- stubs/ext-ds.stub | 13 ++--- .../Analyser/nsrt/ds-sequence-static.php | 54 +++++++++++++++++++ 2 files changed, 61 insertions(+), 6 deletions(-) create mode 100644 tests/PHPStan/Analyser/nsrt/ds-sequence-static.php diff --git a/stubs/ext-ds.stub b/stubs/ext-ds.stub index 4936766ab58..e664bc4e878 100644 --- a/stubs/ext-ds.stub +++ b/stubs/ext-ds.stub @@ -391,6 +391,7 @@ final class Pair implements JsonSerializable * @template TValue * @extends Collection * @extends ArrayAccess + * @phpstan-consistent-templates */ interface Sequence extends Collection, ArrayAccess { @@ -407,7 +408,7 @@ interface Sequence extends Collection, ArrayAccess /** * @param (callable(TValue): bool)|null $callback - * @return Sequence + * @return static */ public function filter(?callable $callback = null); @@ -451,14 +452,14 @@ interface Sequence extends Collection, ArrayAccess /** * @template TNewValue * @param callable(TValue): TNewValue $callback - * @return Sequence + * @return static */ public function map(callable $callback); /** * @template TValue2 * @param iterable $values - * @return Sequence + * @return static */ public function merge(iterable $values); @@ -490,7 +491,7 @@ interface Sequence extends Collection, ArrayAccess public function remove(int $index); /** - * @return Sequence + * @return static */ public function reversed(); @@ -509,7 +510,7 @@ interface Sequence extends Collection, ArrayAccess public function shift(); /** - * @return Sequence + * @return static */ public function slice(int $index, ?int $length = null); @@ -521,7 +522,7 @@ interface Sequence extends Collection, ArrayAccess /** * @param (callable(TValue, TValue): int)|null $comparator - * @return Sequence + * @return static */ public function sorted(?callable $comparator = null); diff --git a/tests/PHPStan/Analyser/nsrt/ds-sequence-static.php b/tests/PHPStan/Analyser/nsrt/ds-sequence-static.php new file mode 100644 index 00000000000..7435710442e --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/ds-sequence-static.php @@ -0,0 +1,54 @@ + $seq + * @param Vector $vec + * @param Deque $deque + */ +function concrete(Sequence $seq, Vector $vec, Deque $deque): void +{ + assertType('Ds\Sequence', $seq->map(static fn (int $i): string => (string) $i)); + assertType('Ds\Sequence', $seq->filter()); + assertType('Ds\Sequence<\'a\'|int>', $seq->merge(['a'])); + assertType('Ds\Sequence', $seq->reversed()); + assertType('Ds\Sequence', $seq->slice(1)); + assertType('Ds\Sequence', $seq->sorted()); + + assertType('Ds\Vector', $vec->map(static fn (int $i): string => (string) $i)); + assertType('Ds\Vector', $vec->slice(1)); + assertType('Ds\Deque', $deque->map(static fn (int $i): string => (string) $i)); + assertType('Ds\Deque', $deque->filter()); +} + +/** + * @template TSeq of Sequence + * @param TSeq $seq + * @return TSeq + */ +function stringify(Sequence $seq): Sequence +{ + assertType('TSeq of Ds\Sequence (function DsSequenceStatic\stringify(), argument)', $seq->filter()); + assertType('TSeq<\'a\'|int>', $seq->merge(['a'])); + + return $seq->map(static fn (int $i): string => (string) $i); +} + +/** + * @param Vector $vec + * @param Deque $deque + * @param Sequence $seq + */ +function callers(Vector $vec, Deque $deque, Sequence $seq): void +{ + assertType('Ds\Vector', stringify($vec)); + assertType('Ds\Deque', stringify($deque)); + assertType('Ds\Sequence', stringify($seq)); +} From 67af652458e748222769e9016e47d09f03ed2264 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Mon, 30 Nov 2026 08:06:22 +0000 Subject: [PATCH 6/7] Look up the members of a generic object on its class without type arguments GenericStaticType::getStaticObjectType() gives the GenericObjectType a class reflection that already carries the type arguments. Methods found on it had their template types resolved before the call, so a conditional return type merged with the native one too early: (false is true ? P : R)|P. Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7 --- src/Type/Generic/GenericObjectType.php | 15 ++ .../generic-static-conditional-return.php | 74 +++++++ turbo-ext/src/GenericObjectType.cpp | 23 +++ turbo-ext/src/ObjectType.cpp | 1 + turbo-ext/src/TypeTraits.h | 1 + turbo-ext/src/generated/GenericObjectType.h | 185 +++++++++--------- 6 files changed, 208 insertions(+), 91 deletions(-) create mode 100644 tests/PHPStan/Analyser/nsrt/generic-static-conditional-return.php diff --git a/src/Type/Generic/GenericObjectType.php b/src/Type/Generic/GenericObjectType.php index 7bac6bf1a24..6cdd8dbc585 100644 --- a/src/Type/Generic/GenericObjectType.php +++ b/src/Type/Generic/GenericObjectType.php @@ -222,6 +222,21 @@ private function isSuperTypeOfInternal(Type $type, bool $acceptsContext): IsSupe return $result; } + /** + * The class reflection given to the constructor can already carry the type arguments + * (GenericStaticType::getStaticObjectType() passes one), and its members would then + * resolve the class's template types before they are called on this type. + */ + public function getNakedClassReflection(): ?ClassReflection + { + $classReflection = parent::getNakedClassReflection(); + if ($classReflection === null || !$classReflection->isGeneric()) { + return $classReflection; + } + + return ReflectionProviderStaticAccessor::getInstance()->getClass($classReflection->getName()); + } + public function getClassReflection(): ?ClassReflection { if ($this->classReflection !== null) { diff --git a/tests/PHPStan/Analyser/nsrt/generic-static-conditional-return.php b/tests/PHPStan/Analyser/nsrt/generic-static-conditional-return.php new file mode 100644 index 00000000000..c9ad8d52833 --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/generic-static-conditional-return.php @@ -0,0 +1,74 @@ += 8.0 + +declare(strict_types = 1); + +namespace GenericStaticConditionalReturn; + +use function PHPStan\Testing\assertType; + +class Promise +{ + +} + +class Result +{ + +} + +/** + * @template TConcurrent of bool + */ +abstract class Base +{ + + /** @return static */ + public function sync(): static + { + throw new \Exception(); + } + + /** @return (TConcurrent is true ? Promise : Result) */ + public function inherited(): Promise|Result + { + throw new \Exception(); + } + +} + +/** + * @template TConcurrent of bool + * @extends Base + */ +class Child extends Base +{ + + /** @return (TConcurrent is true ? Promise : Result) */ + public function own(): Promise|Result + { + throw new \Exception(); + } + + /** @return (TConcurrent is true ? 'promise' : 'result') */ + public function withoutObjects(): string + { + throw new \Exception(); + } + +} + +/** + * @param Child $concurrent + * @param Child $sync + */ +function test(Child $concurrent, Child $sync): void +{ + assertType('GenericStaticConditionalReturn\Promise', $concurrent->own()); + assertType('GenericStaticConditionalReturn\Result', $sync->own()); + + // static is the same Child as the declared one + assertType('GenericStaticConditionalReturn\Child', $concurrent->sync()); + assertType('GenericStaticConditionalReturn\Result', $concurrent->sync()->own()); + assertType('GenericStaticConditionalReturn\Result', $concurrent->sync()->inherited()); + assertType('\'result\'', $concurrent->sync()->withoutObjects()); +} diff --git a/turbo-ext/src/GenericObjectType.cpp b/turbo-ext/src/GenericObjectType.cpp index 0ae93792080..d6b7b6d42d2 100644 --- a/turbo-ext/src/GenericObjectType.cpp +++ b/turbo-ext/src/GenericObjectType.cpp @@ -49,6 +49,7 @@ zend_class_entry *pt_ce_generic_object_type = nullptr; /* the handlers the $this-dispatch fast paths identify */ static void ZEND_FASTCALL gotGetClassReflection(INTERNAL_FUNCTION_PARAMETERS); +static void ZEND_FASTCALL gotGetNakedClassReflection(INTERNAL_FUNCTION_PARAMETERS); static void ZEND_FASTCALL gotGetTypes(INTERNAL_FUNCTION_PARAMETERS); static void ZEND_FASTCALL gotRecreate(INTERNAL_FUNCTION_PARAMETERS); static void ZEND_FASTCALL gotGetUnresolvedPropertyPrototype(INTERNAL_FUNCTION_PARAMETERS); @@ -424,6 +425,26 @@ class GenericObjectType return result; } + /* parent::getNakedClassReflection(), but the provider's reflection for + * a generic class: the constructor's can already carry the type + * arguments (GenericStaticType::getStaticObjectType() passes one); + * null for an unknown class; UNDEF = pending exception */ + zv::Val getNakedClassReflection() const + { + zv::Val reflection = pt_object_type_get_naked_class_reflection(self); + if (UNEXPECTED(reflection.isUndef())) return zv::Val(); + if (!zv::Ref(reflection.raw()).isObject()) return reflection; + bool isGeneric; + if (UNEXPECTED(!pt_type_call_bool(Z_OBJ_P(reflection.raw()), PT_LC("isgeneric"), 0, NULL, isGeneric))) return zv::Val(); + if (!isGeneric) return reflection; + + zv::Val name = pt_type_call(Z_OBJ_P(reflection.raw()), PT_LC("getname"), 0, NULL); + if (UNEXPECTED(name.isUndef())) return zv::Val(); + zv::Val provider = pt_reflection_provider_instance(); + if (UNEXPECTED(provider.isUndef())) return zv::Val(); + return pt_reflection_provider_get_class(Z_OBJ_P(provider.raw()), name.raw()); + } + /* the constructor's reflection, else the provider's parameterized with * the type arguments and variances (memoized); null for an unknown * class; UNDEF = pending exception */ @@ -1063,6 +1084,7 @@ static void pt_got_value_of(INTERNAL_FUNCTION_PARAMETERS, zv::Val (GenericObject } static void ZEND_FASTCALL gotGetClassReflection(INTERNAL_FUNCTION_PARAMETERS) { pt_got_value(INTERNAL_FUNCTION_PARAM_PASSTHRU, &GenericObjectType::getClassReflection); } +static void ZEND_FASTCALL gotGetNakedClassReflection(INTERNAL_FUNCTION_PARAMETERS) { pt_got_value(INTERNAL_FUNCTION_PARAM_PASSTHRU, &GenericObjectType::getNakedClassReflection); } static void ZEND_FASTCALL gotGetTypes(INTERNAL_FUNCTION_PARAMETERS) { pt_got_value(INTERNAL_FUNCTION_PARAM_PASSTHRU, &GenericObjectType::getTypes); } static void ZEND_FASTCALL gotRecreate(INTERNAL_FUNCTION_PARAMETERS) @@ -1126,6 +1148,7 @@ PT_MINIT_REGISTRATION(pt_register_generic_object_type) }); cls.op(); + cls.method(sigs::getNakedClassReflection, gotGetNakedClassReflection); cls.method(sigs::getClassReflection, gotGetClassReflection); cls.op(); diff --git a/turbo-ext/src/ObjectType.cpp b/turbo-ext/src/ObjectType.cpp index 81c838d06ae..6a7acfc4f54 100644 --- a/turbo-ext/src/ObjectType.cpp +++ b/turbo-ext/src/ObjectType.cpp @@ -3350,6 +3350,7 @@ void pt_object_type_construct(zend_object *self, zend_string *className, zval *s zv::Val pt_object_type_describe(zend_object *self, zval *level) { return ObjectType(self).describe(level); } zv::Val pt_object_type_get_class_reflection(zend_object *self) { return ObjectType(self).getClassReflection(); } +zv::Val pt_object_type_get_naked_class_reflection(zend_object *self) { return ObjectType(self).getNakedClassReflection(); } bool pt_object_type_equals(zend_object *self, zval *type, bool &out) { return ObjectType(self).equals(type, out); } zv::Val pt_object_type_get_referenced_classes(zend_object *self) { return ObjectType(self).getReferencedClasses(); } zv::Val pt_object_type_is_super_type_of(zend_object *self, zval *type) { return ObjectType(self).isSuperTypeOf(type); } diff --git a/turbo-ext/src/TypeTraits.h b/turbo-ext/src/TypeTraits.h index 5e0008c6292..72a53d602a7 100644 --- a/turbo-ext/src/TypeTraits.h +++ b/turbo-ext/src/TypeTraits.h @@ -749,6 +749,7 @@ void pt_object_type_construct(zend_object *self, zend_string *className, zval *s * UNDEF = pending exception (equals(): false = pending exception) */ zv::Val pt_object_type_describe(zend_object *self, zval *level); zv::Val pt_object_type_get_class_reflection(zend_object *self); +zv::Val pt_object_type_get_naked_class_reflection(zend_object *self); bool pt_object_type_equals(zend_object *self, zval *type, bool &out); zv::Val pt_object_type_get_referenced_classes(zend_object *self); zv::Val pt_object_type_is_super_type_of(zend_object *self, zval *type); diff --git a/turbo-ext/src/generated/GenericObjectType.h b/turbo-ext/src/generated/GenericObjectType.h index a6542d69a8e..6238632a055 100644 --- a/turbo-ext/src/generated/GenericObjectType.h +++ b/turbo-ext/src/generated/GenericObjectType.h @@ -57,43 +57,44 @@ inline constexpr char strings[] = "isSuperTypeOf\0" /* 308 */ "acceptsContext\0" /* 322 */ "isSuperTypeOfInternal\0" /* 337 */ - "getClassReflection\0" /* 359 */ - "propertyName\0" /* 378 */ - "scope\0" /* 391 */ - "PHPStan\\Reflection\\ClassMemberAccessAnswerer\0" /* 397 */ - "PHPStan\\Reflection\\ExtendedPropertyReflection\0" /* 442 */ - "getProperty\0" /* 488 */ - "PHPStan\\Reflection\\Type\\UnresolvedPropertyPrototypeReflection\0" /* 500 */ - "getUnresolvedPropertyPrototype\0" /* 562 */ - "getInstanceProperty\0" /* 593 */ - "getUnresolvedInstancePropertyPrototype\0" /* 613 */ - "getStaticProperty\0" /* 652 */ - "getUnresolvedStaticPropertyPrototype\0" /* 670 */ - "methodName\0" /* 707 */ - "PHPStan\\Reflection\\ExtendedMethodReflection\0" /* 718 */ - "getMethod\0" /* 762 */ - "PHPStan\\Reflection\\Type\\UnresolvedMethodPrototypeReflection\0" /* 772 */ - "getUnresolvedMethodPrototype\0" /* 832 */ - "receivedType\0" /* 861 */ - "PHPStan\\Type\\Generic\\TemplateTypeMap\0" /* 874 */ - "inferTemplateTypes\0" /* 911 */ - "positionVariance\0" /* 930 */ - "PHPStan\\Type\\Generic\\TemplateTypeVariance\0" /* 947 */ - "getReferencedTemplateTypes\0" /* 989 */ - "cb\0" /* 1016 */ - "traverse\0" /* 1019 */ - "right\0" /* 1028 */ - "traverseSimultaneously\0" /* 1034 */ - "className\0" /* 1057 */ - "PHPStan\\Type\\Generic\\GenericObjectType\0" /* 1067 */ - "recreate\0" /* 1106 */ - "changeVariances\0" /* 1115 */ - "withoutFinalByKeywordOverride\0" /* 1131 */ - "changeSubtractedType\0" /* 1161 */ - "PHPStan\\PhpDocParser\\Ast\\Type\\TypeNode\0" /* 1182 */ - "toPhpDocNode\0" /* 1221 */ - "hasTemplateOrLateResolvableType\0" /* 1234 */ - "hasUnresolvedTemplateArgumentType"; /* 1266 */ + "getNakedClassReflection\0" /* 359 */ + "getClassReflection\0" /* 383 */ + "propertyName\0" /* 402 */ + "scope\0" /* 415 */ + "PHPStan\\Reflection\\ClassMemberAccessAnswerer\0" /* 421 */ + "PHPStan\\Reflection\\ExtendedPropertyReflection\0" /* 466 */ + "getProperty\0" /* 512 */ + "PHPStan\\Reflection\\Type\\UnresolvedPropertyPrototypeReflection\0" /* 524 */ + "getUnresolvedPropertyPrototype\0" /* 586 */ + "getInstanceProperty\0" /* 617 */ + "getUnresolvedInstancePropertyPrototype\0" /* 637 */ + "getStaticProperty\0" /* 676 */ + "getUnresolvedStaticPropertyPrototype\0" /* 694 */ + "methodName\0" /* 731 */ + "PHPStan\\Reflection\\ExtendedMethodReflection\0" /* 742 */ + "getMethod\0" /* 786 */ + "PHPStan\\Reflection\\Type\\UnresolvedMethodPrototypeReflection\0" /* 796 */ + "getUnresolvedMethodPrototype\0" /* 856 */ + "receivedType\0" /* 885 */ + "PHPStan\\Type\\Generic\\TemplateTypeMap\0" /* 898 */ + "inferTemplateTypes\0" /* 935 */ + "positionVariance\0" /* 954 */ + "PHPStan\\Type\\Generic\\TemplateTypeVariance\0" /* 971 */ + "getReferencedTemplateTypes\0" /* 1013 */ + "cb\0" /* 1040 */ + "traverse\0" /* 1043 */ + "right\0" /* 1052 */ + "traverseSimultaneously\0" /* 1058 */ + "className\0" /* 1081 */ + "PHPStan\\Type\\Generic\\GenericObjectType\0" /* 1091 */ + "recreate\0" /* 1130 */ + "changeVariances\0" /* 1139 */ + "withoutFinalByKeywordOverride\0" /* 1155 */ + "changeSubtractedType\0" /* 1185 */ + "PHPStan\\PhpDocParser\\Ast\\Type\\TypeNode\0" /* 1206 */ + "toPhpDocNode\0" /* 1245 */ + "hasTemplateOrLateResolvableType\0" /* 1258 */ + "hasUnresolvedTemplateArgumentType"; /* 1290 */ inline constexpr reg::PackedArg args[] = { reg::packed(0, MAY_BE_STRING), /* __construct $mainType */ reg::packed(9, MAY_BE_ARRAY), /* __construct $types */ @@ -115,51 +116,52 @@ inline constexpr reg::PackedArg args[] = { reg::packed(173, 0, 30), /* isSuperTypeOfInternal $type */ reg::packed(322, MAY_BE_BOOL), /* isSuperTypeOfInternal $acceptsContext */ reg::packed(163, 0, 275), /* isSuperTypeOfInternal return */ + reg::packed(163, MAY_BE_NULL, 69), /* getNakedClassReflection return */ reg::packed(163, MAY_BE_NULL, 69), /* getClassReflection return */ - reg::packed(378, MAY_BE_STRING), /* getProperty $propertyName */ - reg::packed(391, 0, 397), /* getProperty $scope */ - reg::packed(163, 0, 442), /* getProperty return */ - reg::packed(378, MAY_BE_STRING), /* getUnresolvedPropertyPrototype $propertyName */ - reg::packed(391, 0, 397), /* getUnresolvedPropertyPrototype $scope */ - reg::packed(163, 0, 500), /* getUnresolvedPropertyPrototype return */ - reg::packed(378, MAY_BE_STRING), /* getInstanceProperty $propertyName */ - reg::packed(391, 0, 397), /* getInstanceProperty $scope */ - reg::packed(163, 0, 442), /* getInstanceProperty return */ - reg::packed(378, MAY_BE_STRING), /* getUnresolvedInstancePropertyPrototype $propertyName */ - reg::packed(391, 0, 397), /* getUnresolvedInstancePropertyPrototype $scope */ - reg::packed(163, 0, 500), /* getUnresolvedInstancePropertyPrototype return */ - reg::packed(378, MAY_BE_STRING), /* getStaticProperty $propertyName */ - reg::packed(391, 0, 397), /* getStaticProperty $scope */ - reg::packed(163, 0, 442), /* getStaticProperty return */ - reg::packed(378, MAY_BE_STRING), /* getUnresolvedStaticPropertyPrototype $propertyName */ - reg::packed(391, 0, 397), /* getUnresolvedStaticPropertyPrototype $scope */ - reg::packed(163, 0, 500), /* getUnresolvedStaticPropertyPrototype return */ - reg::packed(707, MAY_BE_STRING), /* getMethod $methodName */ - reg::packed(391, 0, 397), /* getMethod $scope */ - reg::packed(163, 0, 718), /* getMethod return */ - reg::packed(707, MAY_BE_STRING), /* getUnresolvedMethodPrototype $methodName */ - reg::packed(391, 0, 397), /* getUnresolvedMethodPrototype $scope */ - reg::packed(163, 0, 772), /* getUnresolvedMethodPrototype return */ - reg::packed(861, 0, 30), /* inferTemplateTypes $receivedType */ - reg::packed(163, 0, 874), /* inferTemplateTypes return */ - reg::packed(930, 0, 947), /* getReferencedTemplateTypes $positionVariance */ + reg::packed(402, MAY_BE_STRING), /* getProperty $propertyName */ + reg::packed(415, 0, 421), /* getProperty $scope */ + reg::packed(163, 0, 466), /* getProperty return */ + reg::packed(402, MAY_BE_STRING), /* getUnresolvedPropertyPrototype $propertyName */ + reg::packed(415, 0, 421), /* getUnresolvedPropertyPrototype $scope */ + reg::packed(163, 0, 524), /* getUnresolvedPropertyPrototype return */ + reg::packed(402, MAY_BE_STRING), /* getInstanceProperty $propertyName */ + reg::packed(415, 0, 421), /* getInstanceProperty $scope */ + reg::packed(163, 0, 466), /* getInstanceProperty return */ + reg::packed(402, MAY_BE_STRING), /* getUnresolvedInstancePropertyPrototype $propertyName */ + reg::packed(415, 0, 421), /* getUnresolvedInstancePropertyPrototype $scope */ + reg::packed(163, 0, 524), /* getUnresolvedInstancePropertyPrototype return */ + reg::packed(402, MAY_BE_STRING), /* getStaticProperty $propertyName */ + reg::packed(415, 0, 421), /* getStaticProperty $scope */ + reg::packed(163, 0, 466), /* getStaticProperty return */ + reg::packed(402, MAY_BE_STRING), /* getUnresolvedStaticPropertyPrototype $propertyName */ + reg::packed(415, 0, 421), /* getUnresolvedStaticPropertyPrototype $scope */ + reg::packed(163, 0, 524), /* getUnresolvedStaticPropertyPrototype return */ + reg::packed(731, MAY_BE_STRING), /* getMethod $methodName */ + reg::packed(415, 0, 421), /* getMethod $scope */ + reg::packed(163, 0, 742), /* getMethod return */ + reg::packed(731, MAY_BE_STRING), /* getUnresolvedMethodPrototype $methodName */ + reg::packed(415, 0, 421), /* getUnresolvedMethodPrototype $scope */ + reg::packed(163, 0, 796), /* getUnresolvedMethodPrototype return */ + reg::packed(885, 0, 30), /* inferTemplateTypes $receivedType */ + reg::packed(163, 0, 898), /* inferTemplateTypes return */ + reg::packed(954, 0, 971), /* getReferencedTemplateTypes $positionVariance */ reg::packed(163, MAY_BE_ARRAY), /* getReferencedTemplateTypes return */ - reg::packed(1016, MAY_BE_CALLABLE), /* traverse $cb */ + reg::packed(1040, MAY_BE_CALLABLE), /* traverse $cb */ reg::packed(163, 0, 30), /* traverse return */ - reg::packed(1028, 0, 30), /* traverseSimultaneously $right */ - reg::packed(1016, MAY_BE_CALLABLE), /* traverseSimultaneously $cb */ + reg::packed(1052, 0, 30), /* traverseSimultaneously $right */ + reg::packed(1040, MAY_BE_CALLABLE), /* traverseSimultaneously $cb */ reg::packed(163, 0, 30), /* traverseSimultaneously return */ - reg::packed(1057, MAY_BE_STRING), /* recreate $className */ + reg::packed(1081, MAY_BE_STRING), /* recreate $className */ reg::packed(9, MAY_BE_ARRAY), /* recreate $types */ reg::packed(15, MAY_BE_NULL, 30), /* recreate $subtractedType */ reg::packed(104, MAY_BE_ARRAY, reg::NoString, false, false, 114), /* recreate $variances */ - reg::packed(163, 0, 1067), /* recreate return */ + reg::packed(163, 0, 1091), /* recreate return */ reg::packed(104, MAY_BE_ARRAY), /* changeVariances $variances */ - reg::packed(163, 0, 1067), /* changeVariances return */ + reg::packed(163, 0, 1091), /* changeVariances return */ 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(163, 0, 1206), /* toPhpDocNode return */ reg::packed(163, MAY_BE_BOOL), /* hasTemplateOrLateResolvableType return */ reg::packed(163, MAY_BE_BOOL), /* hasUnresolvedTemplateArgumentType return */ }; @@ -177,26 +179,27 @@ inline constexpr sigtab::Sig getVariances = { { 215 /* getVariances */, 0, 11, 0 inline constexpr sigtab::Sig accepts = { { 267 /* accepts */, 2, 12, 2, 14, ZEND_ACC_PUBLIC } }; inline constexpr sigtab::Sig isSuperTypeOf = { { 308 /* isSuperTypeOf */, 1, 15, 1, 16, ZEND_ACC_PUBLIC } }; inline constexpr sigtab::Sig isSuperTypeOfInternal = { { 337 /* isSuperTypeOfInternal */, 2, 17, 2, 19, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig getClassReflection = { { 359 /* getClassReflection */, 0, 20, 0, 20, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getProperty = { { 488 /* getProperty */, 2, 21, 2, 23, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getUnresolvedPropertyPrototype = { { 562 /* getUnresolvedPropertyPrototype */, 2, 24, 2, 26, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getInstanceProperty = { { 593 /* getInstanceProperty */, 2, 27, 2, 29, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getUnresolvedInstancePropertyPrototype = { { 613 /* getUnresolvedInstancePropertyPrototype */, 2, 30, 2, 32, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getStaticProperty = { { 652 /* getStaticProperty */, 2, 33, 2, 35, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getUnresolvedStaticPropertyPrototype = { { 670 /* getUnresolvedStaticPropertyPrototype */, 2, 36, 2, 38, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getMethod = { { 762 /* getMethod */, 2, 39, 2, 41, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getUnresolvedMethodPrototype = { { 832 /* getUnresolvedMethodPrototype */, 2, 42, 2, 44, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig inferTemplateTypes = { { 911 /* inferTemplateTypes */, 1, 45, 1, 46, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getReferencedTemplateTypes = { { 989 /* getReferencedTemplateTypes */, 1, 47, 1, 48, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig traverse = { { 1019 /* traverse */, 1, 49, 1, 50, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig traverseSimultaneously = { { 1034 /* traverseSimultaneously */, 2, 51, 2, 53, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig recreate = { { 1106 /* recreate */, 3, 54, 4, 58, ZEND_ACC_PROTECTED } }; -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 hasUnresolvedTemplateArgumentType = { { 1266 /* hasUnresolvedTemplateArgumentType */, 0, 66, 0, 66, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getNakedClassReflection = { { 359 /* getNakedClassReflection */, 0, 20, 0, 20, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getClassReflection = { { 383 /* getClassReflection */, 0, 21, 0, 21, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getProperty = { { 512 /* getProperty */, 2, 22, 2, 24, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnresolvedPropertyPrototype = { { 586 /* getUnresolvedPropertyPrototype */, 2, 25, 2, 27, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getInstanceProperty = { { 617 /* getInstanceProperty */, 2, 28, 2, 30, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnresolvedInstancePropertyPrototype = { { 637 /* getUnresolvedInstancePropertyPrototype */, 2, 31, 2, 33, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getStaticProperty = { { 676 /* getStaticProperty */, 2, 34, 2, 36, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnresolvedStaticPropertyPrototype = { { 694 /* getUnresolvedStaticPropertyPrototype */, 2, 37, 2, 39, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getMethod = { { 786 /* getMethod */, 2, 40, 2, 42, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnresolvedMethodPrototype = { { 856 /* getUnresolvedMethodPrototype */, 2, 43, 2, 45, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig inferTemplateTypes = { { 935 /* inferTemplateTypes */, 1, 46, 1, 47, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getReferencedTemplateTypes = { { 1013 /* getReferencedTemplateTypes */, 1, 48, 1, 49, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig traverse = { { 1043 /* traverse */, 1, 50, 1, 51, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig traverseSimultaneously = { { 1058 /* traverseSimultaneously */, 2, 52, 2, 54, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig recreate = { { 1130 /* recreate */, 3, 55, 4, 59, ZEND_ACC_PROTECTED } }; +inline constexpr sigtab::Sig changeVariances = { { 1139 /* changeVariances */, 1, 60, 1, 61, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig withoutFinalByKeywordOverride = { { 1155 /* withoutFinalByKeywordOverride */, 0, 62, 0, 62, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig changeSubtractedType = { { 1185 /* changeSubtractedType */, 1, 63, 1, 64, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig toPhpDocNode = { { 1245 /* toPhpDocNode */, 0, 65, 0, 65, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig hasTemplateOrLateResolvableType = { { 1258 /* hasTemplateOrLateResolvableType */, 0, 66, 0, 66, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig hasUnresolvedTemplateArgumentType = { { 1290 /* hasUnresolvedTemplateArgumentType */, 0, 67, 0, 67, ZEND_ACC_PUBLIC } }; } // namespace sig } // namespace ptdecl::GenericObjectType From 84cc9a479f30cd848c72eddee84286605a15f54b Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Mon, 30 Nov 2026 08:19:48 +0000 Subject: [PATCH 7/7] =?UTF-8?q?Type=20new=20$class(=E2=80=A6)=20on=20a=20c?= =?UTF-8?q?lass-string=20of=20a=20template=20type=20bound=20by=20a=20class?= =?UTF-8?q?=20with=20consistent=20templates=20as=20an=20application=20of?= =?UTF-8?q?=20that=20template=20type?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit new $class($v) with class-string $class, K of IFoo and IFoo with @phpstan-consistent-templates is K, its arguments inferred from the constructor like those of new Foo($v). A K is a K. Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7 --- src/Analyser/ExprHandler/NewHandler.php | 20 +- src/Type/Generic/TemplateTypeApplication.php | 63 +++++ tests/PHPStan/Analyser/nsrt/bug-12646.php | 79 ++++++ tests/PHPStan/Analyser/nsrt/bug-4971.php | 62 +++++ .../Rules/Functions/ReturnTypeRuleTest.php | 15 ++ .../Rules/Methods/CallMethodsRuleTest.php | 9 + .../Generic/TemplateTypeApplicationTest.php | 60 +++++ .../data/template-type-application.php | 15 ++ turbo-ext/src/NewHandler.cpp | 36 ++- turbo-ext/src/TemplateTypeApplication.cpp | 116 +++++++++ turbo-ext/src/TypeTraits.cpp | 10 + turbo-ext/src/TypeTraits.h | 11 + .../src/generated/TemplateTypeApplication.h | 236 ++++++++++-------- 13 files changed, 620 insertions(+), 112 deletions(-) create mode 100644 tests/PHPStan/Analyser/nsrt/bug-12646.php create mode 100644 tests/PHPStan/Analyser/nsrt/bug-4971.php create mode 100644 tests/PHPStan/Type/Generic/TemplateTypeApplicationTest.php create mode 100644 tests/PHPStan/Type/Generic/data/template-type-application.php diff --git a/src/Analyser/ExprHandler/NewHandler.php b/src/Analyser/ExprHandler/NewHandler.php index fe7611f2bf1..345d5f98704 100644 --- a/src/Analyser/ExprHandler/NewHandler.php +++ b/src/Analyser/ExprHandler/NewHandler.php @@ -62,6 +62,7 @@ use PHPStan\Type\Generic\GenericObjectType; use PHPStan\Type\Generic\GenericStaticType; use PHPStan\Type\Generic\TemplateType; +use PHPStan\Type\Generic\TemplateTypeApplication; use PHPStan\Type\Generic\TemplateTypeHelper; use PHPStan\Type\Generic\TemplateTypeMap; use PHPStan\Type\Generic\TemplateTypeVariance; @@ -531,7 +532,24 @@ private function resolveReturnType(MutatingScope $scope, Expr $expr, ?Parameters if ($classExprType === null) { throw new ShouldNotHappenException(); } - return $classExprType->getObjectTypeOrClassStringObjectType(); + $objectType = $classExprType->getObjectTypeOrClassStringObjectType(); + if ($preResolvedAcceptor === null) { + return $objectType; + } + + // new $class(…) on a class-string: TColl<…> with the arguments the constructor infers + $application = TemplateTypeApplication::ofInstantiation($objectType); + if ($application === null) { + return $objectType; + } + + $frame = $allowUnresolved ? $scope->getCurrentTemplateArgumentFrame() : null; + $arguments = TypeTraverser::map($application->getApplication(), new GenericTypeTemplateTraverser($preResolvedAcceptor->getResolvedTemplateTypeMap(), $expr, $frame, $allowUnresolved)); + if (!$arguments instanceof GenericStaticType) { + return $objectType; + } + + return new TemplateTypeApplication($application->getConstructor(), $arguments, true); } /** diff --git a/src/Type/Generic/TemplateTypeApplication.php b/src/Type/Generic/TemplateTypeApplication.php index ab09d844751..af90f6abbd7 100644 --- a/src/Type/Generic/TemplateTypeApplication.php +++ b/src/Type/Generic/TemplateTypeApplication.php @@ -9,6 +9,7 @@ use PHPStan\Reflection\ConsistentTemplatesHelper; use PHPStan\Reflection\ExtendedMethodReflection; use PHPStan\Reflection\ExtendedPropertyReflection; +use PHPStan\Reflection\ReflectionProviderStaticAccessor; use PHPStan\Reflection\Type\UnresolvedMethodPrototypeReflection; use PHPStan\Reflection\Type\UnresolvedPropertyPrototypeReflection; use PHPStan\Turbo\ShadowedByTurboExtension; @@ -24,6 +25,7 @@ use PHPStan\Type\VerbosityLevel; use function array_map; use function array_merge; +use function count; use function implode; use function sprintf; @@ -84,6 +86,38 @@ public static function ofCalledOnType(Type $calledOnType, StaticType $static): ? return new self($calledOnType, $static, true); } + /** + * `new $class(…)` on a class-string is a TColl<…> when the class TColl is bound by + * has `@phpstan-consistent-templates`: this application of TColl to that class's own + * template types, for the caller to resolve from the constructor's arguments. + */ + public static function ofInstantiation(Type $objectType): ?self + { + if (!$objectType instanceof TemplateType) { + return null; + } + + $classReflections = $objectType->getBound()->getObjectClassReflections(); + if (count($classReflections) !== 1) { + return null; + } + + $classReflection = ReflectionProviderStaticAccessor::getInstance()->getClass($classReflections[0]->getName()); + if (!$classReflection->isGeneric()) { + return null; + } + + if ((new ConsistentTemplatesHelper())->findConsistentTemplatesClass($classReflection) === null) { + return null; + } + + return new self( + $objectType, + new GenericStaticType($classReflection, $classReflection->typeMapToList($classReflection->getTemplateTypeMap()), null, []), + true, + ); + } + public function isConsistent(): bool { return $this->consistent; @@ -189,6 +223,35 @@ public function accepts(Type $type, bool $strictTypes): AcceptsResult return $accepts; } + public function isSubTypeOf(Type $otherType): IsSuperTypeOfResult + { + // a TColl is a TColl + if (!$this->isResolvable() && $otherType->isSuperTypeOf($this->constructor)->yes()) { + return IsSuperTypeOfResult::createYes(); + } + + $result = $this->resolve(); + if ($result instanceof CompoundType) { + return $result->isSubTypeOf($otherType); + } + + return $otherType->isSuperTypeOf($result); + } + + public function isAcceptedBy(Type $acceptingType, bool $strictTypes): AcceptsResult + { + if (!$this->isResolvable() && $acceptingType->accepts($this->constructor, $strictTypes)->yes()) { + return AcceptsResult::createYes(); + } + + $result = $this->resolve(); + if ($result instanceof CompoundType) { + return $result->isAcceptedBy($acceptingType, $strictTypes); + } + + return $acceptingType->accepts($result, $strictTypes); + } + public function inferTemplateTypes(Type $receivedType): TemplateTypeMap { // the received object is the class the constructor stands for, diff --git a/tests/PHPStan/Analyser/nsrt/bug-12646.php b/tests/PHPStan/Analyser/nsrt/bug-12646.php new file mode 100644 index 00000000000..244b59a73df --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/bug-12646.php @@ -0,0 +1,79 @@ += 8.1 + +declare(strict_types = 1); + +namespace Bug12646; + +use function PHPStan\Testing\assertType; + +class Promise { + public function doPromise(): string { + return "promise"; + } +} + +interface Result {} +class ResultA implements Result { + public function doA(): string { + return "a"; + } +} + +/** + * @template TypeConcurrent of bool + * @phpstan-consistent-templates + */ +abstract class Communicator +{ + /** @param TypeConcurrent $concurrent */ + public function __construct(readonly private bool $concurrent) {} + /** + * @template TypeResult of Result + * @param class-string $resultClass + * @return (TypeConcurrent is true ? Promise : TypeResult) + */ + protected function getResultOrPromise(string $resultClass): Result|Promise + { + return $this->concurrent ? new Promise() : new $resultClass(); + } +} + +/** + * @template TypeConcurrent of bool + * @extends Communicator + */ +class ACommunicator extends Communicator +{ + /** @param TypeConcurrent $concurrent */ + public function __construct(bool $concurrent) + { + parent::__construct($concurrent); + } + /** @return (TypeConcurrent is true ? Promise : ResultA) */ + public function findResult(): ResultA|Promise + { + return $this->getResultOrPromise(ResultA::class); + } +} + +/** + * @template TypeCommunicator of Communicator + * @template TypeConcurrent of bool + * @param class-string $communicatorClass + * @param TypeConcurrent $concurrent + * @return TypeCommunicator + */ +function communicatorFactory(string $communicatorClass, bool $concurrent): Communicator +{ + return new $communicatorClass($concurrent); +} + +(new ACommunicator(false))->findResult()->doA(); +(new ACommunicator(true))->findResult()->doPromise(); + +// [QUESTION] Why dont these work, if above works? +assertType('Bug12646\\ACommunicator', communicatorFactory(ACommunicator::class, false)); +assertType('Bug12646\\ResultA', communicatorFactory(ACommunicator::class, false)->findResult()); +communicatorFactory(ACommunicator::class, false)->findResult()->doA(); +assertType('Bug12646\\Promise', communicatorFactory(ACommunicator::class, true)->findResult()); +communicatorFactory(ACommunicator::class, true)->findResult()->doPromise(); \ No newline at end of file diff --git a/tests/PHPStan/Analyser/nsrt/bug-4971.php b/tests/PHPStan/Analyser/nsrt/bug-4971.php new file mode 100644 index 00000000000..fb7718314b1 --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/bug-4971.php @@ -0,0 +1,62 @@ + + */ +class Foo implements IFoo +{ + /** @var T */ + private $v; + /** + * @param T $v + */ + public function __construct($v) + { + $this->v = $v; + } +} + +/** + * @template T + * @template K of IFoo + * @param T $v + * @param class-string $class + * @return K + */ +function make1($v, string $class) +{ + return new $class($v); +} + +/** + * @template T + * @template K of IFoo + * @param T $v + * @param class-string $class + * @return K + */ +function make2($v, string $class) +{ + return new $class($v); +} + +$obj1 = make1(1, Foo::class); +assertType('Bug4971\\Foo', $obj1); + +$obj2 = make2(1, Foo::class); // I want to type Foo +assertType('Bug4971\\Foo', $obj2); diff --git a/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php b/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php index 73bf90f7ac9..981415d803f 100644 --- a/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php +++ b/tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php @@ -672,6 +672,21 @@ public function testBug13394(): void $this->analyse([__DIR__ . '/data/bug-13394.php'], []); } + public function testBug4971(): void + { + $this->checkNullables = true; + $this->checkExplicitMixed = true; + $this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-4971.php'], []); + } + + #[RequiresPhp('>= 8.1.0')] + public function testBug12646(): void + { + $this->checkNullables = true; + $this->checkExplicitMixed = true; + $this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-12646.php'], []); + } + #[RequiresPhp('>= 8.1.0')] public function testBug15873(): void { diff --git a/tests/PHPStan/Rules/Methods/CallMethodsRuleTest.php b/tests/PHPStan/Rules/Methods/CallMethodsRuleTest.php index 4e4555896b0..d80288f3116 100644 --- a/tests/PHPStan/Rules/Methods/CallMethodsRuleTest.php +++ b/tests/PHPStan/Rules/Methods/CallMethodsRuleTest.php @@ -4732,6 +4732,15 @@ public function testBug13400(): void $this->analyse([__DIR__ . '/data/bug-13400.php'], []); } + #[RequiresPhp('>= 8.1.0')] + public function testBug12646(): void + { + $this->checkThisOnly = false; + $this->checkNullables = true; + $this->checkUnionTypes = true; + $this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-12646.php'], []); + } + public function testBug14872(): void { $this->checkThisOnly = false; diff --git a/tests/PHPStan/Type/Generic/TemplateTypeApplicationTest.php b/tests/PHPStan/Type/Generic/TemplateTypeApplicationTest.php new file mode 100644 index 00000000000..64544d5a670 --- /dev/null +++ b/tests/PHPStan/Type/Generic/TemplateTypeApplicationTest.php @@ -0,0 +1,60 @@ + + */ + private static function createApplication(): array + { + $constructor = TemplateTypeFactory::create( + TemplateTypeScope::createWithFunction('f'), + 'K', + new ObjectType(Coll::class), + TemplateTypeVariance::createInvariant(), + ); + + return [ + $constructor, + new TemplateTypeApplication( + $constructor, + new GenericStaticType(self::createReflectionProvider()->getClass(Coll::class), [new IntegerType()], null, []), + true, + ), + ]; + } + + public function testIsSubTypeOf(): void + { + [$constructor, $application] = self::createApplication(); + + // a K is a K, which a Coll is only maybe + $this->assertTrue(TypeCombinator::union($constructor, new NullType())->isSuperTypeOf($application)->yes()); + + // a K is a Coll, which is a Vec only maybe + $this->assertTrue((new GenericObjectType(Vec::class, [new IntegerType()]))->isSuperTypeOf($application)->maybe()); + } + + public function testIsAcceptedBy(): void + { + [$constructor, $application] = self::createApplication(); + + // a K is a K + $this->assertTrue(TypeCombinator::union($constructor, new NullType())->accepts($application, true)->yes()); + + // a K is a Coll, which is a Vec only maybe + $this->assertTrue((new GenericObjectType(Vec::class, [new IntegerType()]))->accepts($application, true)->maybe()); + } + +} diff --git a/tests/PHPStan/Type/Generic/data/template-type-application.php b/tests/PHPStan/Type/Generic/data/template-type-application.php new file mode 100644 index 00000000000..c3688e40767 --- /dev/null +++ b/tests/PHPStan/Type/Generic/data/template-type-application.php @@ -0,0 +1,15 @@ + + */ +final class Vec implements Coll {} diff --git a/turbo-ext/src/NewHandler.cpp b/turbo-ext/src/NewHandler.cpp index 6cb74d9520e..115da4fa0d3 100644 --- a/turbo-ext/src/NewHandler.cpp +++ b/turbo-ext/src/NewHandler.cpp @@ -1042,7 +1042,41 @@ class NewHandler pt_throw_should_not_happen(); return zv::Val(); } - return getObjectTypeOrClassStringObjectType(classExprType); + zv::Val objectType = getObjectTypeOrClassStringObjectType(classExprType); + if (UNEXPECTED(objectType.isUndef())) return zv::Val(); + if (preResolvedAcceptor == NULL || Z_TYPE_P(preResolvedAcceptor) == IS_NULL) return objectType; + if (UNEXPECTED(!zv::Ref(objectType.raw()).isObject())) { + zend_type_error("phpstan_turbo: getObjectTypeOrClassStringObjectType() must return %s", ptcls::type); + return zv::Val(); + } + + // new $class(…) on a class-string: TColl<…> with the arguments the constructor infers + zv::Val application = pt_template_type_application_of_instantiation(objectType.raw()); + if (UNEXPECTED(application.isUndef())) return zv::Val(); + if (Z_TYPE_P(application.raw()) == IS_NULL) return objectType; + + zv::Val frame = zv::Val::null(); + if (allowUnresolved) { + frame = pt_mutating_scope_get_current_template_argument_frame(Z_OBJ_P(scope)); + if (UNEXPECTED(frame.isUndef())) return zv::Val(); + } + zv::Val resolvedTemplateTypeMap = acceptorResolvedTemplateTypeMap(preResolvedAcceptor); + if (UNEXPECTED(resolvedTemplateTypeMap.isUndef())) return zv::Val(); + zval allowUnresolvedZv = {}; + ZVAL_BOOL(&allowUnresolvedZv, allowUnresolved); + zv::Args traverserArgv{resolvedTemplateTypeMap.raw(), expr, frame.raw(), &allowUnresolvedZv}; + zv::Val traverser = pt_type_new(PT_CLASS_GENERIC_TYPE_TEMPLATE_TRAVERSER, 4, traverserArgv); + if (UNEXPECTED(traverser.isUndef())) return zv::Val(); + zv::Val applied = pt_type_call(Z_OBJ_P(application.raw()), PT_LC("getapplication"), 0, NULL); + if (UNEXPECTED(applied.isUndef())) return zv::Val(); + zval arguments; + if (UNEXPECTED(!pt_type_traverser_map(&arguments, applied.raw(), traverser.raw()))) return zv::Val(); + zv::Val argumentsVal = zv::Val::adopt(arguments); + if (!zv::Ref(argumentsVal.raw()).isObject() || !instanceof_function(Z_OBJCE_P(argumentsVal.raw()), pt_ce_generic_static_type)) return objectType; + + zv::Val constructor = pt_type_call(Z_OBJ_P(application.raw()), PT_LC("getconstructor"), 0, NULL); + if (UNEXPECTED(constructor.isUndef())) return zv::Val(); + return pt_template_type_application_new(constructor.raw(), argumentsVal.raw(), true); } /* Mirrors exactInstantiation(); $preResolvedAcceptor / $argsResult NULL diff --git a/turbo-ext/src/TemplateTypeApplication.cpp b/turbo-ext/src/TemplateTypeApplication.cpp index daa43bc241a..631c0a5ae48 100644 --- a/turbo-ext/src/TemplateTypeApplication.cpp +++ b/turbo-ext/src/TemplateTypeApplication.cpp @@ -88,6 +88,67 @@ class TemplateTypeApplication return createInstance(calledOnType, staticType, true); } + /* ofInstantiation(Type $objectType): ?self — `new $class(…)` on a + * class-string whose bound class has consistent templates is + * TColl applied to that class's own template types; IS_NULL for none, + * UNDEF = pending exception */ + static zv::Val ofInstantiation(zval *objectType) + { + bool isTemplate; + if (UNEXPECTED(!pt_type_instanceof(objectType, PT_CLASS_TEMPLATE_TYPE, isTemplate))) return zv::Val(); + if (!isTemplate) return zv::Val::null(); + + zv::Val bound = pt_type_call(Z_OBJ_P(objectType), 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(); + } + zv::Val reflections = pt_type_call(Z_OBJ_P(bound.raw()), PT_LC("getobjectclassreflections"), 0, NULL); + if (UNEXPECTED(reflections.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(reflections.raw()).isArray())) { + zend_type_error("phpstan_turbo: getObjectClassReflections() must return an array"); + return zv::Val(); + } + if (zend_hash_num_elements(Z_ARRVAL_P(reflections.raw())) != 1) return zv::Val::null(); + zval *first = zend_hash_index_find(Z_ARRVAL_P(reflections.raw()), 0); + if (UNEXPECTED(first == NULL)) { + zend_throw_error(NULL, "phpstan_turbo: getObjectClassReflections() must return a list"); + return zv::Val(); + } + ZVAL_DEREF(first); + zv::Val name = pt_type_call(Z_OBJ_P(first), PT_LC("getname"), 0, NULL); + if (UNEXPECTED(name.isUndef())) return zv::Val(); + zv::Val provider = pt_reflection_provider_instance(); + if (UNEXPECTED(provider.isUndef())) return zv::Val(); + zv::Val classReflection = pt_reflection_provider_get_class(Z_OBJ_P(provider.raw()), name.raw()); + if (UNEXPECTED(classReflection.isUndef())) return zv::Val(); + if (UNEXPECTED(!zv::Ref(classReflection.raw()).isObject())) { + zend_type_error("phpstan_turbo: getClass() must return an object"); + return zv::Val(); + } + bool isGeneric; + if (UNEXPECTED(!pt_type_call_bool(Z_OBJ_P(classReflection.raw()), PT_LC("isgeneric"), 0, NULL, isGeneric))) return zv::Val(); + if (!isGeneric) return zv::Val::null(); + + zv::Val helper = pt_type_new(PT_CLASS_CONSISTENT_TEMPLATES_HELPER, 0, NULL); + if (UNEXPECTED(helper.isUndef())) return zv::Val(); + zv::Val found = pt_type_call(Z_OBJ_P(helper.raw()), PT_LC("findconsistenttemplatesclass"), 1, classReflection.raw()); + if (UNEXPECTED(found.isUndef())) return zv::Val(); + if (Z_TYPE_P(found.raw()) == IS_NULL) return zv::Val::null(); + + zv::Val templateTypeMap = pt_class_reflection_get_template_type_map(Z_OBJ_P(classReflection.raw())); + if (UNEXPECTED(templateTypeMap.isUndef())) return zv::Val(); + zv::Val types = pt_class_reflection_type_map_to_list(Z_OBJ_P(classReflection.raw()), templateTypeMap.raw()); + if (UNEXPECTED(types.isUndef())) return zv::Val(); + zv::Arr noVariances = zv::Arr::empty(); + zval application; + if (UNEXPECTED(!pt_generic_static_type_new(&application, classReflection.raw(), types.raw(), NULL, noVariances.raw()))) return zv::Val(); + zv::Val applicationVal = zv::Val::adopt(application); + + return createInstance(objectType, applicationVal.raw(), true); + } + /* the slots (borrowed); NULL with an Error pending when the constructor * never ran — the twin's typed-property read raises the same */ [[nodiscard]] zval *constructor() const { return slot(self, slots::constructor, "constructor"); } @@ -478,6 +539,40 @@ class TemplateTypeApplication zv::Val getUnresolvedInstancePropertyPrototype(zend_string *name, zval *scope) const { return prototype(PT_LC("getunresolvedinstancepropertyprototype"), name, scope, PT_LC("withfechedontype")); } zv::Val getUnresolvedStaticPropertyPrototype(zend_string *name, zval *scope) const { return prototype(PT_LC("getunresolvedstaticpropertyprototype"), name, scope, PT_LC("withfechedontype")); } + /* a TColl is a TColl: yes while the constructor is not known yet and + * $otherType is a supertype of it (accepts it); else the trait's body; + * UNDEF = pending exception */ + zv::Val isSubTypeOf(zval *otherType) const + { + bool resolvable; + if (UNEXPECTED(!isResolvable(resolvable))) return zv::Val(); + if (!resolvable) { + zval *ctor = constructor(); + if (UNEXPECTED(ctor == NULL)) return zv::Val(); + zend_long result = pt_type_call_result_trinary(Z_OBJ_P(otherType), PT_LC("issupertypeof"), 1, ctor); + if (UNEXPECTED(result < 0)) return zv::Val(); + if (result == PT_TRI_YES) return pt_type_is_super_type_of_result(PT_TRI_YES); + } + return pt_type_late_resolvable_is_sub_type_of(self, pt_ce_template_type_application, otherType); + } + + zv::Val isAcceptedBy(zval *acceptingType, bool strictTypes) const + { + bool resolvable; + if (UNEXPECTED(!isResolvable(resolvable))) return zv::Val(); + if (!resolvable) { + zval *ctor = constructor(); + if (UNEXPECTED(ctor == NULL)) return zv::Val(); + zval args[2]; + ZVAL_COPY_VALUE(&args[0], ctor); + ZVAL_BOOL(&args[1], strictTypes); + zend_long result = pt_type_call_result_trinary(Z_OBJ_P(acceptingType), PT_LC("accepts"), 2, args); + if (UNEXPECTED(result < 0)) return zv::Val(); + if (result == PT_TRI_YES) return pt_type_accepts_result(PT_TRI_YES); + } + return pt_type_late_resolvable_is_accepted_by(self, pt_ce_template_type_application, acceptingType, strictTypes); + } + private: zend_object *self; @@ -633,6 +728,17 @@ PT_MINIT_REGISTRATION(pt_register_template_type_application) PT_RETURN_VAL(TemplateTypeApplication::ofCalledOnType(calledOnType, staticType)); }); + cls.method(sigs::ofInstantiation, [](INTERNAL_FUNCTION_PARAMETERS) { + zval *objectType; + ZEND_PARSE_PARAMETERS_START(1, 1) + Z_PARAM_OBJECT_OF_CLASS(objectType, pt_ce_type_interface()) + ZEND_PARSE_PARAMETERS_END(); + PT_RETURN_VAL(TemplateTypeApplication::ofInstantiation(objectType)); + }); + + cls.method<&TemplateTypeApplication::isSubTypeOf, zp::TypeObj>(sigs::isSubTypeOf); + cls.method<&TemplateTypeApplication::isAcceptedBy, zp::TypeObj, zp::Bool>(sigs::isAcceptedBy); + cls.method<&TemplateTypeApplication::isConsistent>(sigs::isConsistent); cls.method<&TemplateTypeApplication::getConstructor>(sigs::getConstructor); @@ -705,3 +811,13 @@ zv::Val pt_template_type_application_of_called_on_type(zval *calledOnType, zval { return TemplateTypeApplication::ofCalledOnType(calledOnType, staticType); } + +zv::Val pt_template_type_application_of_instantiation(zval *objectType) +{ + return TemplateTypeApplication::ofInstantiation(objectType); +} + +zv::Val pt_template_type_application_new(zval *constructor, zval *application, bool consistent) +{ + return TemplateTypeApplication::createInstance(constructor, application, consistent); +} diff --git a/turbo-ext/src/TypeTraits.cpp b/turbo-ext/src/TypeTraits.cpp index 414ee4a9859..ef4fe0be614 100644 --- a/turbo-ext/src/TypeTraits.cpp +++ b/turbo-ext/src/TypeTraits.cpp @@ -3843,6 +3843,16 @@ zv::Val pt_type_late_resolvable_is_super_type_of_default(zend_object *self, zend return LateResolvable(self, scope).isSuperTypeOfDefault(type); } +zv::Val pt_type_late_resolvable_is_sub_type_of(zend_object *self, zend_class_entry *scope, zval *otherType) +{ + return LateResolvable(self, scope).isSubTypeOf(otherType); +} + +zv::Val pt_type_late_resolvable_is_accepted_by(zend_object *self, zend_class_entry *scope, zval *acceptingType, bool strictTypes) +{ + return LateResolvable(self, scope).isAcceptedBy(acceptingType, strictTypes); +} + zv::Val pt_type_describe_generic_of(const char *identifier, size_t identifierLen, zval *type, zval *level) { if (UNEXPECTED(Z_TYPE_P(type) != IS_OBJECT)) { diff --git a/turbo-ext/src/TypeTraits.h b/turbo-ext/src/TypeTraits.h index 72a53d602a7..09aa6755ae2 100644 --- a/turbo-ext/src/TypeTraits.h +++ b/turbo-ext/src/TypeTraits.h @@ -173,6 +173,12 @@ zv::Val pt_type_new(int classIdx, uint32_t argc, zval *argv); /* TemplateTypeApplication::ofCalledOnType($calledOnType, $static): the * application, or NULL (IS_NULL) for none; UNDEF = pending exception */ zv::Val pt_template_type_application_of_called_on_type(zval *calledOnType, zval *staticType); +/* TemplateTypeApplication::ofInstantiation($objectType): the application, + * or IS_NULL for none; UNDEF = pending exception */ +zv::Val pt_template_type_application_of_instantiation(zval *objectType); +/* new TemplateTypeApplication($constructor, $application, $consistent); + * UNDEF = pending exception */ +zv::Val pt_template_type_application_new(zval *constructor, zval *application, bool consistent); /* {{{ Type::toValueSet() (ValueSet.cpp) */ @@ -1146,6 +1152,11 @@ zv::Val pt_type_late_resolvable_resolve(zend_object *self, zend_class_entry *sco /* the trait's private isSuperTypeOfDefault($type) body, for the classes * whose own isSuperTypeOf() falls back to it; UNDEF = pending exception */ zv::Val pt_type_late_resolvable_is_super_type_of_default(zend_object *self, zend_class_entry *scope, zval *type); +/* the trait's isSubTypeOf($otherType) / isAcceptedBy($acceptingType, + * $strictTypes) bodies, for the classes that override them with a case + * of their own first; UNDEF = pending exception */ +zv::Val pt_type_late_resolvable_is_sub_type_of(zend_object *self, zend_class_entry *scope, zval *otherType); +zv::Val pt_type_late_resolvable_is_accepted_by(zend_object *self, zend_class_entry *scope, zval *acceptingType, bool strictTypes); /* TypeUtils::containsTemplateType($type) — the shadowing class's body * (TypeUtils.cpp); false = pending exception */ [[nodiscard]] bool pt_type_utils_contains_template_type(zval *type, bool &out); diff --git a/turbo-ext/src/generated/TemplateTypeApplication.h b/turbo-ext/src/generated/TemplateTypeApplication.h index 76395ea4df1..6b99c6934d2 100644 --- a/turbo-ext/src/generated/TemplateTypeApplication.h +++ b/turbo-ext/src/generated/TemplateTypeApplication.h @@ -54,52 +54,58 @@ inline constexpr char strings[] = "\0" /* 148 */ "PHPStan\\Type\\Generic\\TemplateTypeApplication\0" /* 149 */ "ofCalledOnType\0" /* 194 */ - "isConsistent\0" /* 209 */ - "getConstructor\0" /* 222 */ - "getApplication\0" /* 237 */ - "getReferencedClasses\0" /* 252 */ - "positionVariance\0" /* 273 */ - "PHPStan\\Type\\Generic\\TemplateTypeVariance\0" /* 290 */ - "getReferencedTemplateTypes\0" /* 332 */ - "type\0" /* 359 */ - "equals\0" /* 364 */ - "level\0" /* 371 */ - "PHPStan\\Type\\VerbosityLevel\0" /* 377 */ - "describe\0" /* 405 */ - "isResolvable\0" /* 414 */ - "getResult\0" /* 427 */ - "PHPStan\\Type\\IsSuperTypeOfResult\0" /* 437 */ - "isSuperTypeOf\0" /* 470 */ - "strictTypes\0" /* 484 */ - "PHPStan\\Type\\AcceptsResult\0" /* 496 */ - "accepts\0" /* 523 */ - "receivedType\0" /* 531 */ - "PHPStan\\Type\\Generic\\TemplateTypeMap\0" /* 544 */ - "inferTemplateTypes\0" /* 581 */ - "methodName\0" /* 600 */ - "scope\0" /* 611 */ - "PHPStan\\Reflection\\ClassMemberAccessAnswerer\0" /* 617 */ - "PHPStan\\Reflection\\ExtendedMethodReflection\0" /* 662 */ - "getMethod\0" /* 706 */ - "propertyName\0" /* 716 */ - "PHPStan\\Reflection\\ExtendedPropertyReflection\0" /* 729 */ - "getProperty\0" /* 775 */ - "getInstanceProperty\0" /* 787 */ - "getStaticProperty\0" /* 807 */ - "PHPStan\\Reflection\\Type\\UnresolvedMethodPrototypeReflection\0" /* 825 */ - "getUnresolvedMethodPrototype\0" /* 885 */ - "PHPStan\\Reflection\\Type\\UnresolvedPropertyPrototypeReflection\0" /* 914 */ - "getUnresolvedPropertyPrototype\0" /* 976 */ - "getUnresolvedInstancePropertyPrototype\0" /* 1007 */ - "getUnresolvedStaticPropertyPrototype\0" /* 1046 */ - "isSameUnresolvedClass\0" /* 1083 */ - "cb\0" /* 1105 */ - "traverse\0" /* 1108 */ - "right\0" /* 1117 */ - "traverseSimultaneously\0" /* 1123 */ - "create\0" /* 1146 */ - "PHPStan\\PhpDocParser\\Ast\\Type\\TypeNode\0" /* 1153 */ - "toPhpDocNode"; /* 1192 */ + "objectType\0" /* 209 */ + "ofInstantiation\0" /* 220 */ + "isConsistent\0" /* 236 */ + "getConstructor\0" /* 249 */ + "getApplication\0" /* 264 */ + "getReferencedClasses\0" /* 279 */ + "positionVariance\0" /* 300 */ + "PHPStan\\Type\\Generic\\TemplateTypeVariance\0" /* 317 */ + "getReferencedTemplateTypes\0" /* 359 */ + "type\0" /* 386 */ + "equals\0" /* 391 */ + "level\0" /* 398 */ + "PHPStan\\Type\\VerbosityLevel\0" /* 404 */ + "describe\0" /* 432 */ + "isResolvable\0" /* 441 */ + "getResult\0" /* 454 */ + "PHPStan\\Type\\IsSuperTypeOfResult\0" /* 464 */ + "isSuperTypeOf\0" /* 497 */ + "strictTypes\0" /* 511 */ + "PHPStan\\Type\\AcceptsResult\0" /* 523 */ + "accepts\0" /* 550 */ + "otherType\0" /* 558 */ + "isSubTypeOf\0" /* 568 */ + "acceptingType\0" /* 580 */ + "isAcceptedBy\0" /* 594 */ + "receivedType\0" /* 607 */ + "PHPStan\\Type\\Generic\\TemplateTypeMap\0" /* 620 */ + "inferTemplateTypes\0" /* 657 */ + "methodName\0" /* 676 */ + "scope\0" /* 687 */ + "PHPStan\\Reflection\\ClassMemberAccessAnswerer\0" /* 693 */ + "PHPStan\\Reflection\\ExtendedMethodReflection\0" /* 738 */ + "getMethod\0" /* 782 */ + "propertyName\0" /* 792 */ + "PHPStan\\Reflection\\ExtendedPropertyReflection\0" /* 805 */ + "getProperty\0" /* 851 */ + "getInstanceProperty\0" /* 863 */ + "getStaticProperty\0" /* 883 */ + "PHPStan\\Reflection\\Type\\UnresolvedMethodPrototypeReflection\0" /* 901 */ + "getUnresolvedMethodPrototype\0" /* 961 */ + "PHPStan\\Reflection\\Type\\UnresolvedPropertyPrototypeReflection\0" /* 990 */ + "getUnresolvedPropertyPrototype\0" /* 1052 */ + "getUnresolvedInstancePropertyPrototype\0" /* 1083 */ + "getUnresolvedStaticPropertyPrototype\0" /* 1122 */ + "isSameUnresolvedClass\0" /* 1159 */ + "cb\0" /* 1181 */ + "traverse\0" /* 1184 */ + "right\0" /* 1193 */ + "traverseSimultaneously\0" /* 1199 */ + "create\0" /* 1222 */ + "PHPStan\\PhpDocParser\\Ast\\Type\\TypeNode\0" /* 1229 */ + "toPhpDocNode"; /* 1268 */ inline constexpr reg::PackedArg args[] = { reg::packed(0, 0, 12), /* __construct $constructor */ reg::packed(30, 0, 42), /* __construct $application */ @@ -107,60 +113,67 @@ inline constexpr reg::PackedArg args[] = { reg::packed(104, 0, 12), /* ofCalledOnType $calledOnType */ reg::packed(117, 0, 124), /* ofCalledOnType $static */ reg::packed(148, MAY_BE_NULL, 149), /* ofCalledOnType return */ + reg::packed(209, 0, 12), /* ofInstantiation $objectType */ + reg::packed(148, MAY_BE_NULL, 149), /* ofInstantiation return */ reg::packed(148, MAY_BE_BOOL), /* isConsistent return */ reg::packed(148, 0, 12), /* getConstructor return */ reg::packed(148, 0, 42), /* getApplication return */ reg::packed(148, MAY_BE_ARRAY), /* getReferencedClasses return */ - reg::packed(273, 0, 290), /* getReferencedTemplateTypes $positionVariance */ + reg::packed(300, 0, 317), /* getReferencedTemplateTypes $positionVariance */ reg::packed(148, MAY_BE_ARRAY), /* getReferencedTemplateTypes return */ - reg::packed(359, 0, 12), /* equals $type */ + reg::packed(386, 0, 12), /* equals $type */ reg::packed(148, MAY_BE_BOOL), /* equals return */ - reg::packed(371, 0, 377), /* describe $level */ + reg::packed(398, 0, 404), /* describe $level */ reg::packed(148, MAY_BE_STRING), /* describe return */ reg::packed(148, MAY_BE_BOOL), /* isResolvable return */ reg::packed(148, 0, 12), /* getResult return */ - reg::packed(359, 0, 12), /* isSuperTypeOf $type */ - reg::packed(148, 0, 437), /* isSuperTypeOf return */ - reg::packed(359, 0, 12), /* accepts $type */ - reg::packed(484, MAY_BE_BOOL), /* accepts $strictTypes */ - reg::packed(148, 0, 496), /* accepts return */ - reg::packed(531, 0, 12), /* inferTemplateTypes $receivedType */ - reg::packed(148, 0, 544), /* inferTemplateTypes return */ - reg::packed(600, MAY_BE_STRING), /* getMethod $methodName */ - reg::packed(611, 0, 617), /* getMethod $scope */ - reg::packed(148, 0, 662), /* getMethod return */ - reg::packed(716, MAY_BE_STRING), /* getProperty $propertyName */ - reg::packed(611, 0, 617), /* getProperty $scope */ - reg::packed(148, 0, 729), /* getProperty return */ - reg::packed(716, MAY_BE_STRING), /* getInstanceProperty $propertyName */ - reg::packed(611, 0, 617), /* getInstanceProperty $scope */ - reg::packed(148, 0, 729), /* getInstanceProperty return */ - reg::packed(716, MAY_BE_STRING), /* getStaticProperty $propertyName */ - reg::packed(611, 0, 617), /* getStaticProperty $scope */ - reg::packed(148, 0, 729), /* getStaticProperty return */ - reg::packed(600, MAY_BE_STRING), /* getUnresolvedMethodPrototype $methodName */ - reg::packed(611, 0, 617), /* getUnresolvedMethodPrototype $scope */ - reg::packed(148, 0, 825), /* getUnresolvedMethodPrototype return */ - reg::packed(716, MAY_BE_STRING), /* getUnresolvedPropertyPrototype $propertyName */ - reg::packed(611, 0, 617), /* getUnresolvedPropertyPrototype $scope */ - reg::packed(148, 0, 914), /* getUnresolvedPropertyPrototype return */ - reg::packed(716, MAY_BE_STRING), /* getUnresolvedInstancePropertyPrototype $propertyName */ - reg::packed(611, 0, 617), /* getUnresolvedInstancePropertyPrototype $scope */ - reg::packed(148, 0, 914), /* getUnresolvedInstancePropertyPrototype return */ - reg::packed(716, MAY_BE_STRING), /* getUnresolvedStaticPropertyPrototype $propertyName */ - reg::packed(611, 0, 617), /* getUnresolvedStaticPropertyPrototype $scope */ - reg::packed(148, 0, 914), /* getUnresolvedStaticPropertyPrototype return */ - reg::packed(359, 0, 12), /* isSameUnresolvedClass $type */ + reg::packed(386, 0, 12), /* isSuperTypeOf $type */ + reg::packed(148, 0, 464), /* isSuperTypeOf return */ + reg::packed(386, 0, 12), /* accepts $type */ + reg::packed(511, MAY_BE_BOOL), /* accepts $strictTypes */ + reg::packed(148, 0, 523), /* accepts return */ + reg::packed(558, 0, 12), /* isSubTypeOf $otherType */ + reg::packed(148, 0, 464), /* isSubTypeOf return */ + reg::packed(580, 0, 12), /* isAcceptedBy $acceptingType */ + reg::packed(511, MAY_BE_BOOL), /* isAcceptedBy $strictTypes */ + reg::packed(148, 0, 523), /* isAcceptedBy return */ + reg::packed(607, 0, 12), /* inferTemplateTypes $receivedType */ + reg::packed(148, 0, 620), /* inferTemplateTypes return */ + reg::packed(676, MAY_BE_STRING), /* getMethod $methodName */ + reg::packed(687, 0, 693), /* getMethod $scope */ + reg::packed(148, 0, 738), /* getMethod return */ + reg::packed(792, MAY_BE_STRING), /* getProperty $propertyName */ + reg::packed(687, 0, 693), /* getProperty $scope */ + reg::packed(148, 0, 805), /* getProperty return */ + reg::packed(792, MAY_BE_STRING), /* getInstanceProperty $propertyName */ + reg::packed(687, 0, 693), /* getInstanceProperty $scope */ + reg::packed(148, 0, 805), /* getInstanceProperty return */ + reg::packed(792, MAY_BE_STRING), /* getStaticProperty $propertyName */ + reg::packed(687, 0, 693), /* getStaticProperty $scope */ + reg::packed(148, 0, 805), /* getStaticProperty return */ + reg::packed(676, MAY_BE_STRING), /* getUnresolvedMethodPrototype $methodName */ + reg::packed(687, 0, 693), /* getUnresolvedMethodPrototype $scope */ + reg::packed(148, 0, 901), /* getUnresolvedMethodPrototype return */ + reg::packed(792, MAY_BE_STRING), /* getUnresolvedPropertyPrototype $propertyName */ + reg::packed(687, 0, 693), /* getUnresolvedPropertyPrototype $scope */ + reg::packed(148, 0, 990), /* getUnresolvedPropertyPrototype return */ + reg::packed(792, MAY_BE_STRING), /* getUnresolvedInstancePropertyPrototype $propertyName */ + reg::packed(687, 0, 693), /* getUnresolvedInstancePropertyPrototype $scope */ + reg::packed(148, 0, 990), /* getUnresolvedInstancePropertyPrototype return */ + reg::packed(792, MAY_BE_STRING), /* getUnresolvedStaticPropertyPrototype $propertyName */ + reg::packed(687, 0, 693), /* getUnresolvedStaticPropertyPrototype $scope */ + reg::packed(148, 0, 990), /* getUnresolvedStaticPropertyPrototype return */ + reg::packed(386, 0, 12), /* isSameUnresolvedClass $type */ reg::packed(148, MAY_BE_BOOL), /* isSameUnresolvedClass return */ - reg::packed(1105, MAY_BE_CALLABLE), /* traverse $cb */ + reg::packed(1181, MAY_BE_CALLABLE), /* traverse $cb */ reg::packed(148, 0, 12), /* traverse return */ - reg::packed(1117, 0, 12), /* traverseSimultaneously $right */ - reg::packed(1105, MAY_BE_CALLABLE), /* traverseSimultaneously $cb */ + reg::packed(1193, 0, 12), /* traverseSimultaneously $right */ + reg::packed(1181, MAY_BE_CALLABLE), /* traverseSimultaneously $cb */ reg::packed(148, 0, 12), /* traverseSimultaneously return */ reg::packed(0, 0, 12), /* create $constructor */ reg::packed(30, 0, 12), /* create $application */ reg::packed(148, 0, 12), /* create return */ - reg::packed(148, 0, 1153), /* toPhpDocNode return */ + reg::packed(148, 0, 1229), /* toPhpDocNode return */ }; using Sig = reg::Sig; } // namespace sigtab @@ -169,31 +182,34 @@ using Sig = reg::Sig; namespace sig { inline constexpr sigtab::Sig __construct = { { 92 /* __construct */, 3, 0, 3, reg::NoArg, ZEND_ACC_PUBLIC } }; inline constexpr sigtab::Sig ofCalledOnType = { { 194 /* ofCalledOnType */, 2, 3, 2, 5, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } }; -inline constexpr sigtab::Sig isConsistent = { { 209 /* isConsistent */, 0, 6, 0, 6, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getConstructor = { { 222 /* getConstructor */, 0, 7, 0, 7, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getApplication = { { 237 /* getApplication */, 0, 8, 0, 8, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getReferencedClasses = { { 252 /* getReferencedClasses */, 0, 9, 0, 9, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getReferencedTemplateTypes = { { 332 /* getReferencedTemplateTypes */, 1, 10, 1, 11, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig equals = { { 364 /* equals */, 1, 12, 1, 13, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig describe = { { 405 /* describe */, 1, 14, 1, 15, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isResolvable = { { 414 /* isResolvable */, 0, 16, 0, 16, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getResult = { { 427 /* getResult */, 0, 17, 0, 17, ZEND_ACC_PROTECTED } }; -inline constexpr sigtab::Sig isSuperTypeOf = { { 470 /* isSuperTypeOf */, 1, 18, 1, 19, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig accepts = { { 523 /* accepts */, 2, 20, 2, 22, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig inferTemplateTypes = { { 581 /* inferTemplateTypes */, 1, 23, 1, 24, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getMethod = { { 706 /* getMethod */, 2, 25, 2, 27, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getProperty = { { 775 /* getProperty */, 2, 28, 2, 30, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getInstanceProperty = { { 787 /* getInstanceProperty */, 2, 31, 2, 33, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getStaticProperty = { { 807 /* getStaticProperty */, 2, 34, 2, 36, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getUnresolvedMethodPrototype = { { 885 /* getUnresolvedMethodPrototype */, 2, 37, 2, 39, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getUnresolvedPropertyPrototype = { { 976 /* getUnresolvedPropertyPrototype */, 2, 40, 2, 42, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getUnresolvedInstancePropertyPrototype = { { 1007 /* getUnresolvedInstancePropertyPrototype */, 2, 43, 2, 45, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getUnresolvedStaticPropertyPrototype = { { 1046 /* getUnresolvedStaticPropertyPrototype */, 2, 46, 2, 48, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isSameUnresolvedClass = { { 1083 /* isSameUnresolvedClass */, 1, 49, 1, 50, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig traverse = { { 1108 /* traverse */, 1, 51, 1, 52, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig traverseSimultaneously = { { 1123 /* traverseSimultaneously */, 2, 53, 2, 55, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig create = { { 1146 /* create */, 2, 56, 2, 58, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig toPhpDocNode = { { 1192 /* toPhpDocNode */, 0, 59, 0, 59, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig ofInstantiation = { { 220 /* ofInstantiation */, 1, 6, 1, 7, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } }; +inline constexpr sigtab::Sig isConsistent = { { 236 /* isConsistent */, 0, 8, 0, 8, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getConstructor = { { 249 /* getConstructor */, 0, 9, 0, 9, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getApplication = { { 264 /* getApplication */, 0, 10, 0, 10, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getReferencedClasses = { { 279 /* getReferencedClasses */, 0, 11, 0, 11, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getReferencedTemplateTypes = { { 359 /* getReferencedTemplateTypes */, 1, 12, 1, 13, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig equals = { { 391 /* equals */, 1, 14, 1, 15, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig describe = { { 432 /* describe */, 1, 16, 1, 17, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isResolvable = { { 441 /* isResolvable */, 0, 18, 0, 18, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getResult = { { 454 /* getResult */, 0, 19, 0, 19, ZEND_ACC_PROTECTED } }; +inline constexpr sigtab::Sig isSuperTypeOf = { { 497 /* isSuperTypeOf */, 1, 20, 1, 21, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig accepts = { { 550 /* accepts */, 2, 22, 2, 24, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isSubTypeOf = { { 568 /* isSubTypeOf */, 1, 25, 1, 26, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isAcceptedBy = { { 594 /* isAcceptedBy */, 2, 27, 2, 29, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig inferTemplateTypes = { { 657 /* inferTemplateTypes */, 1, 30, 1, 31, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getMethod = { { 782 /* getMethod */, 2, 32, 2, 34, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getProperty = { { 851 /* getProperty */, 2, 35, 2, 37, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getInstanceProperty = { { 863 /* getInstanceProperty */, 2, 38, 2, 40, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getStaticProperty = { { 883 /* getStaticProperty */, 2, 41, 2, 43, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnresolvedMethodPrototype = { { 961 /* getUnresolvedMethodPrototype */, 2, 44, 2, 46, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnresolvedPropertyPrototype = { { 1052 /* getUnresolvedPropertyPrototype */, 2, 47, 2, 49, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnresolvedInstancePropertyPrototype = { { 1083 /* getUnresolvedInstancePropertyPrototype */, 2, 50, 2, 52, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnresolvedStaticPropertyPrototype = { { 1122 /* getUnresolvedStaticPropertyPrototype */, 2, 53, 2, 55, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isSameUnresolvedClass = { { 1159 /* isSameUnresolvedClass */, 1, 56, 1, 57, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig traverse = { { 1184 /* traverse */, 1, 58, 1, 59, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig traverseSimultaneously = { { 1199 /* traverseSimultaneously */, 2, 60, 2, 62, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig create = { { 1222 /* create */, 2, 63, 2, 65, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig toPhpDocNode = { { 1268 /* toPhpDocNode */, 0, 66, 0, 66, ZEND_ACC_PUBLIC } }; } // namespace sig } // namespace ptdecl::TemplateTypeApplication