Skip to content

Commit 66ec5e6

Browse files
committed
Solve linked invariant template arguments together
1 parent a82b7e9 commit 66ec5e6

10 files changed

Lines changed: 651 additions & 1 deletion

‎src/Analyser/Generics/TemplateArgumentObserver.php‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,23 @@
22

33
namespace PHPStan\Analyser\Generics;
44

5+
use PhpParser\Node\Expr;
56
use PHPStan\DependencyInjection\AutowiredService;
7+
use PHPStan\Reflection\ParametersAcceptor;
8+
use PHPStan\Reflection\ResolvedFunctionVariant;
69
use PHPStan\Type\Generic\TemplateType;
710
use PHPStan\Type\Generic\TemplateTypeHelper;
11+
use PHPStan\Type\Generic\TemplateTypeMap;
812
use PHPStan\Type\Generic\TemplateTypeVariance;
913
use PHPStan\Type\Generic\UnresolvedTemplateArgumentType;
1014
use PHPStan\Type\MixedType;
1115
use PHPStan\Type\NeverType;
1216
use PHPStan\Type\Type;
1317
use PHPStan\Type\TypeTraverser;
1418
use PHPStan\Type\UnionType;
19+
use function array_merge;
1520
use function count;
21+
use function is_string;
1622

1723
/**
1824
* Matches declared and actual types to collect constraints on unresolved
@@ -67,6 +73,64 @@ public function collectArgument(Type $parameterType, Type $argumentType, bool $i
6773
return $this->observeArgument(TemplateArgumentConstraints::createEmpty(), $parameterType, $argumentType);
6874
}
6975

76+
/**
77+
* Keep a call's inferable parameters shared across all of its arguments.
78+
* Invariant uses relate fresh instances instead of fixing each one from
79+
* the arguments seen so far. The call's return type uses the same site.
80+
*
81+
* @param array<int|string, Type> $argumentTypes
82+
*/
83+
public function collectCall(Expr $site, ParametersAcceptor $acceptor, array $argumentTypes, ?TemplateTypeMap $classTemplates = null): TemplateArgumentConstraints
84+
{
85+
$constraints = TemplateArgumentConstraints::createEmpty();
86+
if ($acceptor instanceof ResolvedFunctionVariant) {
87+
$acceptor = $acceptor->getOriginalParametersAcceptor();
88+
}
89+
$templates = new TemplateTypeMap(array_merge($classTemplates !== null ? $classTemplates->getTypes() : [], $acceptor->getTemplateTypeMap()->getTypes()));
90+
if ($templates->isEmpty()) {
91+
return $constraints;
92+
}
93+
$hasMarkers = false;
94+
foreach ($argumentTypes as $argumentType) {
95+
if (!$this->containsMarker($argumentType)) {
96+
continue;
97+
}
98+
$hasMarkers = true;
99+
break;
100+
}
101+
if (!$hasMarkers) {
102+
return $constraints;
103+
}
104+
105+
$parameters = $acceptor->getParameters();
106+
$parametersByName = [];
107+
foreach ($parameters as $parameter) {
108+
$parametersByName[$parameter->getName()] = $parameter;
109+
}
110+
foreach ($argumentTypes as $i => $argumentType) {
111+
$parameter = is_string($i) ? ($parametersByName[$i] ?? null) : ($parameters[$i] ?? null);
112+
$parameter ??= $acceptor->isVariadic() && count($parameters) > 0 ? $parameters[count($parameters) - 1] : null;
113+
if ($parameter === null) {
114+
continue;
115+
}
116+
$parameterType = TypeTraverser::map($parameter->getType(), static function (Type $type, callable $traverse) use ($site, $templates, &$constraints): Type {
117+
if (!$type instanceof TemplateType || $type->isArgument()) {
118+
return $traverse($type);
119+
}
120+
$template = $templates->getType($type->getName());
121+
if (!$template instanceof TemplateType || !$template->getScope()->equals($type->getScope())) {
122+
return $type;
123+
}
124+
$marker = new UnresolvedTemplateArgumentType($site, $type, null);
125+
$constraints = $constraints->withSite($marker);
126+
return $marker;
127+
});
128+
$constraints = $this->observeArgument($constraints, $parameterType, $argumentType);
129+
}
130+
131+
return $constraints;
132+
}
133+
70134
/**
71135
* $actual flows into $declared: a property's writable type, a parameter
72136
* type, a declared return type, a @var type.
@@ -246,6 +310,24 @@ private function observeLowerBound(TemplateArgumentConstraints $constraints, Typ
246310
if (!isset($ancestorArguments[$i])) {
247311
continue;
248312
}
313+
if ($parameterArgument instanceof UnresolvedTemplateArgumentType) {
314+
$template = $parameterReflection->typeMapToList($parameterReflection->getTemplateTypeMap())[$i] ?? null;
315+
if ($template instanceof TemplateType) {
316+
$variance = $parameterReflection->getCallSiteVarianceMap()->getVariance($template->getName()) ?? TemplateTypeVariance::createInvariant();
317+
$variance = $variance->invariant() ? $template->getVariance() : $variance;
318+
if ($variance->invariant()) {
319+
$constraints = $constraints->withSend($parameterArgument, $ancestorArguments[$i], $variance);
320+
continue;
321+
}
322+
if ($variance->contravariant()) {
323+
$constraints = $constraints->withSend($parameterArgument, $ancestorArguments[$i], TemplateTypeVariance::createCovariant());
324+
continue;
325+
}
326+
if ($variance->bivariant()) {
327+
continue;
328+
}
329+
}
330+
}
249331
$constraints = $this->observeLowerBound($constraints, $parameterArgument, $ancestorArguments[$i]);
250332
}
251333

‎src/Analyser/Generics/TemplateArgumentSolver.php‎

Lines changed: 91 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,12 @@
99
use PHPStan\Type\Type;
1010
use PHPStan\Type\TypeCombinator;
1111
use PHPStan\Type\TypeTraverser;
12+
use PHPStan\Type\UnionType;
13+
use function array_filter;
1214
use function array_key_exists;
1315
use function array_keys;
16+
use function array_merge;
17+
use function array_values;
1418
use function count;
1519
use function spl_object_id;
1620

@@ -32,18 +36,103 @@ public function __construct(
3236
/** @return array<string, Type> */
3337
public function solve(): array
3438
{
39+
$this->mergeEqualArguments();
3540
foreach (array_keys($this->observations) as $key) {
3641
$this->resolveKey($key);
3742
}
43+
foreach ($this->representatives as $key => $representative) {
44+
$this->resolutions[$key] = $this->resolveKey($representative);
45+
}
3846

3947
return $this->resolutions;
4048
}
4149

