Skip to content

Commit 53c0b95

Browse files
committed
Resolve a template contravariant in the return type to its upper bound
A template inferred from both kinds of position, such as the T in @PARAM T $value and @PARAM callable(T): void $handler, has a lower and an upper bound, and the lower one always won. That is the most precise choice when the return type uses T covariantly, but when it uses T only in contravariant positions, as in @return callable(T): void, a larger T is the more precise return type. handler(1, $intOrStringHandler) returned callable(1): void, which a callable(int|string): void parameter rejected. Such a template now resolves to its upper bound, the rule of Pierce and Turner's local type inference. A template the return type uses covariantly, in both kinds of position, or not at all keeps the lower bound. TemplateTypeMap::getUpperBoundTypes() exposes the upper bounds. Amp-Thread-ID: https://ampcode.com/threads/T-01a21c3c-cedc-7330-a083-cc986590888f
1 parent 7fa98fe commit 53c0b95

8 files changed

Lines changed: 225 additions & 36 deletions

File tree

‎src/Reflection/GenericParametersAcceptorResolver.php‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ public static function resolve(array $argTypes, ParametersAcceptor $parametersAc
174174
$resolvedTemplateTypeMap = new TemplateTypeMap(array_merge(
175175
$parametersAcceptor->getTemplateTypeMap()->map(static fn (string $name, Type $type): Type => new ErrorType())->getTypes(),
176176
$typeMap->getTypes(),
177+
self::resolveContravariantReturnTemplateTypes($returnType, $typeMap->getUpperBoundTypes()),
177178
));
178179

179180
$originalParametersAcceptor = $parametersAcceptor;
@@ -231,6 +232,42 @@ public static function resolve(array $argTypes, ParametersAcceptor $parametersAc
231232
return $result;
232233
}
233234

235+
/**
236+
* A template that occurs in the return type only in contravariant positions, such as
237+
* the T in callable(T): void, makes the return type more precise the larger it is, so it
238+
* resolves to its upper bound rather than to the lower bound getTypes() prefers.
239+
*
240+
* @param array<string, Type> $upperBoundTypes
241+
* @return array<string, Type>
242+
*/
243+
private static function resolveContravariantReturnTemplateTypes(Type $returnType, array $upperBoundTypes): array
244+
{
245+
if ($upperBoundTypes === []) {
246+
return [];
247+
}
248+
249+
$contravariantOnly = [];
250+
foreach ($returnType->getReferencedTemplateTypes(TemplateTypeVariance::createCovariant()) as $reference) {
251+
$name = $reference->getType()->getName();
252+
if (!array_key_exists($name, $upperBoundTypes)) {
253+
continue;
254+
}
255+
256+
$contravariantOnly[$name] = ($contravariantOnly[$name] ?? true) && $reference->getPositionVariance()->contravariant();
257+
}
258+
259+
$resolved = [];
260+
foreach ($contravariantOnly as $name => $isContravariantOnly) {
261+
if (!$isContravariantOnly) {
262+
continue;
263+
}
264+
265+
$resolved[$name] = $upperBoundTypes[$name];
266+
}
267+
268+
return $resolved;
269+
}
270+
234271
/**
235272
* @return TemplateTypeMap|null null when the parameter type is no callable with a type predicate
236273
*/

‎src/Type/Generic/TemplateTypeMap.php‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,17 @@ public function getTypes(): array
110110
return $types;
111111
}
112112

