Repository navigation
Expand file tree
/
Copy pathClosureSignatureInference.php
More file actions
1209 lines (1095 loc) · 36.8 KB
/
Copy pathClosureSignatureInference.php
File metadata and controls
1209 lines (1095 loc) · 36.8 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
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\Generics;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrowFunction;
use PhpParser\Node\Expr\Closure;
use PHPStan\Analyser\ExpressionResultStorage;
use PHPStan\Analyser\MutatingScope;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Reflection\Native\NativeParameterReflection;
use PHPStan\Reflection\PassedByReference;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\ClosureType;
use PHPStan\Type\Generic\TemplateTypeFactory;
use PHPStan\Type\Generic\TemplateTypeScope;
use PHPStan\Type\Generic\TemplateTypeVariance;
use PHPStan\Type\Generic\UnresolvedTemplateArgumentType;
use PHPStan\Type\MixedType;
use PHPStan\Type\NullType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeTraverser;
use PHPStan\Type\UnionType;
use function array_keys;
use function array_pop;
use function count;
use function in_array;
use function is_array;
use function is_string;
use function spl_object_id;
use function str_starts_with;
use function strlen;
use function substr;
/**
* Infers the signature of a closure or an arrow function written where nothing
* types it - assigned to a variable, put in an array - from where its value goes
* in the rest of the enclosing body: the arguments it is invoked with and the
* callable types it is sent to (parameters, returns, typed properties, @var).
*
* During the observation pass of the body (see
* StatementsHandler::processBodyStmtNodesTwoPass()) the closure's ClosureType
* carries a marker per parameter - an UnresolvedTemplateArgumentType whose site
* is the closure node and whose delegate is the declared parameter type - so
* the value can be followed through variables, arrays and unions by its type.
* Invocations put their arguments as lower bounds on the markers, callable send
* targets put their parameter types as lower bounds and their return type as an
* upper bound on the return marker. The body itself is walked with the declared
* types, exactly as without the inference.
*
* The second pass walks the body with the resolved parameter types (intersected
* with the declared ones, as for a closure passed straight to a callable
* parameter) and gives returned expressions the resolved return bound as their
* expected type.
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/ClosureSignatureInference.cpp')]
final class ClosureSignatureInference
{
public const RETURN_TEMPLATE_NAME = '@return';
/**
* A by-ref use `&$x` of a closure whose effects apply where it is invoked:
* its marker's lower bounds are the types of `$x` at the invocations.
*/
private const BY_REF_TEMPLATE_PREFIX = '&';
/**
* The type a by-ref variable `$x` had at an invocation in the second pass -
* kept apart from the observation's `&$x` facts, which a replayed statement's
* recorded scope still carries.
*/
private const ENTRY_TEMPLATE_PREFIX = '~';
/** A call invoking such a closure - its statement is walked again in the second pass. */
private const INVOCATION_TEMPLATE_NAME = '@invokes';
private const BY_REF_USES_ATTRIBUTE = 'closureSignatureByRefUses';
private const ARROW_FUNCTION_OUTER_VARIABLES_ATTRIBUTE = 'closureSignatureArrowFunctionOuterVariables';
private const CLOSED_BODY_ATTRIBUTE = 'closureSignatureClosedBody';
private const ASSIGNED_CLOSURES_ATTRIBUTE = 'closureSignatureAssignedClosures';
private const REBOUND_VARIABLES_ATTRIBUTE = 'closureSignatureReboundVariables';
public function __construct(
#[AutowiredParameter(ref: '%featureToggles.closureSignaturesFromUsages%')]
private bool $enabled,
)
{
}
public static function isClosureSignatureMarker(UnresolvedTemplateArgumentType $marker): bool
{
$site = $marker->getSite();
return $site instanceof Closure || $site instanceof ArrowFunction;
}
public static function isReturnMarker(UnresolvedTemplateArgumentType $marker): bool
{
return $marker->getTemplateName() === self::RETURN_TEMPLATE_NAME && self::isClosureSignatureMarker($marker);
}
public static function isByRefMarker(UnresolvedTemplateArgumentType $marker): bool
{
return str_starts_with($marker->getTemplateName(), self::BY_REF_TEMPLATE_PREFIX) && $marker->getSite() instanceof Closure;
}
/**
* The markers of the by-ref uses of a closure written where nothing types it,
* by variable name - while observing, and in the second pass for a site the
* observation resolved. Empty for a closure whose invocations cannot be
* followed: a generator (invoking it does not run the body), a closure
* invoking its own by-ref variable.
*
* @return array<string, Type>
*/
public function getByRefUseMarkers(MutatingScope $scope, Closure|ArrowFunction $expr): array
{
if (!$expr instanceof Closure) {
return [];
}
$names = self::byRefUseNames($expr);
if ($names === []) {
return [];
}
$frame = $this->getFrame($scope);
if ($frame === null) {
return [];
}
if (!$frame->isObservingClosures() && $frame->getByRefSiteMode($expr) === null) {
return [];
}
$body = $frame->getClosureSignatureBody();
if ($body === null) {
return [];
}
$reboundNames = self::getReboundVariableNames($body, $frame->getClosureSignatureStmts());
foreach ($names as $name) {
// unset or bound to another reference, the variable no longer is the
// one the closure writes to - its effects stay the creation-time fixpoint
if (isset($reboundNames[$name])) {
return [];
}
}
$markers = [];
foreach ($names as $name) {
$markers[$name] = new UnresolvedTemplateArgumentType(
$expr,
TemplateTypeFactory::create(TemplateTypeScope::createWithAnonymousFunction(), self::BY_REF_TEMPLATE_PREFIX . $name, null, TemplateTypeVariance::createCovariant()),
$scope->hasVariableType($name)->yes() ? $scope->getVariableType($name) : new NullType(),
);
}
return $markers;
}
/**
* How the second pass treats the by-ref uses of the closure: `local` when
* every invocation was seen, `escaped` when its value went where it can be
* invoked at any time, null when the by-ref uses keep the creation-time
* fixpoint (no observation, or observing right now).
*
* @return 'local'|'escaped'|null
*/
public function getByRefSiteMode(MutatingScope $scope, Closure $expr): ?string
{
$frame = $this->getFrame($scope);
if ($frame === null || $frame->isObservingClosures()) {
return null;
}
return $frame->getByRefSiteMode($expr);
}
/**
* Where the fixpoint of an escaped closure's by-ref variable starts: the
* state it was created in joined with every state it was invoked from.
*/
public function getByRefSeed(MutatingScope $scope, Closure $expr, string $name): ?Type
{
$frame = $this->getFrame($scope);
if ($frame === null || $frame->isObservingClosures()) {
return null;
}
return $frame->resolve($expr, self::BY_REF_TEMPLATE_PREFIX . $name);
}
/**
* The scope the closure was created in, when the invocation runs in the
* same walk of the same function-like - the only place its by-ref
* variables are the ones the scope tracks. Its by-value uses enter the
* invoked body as they were there.
*/
public static function findCreationScope(MutatingScope $scope, ExpressionResultStorage $storage, Closure $expr): ?MutatingScope
{
$creationResult = $storage->findExpressionResult($expr);
if ($creationResult === null) {
return null;
}
$creationScope = $creationResult->getBeforeScope();
if (
$creationScope->getAnonymousFunctionReflection() !== $scope->getAnonymousFunctionReflection()
|| $creationScope->getFunction() !== $scope->getFunction()
) {
return null;
}
return $creationScope;
}
/**
* A value captured by another function-like - a closure's use, an arrow
* function's outer variable: the closures it carries can be invoked when
* that one runs, so their by-ref uses keep the creation-time fixpoint.
*/
public static function collectCaptureEscapes(Type $type): TemplateArgumentConstraints
{
$constraints = TemplateArgumentConstraints::createEmpty();
TypeTraverser::map($type, static function (Type $type, callable $traverse) use (&$constraints): Type {
if ($type instanceof ClosureType) {
foreach ($type->getByRefUseTypes() as $marker) {
if (!$marker instanceof UnresolvedTemplateArgumentType) {
continue;
}
$constraints = $constraints->withUnconstrainingSend($marker);
}
}
return $traverse($type);
});
return $constraints;
}
/**
* The closures in $type go where nothing describes how they are invoked:
* their parameters keep the declared types, their returned closures are
* typed by nothing and their by-ref uses keep the creation-time fixpoint.
*/
public static function collectEscapes(Type $type): TemplateArgumentConstraints
{
$constraints = TemplateArgumentConstraints::createEmpty();
foreach (self::collectMarkers($type) as $marker) {
$constraints = $constraints->withUnconstrainingSend($marker);
}
return $constraints;
}
/**
* The callee of a call: a closure written where nothing types it learns its
* arguments through the call's parameters, but the value it returns goes
* where nothing follows it. A closure carried by any other callee - the
* object of an array callable - is invoked as nothing describes.
*/
public static function collectInvokedCallee(Type $calleeType): TemplateArgumentConstraints
{
$constraints = TemplateArgumentConstraints::createEmpty();
foreach ($calleeType instanceof UnionType ? $calleeType->getTypes() : [$calleeType] as $member) {
if (!$member instanceof ClosureType) {
$constraints = $constraints->merge(self::collectEscapes($member));
continue;
}
$returnType = $member->getReturnType();
if (!$returnType instanceof UnresolvedTemplateArgumentType || !self::isReturnMarker($returnType)) {
continue;
}
$constraints = $constraints->withUnconstrainingSend($returnType);
}
return $constraints;
}
/**
* $input was merged into $result - two branches of a variable, the arms of
* a ternary, a value written into an array. A union absorbs a closure into a
* wider member (Closure, callable, mixed, a closure with declared
* parameters): nothing follows the closures whose markers $result lost, so
* they escape.
*/
public static function collectAbsorbed(Type $input, Type $result): TemplateArgumentConstraints
{
return self::collectAbsorbedInto([$input], $result);
}
/**
* The values of $inputs merged into $result - the items of an array
* literal, the members of a union. See collectAbsorbed(). The markers
* $result kept are collected once for all of them: a large literal of
* closure-carrying items would otherwise traverse the whole array type
* once per item.
*
* @param list<Type> $inputs
*/
public static function collectAbsorbedInto(array $inputs, Type $result): TemplateArgumentConstraints
{
$constraints = TemplateArgumentConstraints::createEmpty();
$kept = null;
foreach ($inputs as $input) {
if ($input === $result) {
continue;
}
$markers = self::collectMarkers($input);
if ($markers === []) {
continue;
}
$kept ??= self::collectMarkers($result);
foreach ($markers as $key => $marker) {
if (isset($kept[$key])) {
continue;
}
$constraints = $constraints->withUnconstrainingSend($marker);
}
}
return $constraints;
}
/**
* The values of $types merged into their union - the branches of a ternary,
* of `??`, the arms of a match. See collectAbsorbed().
*
* @param list<Type> $types
*/
public static function collectAbsorbedInUnion(array $types): TemplateArgumentConstraints
{
$constraints = TemplateArgumentConstraints::createEmpty();
$carriesMarkers = false;
foreach ($types as $type) {
if (!self::hasMarkers($type)) {
continue;
}
$carriesMarkers = true;
break;
}
if (!$carriesMarkers) {
return $constraints;
}
return self::collectAbsorbedInto($types, TypeCombinator::union(...$types));
}
/** Whether $type carries a closure written where nothing types it. */
public static function hasMarkers(Type $type): bool
{
return self::collectMarkers($type) !== [];
}
/**
* The markers of the closures written where nothing types them in $type -
* of their parameters, returns and by-ref uses - keyed by site and name.
*
* @return array<string, UnresolvedTemplateArgumentType>
*/
private static function collectMarkers(Type $type): array
{
$markers = [];
TypeTraverser::map($type, static function (Type $type, callable $traverse) use (&$markers): Type {
if ($type instanceof ClosureType) {
foreach ($type->getByRefUseTypes() as $marker) {
if (!$marker instanceof UnresolvedTemplateArgumentType) {
continue;
}
$markers[spl_object_id($marker->getSite()) . '#' . $marker->getTemplateName()] = $marker;
}
}
if ($type instanceof UnresolvedTemplateArgumentType) {
if (self::isClosureSignatureMarker($type)) {
$markers[spl_object_id($type->getSite()) . '#' . $type->getTemplateName()] = $type;
}
$initial = $type->getInitialType();
if ($initial !== null) {
$traverse($initial);
}
return $type;
}
return $traverse($type);
});
return $markers;
}
/**
* An invocation of the closure: the type of every by-ref variable at the
* call joins the variable's entry, and while observing, the call becomes a
* site so the second pass walks its statement again.
*/
public static function collectInvocation(MutatingScope $scope, Expr $call, ClosureType $closureType, bool $observing): TemplateArgumentConstraints
{
$constraints = TemplateArgumentConstraints::createEmpty();
if ($observing) {
$constraints = $constraints->withSite(new UnresolvedTemplateArgumentType(
$call,
TemplateTypeFactory::create(TemplateTypeScope::createWithAnonymousFunction(), self::INVOCATION_TEMPLATE_NAME, null, TemplateTypeVariance::createInvariant()),
null,
));
}
foreach ($closureType->getByRefUseTypes() as $name => $marker) {
if (!$marker instanceof UnresolvedTemplateArgumentType) {
continue;
}
$type = $scope->hasVariableType($name)->yes() ? $scope->getVariableType($name) : new NullType();
if ($observing) {
$constraints = $constraints->withLowerBound($marker, $type);
continue;
}
$constraints = $constraints->withLowerBound(
new UnresolvedTemplateArgumentType($marker->getSite(), TemplateTypeFactory::create(TemplateTypeScope::createWithAnonymousFunction(), self::ENTRY_TEMPLATE_PREFIX . $name, null, TemplateTypeVariance::createInvariant()), null),
$type,
);
}
return $constraints;
}
/**
* The types the by-ref variables of closures had at their second-pass
* invocations reaching the scope, by spl_object_id() of the closure and
* variable name.
*
* @return array<int, array<string, Type>>
*/
public static function collectByRefEntryTypes(MutatingScope $scope): array
{
$constraints = $scope->getTemplateArgumentConstraints();
if ($constraints === null) {
return [];
}
$types = [];
foreach ($constraints->getFacts() as [$marker, $type]) {
if ($type === null || !str_starts_with($marker->getTemplateName(), self::ENTRY_TEMPLATE_PREFIX)) {
continue;
}
$site = $marker->getSite();
if (!$site instanceof Closure) {
continue;
}
$id = spl_object_id($site);
$name = substr($marker->getTemplateName(), strlen(self::ENTRY_TEMPLATE_PREFIX));
$types[$id][$name] = isset($types[$id][$name]) ? TypeCombinator::union($types[$id][$name], $type) : $type;
}
return $types;
}
/**
* The variables of the enclosing scope an arrow function captures - every
* variable its body mentions that is not its own parameter.
*
* @return array<int, string>
*/
public static function getArrowFunctionOuterVariables(ArrowFunction $expr): array
{
$cached = $expr->getAttribute(self::ARROW_FUNCTION_OUTER_VARIABLES_ATTRIBUTE);
if (is_array($cached)) {
return $cached;
}
$parameters = [];
foreach ($expr->params as $param) {
if (!$param->var instanceof Expr\Variable || !is_string($param->var->name)) {
continue;
}
$parameters[$param->var->name] = true;
}
$names = [];
$stack = [$expr->expr];
while (count($stack) > 0) {
$node = array_pop($stack);
if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassLike) {
continue;
}
if ($node instanceof Closure) {
// a closure captures through its use clause only
foreach ($node->uses as $use) {
$stack[] = $use->var;
}
continue;
}
if ($node instanceof Expr\Variable && is_string($node->name) && !isset($parameters[$node->name]) && $node->name !== 'this') {
$names[$node->name] = true;
}
foreach ($node->getSubNodeNames() as $subNodeName) {
$subNode = $node->$subNodeName;
if ($subNode instanceof Node) {
$stack[] = $subNode;
} elseif (is_array($subNode)) {
foreach ($subNode as $item) {
if (!$item instanceof Node) {
continue;
}
$stack[] = $item;
}
}
}
}
$names = array_keys($names);
$expr->setAttribute(self::ARROW_FUNCTION_OUTER_VARIABLES_ATTRIBUTE, $names);
return $names;
}
/**
* The names of the closure's by-ref uses whose invocations can be followed;
* empty for a generator or a closure invoking one of its own by-ref variables.
*
* @return array<int, string>
*/
private static function byRefUseNames(Closure $expr): array
{
$cached = $expr->getAttribute(self::BY_REF_USES_ATTRIBUTE);
if (is_array($cached)) {
return $cached;
}
$names = [];
foreach ($expr->uses as $use) {
if (!$use->byRef || !is_string($use->var->name)) {
continue;
}
$names[] = $use->var->name;
}
if ($names !== [] && self::bodyYieldsOrInvokes($expr->stmts, $names)) {
$names = [];
}
$expr->setAttribute(self::BY_REF_USES_ATTRIBUTE, $names);
return $names;
}
/**
* @param Node\Stmt[] $stmts
* @param array<int, string> $names
*/
private static function bodyYieldsOrInvokes(array $stmts, array $names): bool
{
$stack = $stmts;
// closures and arrow functions written in the body: their yields are
// their own, but they can invoke the variables on the body's behalf
$nestedStack = [];
while (count($stack) > 0 || count($nestedStack) > 0) {
$nested = count($stack) === 0;
$node = $nested ? array_pop($nestedStack) : array_pop($stack);
if (!$nested && ($node instanceof Closure || $node instanceof ArrowFunction)) {
$nestedStack[] = $node;
continue;
}
if (
($node instanceof Node\FunctionLike && !$node instanceof Closure && !$node instanceof ArrowFunction)
|| $node instanceof Node\Stmt\ClassLike
) {
continue;
}
if (!$nested && ($node instanceof Expr\Yield_ || $node instanceof Expr\YieldFrom)) {
return true;
}
if (
$node instanceof Expr\FuncCall
&& $node->name instanceof Expr\Variable
&& is_string($node->name->name)
&& in_array($node->name->name, $names, true)
) {
return true;
}
foreach ($node->getSubNodeNames() as $subNodeName) {
$subNode = $node->$subNodeName;
$subNodes = is_array($subNode) ? $subNode : [$subNode];
foreach ($subNodes as $item) {
if (!$item instanceof Node) {
continue;
}
if ($nested) {
$nestedStack[] = $item;
} else {
$stack[] = $item;
}
}
}
}
return false;
}
/**
* The variables the body unsets or binds to another reference - `unset()`,
* `=&`, a by-reference foreach value or destructuring, `static`, `global`.
* A by-ref use of such a variable may no longer share its value with the
* body's variable where the closure is invoked.
*
* @param Node\Stmt[] $stmts
* @return array<string, true>
*/
private static function getReboundVariableNames(Node $body, array $stmts): array
{
/** @var array<string, true>|null $cached */
$cached = $body->getAttribute(self::REBOUND_VARIABLES_ATTRIBUTE);
if ($cached !== null) {
return $cached;
}
$names = [];
$stack = $stmts;
while (count($stack) > 0) {
$node = array_pop($stack);
if ($node instanceof Node\FunctionLike || $node instanceof Node\Stmt\ClassLike) {
continue;
}
if ($node instanceof Node\Stmt\Unset_) {
foreach ($node->vars as $var) {
self::collectVariableName($var, $names);
}
} elseif ($node instanceof Expr\AssignRef) {
self::collectVariableName($node->var, $names);
} elseif ($node instanceof Node\Stmt\Foreach_) {
if ($node->byRef) {
self::collectVariableName($node->valueVar, $names);
}
self::collectByRefItemNames($node->valueVar, $names);
} elseif ($node instanceof Expr\Assign) {
self::collectByRefItemNames($node->var, $names);
} elseif ($node instanceof Node\Stmt\Static_) {
foreach ($node->vars as $staticVar) {
self::collectVariableName($staticVar->var, $names);
}
} elseif ($node instanceof Node\Stmt\Global_) {
foreach ($node->vars as $var) {
self::collectVariableName($var, $names);
}
}
foreach ($node->getSubNodeNames() as $subNodeName) {
$subNode = $node->$subNodeName;
if ($subNode instanceof Node) {
$stack[] = $subNode;
} elseif (is_array($subNode)) {
foreach ($subNode as $item) {
if (!$item instanceof Node) {
continue;
}
$stack[] = $item;
}
}
}
}
$body->setAttribute(self::REBOUND_VARIABLES_ATTRIBUTE, $names);
return $names;
}
/**
* @param array<string, true> $names
*/
private static function collectVariableName(Node $node, array &$names): void
{
if (!$node instanceof Expr\Variable || !is_string($node->name)) {
return;
}
$names[$node->name] = true;
}
/**
* The variables a destructuring target binds by reference: `[&$x] = ...`.
*
* @param array<string, true> $names
*/
private static function collectByRefItemNames(Expr $target, array &$names): void
{
if (!$target instanceof Expr\List_ && !$target instanceof Expr\Array_) {
return;
}
foreach ($target->items as $item) {
if ($item === null) {
continue;
}
if ($item->byRef) {
self::collectVariableName($item->value, $names);
continue;
}
self::collectByRefItemNames($item->value, $names);
}
}
/** @return non-empty-string */
private static function parameterTemplateName(string $parameterName): string
{
return '$' . $parameterName;
}
/**
* The frame the closure's signature is inferred under - null when the
* inference is off, the closure is not inside an analysed body, or it has
* a context of its own (see ContextualClosureParameterResolver::hasContext()).
*/
private function getFrame(MutatingScope $scope): ?TemplateArgumentFrame
{
if (!$this->enabled) {
return null;
}
$frame = $scope->getCurrentTemplateArgumentFrame();
if ($frame === null || !$frame->isObservingClosures()) {
return $frame;
}
// the body is scanned only once one of its closures asks
$body = $frame->getClosureSignatureBody();
if ($body === null || !$this->isClosedBody($body, $frame->getClosureSignatureStmts())) {
return null;
}
return $frame;
}
/**
* Whether the closures written where nothing types them get markers now -
* the observation pass of a body whose variables no outside code reaches.
*/
public function isObserving(MutatingScope $scope): bool
{
$frame = $this->getFrame($scope);
return $frame !== null && $frame->isObservingClosures();
}
/**
* The parameters of the closure's own ClosureType: markers while observing,
* the resolved types once resolved, the declared ones otherwise.
*
* @param list<NativeParameterReflection> $declaredParameters
* @return list<NativeParameterReflection>
*/
public function getSignatureParameters(MutatingScope $scope, Closure|ArrowFunction $expr, array $declaredParameters): array
{
$frame = $this->getFrame($scope);
if ($frame === null) {
return $declaredParameters;
}
$parameters = [];
foreach ($declaredParameters as $parameter) {
// a variadic parameter collects arguments of different positions into
// one list - spread again, one element type fits none of them
if (!$parameter->passedByReference()->no() || $parameter->isVariadic()) {
$parameters[] = $parameter;
continue;
}
if ($frame->isObservingClosures() || $frame->isSettledClosureSite($expr)) {
$type = $this->createParameterMarker($expr, $parameter);
} else {
$type = $frame->resolve($expr, self::parameterTemplateName($parameter->getName()));
if ($type === null) {
$parameters[] = $parameter;
continue;
}
}
$parameters[] = new NativeParameterReflection(
$parameter->getName(),
$parameter->isOptional(),
$type,
$parameter->passedByReference(),
$parameter->isVariadic(),
$parameter->getDefaultValue(),
);
}
return $parameters;
}
/**
* The parameter types the body is walked with in the second pass - null
* while observing or when nothing was resolved, so the body sees the
* declared types.
*
* @return list<NativeParameterReflection>|null
*/
public function getBodyParameters(MutatingScope $scope, Closure|ArrowFunction $expr): ?array
{
$frame = $this->getFrame($scope);
if ($frame === null || $frame->isObservingClosures() || $frame->isSettledClosureSite($expr)) {
return null;
}
$parameters = [];
$resolvedAny = false;
foreach ($expr->params as $param) {
if (!$param->var instanceof Expr\Variable || !is_string($param->var->name)) {
return null;
}
$type = !$param->byRef
? $frame->resolve($expr, self::parameterTemplateName($param->var->name))
: null;
if ($type !== null) {
$resolvedAny = true;
}
$parameters[] = new NativeParameterReflection(
$param->var->name,
$param->default !== null || $param->variadic,
$type ?? new MixedType(),
$param->byRef ? PassedByReference::createCreatesNewVariable() : PassedByReference::createNo(),
$param->variadic,
null,
);
}
return $resolvedAny ? $parameters : null;
}
/**
* Wraps the body-inferred return type in the return marker while observing,
* when the closure returns something whose own typing depends on its
* expected type (a closure, an arrow function, an array literal).
*/
public function getSignatureReturnType(MutatingScope $scope, Closure|ArrowFunction $expr, Type $returnType): Type
{
if ($returnType instanceof UnresolvedTemplateArgumentType) {
return $returnType;
}
$frame = $this->getFrame($scope);
if (
$frame === null
|| (!$frame->isObservingClosures() && !$frame->isSettledClosureSite($expr))
|| !self::returnsContextTypedExpression($expr)
) {
return $returnType;
}
return new UnresolvedTemplateArgumentType(
$expr,
TemplateTypeFactory::create(TemplateTypeScope::createWithAnonymousFunction(), self::RETURN_TEMPLATE_NAME, null, TemplateTypeVariance::createCovariant()),
$returnType,
);
}
/**
* The expected type of the expressions the closure returns, resolved from
* the callable types it was sent to - null when unknown.
*/
public function getExpectedReturnType(MutatingScope $scope, Closure|ArrowFunction $expr): ?Type
{
$frame = $this->getFrame($scope);
if ($frame === null || $frame->isObservingClosures()) {
return null;
}
$type = $frame->resolve($expr, self::RETURN_TEMPLATE_NAME);
if ($type === null || $type instanceof MixedType) {
return null;
}
return $type;
}
/**
* The markers a closure creates while observing, as sites of the body, plus
* the default values of its optional parameters as contravariant sends - they
* join what the closure is invoked with, but alone they say nothing about a
* closure nothing invokes.
*/
public function collectSites(MutatingScope $scope, Type $closureType): TemplateArgumentConstraints
{
$constraints = TemplateArgumentConstraints::createEmpty();
$frame = $this->getFrame($scope);
if ($frame === null || !$frame->isObservingClosures()) {
return $constraints;
}
foreach ($closureType->getCallableParametersAcceptors($scope) as $acceptor) {
foreach ($acceptor->getParameters() as $parameter) {
$marker = $parameter->getType();
if (!$marker instanceof UnresolvedTemplateArgumentType || !self::isClosureSignatureMarker($marker)) {
continue;
}
$constraints = $constraints->withSite($marker);
$default = $parameter->getDefaultValue();
if ($default === null) {
continue;
}
// an invocation can always omit it
$constraints = $constraints->withSend($marker, $default, TemplateTypeVariance::createContravariant());
}
$returnMarker = $acceptor->getReturnType();
if (!$returnMarker instanceof UnresolvedTemplateArgumentType || !self::isReturnMarker($returnMarker)) {
continue;
}
$constraints = $constraints->withSite($returnMarker);
}
if ($closureType instanceof ClosureType) {
foreach ($closureType->getByRefUseTypes() as $marker) {
if (!$marker instanceof UnresolvedTemplateArgumentType) {
continue;
}
$constraints = $constraints->withSite($marker);
}
}
return $constraints;
}
private function createParameterMarker(Closure|ArrowFunction $expr, NativeParameterReflection $parameter): UnresolvedTemplateArgumentType
{
return new UnresolvedTemplateArgumentType(
$expr,
TemplateTypeFactory::create(TemplateTypeScope::createWithAnonymousFunction(), self::parameterTemplateName($parameter->getName()), null, TemplateTypeVariance::createContravariant()),
$parameter->getType(),
);
}
private static function returnsContextTypedExpression(Closure|ArrowFunction $expr): bool
{
if ($expr instanceof ArrowFunction) {
return self::isContextTyped($expr->expr);
}
$cached = $expr->getAttribute('closureSignatureReturnsContextTyped');
if ($cached !== null) {
return $cached;
}
$returnsContextTyped = false;
$stack = $expr->stmts;
while (count($stack) > 0) {
$node = array_pop($stack);
if ($node instanceof Node\Stmt\Return_) {
if ($node->expr !== null && self::isContextTyped($node->expr)) {
$returnsContextTyped = true;
break;
}
continue;
}
if ($node instanceof Node\FunctionLike || $node instanceof Node\Stmt\ClassLike) {
continue;
}
foreach ($node->getSubNodeNames() as $subNodeName) {
$subNode = $node->$subNodeName;
if ($subNode instanceof Node) {
$stack[] = $subNode;
} elseif (is_array($subNode)) {
foreach ($subNode as $item) {
if (!$item instanceof Node) {
continue;
}
$stack[] = $item;
}
}
}
}
$expr->setAttribute('closureSignatureReturnsContextTyped', $returnsContextTyped);
return $returnsContextTyped;
}
/**
* Whether every place a closure's value can reach while the body runs is in
* the body itself. Not so when the body shares variables with code outside
* of it: `global`, `$GLOBALS`, variable variables, include/eval,
* extract()/compact()/get_defined_vars(), or a write to a variable bound by
* reference to the caller (a by-reference parameter or use). Closures and
* arrow functions inside the body are scanned too - they run on its behalf.
*
* @param Node\Stmt[] $stmts
*/
public function isClosedBody(Node $functionLike, array $stmts): bool
{
if (!$this->enabled) {
return false;
}
$cached = $functionLike->getAttribute(self::CLOSED_BODY_ATTRIBUTE);
if ($cached !== null) {
return $cached;
}
$closed = self::scanClosedBody($functionLike, $stmts);
$functionLike->setAttribute(self::CLOSED_BODY_ATTRIBUTE, $closed);
return $closed;
}
/**
* @param Node\Stmt[] $stmts
*/
private static function scanClosedBody(Node $functionLike, array $stmts): bool
{