50+
/** @var array<string, string> */
51+
private array $representatives = [];
52+
53+
private function representative(string $key): string
54+
{
55+
$representative = $this->representatives[$key] ?? $key;
56+
if ($representative === $key) {
57+
return $key;
58+
}
59+
return $this->representatives[$key] = $this->representative($representative);
60+
}
61+
62+
/** Invariant arguments share one variable until all their bounds are known. */
63+
private function mergeEqualArguments(): void
64+
{
65+
$ranks = [];
66+
foreach ($this->observations as $key => $observation) {
67+
foreach ($observation['sends'] as [$sent, $variance]) {
68+
if (!$variance->invariant() || !$sent instanceof UnresolvedTemplateArgumentType) {
69+
continue;
70+
}
71+
$other = self::key($sent->getSite(), $sent->getTemplateName());
72+
if (!isset($this->observations[$other])) {
73+
continue;
74+
}
75+
$left = $this->representative($key);
76+
$right = $this->representative($other);
77+
if ($left === $right) {
78+
continue;
79+
}
80+
$leftRank = $ranks[$left] ?? 0;
81+
$rightRank = $ranks[$right] ?? 0;
82+
if ($leftRank < $rightRank) {
83+
$this->representatives[$left] = $right;
84+
} else {
85+
$this->representatives[$right] = $left;
86+
if ($leftRank === $rightRank) {
87+
$ranks[$left] = $leftRank + 1;
88+
}
89+
}
90+
}
91+
}
92+
if ($this->representatives === []) {
93+
return;
94+
}
95+
$observations = [];
96+
foreach ($this->observations as $key => $observation) {
97+
$representative = $this->representative($key);
98+
$this->representatives[$key] = $representative;
99+
$initial = $observation['initial'];
100+
$observation['initial'] = $initial !== null ? $this->removeSelfBounds($initial, $representative) : null;
101+
$observation['sends'] = array_values(array_filter($observation['sends'], fn (array $send): bool => !$send[0] instanceof UnresolvedTemplateArgumentType
102+
|| $this->representative(self::key($send[0]->getSite(), $send[0]->getTemplateName())) !== $representative));
103+
if (!isset($observations[$representative])) {
104+
$observations[$representative] = $observation;
105+
continue;
106+
}
107+
$merged = $observations[$representative];
108+
if ($observation['initial'] !== null) {
109+
$merged['initial'] = $merged['initial'] !== null ? TypeCombinator::union($merged['initial'], $observation['initial']) : $observation['initial'];
110+
}
111+
$merged['sends'] = array_merge($merged['sends'], $observation['sends']);
112+
$merged['lowerBounds'] = array_merge($merged['lowerBounds'], $observation['lowerBounds']);
113+
$merged['unconstrainingSend'] = $merged['unconstrainingSend'] || $observation['unconstrainingSend'];
114+
$observations[$representative] = $merged;
115+
}
116+
$this->observations = $observations;
117+
}
118+
119+
private function removeSelfBounds(Type $type, string $key): Type
120+
{
121+
if ($type instanceof UnresolvedTemplateArgumentType && $this->representative(self::key($type->getSite(), $type->getTemplateName())) === $key) {
122+
return new NeverType();
123+
}
124+
if ($type instanceof UnionType) {
125+
return $type->traverse(fn (Type $member): Type => $this->removeSelfBounds($member, $key));
126+
}
127+
return $type;
128+
}
129+
42130
/** @var array<string, true> */
43131
private array $resolving = [];
44132