113+
/**
114+
* The upper bounds alone, including those of templates that also have a lower bound,
115+
* which getTypes() prefers.
116+
*
117+
* @return array<string, Type>
118+
*/
119+
public function getUpperBoundTypes(): array
120+
{
121+
return $this->upperBoundTypes;
122+
}
123+
113124
public function hasType(string $name): bool
114125
{
115126
return array_key_exists($name, $this->getTypes());
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
<?php
2+
3+
namespace TemplateReturnVariance;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
/** @template-contravariant T */
8+
interface Consumer
9+
{
10+
11+
/** @param T $value */
12+
public function accept($value): void;
13+
14+
}
15+
16+
/**
17+
* @template T
18+
* @param T $value
19+
* @param callable(T): void $handler
20+
* @return callable(T): void
21+
*/
22+
function handler($value, callable $handler): callable
23+
{
24+
return $handler;
25+
}
26+
27+
/**
28+
* @template T
29+
* @param T $value
30+
* @param Consumer<T> $consumer
31+
* @return Consumer<T>
32+
*/
33+
function consumer($value, Consumer $consumer): Consumer
34+
{
35+
return $consumer;
36+
}
37+
38+
/**
39+
* @template T
40+
* @param T $value
41+
* @param callable(T): void $handler
42+
* @return T
43+
*/
44+
function value($value, callable $handler)
45+
{
46+
return $value;
47+
}
48+
49+
/**
50+
* @template T
51+
* @param T $value
52+
* @param callable(T): void $handler
53+
* @return array{T, callable(T): void}
54+
*/
55+
function both($value, callable $handler): array
56+
{
57+
return [$value, $handler];
58+
}
59+
60+
/**
61+
* @template T
62+
* @param T $value
63+
* @param callable(T): void $handler
64+
* @return callable(callable(T): void): void
65+
*/
66+
function nested($value, callable $handler): callable
67+
{
68+
return static function (callable $cb) use ($value): void {
69+
$cb($value);
70+
};
71+
}
72+
73+
/**
74+
* @template T
75+
* @param callable(T): void $handler
76+
* @return callable(T): void
77+
*/
78+
function onlyHandler(callable $handler): callable
79+
{
80+
return $handler;
81+
}
82+
83+
/** @param callable(int|string): void $handler */
84+
function takesHandler(callable $handler): void
85+
{
86+
}
87+
88+
/** @param Consumer<int|string> $consumer */
89+
function takesConsumer(Consumer $consumer): void
90+
{
91+
}
92+
93+
/**
94+
* @param callable(int|string): void $intOrStringHandler
95+
* @param Consumer<int|string> $intOrStringConsumer
96+
*/
97+
function test(callable $intOrStringHandler, Consumer $intOrStringConsumer): void
98+
{
99+
// T only in contravariant positions of the return type: the upper bound
100+
assertType('callable(int|string): void', handler(1, $intOrStringHandler));
101+
assertType('TemplateReturnVariance\Consumer<int|string>', consumer(1, $intOrStringConsumer));
102+
103+
$handler = handler(1, $intOrStringHandler);
104+
takesHandler($handler);
105+
$consumer = consumer(1, $intOrStringConsumer);
106+
takesConsumer($consumer);
107+
108+
// T covariant in the return type, or in both kinds of position: the lower bound
109+
assertType('1', value(1, $intOrStringHandler));
110+
assertType('array{1, callable(1): void}', both(1, $intOrStringHandler));
111+
assertType('callable(callable(1): void): void', nested(1, $intOrStringHandler));
112+
113+
// no lower bound: the upper bound, as before
114+
assertType('callable(int|string): void', onlyHandler($intOrStringHandler));
115+
}

‎tests/PHPStan/Rules/Functions/CallToFunctionParametersRuleTest.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3709,6 +3709,11 @@ public function testTemplateBoundsVariance(): void
37093709
$this->analyse([__DIR__ . '/../../Analyser/nsrt/template-bounds-variance.php'], []);
37103710
}
37113711

3712+
public function testTemplateReturnVariance(): void
3713+
{
3714+
$this->analyse([__DIR__ . '/../../Analyser/nsrt/template-return-variance.php'], []);
3715+
}
3716+
37123717
#[RequiresPhp('>= 8.1.0')]
37133718
public function testBug13875(): void
37143719
{

‎turbo-ext/src/TemplateTypeMap.cpp‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,14 @@ class TemplateTypeMap
174174
return zv::Val(std::move(result));
175175
}
176176

177+
/* getUpperBoundTypes(): $this->upperBoundTypes; UNDEF = pending exception */
178+
zv::Val getUpperBoundTypes() const
179+
{
180+
zval *upper = this->upperBoundTypes();
181+
if (UNEXPECTED(upper == NULL)) return zv::Val();
182+
return zv::Val::copyOf(zv::Ref(upper));
183+
}
184+
177185
/* array_key_exists($name, $this->getTypes()); false = pending exception */
178186
[[nodiscard]] bool hasType(zend_string *name, bool &out) const
179187
{
@@ -546,6 +554,11 @@ PT_MINIT_REGISTRATION(pt_register_template_type_map)
546554
});
547555
cls.op<PT_OP_GET_TYPES, &TemplateTypeMap::getTypes>();
548556

