Skip to content

Commit 13a9180

Browse files
committed
Keep static<…> on the class when a subclass cannot hold its type arguments
`static<U>` 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<int>`, holds only ints whatever U is: `$intVec->map(fn (int $i): string => …)` was IntVec. Such a type now stays `Coll<string>`, which is all that is known. The class's own templates stand for what the subclass passes to them, so `static<T>` on IntVec is still IntVec, while `static<V, K>` on `IntStringPair extends Pair<int, string>` is `Pair<string, int>`. Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7
1 parent 671e1ed commit 13a9180

5 files changed

Lines changed: 334 additions & 41 deletions

File tree

‎src/Type/Generic/GenericStaticType.php‎

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
use function array_key_exists;
2020
use function array_keys;
2121
use function array_map;
22+
use function array_search;
2223
use function count;
2324

2425
/** @api */
@@ -122,7 +123,7 @@ public function changeBaseClass(ClassReflection $classReflection): StaticType
122123
}
123124

124125
if (!$classReflection->isGeneric()) {
125-
return new StaticType($classReflection);
126+
return $this->keepingTypeArguments(new StaticType($classReflection));
126127
}
127128

128129
$templateTags = $this->getClassReflection()->getTemplateTags();
@@ -177,7 +178,51 @@ public function changeBaseClass(ClassReflection $classReflection): StaticType
177178
$newClassVariances[$templateType->getName()] = $indexedVariances[$typeName];
178179
}
179180

180-
return new self($classReflection, $classReflection->typeMapToList(new TemplateTypeMap($newClassTypes)), $this->subtractedType, $classReflection->varianceMapToList(new TemplateTypeVarianceMap($newClassVariances)));
181+
return $this->keepingTypeArguments(new self($classReflection, $classReflection->typeMapToList(new TemplateTypeMap($newClassTypes)), $this->subtractedType, $classReflection->varianceMapToList(new TemplateTypeVarianceMap($newClassVariances))));
182+
}
183+
184+
/**
185+
* A subclass that does not pass the type arguments on to the class, like
186+
* `IntList implements Collection<int>` for `static<string>`, cannot hold them,
187+
* so the type stays on the class: `Collection<string>` is all that is known.
188+
*/
189+
private function keepingTypeArguments(StaticType $changed): StaticType
190+
{
191+
$ancestor = $changed->getStaticObjectType()->getAncestorWithClassName($this->getClassName());
192+
if ($ancestor === null) {
193+
return $changed;
194+
}
195+
196+
$ancestorReflection = $ancestor->getClassReflection();
197+
if ($ancestorReflection === null || !$ancestorReflection->isGeneric()) {
198+
return $changed;
199+
}
200+
201+
// the class's own templates stand for what the subclass passes to them,
202+
// and so do the arguments left out
203+
$ancestorTypes = $ancestorReflection->typeMapToList($ancestorReflection->getActiveTemplateTypeMap());
204+
$templateNames = array_keys($this->getClassReflection()->getTemplateTags());
205+
$types = $ancestorTypes;
206+
foreach ($this->types as $i => $type) {
207+
if (
208+
$type instanceof TemplateType
209+
&& $type->getScope()->getClassName() === $this->getClassName()
210+
&& $type->getScope()->getFunctionName() === null
211+
) {
212+
$index = array_search($type->getName(), $templateNames, true);
213+
if ($index !== false && array_key_exists($index, $ancestorTypes)) {
214+
$type = $ancestorTypes[$index];
215+
}
216+
}
217+
$types[$i] = $type;
218+
}
219+
220+
$requested = new GenericObjectType($this->getClassName(), $types, variances: $this->variances);
221+
if ($requested->isSuperTypeOf($ancestor)->yes()) {
222+
return $changed;
223+
}
224+
225+
return $this;
181226
}
182227

183228
public function isSuperTypeOf(Type $type): IsSuperTypeOfResult

‎tests/PHPStan/Analyser/nsrt/class-constant-static-type.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,5 +60,5 @@ function test(Base $base, Child $child, GenericBase $genericBase, GenericChild $
6060
assertType('class-string<ClassConstantStaticType\Child>', $child::IMPL);
6161
assertType('list<class-string<ClassConstantStaticType\Child>>', $child::IMPLS);
6262
assertType('class-string<ClassConstantStaticType\GenericBase<int>>', $genericBase::IMPL);
63-
assertType('class-string<ClassConstantStaticType\GenericChild>', $genericChild::IMPL);
63+
assertType('class-string<ClassConstantStaticType\GenericBase<int>>', $genericChild::IMPL);
6464
}
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace GenericStaticSubclassArguments;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
/** @template-covariant T */
8+
interface Coll
9+
{
10+
11+
/** @return static<T> */
12+
public function filter();
13+
14+
/**
15+
* @template U
16+
* @param callable(T): U $f
17+
* @return static<U>
18+
*/
19+
public function map(callable $f);
20+
21+
}
22+
23+
/** @implements Coll<int> */
24+
final class IntVec implements Coll
25+
{
26+
27+
public function filter()
28+
{
29+
return $this;
30+
}
31+
32+
public function map(callable $f)
33+
{
34+
throw new \Exception();
35+
}
36+
37+
}
38+
39+
/**
40+
* @template-covariant T
41+
* @implements Coll<T>
42+
*/
43+
final class Vec implements Coll
44+
{
45+
46+
public function filter()
47+
{
48+
return $this;
49+
}
50+
51+
public function map(callable $f)
52+
{
53+
throw new \Exception();
54+
}
55+
56+
}
57+
58+
/**
59+
* @template K
60+
* @template-covariant V
61+
* @implements Coll<V>
62+
*/
63+
final class Dict implements Coll
64+
{
65+
66+
public function filter()
67+
{
68+
return $this;
69+
}
70+
71+
public function map(callable $f)
72+
{
73+
throw new \Exception();
74+
}
75+
76+
}
77+
78+
/**
79+
* @template K
80+
* @template V
81+
*/
82+
class Pair
83+
{
84+
85+
/** @return static<K, V> */
86+
public function same()
87+
{
88+
return $this;
89+
}
90+
91+
/** @return static<V, K> */
92+
public function flip()
93+
{
94+
throw new \Exception();
95+
}
96+
97+
}
98+
99+
/** @extends Pair<int, string> */
100+
final class IntStringPair extends Pair
101+
{
102+
103+
}
104+
105+
/**
106+
* @param Vec<int> $vec
107+
* @param Dict<string, int> $dict
108+
*/
109+
function test(IntVec $intVec, Vec $vec, Dict $dict, IntStringPair $pair): void
110+
{
111+
// an IntVec holds only ints, the strings are in some Coll
112+
assertType('GenericStaticSubclassArguments\Coll<\'a\'>', $intVec->map(static fn (int $i): string => 'a'));
113+
assertType('GenericStaticSubclassArguments\IntVec', $intVec->filter());
114+
assertType('GenericStaticSubclassArguments\Vec<\'a\'>', $vec->map(static fn (int $i): string => 'a'));
115+
assertType('GenericStaticSubclassArguments\Vec<int>', $vec->filter());
116+
assertType('GenericStaticSubclassArguments\Dict<mixed, \'a\'>', $dict->map(static fn (int $i): string => 'a'));
117+
assertType('GenericStaticSubclassArguments\IntStringPair', $pair->same());
118+
assertType('GenericStaticSubclassArguments\Pair<string, int>', $pair->flip());
119+
}

‎turbo-ext/src/GenericStaticType.cpp‎

Lines changed: 126 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ class GenericStaticType
239239
if (!generic) {
240240
zval result;
241241
if (UNEXPECTED(!pt_static_type_new(&result, classReflection))) return zv::Val();
242-
return zv::Val::adopt(result);
242+
return keepingTypeArguments(zv::Val::adopt(result), ownClassName);
243243
}
244244

245245
/* $templateTags = $this->getClassReflection()->getTemplateTags() */
@@ -348,7 +348,131 @@ class GenericStaticType
348348
zend_type_error("phpstan_turbo: typeMapToList()/varianceMapToList() must return array");
349349
return zv::Val();
350350
}
351-
return create(classReflection, listTypes.raw(), subtracted, listVariances.raw());
351+
return keepingTypeArguments(create(classReflection, listTypes.raw(), subtracted, listVariances.raw()), ownClassName);
352+
}
353+
354+
/* $changed when its static object type's ancestor with the own class name
355+
* is none, not generic, or certainly within the own type arguments, with
356+
* the own class templates and the arguments left out taken from that
357+
* ancestor; $this otherwise; UNDEF = pending exception */
358+
zv::Val keepingTypeArguments(zv::Val changed, zv::Val &ownClassName) const
359+
{
360+
if (UNEXPECTED(changed.isUndef())) return zv::Val();
361+
zv::Val changedObject = pt_type_call(Z_OBJ_P(changed.raw()), PT_LC("getstaticobjecttype"), 0, NULL);
362+
if (UNEXPECTED(changedObject.isUndef())) return zv::Val();
363+
if (UNEXPECTED(!zv::Ref(changedObject.raw()).isObject())) {
364+
zend_type_error("phpstan_turbo: getStaticObjectType() must return an object");
365+
return zv::Val();
366+
}
367+
zv::Val ancestor = pt_type_call(Z_OBJ_P(changedObject.raw()), PT_LC("getancestorwithclassname"), 1, ownClassName.raw());
368+
if (UNEXPECTED(ancestor.isUndef())) return zv::Val();
369+
if (ancestor.isNull()) return changed;
370+
if (UNEXPECTED(!zv::Ref(ancestor.raw()).isObject())) {
371+
zend_type_error("phpstan_turbo: getAncestorWithClassName() must return an object or null");
372+
return zv::Val();
373+
}
374+
zv::Val ancestorReflection = pt_type_call(Z_OBJ_P(ancestor.raw()), PT_LC("getclassreflection"), 0, NULL);
375+
if (UNEXPECTED(ancestorReflection.isUndef())) return zv::Val();
376+
if (ancestorReflection.isNull()) return changed;
377+
if (UNEXPECTED(!zv::Ref(ancestorReflection.raw()).isObject())) {
378+
zend_type_error("phpstan_turbo: getClassReflection() must return an object or null");
379+
return zv::Val();
380+
}
381+
bool ancestorGeneric;
382+
if (UNEXPECTED(!pt_class_reflection_is_generic(Z_OBJ_P(ancestorReflection.raw()), ancestorGeneric))) return zv::Val();
383+
if (!ancestorGeneric) return changed;
384+
385+
/* the class's own templates stand for what the subclass passes to them,
386+
* and so do the arguments left out:
387+
* $ancestorReflection->typeMapToList($ancestorReflection->getActiveTemplateTypeMap()) */
388+
zv::Val ancestorTypeMap = pt_class_reflection_get_active_template_type_map(Z_OBJ_P(ancestorReflection.raw()));
389+
if (UNEXPECTED(ancestorTypeMap.isUndef())) return zv::Val();
390+
zv::Val ancestorTypes = pt_class_reflection_type_map_to_list(Z_OBJ_P(ancestorReflection.raw()), ancestorTypeMap.raw());
391+
if (UNEXPECTED(ancestorTypes.isUndef())) return zv::Val();
392+
if (UNEXPECTED(!zv::Ref(ancestorTypes.raw()).isArray())) {
393+
zend_type_error("phpstan_turbo: typeMapToList() must return array");
394+
return zv::Val();
395+
}
396+
zv::Val ownReflection = pt_static_type_this_class_reflection(self);
397+
if (UNEXPECTED(ownReflection.isUndef())) return zv::Val();
398+
if (UNEXPECTED(!zv::Ref(ownReflection.raw()).isObject())) {
399+
zend_type_error("phpstan_turbo: getClassReflection() must return an object");
400+
return zv::Val();
401+
}
402+
zv::Val templateTags = pt_type_call(Z_OBJ_P(ownReflection.raw()), PT_LC("gettemplatetags"), 0, NULL);
403+
if (UNEXPECTED(templateTags.isUndef())) return zv::Val();
404+
if (UNEXPECTED(!zv::Ref(templateTags.raw()).isArray())) {
405+
zend_type_error("phpstan_turbo: getTemplateTags() must return array");
406+
return zv::Val();
407+
}
408+
zval *ownTypes = types();
409+
zval *ownVariances = ownTypes != NULL ? variances() : NULL;
410+
if (UNEXPECTED(ownVariances == NULL)) return zv::Val();
411+
zval requestedTypes;
412+
ZVAL_ARR(&requestedTypes, zend_array_dup(Z_ARRVAL_P(ancestorTypes.raw())));
413+
zv::Val requestedTypesVal = zv::Val::adopt(requestedTypes);
414+
zend_ulong i;
415+
zval *type;
416+
ZEND_HASH_FOREACH_NUM_KEY_VAL(Z_ARRVAL_P(ownTypes), i, type) {
417+
zval *requested = type;
418+
bool isTemplate;
419+
if (UNEXPECTED(!pt_type_instanceof(type, PT_CLASS_TEMPLATE_TYPE, isTemplate))) return zv::Val();
420+
if (isTemplate) {
421+
zv::Val scope = pt_type_call(Z_OBJ_P(type), PT_LC("getscope"), 0, NULL);
422+
if (UNEXPECTED(scope.isUndef())) return zv::Val();
423+
if (UNEXPECTED(!zv::Ref(scope.raw()).isObject())) {
424+
zend_type_error("phpstan_turbo: getScope() must return an object");
425+
return zv::Val();
426+
}
427+
zv::Val scopeClassName = pt_type_call(Z_OBJ_P(scope.raw()), PT_LC("getclassname"), 0, NULL);
428+
if (UNEXPECTED(scopeClassName.isUndef())) return zv::Val();
429+
bool ownTemplate = zend_is_identical(scopeClassName.raw(), ownClassName.raw());
430+
if (ownTemplate) {
431+
zv::Val scopeFunctionName = pt_type_call(Z_OBJ_P(scope.raw()), PT_LC("getfunctionname"), 0, NULL);
432+
if (UNEXPECTED(scopeFunctionName.isUndef())) return zv::Val();
433+
ownTemplate = scopeFunctionName.isNull();
434+
}
435+
if (ownTemplate) {
436+
zv::Val name = pt_type_call(Z_OBJ_P(type), PT_LC("getname"), 0, NULL);
437+
if (UNEXPECTED(name.isUndef())) return zv::Val();
438+
/* array_search($type->getName(), $templateNames, true) */
439+
zend_long index = -1;
440+
zend_long position = 0;
441+
zend_string *tagName;
442+
zend_ulong tagIndex;
443+
ZEND_HASH_FOREACH_KEY(Z_ARRVAL_P(templateTags.raw()), tagIndex, tagName) {
444+
zval key;
445+
if (tagName != NULL) {
446+
ZVAL_STR(&key, tagName);
447+
} else {
448+
ZVAL_LONG(&key, (zend_long) tagIndex);
449+
}
450+
if (zend_is_identical(&key, name.raw())) {
451+
index = position;
452+
break;
453+
}
454+
position++;
455+
} ZEND_HASH_FOREACH_END();
456+
if (index >= 0) {
457+
zval *ancestorType = zend_hash_index_find(Z_ARRVAL_P(ancestorTypes.raw()), (zend_ulong) index);
458+
if (ancestorType != NULL) requested = ancestorType;
459+
}
460+
}
461+
}
462+
Z_TRY_ADDREF_P(requested);
463+
zend_hash_index_update(Z_ARRVAL_P(requestedTypesVal.raw()), i, requested);
464+
} ZEND_HASH_FOREACH_END();
465+
466+
/* new GenericObjectType($this->getClassName(), $types, null, null, $this->variances) */
467+
zval requestedRaw;
468+
if (UNEXPECTED(!pt_generic_object_type_new(&requestedRaw, Z_STR_P(ownClassName.raw()), requestedTypesVal.raw(), NULL, NULL, ownVariances))) return zv::Val();
469+
zv::Val requestedType = zv::Val::adopt(requestedRaw);
470+
zv::Val result = pt_type_op(Z_OBJ_P(requestedType.raw()), PT_OP_IS_SUPER_TYPE_OF, 1, ancestor.raw());
471+
if (UNEXPECTED(result.isUndef())) return zv::Val();
472+
zend_long value = pt_type_result_trinary(result.raw());
473+
if (UNEXPECTED(value < 0)) return zv::Val();
474+
if (value == PT_TRI_YES) return changed;
475+
return thisValue();
352476
}
353477

354478
/* the CompoundType callback; the static object types' answer for

0 commit comments

Comments
 (0)