45133
private function resolveKey(string $key): Type
46134
{
135+
$key = $this->representative($key);
47136
if (array_key_exists($key, $this->resolutions)) {
48137
return $this->resolutions[$key];
49138
}
@@ -86,7 +175,7 @@ private function substituteResolutions(Type $type): Type
86175

87176
private function substituteMarker(UnresolvedTemplateArgumentType $marker): Type
88177
{
89-
$key = self::key($marker->getSite(), $marker->getTemplateName());
178+
$key = $this->representative(self::key($marker->getSite(), $marker->getTemplateName()));
90179
if (array_key_exists($key, $this->observations)) {
91180
return $this->resolveKey($key);
92181
}
@@ -126,6 +215,7 @@ private function resolveObservation(array $observation): Type
126215
if (!$templateVariance->covariant() || $acceptsAnything) {
127216
$covariantFallback = null;
128217
foreach ($observation['sends'] as [$sent, $variance]) {
218+
$sent = $this->substituteResolutions($sent);
129219
if ($variance->contravariant()) {
130220
// Foo<contravariant int> accepts Foo<X> for every X wider than int
131221
$lowerBounds[] = $sent;

‎src/Analyser/NodeScopeResolver.php‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3172,6 +3172,15 @@ public function processArgs(
31723172
: $metadataAcceptor;
31733173
}
31743174

3175+
if ($resolvedAcceptor !== null && $this->observingTemplateArgumentFrame($scope) !== null) {
3176+
$scope = $scope->addTemplateArgumentConstraints($this->templateArgumentObserver->collectCall(
3177+
$callLike,
3178+
$resolvedAcceptor,
3179+
$gatheredTypes,
3180+
$callLike instanceof New_ && $calleeReflection instanceof MethodReflection ? $calleeReflection->getDeclaringClass()->getTemplateTypeMap() : null,
3181+
));
3182+
}
3183+
31753184
// The by-ref OUT writeback reads the metadata acceptor: it is selected from
31763185
// the full argument count (stable variant). When that single acceptor still
31773186
// carries templates (fast path), its OUT types need generic-resolving from the

‎tests/PHPStan/Analyser/Generics/TemplateArgumentFlowTest.php‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use PHPStan\Testing\TypeInferenceTestCase;
66
use PHPUnit\Framework\Attributes\DataProvider;
77
use function array_merge;
8+
use const PHP_VERSION_ID;
89

910
class TemplateArgumentFlowTest extends TypeInferenceTestCase
1011
{
@@ -13,6 +14,11 @@ class TemplateArgumentFlowTest extends TypeInferenceTestCase
1314
public static function dataConstraintsSurviveControlFlow(): iterable
1415
{
1516
yield from self::gatherAssertTypes(__DIR__ . '/data/constraint-flow.php');
17+
yield from self::gatherAssertTypes(__DIR__ . '/data/joint-inference.php');
18+
if (PHP_VERSION_ID < 80000) {
19+
return;
20+
}
21+
yield from self::gatherAssertTypes(__DIR__ . '/../../Rules/Functions/data/joint-inference-named.php');
1622
}
1723

1824
#[DataProvider('dataConstraintsSurviveControlFlow')]
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace JointInference;
4+
5+
require_once __DIR__ . '/joint-inference.php';
6+
7+
/**
8+
* @param Promise<1> $one
9+
* @param Promise<2> $two
10+
*/
11+
function fixedPromises(Promise $one, Promise $two): void
12+
{
13+
all([$one, $two]);
14+
}
15+
16+
/**
17+
* @param Box<Cat> $cat
18+
* @param Box<Dog> $dog
19+
*/
20+
function fixedBoxes(Box $cat, Box $dog): void
21+
{
22+
both($cat, $dog);
23+
}
24+
25+
/** @param Resolver<int> $resolver */
26+
function requireIntResolver(Resolver $resolver): void
27+
{
28+
}
29+
30+
function incompatibleWrite(): void
31+
{
32+
$one = new Resolver();
33+
$two = new Resolver();
34+
all([$one->getPromise(), $two->getPromise()]);
35+
requireIntResolver($one);
36+
$one->resolve(1);
37+
$two->resolve('wrong');
38+
}
39+
40+
function incompatibleCallback(): void
41+
{
42+
$one = new Resolver();
43+
$two = new Resolver();
44+
$combined = all([$one->getPromise(), $two->getPromise()]);
45+
$one->resolve(1);
46+
$two->resolve(2);
47+
$combined->onCompletion(static function (string $value): void {});
48+
}
49+
50+
/** @param EventCollection<WrittenEvent<'one'>|WrittenEvent<'two'>> $events */
51+
function fixedEvents(EventCollection $events): void
52+
{
53+
new ContainerEvent($events);
54+
}
55+
56+
function incompatibleEvent(): void
57+
{
58+
new ContainerEvent(new EventCollection([new WrittenEvent('one'), new Event()]));
59+
}
60+
61+
/**
62+
* @template T of int
63+
* @param array<Promise<T>> $promises
64+
*/
65+
function allIntegers(array $promises): void
66+
{
67+
}
68+
69+
function incompatibleBound(): void
70+
{
71+
$one = new Resolver();
72+
$two = new Resolver();
73+
allIntegers([$one->getPromise(), $two->getPromise()]);
74+
$one->resolve(1);
75+
$two->resolve('wrong');
76+
}
77+
78+
function incompatibleRead(): void
79+
{
80+
$one = new Resolver();
81+
$two = new Resolver();
82+
$one->getPromise()->onCompletion(static function (int $value): void {});
83+
all([$one->getPromise(), $two->getPromise()]);
84+
$one->resolve(1);
85+
$two->resolve('wrong');
86+
}

0 commit comments

Comments
 (0)