Repository navigation
Expand file tree
/
Copy pathTemplateArgumentObserver.php
More file actions
786 lines (711 loc) · 30.2 KB
/
Copy pathTemplateArgumentObserver.php
File metadata and controls
786 lines (711 loc) · 30.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\Generics;
use PhpParser\Node\Expr;
use PHPStan\Analyser\OutOfClassScope;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Reflection\MissingPropertyFromReflectionException;
use PHPStan\Reflection\ParametersAcceptor;
use PHPStan\Reflection\ResolvedFunctionVariant;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\ClosureType;
use PHPStan\Type\Generic\TemplateType;
use PHPStan\Type\Generic\TemplateTypeHelper;
use PHPStan\Type\Generic\TemplateTypeMap;
use PHPStan\Type\Generic\TemplateTypeVariance;
use PHPStan\Type\Generic\UnresolvedTemplateArgumentType;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\MixedType;
use PHPStan\Type\NeverType;
use PHPStan\Type\ObjectShapeType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeTraverser;
use PHPStan\Type\UnionType;
use function array_filter;
use function array_merge;
use function count;
use function is_string;
/**
* Matches declared and actual types to collect constraints on unresolved
* template arguments. All accumulation is local to a call; the returned
* constraints and the scope's inference context are immutable.
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/TemplateArgumentObserver.cpp')]
final class TemplateArgumentObserver
{
public function collectSites(Type $type): TemplateArgumentConstraints
{
$constraints = TemplateArgumentConstraints::createEmpty();
TypeTraverser::map($type, static function (Type $type, callable $traverse) use (&$constraints): Type {
if ($type instanceof UnresolvedTemplateArgumentType) {
$constraints = $constraints->withSite($type);
$initial = $type->getInitialType();
if ($initial !== null) {
$traverse($initial);
}
return $type;
}
return $traverse($type);
});
return $constraints;
}
/** Skip ordinary recursive generic relationships that cannot contribute a constraint. */
private function containsMarker(Type $type, bool $templateArgumentsOnly = false): bool
{
$contains = false;
TypeTraverser::map($type, static function (Type $type, callable $traverse) use (&$contains, $templateArgumentsOnly): Type {
if ($type instanceof UnresolvedTemplateArgumentType && (!$templateArgumentsOnly || !ClosureSignatureInference::isClosureSignatureMarker($type))) {
$contains = true;
}
return $contains ? $type : $traverse($type);
});
return $contains;
}
public function collectSend(Type $declared, Type $actual): TemplateArgumentConstraints
{
$constraints = $this->observeSend(TemplateArgumentConstraints::createEmpty(), $declared, $actual);
return $this->observeClosureSend($constraints, $declared, $actual);
}
/**
* A call argument flows into its parameter: the closures it carries learn
* what they will be invoked with (see ClosureSignatureInference).
*/
public function collectClosureArgument(Type $parameterType, Type $argumentType): TemplateArgumentConstraints
{
return $this->observeClosureSend(TemplateArgumentConstraints::createEmpty(), $parameterType, $argumentType);
}
/**
* The call's arguments against the acceptor resolved from all of them - a
* generic callable(T) parameter is only informative once T is.
*
* A pure callee cannot invoke what it takes as mixed, so such a parameter
* is no escape.
*
* @param array<int|string, Type> $argumentTypes
*/
public function collectClosureArguments(ParametersAcceptor $acceptor, array $argumentTypes, bool $isPure): TemplateArgumentConstraints
{
$constraints = TemplateArgumentConstraints::createEmpty();
$parameters = null;
$parametersByName = null;
foreach ($argumentTypes as $i => $argumentType) {
if (!$this->containsClosureSignatureMarker($argumentType)) {
continue;
}
if ($parameters === null) {
$parameters = $acceptor->getParameters();
$parametersByName = [];
foreach ($parameters as $parameter) {
$parametersByName[$parameter->getName()] = $parameter;
}
}
$parameter = is_string($i) ? ($parametersByName[$i] ?? null) : ($parameters[$i] ?? null);
$parameter ??= $acceptor->isVariadic() && count($parameters) > 0 ? $parameters[count($parameters) - 1] : null;
if ($parameter === null) {
$constraints = $this->escapeClosures($constraints, $argumentType);
continue;
}
$parameterType = $parameter->getType();
if ($isPure && $parameterType instanceof MixedType && !$parameterType instanceof TemplateType) {
continue;
}
$constraints = $this->observeClosureSend($constraints, $parameterType, $argumentType);
}
return $constraints;
}
/**
* The value leaves the body for somewhere nothing describes (a yielded value,
* an offset of a property): the closures it carries can be invoked with
* anything.
*/
public function collectEscape(Type $type): TemplateArgumentConstraints
{
if (!$this->containsClosureSignatureMarker($type)) {
return TemplateArgumentConstraints::createEmpty();
}
return $this->escapeClosures(TemplateArgumentConstraints::createEmpty(), $type);
}
/** @param array<int|string, Type> $types */
public function carriesClosureSignatureMarkers(array $types): bool
{
foreach ($types as $type) {
if ($this->containsClosureSignatureMarker($type)) {
return true;
}
}
return false;
}
private function containsClosureSignatureMarker(Type $type): bool
{
$contains = false;
TypeTraverser::map($type, static function (Type $type, callable $traverse) use (&$contains): Type {
if (
($type instanceof UnresolvedTemplateArgumentType && ClosureSignatureInference::isClosureSignatureMarker($type))
|| ($type instanceof ClosureType && $type->getByRefUseTypes() !== [])
) {
$contains = true;
}
return $contains ? $type : $traverse($type);
});
return $contains;
}
/**
* $actual, carrying closures whose signature is being inferred, flows into
* $declared. A callable target with a signature puts its parameter types as
* lower bounds on the closure's parameters and its return type as an upper
* bound on the closure's return; any other target lets the closure escape -
* whoever ends up invoking it can pass anything.
*/
private function observeClosureSend(TemplateArgumentConstraints $constraints, Type $declared, Type $actual): TemplateArgumentConstraints
{
if (!$this->containsClosureSignatureMarker($actual)) {
return $constraints;
}
if ($actual instanceof UnionType) {
foreach ($actual->getTypes() as $member) {
$constraints = $this->observeClosureSend($constraints, $declared, $member);
}
return $constraints;
}
if ($actual instanceof ClosureType) {
return $this->observeClosureSendToCallable($constraints, $declared, $actual);
}
if (
!$actual->isObject()->yes()
&& $actual->isIterable()->yes()
&& !$declared->isObject()->yes()
&& $declared->isIterable()->yes()
) {
$constraints = $this->observeClosureSend($constraints, $declared->getIterableKeyType(), $actual->getIterableKeyType());
$declaredValueType = $declared->getIterableValueType();
if ($declaredValueType instanceof MixedType && !$declaredValueType instanceof TemplateType) {
// every value sent to plain mixed escapes - collected from the
// array itself, not from the union of a large constant array's values
return $this->escapeClosures($constraints, $actual);
}
return $this->observeClosureSend($constraints, $declaredValueType, $actual->getIterableValueType());
}
return $this->escapeClosures($constraints, $actual);
}
private function observeClosureSendToCallable(TemplateArgumentConstraints $constraints, Type $declared, ClosureType $actual): TemplateArgumentConstraints
{
if ($declared instanceof UnionType && !$declared instanceof TemplateType) {
$declared = TypeCombinator::union(...array_filter($declared->getTypes(), static fn (Type $member): bool => !$member->isCallable()->no()));
}
if ($declared instanceof MixedType || !$declared->isCallable()->yes()) {
return $this->escapeClosures($constraints, $actual);
}
// whoever is given the closure invokes it when it chooses
$constraints = self::escapeByRefUses($constraints, $actual);
$closureParameters = $actual->getParameters();
$returnMarker = $actual->getReturnType();
foreach ($declared->getCallableParametersAcceptors(new OutOfClassScope()) as $acceptor) {
$targetParameters = $acceptor->getParameters();
if (count($targetParameters) === 0 && $acceptor->isVariadic()) {
// callable, Closure: the parameters are not described
$constraints = $this->escapeClosures($constraints, $actual);
continue;
}
foreach ($closureParameters as $i => $closureParameter) {
$marker = $closureParameter->getType();
if (!$marker instanceof UnresolvedTemplateArgumentType || !ClosureSignatureInference::isClosureSignatureMarker($marker)) {
continue;
}
if ($closureParameter->isVariadic()) {
for ($j = $i; $j < count($targetParameters); $j++) {
$constraints = $constraints->withLowerBound($marker, $targetParameters[$j]->getType());
}
continue;
}
if (isset($targetParameters[$i])) {
$constraints = $constraints->withLowerBound($marker, $targetParameters[$i]->getType());
continue;
}
if (!$acceptor->isVariadic() || count($targetParameters) === 0) {
// never passed: the closure parameter keeps its default
continue;
}
$constraints = $constraints->withLowerBound($marker, $targetParameters[count($targetParameters) - 1]->getType());
}
$targetReturnType = $acceptor->getReturnType();
if ($returnMarker instanceof UnresolvedTemplateArgumentType && ClosureSignatureInference::isReturnMarker($returnMarker)) {
if (!$targetReturnType->isVoid()->yes() && !$targetReturnType instanceof MixedType) {
$constraints = $constraints->withSend($returnMarker, $targetReturnType, TemplateTypeVariance::createCovariant());
}
$returnedType = $returnMarker->getInitialType();
} else {
$returnedType = $returnMarker;
}
if ($returnedType === null) {
continue;
}
// a closure returning closures: the returned ones are sent on
$constraints = $this->observeClosureSend($constraints, $targetReturnType, $returnedType);
}
return $constraints;
}
/**
* The closure's value goes where it can be invoked at any time: its by-ref
* uses keep the creation-time fixpoint.
*/
private static function escapeByRefUses(TemplateArgumentConstraints $constraints, ClosureType $closureType): TemplateArgumentConstraints
{
foreach ($closureType->getByRefUseTypes() as $marker) {
if (!$marker instanceof UnresolvedTemplateArgumentType) {
continue;
}
$constraints = $constraints->withUnconstrainingSend($marker);
}
return $constraints;
}
/**
* The closures in $type go where nothing describes how they are invoked.
*/
private function escapeClosures(TemplateArgumentConstraints $constraints, Type $type): TemplateArgumentConstraints
{
return $constraints->merge(ClosureSignatureInference::collectEscapes($type));
}
public function collectArgument(Type $parameterType, Type $argumentType, bool $isPure = false): TemplateArgumentConstraints
{
// A pure consumer accepting anything cannot initialize an empty object.
if ($isPure && $parameterType instanceof MixedType && !$parameterType instanceof TemplateType) {
return TemplateArgumentConstraints::createEmpty();
}
return $this->observeArgument(TemplateArgumentConstraints::createEmpty(), $parameterType, $argumentType);
}
/**
* Keep a call's inferable parameters shared across all of its arguments.
* Invariant uses relate fresh instances instead of fixing each one from
* the arguments seen so far. The call's return type uses the same site.
*
* @param array<int|string, Type> $argumentTypes
*/
public function collectCall(Expr $site, ParametersAcceptor $acceptor, array $argumentTypes, ?TemplateTypeMap $classTemplates = null): TemplateArgumentConstraints
{
$constraints = TemplateArgumentConstraints::createEmpty();
if ($acceptor instanceof ResolvedFunctionVariant) {
$acceptor = $acceptor->getOriginalParametersAcceptor();
}
$templates = new TemplateTypeMap(array_merge($classTemplates !== null ? $classTemplates->getTypes() : [], $acceptor->getTemplateTypeMap()->getTypes()));
if ($templates->isEmpty()) {
return $constraints;
}
$hasMarkers = false;
foreach ($argumentTypes as $argumentType) {
// a closure whose signature is being inferred is sent through
// collectClosureArguments(), it holds no template argument
if (!$this->containsMarker($argumentType, true)) {
continue;
}
$hasMarkers = true;
break;
}
if (!$hasMarkers) {
return $constraints;
}
$parameters = $acceptor->getParameters();
$parametersByName = [];
foreach ($parameters as $parameter) {
$parametersByName[$parameter->getName()] = $parameter;
}
foreach ($argumentTypes as $i => $argumentType) {
$parameter = is_string($i) ? ($parametersByName[$i] ?? null) : ($parameters[$i] ?? null);
$parameter ??= $acceptor->isVariadic() && count($parameters) > 0 ? $parameters[count($parameters) - 1] : null;
if ($parameter === null) {
continue;
}
$parameterType = $this->replaceInferableTemplates($parameter->getType(), $site, $templates, $constraints);
$constraints = $this->observeArgument($constraints, $parameterType, $argumentType);
}
return $constraints;
}
/**
* Replaces the call's own template types by markers of the call site. A
* marker behaves as its delegate (mixed for a bare @template), so a naked
* marker absorbs the siblings its delegate covers: T|null becomes the marker,
* which is what links Collection<T|null> to a Collection<unresolved> argument.
* A sibling that itself carries a marker of the call is kept next to the
* naked one instead - Foo<T>|T has to keep both members for the argument to
* be matched against Foo<T> first.
*/
private function replaceInferableTemplates(Type $type, Expr $site, TemplateTypeMap $templates, TemplateArgumentConstraints &$constraints): Type
{
// a template with a union bound is a union too - it is a template first
if ($type instanceof UnionType && !$type instanceof TemplateType) {
$naked = [];
$structural = [];
$members = [];
foreach ($type->getTypes() as $member) {
$member = $this->replaceInferableTemplates($member, $site, $templates, $constraints);
$members[] = $member;
if ($member instanceof UnresolvedTemplateArgumentType) {
$naked[] = $member;
} elseif ($this->containsMarker($member)) {
$structural[] = $member;
}
}
if ($naked === []) {
return TypeCombinator::union(...$members);
}
if ($structural === []) {
// a union keeps markers apart from everything else (see
// TypeCombinator::union()) - the absorption is this method's own
return TypeCombinator::union(...array_filter($members, static function (Type $member) use ($naked): bool {
if ($member instanceof UnresolvedTemplateArgumentType) {
return true;
}
foreach ($naked as $marker) {
if ($marker->getDelegate()->isSuperTypeOf($member)->yes()) {
return false;
}
}
return true;
}));
}
return new UnionType([...$naked, ...$structural]);
}
return TypeTraverser::map($type, function (Type $type, callable $traverse) use ($site, $templates, &$constraints): Type {
if ($type instanceof UnionType && !$type instanceof TemplateType) {
return $this->replaceInferableTemplates($type, $site, $templates, $constraints);
}
if (!$type instanceof TemplateType || $type->isArgument()) {
return $traverse($type);
}
$template = $templates->getType($type->getName());
if (!$template instanceof TemplateType || !$template->getScope()->equals($type->getScope())) {
return $type;
}
$marker = new UnresolvedTemplateArgumentType($site, $type, null);
$constraints = $constraints->withSite($marker);
return $marker;
});
}
/**
* $actual flows into $declared: a property's writable type, a parameter
* type, a declared return type, a @var type.
*/
private function observeSend(TemplateArgumentConstraints $constraints, Type $declared, Type $actual, bool $isCallArgument = false): TemplateArgumentConstraints
{
if ($declared instanceof TemplateType || !$this->containsMarker($actual)) {
return $constraints;
}
if ($isCallArgument && $declared instanceof MixedType) {
foreach ($this->collectSites($actual)->getFacts() as [$marker]) {
$constraints = $constraints->withUnconstrainingSend($marker);
}
return $constraints;
}
if ($actual instanceof UnionType) {
foreach ($actual->getTypes() as $member) {
$constraints = $this->observeSend($constraints, $declared, $member, $isCallArgument);
}
return $constraints;
}
if ($declared instanceof UnionType) {
foreach ($declared->getTypes() as $member) {
$constraints = $this->observeSend($constraints, $member, $actual, $isCallArgument);
}
return $constraints;
}
if ($actual instanceof UnresolvedTemplateArgumentType) {
// a bare marker is a derived value (Foo<T>::get()) and never constrains
return $constraints;
}
if ($actual instanceof NeverType) {
// never holds no markers, and is its own iterable key and value type
return $constraints;
}
if ($declared instanceof ObjectShapeType) {
return $this->observeObjectShapeSend($constraints, $declared, $actual, $isCallArgument);
}
if ($declared instanceof IntersectionType) {
// object{...}&Foo - the shape's properties are bounds next to Foo's arguments
foreach ($declared->getTypes() as $member) {
if (!$member instanceof ObjectShapeType) {
continue;
}
$constraints = $this->observeObjectShapeSend($constraints, $member, $actual, $isCallArgument);
}
}
$actualReflections = $actual->getObjectClassReflections();
if (count($actualReflections) === 1) {
$declaredReflections = $declared->getObjectClassReflections();
if (count($declaredReflections) !== 1) {
return $constraints;
}
$declaredReflection = $declaredReflections[0];
// the declared type names an ancestor: its arguments map onto the
// object's through @extends/@implements
$ancestor = $actualReflections[0]->getAncestorWithClassName($declaredReflection->getName());
if ($ancestor === null || !$ancestor->isGeneric()) {
return $constraints;
}
$templates = $ancestor->typeMapToList($ancestor->getTemplateTypeMap());
// Omitted arguments are not explicit constraints to widen to the bounds.
$declaredArguments = $declaredReflection->typeMapToList($declaredReflection->getPossiblyIncompleteActiveTemplateTypeMap());
$declaredVariances = $declaredReflection->getCallSiteVarianceMap();
foreach ($ancestor->typeMapToList($ancestor->getActiveTemplateTypeMap()) as $i => $argument) {
$template = $templates[$i] ?? null;
if (!$template instanceof TemplateType || !isset($declaredArguments[$i])) {
continue;
}
$callSiteVariance = $declaredVariances->getVariance($template->getName()) ?? TemplateTypeVariance::createInvariant();
$effectiveVariance = $callSiteVariance->invariant() ? $template->getVariance() : $callSiteVariance;
$constraints = $this->observeArgumentSend($constraints, $declaredArguments[$i], $argument, $effectiveVariance, $isCallArgument);
}
return $constraints;
}
if (count($actualReflections) > 0 || $actual->isObject()->yes()) {
return $constraints;
}
if (!$actual->isIterable()->yes() || !$declared->isIterable()->yes()) {
return $constraints;
}
// the key and value types of a large constant array are the unions of
// all its keys and values - not built for a target they cannot constrain
$declaredKeyType = $declared->getIterableKeyType();
if (!self::isInertSendTarget($declaredKeyType, $isCallArgument)) {
$constraints = $this->observeSend($constraints, $declaredKeyType, $actual->getIterableKeyType(), $isCallArgument);
}
$declaredValueType = $declared->getIterableValueType();
if (!self::isInertSendTarget($declaredValueType, $isCallArgument)) {
$constraints = $this->observeSend($constraints, $declaredValueType, $actual->getIterableValueType(), $isCallArgument);
}
return $constraints;
}
/**
* Each property of the object flows into the declared property of the shape
* (`(object) ['x' => new Foo(1)]` returned as `object{x: Foo<int>}`).
*/
private function observeObjectShapeSend(TemplateArgumentConstraints $constraints, ObjectShapeType $declared, Type $actual, bool $isCallArgument): TemplateArgumentConstraints
{
if (!$actual->isObject()->yes()) {
return $constraints;
}
$scope = new OutOfClassScope();
foreach ($declared->getProperties() as $name => $declaredPropertyType) {
$name = (string) $name;
if (!$actual->hasInstanceProperty($name)->yes()) {
continue;
}
try {
$actualProperty = $actual->getInstanceProperty($name, $scope);
} catch (MissingPropertyFromReflectionException) {
continue;
}
if (!$actualProperty->isPublic() || $actualProperty->isStatic()) {
continue;
}
$constraints = $this->observeSend($constraints, $declaredPropertyType, $actualProperty->getReadableType(), $isCallArgument);
}
return $constraints;
}
/**
* A template argument of an object sent to the declared argument at the same
* position. A union of several sites' markers (Box<T|U> of zip(of(1), of(2)))
* is split like Hack splits (#1 | #2) <: int: every marker in it gets the
* declared argument as an upper bound. Something flowing into the union does
* not split, so a contravariant send reaches only a lone marker.
*/
private function observeArgumentSend(TemplateArgumentConstraints $constraints, Type $declaredArgument, Type $argument, TemplateTypeVariance $variance, bool $isCallArgument): TemplateArgumentConstraints
{
if ($argument instanceof UnresolvedTemplateArgumentType && !$argument->isClosureSignature()) {
return $this->observeMarkerSend($constraints, $declaredArgument, $argument, $variance, $isCallArgument);
}
if (!$argument instanceof UnionType || $argument instanceof TemplateType) {
return $this->observeSend($constraints, $declaredArgument, $argument, $isCallArgument);
}
$upperBound = $variance->invariant() || $variance->covariant() ? TemplateTypeVariance::createCovariant() : null;
foreach ($argument->getTypes() as $member) {
if (!$member instanceof UnresolvedTemplateArgumentType || $member->isClosureSignature()) {
$constraints = $this->observeSend($constraints, $declaredArgument, $member, $isCallArgument);
continue;
}
if ($upperBound === null) {
continue;
}
$constraints = $this->observeMarkerSend($constraints, $declaredArgument, $member, $upperBound, $isCallArgument);
}
return $constraints;
}
private function observeMarkerSend(TemplateArgumentConstraints $constraints, Type $declaredArgument, UnresolvedTemplateArgumentType $marker, TemplateTypeVariance $variance, bool $isCallArgument): TemplateArgumentConstraints
{
$initial = $marker->getInitialType();
if (
$isCallArgument
&& ($initial === null || $initial instanceof NeverType)
&& self::hasOnlyInferableTemplates($declaredArgument)
) {
$declaredArgument = TemplateTypeHelper::resolveToDefaults($declaredArgument);
}
if (self::isUninformativeSendTarget($declaredArgument)) {
// An unresolved call parameter, like mixed, uses the object without
// constraining it. Return/property templates are fixed by their
// declaration and must keep an empty argument compatible with them.
if (($isCallArgument && self::hasOnlyInferableTemplates($declaredArgument)) || ($declaredArgument instanceof MixedType && !$declaredArgument instanceof TemplateType)) {
$constraints = $constraints->withUnconstrainingSend($marker);
}
return $constraints;
}
$constraints = $constraints->withSend($marker, $declaredArgument, $variance);
if ($initial === null) {
return $constraints;
}
// a site whose inferred argument itself carries markers: nested in objects
// (wrap(new Foo(1))), or bare as the sites it was inferred from
// (collect(of(1), of(2)) returning Coll<U>) - an upper bound of the site
// bounds those from above too
return $this->observeArgumentSend($constraints, $declaredArgument, $initial, $variance, $isCallArgument);
}
/**
* observeSend() observes nothing sent to plain mixed outside a call
* argument: a union recurses into its members, a bare marker never
* constrains, mixed names no class and is not certainly iterable.
*/
private static function isInertSendTarget(Type $declared, bool $isCallArgument): bool
{
return !$isCallArgument && $declared instanceof MixedType && !$declared instanceof TemplateType;
}
/**
* An argument was passed to a parameter: the argument's markers are sent to
* the parameter type, and a parameter type carrying the receiver's markers
* (add(T $x) on Foo<unresolved>) puts the argument as a lower bound on them.
*/
private function observeArgument(TemplateArgumentConstraints $constraints, Type $parameterType, Type $argumentType): TemplateArgumentConstraints
{
$constraints = $this->observeSend($constraints, $parameterType, $argumentType, true);
$constraints = $this->observeLowerBound($constraints, $parameterType, $argumentType);
return $constraints;
}
private function observeLowerBound(TemplateArgumentConstraints $constraints, Type $parameterType, Type $argumentType): TemplateArgumentConstraints
{
if (!$this->containsMarker($parameterType)) {
return $constraints;
}
if ($parameterType instanceof UnresolvedTemplateArgumentType) {
$constraints = $constraints->withLowerBound($parameterType, $argumentType);
return $constraints;
}
if ($parameterType instanceof NeverType) {
// never is its own iterable key and value type
return $constraints;
}
if ($parameterType instanceof TemplateType || $parameterType->isCallable()->yes()) {
// callable parameters put the template in a contravariant position:
// what they say about it is an upper bound, not something flowing in
return $constraints;
}
if ($parameterType instanceof UnionType) {
// Mirrors UnionType::inferTemplateTypes(): an argument member that a
// sibling takes - a marker-free member accepting it, or a member
// carrying the call's markers matching it structurally (Foo<T> for a
// Foo<X>) - does not flow into a naked marker next to it. T|Foo<T>
// receiving Foo<X> binds T to X, not to Foo<X> as well.
$argumentMembers = $argumentType instanceof UnionType ? $argumentType->getTypes() : [$argumentType];
foreach ($argumentMembers as $argumentMember) {
$taken = false;
foreach ($parameterType->getTypes() as $member) {
if ($member instanceof UnresolvedTemplateArgumentType) {
continue;
}
if (!$this->containsMarker($member)) {
if ($member->isSuperTypeOf($argumentMember)->yes()) {
$taken = true;
}
continue;
}
$before = $constraints;
$constraints = $this->observeLowerBound($constraints, $member, $argumentMember);
if ($constraints === $before) {
continue;
}
$taken = true;
}
if ($taken) {
continue;
}
foreach ($parameterType->getTypes() as $member) {
if (!$member instanceof UnresolvedTemplateArgumentType) {
continue;
}
$constraints = $this->observeLowerBound($constraints, $member, $argumentMember);
}
}
return $constraints;
}
if ($argumentType instanceof UnionType) {
foreach ($argumentType->getTypes() as $member) {
$constraints = $this->observeLowerBound($constraints, $parameterType, $member);
}
return $constraints;
}
$parameterReflections = $parameterType->getObjectClassReflections();
if (count($parameterReflections) === 1) {
$parameterReflection = $parameterReflections[0];
if (!$parameterReflection->isGeneric()) {
return $constraints;
}
$argumentReflections = $argumentType->getObjectClassReflections();
if (count($argumentReflections) !== 1) {
return $constraints;
}
$ancestor = $argumentReflections[0]->getAncestorWithClassName($parameterReflection->getName());
if ($ancestor === null) {
return $constraints;
}
$ancestorArguments = $ancestor->typeMapToList($ancestor->getActiveTemplateTypeMap());
foreach ($parameterReflection->typeMapToList($parameterReflection->getActiveTemplateTypeMap()) as $i => $parameterArgument) {
if (!isset($ancestorArguments[$i])) {
continue;
}
if ($parameterArgument instanceof UnresolvedTemplateArgumentType) {
$template = $parameterReflection->typeMapToList($parameterReflection->getTemplateTypeMap())[$i] ?? null;
if ($template instanceof TemplateType) {
$variance = $parameterReflection->getCallSiteVarianceMap()->getVariance($template->getName()) ?? TemplateTypeVariance::createInvariant();
$variance = $variance->invariant() ? $template->getVariance() : $variance;
if ($variance->invariant()) {
$constraints = $constraints->withSend($parameterArgument, $ancestorArguments[$i], $variance);
continue;
}
if ($variance->contravariant()) {
$constraints = $constraints->withSend($parameterArgument, $ancestorArguments[$i], TemplateTypeVariance::createCovariant());
continue;
}
if ($variance->bivariant()) {
continue;
}
}
}
$constraints = $this->observeLowerBound($constraints, $parameterArgument, $ancestorArguments[$i]);
}
return $constraints;
}
if (count($parameterReflections) > 0 || $parameterType->isObject()->yes()) {
return $constraints;
}
if (!$parameterType->isIterable()->yes() || !$argumentType->isIterable()->yes()) {
return $constraints;
}
$constraints = $this->observeLowerBound($constraints, $parameterType->getIterableKeyType(), $argumentType->getIterableKeyType());
$constraints = $this->observeLowerBound($constraints, $parameterType->getIterableValueType(), $argumentType->getIterableValueType());
return $constraints;
}
private static function isUninformativeSendTarget(Type $declaredArgument): bool
{
// Foo<mixed> accepts every Foo<X> (TemplateTypeVariance::isValidVariance)
// and a declared argument with unresolved template types is no target yet
return ($declaredArgument instanceof MixedType && !$declaredArgument instanceof TemplateType)
|| $declaredArgument->hasTemplateOrLateResolvableType();
}
private static function hasOnlyInferableTemplates(Type $type): bool
{
$references = $type->getReferencedTemplateTypes(TemplateTypeVariance::createInvariant());
foreach ($references as $reference) {
if ($reference->getType()->isArgument()) {
return false;
}
}
return count($references) > 0;
}
}