557+
cls.method(sigs::getUpperBoundTypes, [](INTERNAL_FUNCTION_PARAMETERS) {
558+
ZEND_PARSE_PARAMETERS_NONE();
559+
PT_RETURN_VAL(PT_TTM_THIS.getUpperBoundTypes());
560+
});
561+
549562
cls.method(sigs::hasType, [](INTERNAL_FUNCTION_PARAMETERS) {
550563
zend_string *name;
551564
if (!zp::parse<zp::Str>(execute_data, name)) RETURN_THROWS();

‎turbo-ext/src/generated/TemplateTypeMap.h‎

Lines changed: 39 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -44,21 +44,22 @@ inline constexpr char strings[] =
4444
"isEmpty\0" /* 123 */
4545
"count\0" /* 131 */
4646
"getTypes\0" /* 137 */
47-
"name\0" /* 146 */
48-
"hasType\0" /* 151 */
49-
"PHPStan\\Type\\Type\0" /* 159 */
50-
"getType\0" /* 177 */
51-
"unsetType\0" /* 185 */
52-
"other\0" /* 195 */
53-
"union\0" /* 201 */
54-
"benevolentUnion\0" /* 207 */
55-
"a\0" /* 223 */
56-
"b\0" /* 225 */
57-
"cb\0" /* 227 */
58-
"combine\0" /* 230 */
59-
"intersect\0" /* 238 */
60-
"map\0" /* 248 */
61-
"resolveToBounds"; /* 252 */
47+
"getUpperBoundTypes\0" /* 146 */
48+
"name\0" /* 165 */
49+
"hasType\0" /* 170 */
50+
"PHPStan\\Type\\Type\0" /* 178 */
51+
"getType\0" /* 196 */
52+
"unsetType\0" /* 204 */
53+
"other\0" /* 214 */
54+
"union\0" /* 220 */
55+
"benevolentUnion\0" /* 226 */
56+
"a\0" /* 242 */
57+
"b\0" /* 244 */
58+
"cb\0" /* 246 */
59+
"combine\0" /* 249 */
60+
"intersect\0" /* 257 */
61+
"map\0" /* 267 */
62+
"resolveToBounds"; /* 271 */
6263
inline constexpr reg::PackedArg args[] = {
6364
reg::packed(0, MAY_BE_ARRAY), /* __construct $types */
6465
reg::packed(6, MAY_BE_ARRAY, reg::NoString, false, false, 22), /* __construct $lowerBoundTypes */
@@ -68,23 +69,24 @@ inline constexpr reg::PackedArg args[] = {
6869
reg::packed(37, MAY_BE_BOOL), /* isEmpty return */
6970
reg::packed(37, MAY_BE_LONG), /* count return */
7071
reg::packed(37, MAY_BE_ARRAY), /* getTypes return */
71-
reg::packed(146, MAY_BE_STRING), /* hasType $name */
72+
reg::packed(37, MAY_BE_ARRAY), /* getUpperBoundTypes return */
73+
reg::packed(165, MAY_BE_STRING), /* hasType $name */
7274
reg::packed(37, MAY_BE_BOOL), /* hasType return */
73-
reg::packed(146, MAY_BE_STRING), /* getType $name */
74-
reg::packed(37, MAY_BE_NULL, 159), /* getType return */
75-
reg::packed(146, MAY_BE_STRING), /* unsetType $name */
75+
reg::packed(165, MAY_BE_STRING), /* getType $name */
76+
reg::packed(37, MAY_BE_NULL, 178), /* getType return */
77+
reg::packed(165, MAY_BE_STRING), /* unsetType $name */
7678
reg::packed(37, 0, 38), /* unsetType return */
77-
reg::packed(195, 0, 38), /* union $other */
79+
reg::packed(214, 0, 38), /* union $other */
7880
reg::packed(37, 0, 38), /* union return */
79-
reg::packed(195, 0, 38), /* benevolentUnion $other */
81+
reg::packed(214, 0, 38), /* benevolentUnion $other */
8082
reg::packed(37, 0, 38), /* benevolentUnion return */
81-
reg::packed(223, 0, 159), /* combine $a */
82-
reg::packed(225, 0, 159), /* combine $b */
83-
reg::packed(227, MAY_BE_CALLABLE), /* combine $cb */
84-
reg::packed(37, 0, 159), /* combine return */
85-
reg::packed(195, 0, 38), /* intersect $other */
83+
reg::packed(242, 0, 178), /* combine $a */
84+
reg::packed(244, 0, 178), /* combine $b */
85+
reg::packed(246, MAY_BE_CALLABLE), /* combine $cb */
86+
reg::packed(37, 0, 178), /* combine return */
87+
reg::packed(214, 0, 38), /* intersect $other */
8688
reg::packed(37, 0, 38), /* intersect return */
87-
reg::packed(227, MAY_BE_CALLABLE), /* map $cb */
89+
reg::packed(246, MAY_BE_CALLABLE), /* map $cb */
8890
reg::packed(37, 0, 38), /* map return */
8991
reg::packed(37, 0, 38), /* resolveToBounds return */
9092
};
@@ -100,15 +102,16 @@ inline constexpr sigtab::Sig createEmpty = { { 111 /* createEmpty */, 0, 4, 0, 4
100102
inline constexpr sigtab::Sig isEmpty = { { 123 /* isEmpty */, 0, 5, 0, 5, ZEND_ACC_PUBLIC } };
101103
inline constexpr sigtab::Sig count = { { 131 /* count */, 0, 6, 0, 6, ZEND_ACC_PUBLIC } };
102104
inline constexpr sigtab::Sig getTypes = { { 137 /* getTypes */, 0, 7, 0, 7, ZEND_ACC_PUBLIC } };
103-
inline constexpr sigtab::Sig hasType = { { 151 /* hasType */, 1, 8, 1, 9, ZEND_ACC_PUBLIC } };
104-
inline constexpr sigtab::Sig getType = { { 177 /* getType */, 1, 10, 1, 11, ZEND_ACC_PUBLIC } };
105-
inline constexpr sigtab::Sig unsetType = { { 185 /* unsetType */, 1, 12, 1, 13, ZEND_ACC_PUBLIC } };
106-
inline constexpr sigtab::Sig union_ = { { 201 /* union */, 1, 14, 1, 15, ZEND_ACC_PUBLIC } };
107-
inline constexpr sigtab::Sig benevolentUnion = { { 207 /* benevolentUnion */, 1, 16, 1, 17, ZEND_ACC_PUBLIC } };
108-
inline constexpr sigtab::Sig combine = { { 230 /* combine */, 3, 18, 3, 21, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } };
109-
inline constexpr sigtab::Sig intersect = { { 238 /* intersect */, 1, 22, 1, 23, ZEND_ACC_PUBLIC } };
110-
inline constexpr sigtab::Sig map = { { 248 /* map */, 1, 24, 1, 25, ZEND_ACC_PUBLIC } };
111-
inline constexpr sigtab::Sig resolveToBounds = { { 252 /* resolveToBounds */, 0, 26, 0, 26, ZEND_ACC_PUBLIC } };
105+
inline constexpr sigtab::Sig getUpperBoundTypes = { { 146 /* getUpperBoundTypes */, 0, 8, 0, 8, ZEND_ACC_PUBLIC } };
106+
inline constexpr sigtab::Sig hasType = { { 170 /* hasType */, 1, 9, 1, 10, ZEND_ACC_PUBLIC } };
107+
inline constexpr sigtab::Sig getType = { { 196 /* getType */, 1, 11, 1, 12, ZEND_ACC_PUBLIC } };
108+
inline constexpr sigtab::Sig unsetType = { { 204 /* unsetType */, 1, 13, 1, 14, ZEND_ACC_PUBLIC } };
109+
inline constexpr sigtab::Sig union_ = { { 220 /* union */, 1, 15, 1, 16, ZEND_ACC_PUBLIC } };
110+
inline constexpr sigtab::Sig benevolentUnion = { { 226 /* benevolentUnion */, 1, 17, 1, 18, ZEND_ACC_PUBLIC } };
111+
inline constexpr sigtab::Sig combine = { { 249 /* combine */, 3, 19, 3, 22, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } };
112+
inline constexpr sigtab::Sig intersect = { { 257 /* intersect */, 1, 23, 1, 24, ZEND_ACC_PUBLIC } };
113+
inline constexpr sigtab::Sig map = { { 267 /* map */, 1, 25, 1, 26, ZEND_ACC_PUBLIC } };
114+
inline constexpr sigtab::Sig resolveToBounds = { { 271 /* resolveToBounds */, 0, 27, 0, 27, ZEND_ACC_PUBLIC } };
112115
} // namespace sig
113116

114117
} // namespace ptdecl::TemplateTypeMap

‎turbo-ext/tests/smoke.php‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1712,6 +1712,8 @@ public function traverse(\PHPStan\Type\Type $type, callable $traverse): \PHPStan
17121712
check(($ttmPhp->unsetType($ttmName) === $ttmPhp) === ($ttmNative->unsetType($ttmName) === $ttmNative), "TemplateTypeMap $ttmLabel unsetType($ttmName) returns \$this on both sides or neither");
17131713
check(($ttmPhp->unsetType($ttmName) === \PHPStan\Type\Generic\TemplateTypeMap::createEmpty()) === ($ttmNative->unsetType($ttmName) === \PHPStanTurbo\TemplateTypeMap::createEmpty()), "TemplateTypeMap $ttmLabel unsetType($ttmName) returns the empty singleton on both sides or neither");
17141714
}
1715+
check($ttmView($ttmPhp->getUpperBoundTypes()) === $ttmView($ttmNative->getUpperBoundTypes()), "TemplateTypeMap $ttmLabel getUpperBoundTypes()");
1716+
check($ttmView($ttmPhp->swapBounds()->getUpperBoundTypes()) === $ttmView($ttmNative->swapBounds()->getUpperBoundTypes()), "TemplateTypeMap $ttmLabel swapBounds() getUpperBoundTypes()");
17151717
check($ttmView($ttmPhp->swapBounds()->getTypes()) === $ttmView($ttmNative->swapBounds()->getTypes()), "TemplateTypeMap $ttmLabel swapBounds()");
17161718
check($ttmView($ttmPhp->swapBounds()->swapBounds()->getTypes()) === $ttmView($ttmNative->swapBounds()->swapBounds()->getTypes()), "TemplateTypeMap $ttmLabel swapBounds() twice");
17171719
check($ttmView($ttmPhp->convertToLowerBoundTypes()->getTypes()) === $ttmView($ttmNative->convertToLowerBoundTypes()->getTypes()), "TemplateTypeMap $ttmLabel convertToLowerBoundTypes()");

‎turbo-ext/tests/type-family.php‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4990,13 +4990,16 @@ public function getKeyType(): \PHPStan\Type\Type
49904990
$r["$label count"] = $map->count();
49914991
$r["$label resolveToBounds"] = $view($map->resolveToBounds()->getTypes());
49924992
$r["$label resolveToBounds identity"] = $map->resolveToBounds() === $map->resolveToBounds();
4993+
$r["$label getUpperBoundTypes"] = $view($map->getUpperBoundTypes());
49934994
$r["$label swapBounds"] = $view($map->swapBounds()->getTypes());
49944995
$r["$label swapBounds twice"] = $view($map->swapBounds()->swapBounds()->getTypes());
49954996
$r["$label convertToLowerBoundTypes"] = $view($map->convertToLowerBoundTypes()->getTypes());
49964997
foreach ($maps as $otherLabel => $other) {
49974998
$r["$label union $otherLabel"] = $view($map->union($other)->getTypes());
49984999
$r["$label benevolentUnion $otherLabel"] = $view($map->benevolentUnion($other)->getTypes());
49995000
$r["$label intersect $otherLabel"] = $view($map->intersect($other)->getTypes());
5001+
$r["$label union $otherLabel upper bounds"] = $view($map->union($other)->getUpperBoundTypes());
5002+
$r["$label intersect $otherLabel upper bounds"] = $view($map->intersect($other)->getUpperBoundTypes());
50005003
$r["$label union $otherLabel swapped"] = $view($map->union($other)->swapBounds()->getTypes());
50015004
$r["$label intersect $otherLabel swapped"] = $view($map->intersect($other)->swapBounds()->getTypes());
50025005
}

0 commit comments

Comments
 (0)