Repository navigation
Expand file tree
/
Copy pathStatementsHandler.php
More file actions
2083 lines (1919 loc) · 76 KB
/
Copy pathStatementsHandler.php
File metadata and controls
2083 lines (1919 loc) · 76 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;
use Closure;
use PhpParser\Comment\Doc;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\AssignRef;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt\Goto_;
use PHPStan\Analyser\Generics\ClosureSignatureInference;
use PHPStan\Analyser\Generics\StaticVariableInference;
use PHPStan\Analyser\Generics\TemplateArgumentConstraints;
use PHPStan\Analyser\Generics\TemplateArgumentFrame;
use PHPStan\Analyser\Generics\TemplateArgumentObserver;
use PHPStan\Analyser\Generics\TemplateArgumentResolver;
use PHPStan\Analyser\Generics\TemplateArgumentStats;
use PHPStan\Dependency\Dependencies;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\DependencyInjection\Container;
use PHPStan\Node\ExecutionEndNode;
use PHPStan\Node\PropertyHookStatementNode;
use PHPStan\Node\UnreachableStatementNode;
use PHPStan\Node\VarTagChangedExpressionTypeNode;
use PHPStan\Node\VirtualNode;
use PHPStan\Parser\GotoLabelVisitor;
use PHPStan\PhpDoc\Tag\VarTag;
use PHPStan\TrinaryLogic;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\ClosureType;
use PHPStan\Type\ErrorType;
use PHPStan\Type\FileTypeMapper;
use PHPStan\Type\MixedType;
use PHPStan\Type\NeverType;
use PHPStan\Type\NullType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\UnionType;
use function array_column;
use function array_fill_keys;
use function array_flip;
use function array_key_exists;
use function array_keys;
use function array_merge;
use function array_slice;
use function count;
use function getenv;
use function implode;
use function in_array;
use function is_array;
use function is_int;
use function is_string;
use function min;
use function spl_object_id;
use function sprintf;
/**
* Walks statement lists for NodeScopeResolver - goto convergence, unreachable
* statements, the two-pass function-like body walk - and applies statement-level
* PHPDocs (@var, @throws). A single statement is dispatched to its StmtHandler
* by NodeScopeResolver::processStmtNode().
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/StatementsHandler.cpp')]
final class StatementsHandler
{
/** The last walk inferring the `static` variables walked a statement: [kind, recording from, recording to] */
private const STATIC_WALK_WALKED = 0;
/** It carried a statement's recorded effect over: [kind, statement index, 0] */
private const STATIC_WALK_CARRIED = 1;
/** It converged with the observation pass at a statement - the rest stands: [kind, statement index, 0] */
private const STATIC_WALK_REST = 2;
private const MENTIONED_VARIABLES_ATTRIBUTE = 'templateArgumentMentionedVariables';
/** PHPSTAN_TEMPLATE_ARGUMENTS_DEBUG=1 prints every second-pass re-walk/replay decision. */
private bool $debugTemplateArguments;
public function __construct(
private FileTypeMapper $fileTypeMapper,
private TemplateArgumentObserver $templateArgumentObserver,
private TemplateArgumentResolver $templateArgumentResolver,
private Container $container,
private StaticVariableInference $staticVariableInference,
private RedundantVarTagDetector $redundantVarTagDetector,
#[AutowiredParameter(ref: '%featureToggles.unresolvedTemplateArguments%')]
private bool $unresolvedTemplateArguments,
#[AutowiredParameter(ref: '%reportRedundantVarTag%')]
private bool $reportRedundantVarTag,
)
{
$this->debugTemplateArguments = getenv('PHPSTAN_TEMPLATE_ARGUMENTS_DEBUG') === '1';
}
/**
* @param Node[] $nodes
* @param callable(Node $node, Scope $scope): void $nodeCallback
*/
public function processNodesWithStorage(
NodeScopeResolver $nodeScopeResolver,
array $nodes,
MutatingScope $scope,
ExpressionResultStorage $expressionResultStorage,
callable $nodeCallback,
): ?Dependencies
{
$alreadyTerminated = false;
$exitPoints = [];
$dependencies = [];
$stmts = [];
$stmtToNodeIndex = [];
foreach ($nodes as $i => $node) {
if (!($node instanceof Node\Stmt)) {
continue;
}
$stmtToNodeIndex[count($stmts)] = $i;
$stmts[] = $node;
}
$dummyParent = new Node\Stmt\Nop();
foreach ($stmts as $si => $node) {
if ($alreadyTerminated && !($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassLike || $node instanceof Node\Stmt\Label)) {
continue;
}
$nestedLabelNames = $node->getAttribute(GotoLabelVisitor::NESTED_BACKWARD_GOTO_LABELS_ATTRIBUTE);
if ($nestedLabelNames !== null) {
$scope = $this->resolveBackwardGotoScope(
$nodeScopeResolver,
$dummyParent,
[$node],
$scope,
$expressionResultStorage,
StatementContext::createDeep(),
static fn (string $name): bool => isset($nestedLabelNames[$name]),
false,
);
}
$statementResult = $nodeScopeResolver->processStmtNode($node, $scope, $expressionResultStorage, $nodeCallback, StatementContext::createTopLevel());
$scope = $statementResult->getScope();
$statementDependencies = $statementResult->getDependencies();
if ($statementDependencies !== null) {
$dependencies[] = $statementDependencies;
}
if ($node instanceof Node\Stmt\Label) {
$labelName = $node->name->toString();
[$scope, $alreadyTerminated, $exitPoints] = $this->mergeForwardGotoExitPoints(
$labelName,
$scope,
$alreadyTerminated,
$exitPoints,
);
if ($alreadyTerminated) {
continue;
}
if ($node->getAttribute(GotoLabelVisitor::HAS_BACKWARD_GOTO_ATTRIBUTE) === true) {
$scope = $this->resolveBackwardGotoScope(
$nodeScopeResolver,
$dummyParent,
array_slice($stmts, $si + 1),
$scope,
$expressionResultStorage,
StatementContext::createDeep(),
static fn (string $name): bool => $name === $labelName,
true,
);
}
}
$exitPoints = array_merge($exitPoints, $statementResult->getExitPoints());
if ($alreadyTerminated || !$statementResult->isAlwaysTerminating()) {
continue;
}
$alreadyTerminated = true;
$nextStmts = $this->getNextUnreachableStatements(array_slice($nodes, $stmtToNodeIndex[$si] + 1), true);
$this->processUnreachableStatement($nodeScopeResolver, $nextStmts, $scope, $expressionResultStorage, $nodeCallback);
}
return Dependencies::merge(...$dependencies);
}
/**
* @param Node\Stmt[] $bodyStmts
* @param Closure(string): bool $gotoNameMatcher
*/
private function resolveBackwardGotoScope(
NodeScopeResolver $nodeScopeResolver,
Node $parentNode,
array $bodyStmts,
MutatingScope $scope,
ExpressionResultStorage $storage,
StatementContext $context,
Closure $gotoNameMatcher,
bool $mergeBodyScopeEachIteration,
): MutatingScope
{
$bodyScope = $scope;
$count = 0;
$prevEntryScope = null;
do {
$prevScope = $bodyScope;
if ($mergeBodyScopeEachIteration) {
$bodyScope = $bodyScope->mergeWith($scope);
}
if ($prevEntryScope !== null && $bodyScope->equals($prevEntryScope)) {
// walking is deterministic in the entry scope - an unchanged entry
// reproduces the previous pass's exit, so the verification walk is skipped
$bodyScope = $prevScope;
break;
}
$prevEntryScope = $bodyScope;
$tempStorage = $storage->duplicate();
$bodyScopeResult = $nodeScopeResolver->processStmtNodesInternal(
$parentNode,
$bodyStmts,
$bodyScope,
$tempStorage,
new NoopNodeCallback(),
$context->withoutTemplateArgumentResolution(),
);
$gotoScope = null;
foreach ($bodyScopeResult->getExitPoints() as $ep) {
$epStmt = $ep->getStatement();
if (!($epStmt instanceof Goto_) || !$gotoNameMatcher($epStmt->name->toString())) {
continue;
}
$gotoScope = $gotoScope === null ? $ep->getScope() : $gotoScope->mergeWith($ep->getScope());
}
if ($gotoScope !== null) {
$bodyScope = $scope->mergeWith($gotoScope);
}
if ($bodyScope->equals($prevScope)) {
break;
}
if ($count >= NodeScopeResolver::GENERALIZE_AFTER_ITERATION) {
$bodyScope = $prevScope->generalizeWith($bodyScope);
}
$count++;
} while ($count < NodeScopeResolver::LOOP_SCOPE_ITERATIONS);
return $bodyScope;
}
/**
* @param InternalStatementExitPoint[] $exitPoints
* @return array{MutatingScope, bool, list<InternalStatementExitPoint>}
*/
private function mergeForwardGotoExitPoints(
string $labelName,
MutatingScope $scope,
bool $alreadyTerminated,
array $exitPoints,
): array
{
$newExitPoints = [];
foreach ($exitPoints as $exitPoint) {
$exitStmt = $exitPoint->getStatement();
if ($exitStmt instanceof Goto_ && $exitStmt->name->toString() === $labelName) {
if ($alreadyTerminated) {
$scope = $exitPoint->getScope();
$alreadyTerminated = false;
} else {
$scope = $scope->mergeWith($exitPoint->getScope());
}
} else {
$newExitPoints[] = $exitPoint;
}
}
return [$scope, $alreadyTerminated, $newExitPoints];
}
/**
* @param Node\Stmt[] $nextStmts
* @param callable(Node $node, Scope $scope): void $nodeCallback
*/
private function processUnreachableStatement(NodeScopeResolver $nodeScopeResolver, array $nextStmts, MutatingScope $scope, ExpressionResultStorage $storage, callable $nodeCallback): void
{
if ($nextStmts === []) {
return;
}
$unreachableStatement = null;
$nextStatements = [];
foreach ($nextStmts as $key => $nextStmt) {
if ($key === 0) {
$unreachableStatement = $nextStmt;
continue;
}
$nextStatements[] = $nextStmt;
}
if (!$unreachableStatement instanceof Node\Stmt) {
return;
}
$nodeScopeResolver->callNodeCallback($nodeCallback, new UnreachableStatementNode($unreachableStatement, $nextStatements), $scope, $storage);
}
/**
* @param array<Node> $nodes
* @return list<Node\Stmt>
*/
private function getNextUnreachableStatements(array $nodes, bool $earlyBinding): array
{
$stmts = [];
$isPassedUnreachableStatement = false;
foreach ($nodes as $node) {
if ($node instanceof Node\Stmt\Label) {
break;
}
if ($earlyBinding && ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassLike || $node instanceof Node\Stmt\HaltCompiler)) {
continue;
}
if ($isPassedUnreachableStatement && $node instanceof Node\Stmt) {
$stmts[] = $node;
continue;
}
if ($node instanceof Node\Stmt\Nop || $node instanceof Node\Stmt\InlineHTML) {
continue;
}
if (!$node instanceof Node\Stmt) {
continue;
}
$stmts[] = $node;
$isPassedUnreachableStatement = true;
}
return $stmts;
}
/**
* @param Node\Stmt[] $stmts
* @param callable(Node $node, Scope $scope): void $nodeCallback
*/
public function doProcessStmtNodes(
NodeScopeResolver $nodeScopeResolver,
Node $parentNode,
array $stmts,
MutatingScope $scope,
ExpressionResultStorage $storage,
callable $nodeCallback,
StatementContext $context,
): InternalStatementResult
{
$stmtCount = count($stmts);
$shouldCheckLastStatement = $parentNode instanceof Node\Stmt\Function_
|| $parentNode instanceof Node\Stmt\ClassMethod
|| $parentNode instanceof PropertyHookStatementNode
|| $parentNode instanceof Expr\Closure;
if (
$shouldCheckLastStatement
&& $stmtCount > 0
&& $this->unresolvedTemplateArguments
&& $context->shouldResolveTemplateArguments()
) {
return $this->processBodyStmtNodesTwoPass($nodeScopeResolver, $parentNode, $stmts, $scope, $storage, $nodeCallback, $context);
}
$state = new StatementListWalkState($scope);
foreach ($stmts as $i => $stmt) {
$this->processStatementStep($nodeScopeResolver, $parentNode, $stmts, $i, $stmt, $state, $storage, $nodeCallback, $context, $shouldCheckLastStatement);
}
$statementResult = $state->toResult();
if ($stmtCount === 0 && $shouldCheckLastStatement) {
$returnTypeNode = $parentNode->getReturnType();
if ($parentNode instanceof Expr\Closure) {
$parentNode = new Node\Stmt\Expression($parentNode, $parentNode->getAttributes());
}
// the body is empty - the statement above is a synthetic wrapper around
// the closure, not an expression statement that was processed
$nodeScopeResolver->callNodeCallback($nodeCallback, new ExecutionEndNode(
$parentNode,
$statementResult->toPublic(),
$returnTypeNode !== null,
), $scope, $storage);
}
return $statementResult;
}
/**
* One loop convergence pass. Against the previous pass's per-statement
* entries, a statement is re-walked only when its entry state differs in a
* key spelling no variable, or it mentions a variable whose state differs;
* otherwise its recorded emissions are replayed and its recorded effect is
* carried onto the current scope. Once the entry state equals the previous
* pass's, the rest of the previous pass stands. $record receives this pass's
* entries for the next one.
*
* @param Node\Stmt[] $stmts
* @param callable(Node $node, Scope $scope): void $nodeCallback
* @param array{array<int, array{StatementListWalkState, int}>, ?RecordingNodeCallback}|null $previous
* @param array{array<int, array{StatementListWalkState, int}>, ?RecordingNodeCallback}|null $record
* @param-out array{array<int, array{StatementListWalkState, int}>, ?RecordingNodeCallback} $record
*/
public function processLoopPassStmtNodes(
NodeScopeResolver $nodeScopeResolver,
Node $parentNode,
array $stmts,
MutatingScope $scope,
ExpressionResultStorage $storage,
callable $nodeCallback,
StatementContext $context,
?array $previous,
?array &$record,
): InternalStatementResult
{
$recording = $nodeCallback instanceof RecordingNodeCallback ? $nodeCallback : null;
[$result, $entries] = $this->walkAgainstPreviousPass($nodeScopeResolver, $parentNode, $stmts, $scope, $storage, $nodeCallback, $context, $previous, $recording, false);
$record = [$entries, $recording];
return $result;
}
/**
* The final walk of a loop body that the last convergence pass could not
* stand in for as a whole: like a later pass against $lastPass, with the
* replayed emissions going to the real callback, and every statement
* holding a construct that walks differently outside a pass (a nested
* loop runs its own convergence only here) walked.
*
* @param Node\Stmt[] $stmts
* @param callable(Node $node, Scope $scope): void $nodeCallback
* @param array{array<int, array{StatementListWalkState, int}>, RecordingNodeCallback} $lastPass
*/
public function processLoopFinalStmtNodes(
NodeScopeResolver $nodeScopeResolver,
Node $parentNode,
array $stmts,
MutatingScope $scope,
ExpressionResultStorage $storage,
callable $nodeCallback,
StatementContext $context,
array $lastPass,
): InternalStatementResult
{
return $this->walkAgainstPreviousPass($nodeScopeResolver, $parentNode, $stmts, $scope, $storage, $nodeCallback, $context, $lastPass, $nodeCallback, true)[0];
}
/**
* Against the previous pass's per-statement entries, a statement is
* re-walked only when its entry state differs in a key spelling no
* variable, or it mentions a variable whose state differs; otherwise its
* recorded emissions are replayed into $replayTarget (none without one)
* and its recorded effect is carried onto the current scope. Once the
* entry state equals the previous pass's, the rest of the previous pass
* stands. A final walk records no entries.
*
* @param Node\Stmt[] $stmts
* @param callable(Node $node, Scope $scope): void $nodeCallback
* @param array{array<int, array{StatementListWalkState, int}>, ?RecordingNodeCallback}|null $previous
* @param (callable(Node $node, Scope $scope): void)|null $replayTarget
* @return array{InternalStatementResult, array<int, array{StatementListWalkState, int}>}
*/
private function walkAgainstPreviousPass(
NodeScopeResolver $nodeScopeResolver,
Node $parentNode,
array $stmts,
MutatingScope $scope,
ExpressionResultStorage $storage,
callable $nodeCallback,
StatementContext $context,
?array $previous,
?callable $replayTarget,
bool $finalWalk,
): array
{
$recording = !$finalWalk && $nodeCallback instanceof RecordingNodeCallback ? $nodeCallback : null;
$previousRecording = $previous !== null ? $previous[1] : null;
// a replayed statement's emissions come from the previous recording;
// labels make the statement order no straight line
$canReplay = $previous !== null
&& ($replayTarget === null || $previousRecording !== null)
&& !$this->containsLabels($stmts);
$stmtCount = count($stmts);
// the last statement a final walk walks whatever the state
$lastWalked = -1;
if ($canReplay && $finalWalk) {
for ($i = $stmtCount - 1; $i >= 0; $i--) {
if ($nodeScopeResolver->isContextSensitiveStatement($stmts[$i])) {
$lastWalked = $i;
break;
}
}
}
$state = new StatementListWalkState($scope);
$entries = [];
for ($i = 0; $i < $stmtCount; $i++) {
if (!$finalWalk) {
$entries[$i] = [clone $state, $recording !== null ? $recording->count() : 0];
}
if ($canReplay && ($i > $lastWalked || !$nodeScopeResolver->isContextSensitiveStatement($stmts[$i]))) {
[$recordedEntry, $offset] = $previous[0][$i];
[$recordedExit, $nextOffset] = $previous[0][$i + 1];
$differingRoots = $state->alreadyTerminated === $recordedEntry->alreadyTerminated
? $state->scope->getDifferingVariableRoots($recordedEntry->scope)
: null;
if ($differingRoots === [] && $i > $lastWalked) {
// converged with the previous pass: the rest of it stands
[$recordedEnd, $endOffset] = $previous[0][$stmtCount];
if ($replayTarget !== null && $previousRecording !== null) {
$nodeScopeResolver->replayRecordingRange($previousRecording, $offset, $endOffset, $replayTarget, $storage, $scope);
}
if (!$finalWalk) {
// the previous pass's entries accumulated its own
// points before statement $i: rebase them onto this pass's
[$entryState, $base] = $entries[$i];
for ($j = $i + 1; $j <= $stmtCount; $j++) {
[$recordedState, $recordedOffset] = $previous[0][$j];
$adoptedState = clone $entryState;
$this->appendRecordedStatementResults($adoptedState, $recordedEntry, $recordedState);
$adoptedState->scope = $recordedState->scope;
$entries[$j] = [$adoptedState, $base + $recordedOffset - $offset];
}
}
$this->appendRecordedStatementResults($state, $recordedEntry, $recordedEnd);
$state->scope = $recordedEnd->scope;
return [$state->toResult(), $entries];
}
if ($differingRoots !== null && !$this->statementMentionsAnyVariable($stmts[$i], $this->withByRefClosureHolders($state->scope, $differingRoots))) {
if ($replayTarget !== null && $previousRecording !== null) {
$nodeScopeResolver->replayRecordingRange($previousRecording, $offset, $nextOffset, $replayTarget, $storage, $scope);
}
$exitPointCount = count($state->exitPoints);
$throwPointCount = count($state->throwPoints);
$this->appendRecordedStatementResults($state, $recordedEntry, $recordedExit);
$this->rebaseAppendedPoints($state, $exitPointCount, $throwPointCount, $recordedEntry->scope);
$state->scope = $state->scope->withRecordedStatementDelta($recordedEntry->scope, $recordedExit->scope);
continue;
}
}
$this->processStatementStep($nodeScopeResolver, $parentNode, $stmts, $i, $stmts[$i], $state, $storage, $nodeCallback, $context, false);
}
if (!$finalWalk) {
$entries[$stmtCount] = [clone $state, $recording !== null ? $recording->count() : 0];
}
return [$state->toResult(), $entries];
}
/**
* $variableNames and the variables holding a closure that captures one of
* them by reference: invoking it walks its body with the variable's current
* state (ClosureSignatureInference), so `$c();` reads `$x` without spelling it.
*
* @param list<string> $variableNames
* @return list<string>
*/
private function withByRefClosureHolders(MutatingScope $scope, array $variableNames): array
{
if ($variableNames === []) {
return $variableNames;
}
$differing = array_flip($variableNames);
foreach ([...$scope->getDefinedVariables(), ...$scope->getMaybeDefinedVariables()] as $holder) {
if (isset($differing[$holder])) {
continue;
}
$type = $scope->getVariableType($holder);
foreach ($type instanceof UnionType ? $type->getTypes() : [$type] as $member) {
if (!$member instanceof ClosureType) {
continue;
}
foreach (array_keys($member->getByRefUseTypes()) as $captured) {
if (!isset($differing[$captured])) {
continue;
}
$variableNames[] = $holder;
continue 3;
}
}
}
return $variableNames;
}
/**
* The exit and throw points a replayed statement appended carry scopes of
* the recorded walk; carry the statement's recorded effect onto the current
* entry scope instead.
*/
private function rebaseAppendedPoints(StatementListWalkState $state, int $exitPointCount, int $throwPointCount, MutatingScope $recordedEntry): void
{
$entry = $state->scope;
for ($i = $exitPointCount; $i < count($state->exitPoints); $i++) {
$point = $state->exitPoints[$i];
$state->exitPoints[$i] = $point->withScope($entry->withRecordedStatementDelta($recordedEntry, $point->getScope()));
}
for ($i = $throwPointCount; $i < count($state->throwPoints); $i++) {
$point = $state->throwPoints[$i];
$state->throwPoints[$i] = $point->withScope($entry->withRecordedStatementDelta($recordedEntry, $point->getScope()));
}
}
/**
* One statement of a statement list, advancing $state past it.
*
* @param Node\Stmt[] $stmts
* @param callable(Node $node, Scope $scope): void $nodeCallback
*/
private function processStatementStep(
NodeScopeResolver $nodeScopeResolver,
Node $parentNode,
array $stmts,
int $i,
Node\Stmt $stmt,
StatementListWalkState $state,
ExpressionResultStorage $storage,
callable $nodeCallback,
StatementContext $context,
bool $shouldCheckLastStatement,
): void
{
if ($state->alreadyTerminated && !($stmt instanceof Node\Stmt\Function_ || $stmt instanceof Node\Stmt\ClassLike || $stmt instanceof Node\Stmt\Label)) {
return;
}
$isLast = $i === count($stmts) - 1;
$nestedLabelNames = $stmt->getAttribute(GotoLabelVisitor::NESTED_BACKWARD_GOTO_LABELS_ATTRIBUTE);
if ($nestedLabelNames !== null && $context->isTopLevel()) {
$state->scope = $this->resolveBackwardGotoScope(
$nodeScopeResolver,
$parentNode,
[$stmt],
$state->scope,
$storage,
$context->enterDeep(),
static fn (string $name): bool => isset($nestedLabelNames[$name]),
false,
);
}
$statementResult = $nodeScopeResolver->processStmtNode(
$stmt,
$state->scope,
$storage,
$nodeCallback,
$context,
);
$state->variableFlows[$i] = $statementResult->getVariableFlow();
$state->scope = $statementResult->getScope();
$state->hasYield = $state->hasYield || $statementResult->hasYield();
$statementDependencies = $statementResult->getDependencies();
if ($statementDependencies !== null) {
$state->dependencies[] = $statementDependencies;
}
if ($stmt instanceof Node\Stmt\Label) {
$labelName = $stmt->name->toString();
[$state->scope, $state->alreadyTerminated, $state->exitPoints] = $this->mergeForwardGotoExitPoints(
$labelName,
$state->scope,
$state->alreadyTerminated,
$state->exitPoints,
);
if ($state->alreadyTerminated) {
return;
}
if ($stmt->getAttribute(GotoLabelVisitor::HAS_BACKWARD_GOTO_ATTRIBUTE) === true && $context->isTopLevel()) {
$state->scope = $this->resolveBackwardGotoScope(
$nodeScopeResolver,
$parentNode,
array_slice($stmts, $i + 1),
$state->scope,
$storage,
$context->enterDeep(),
static fn (string $name): bool => $name === $labelName,
true,
);
}
}
if ($shouldCheckLastStatement && $isLast) {
$hasDeclaredReturnType = ($parentNode instanceof Node\FunctionLike || $parentNode instanceof PropertyHookStatementNode)
&& $parentNode->getReturnType() !== null;
$endStatements = $statementResult->getEndStatements();
if (count($endStatements) > 0) {
foreach ($endStatements as $endStatement) {
$endStatementResult = $endStatement->getResult();
$nodeScopeResolver->callNodeCallback($nodeCallback, new ExecutionEndNode(
$endStatement->getStatement(),
(new InternalStatementResult(
$endStatementResult->getScope(),
$state->hasYield,
$endStatementResult->isAlwaysTerminating(),
$endStatementResult->getExitPoints(),
$endStatementResult->getThrowPoints(),
$endStatementResult->getImpurePoints(),
))->toPublic(),
$hasDeclaredReturnType,
$this->readEndStatementExprResult($endStatement->getStatement(), $storage),
), $endStatementResult->getScope(), $storage);
}
} else {
$nodeScopeResolver->callNodeCallback($nodeCallback, new ExecutionEndNode(
$stmt,
(new InternalStatementResult(
$state->scope,
$state->hasYield,
$statementResult->isAlwaysTerminating(),
$statementResult->getExitPoints(),
$statementResult->getThrowPoints(),
$statementResult->getImpurePoints(),
))->toPublic(),
$hasDeclaredReturnType,
$this->readEndStatementExprResult($stmt, $storage),
), $state->scope, $storage);
}
}
$state->exitPoints = array_merge($state->exitPoints, $statementResult->getExitPoints());
$state->throwPoints = array_merge($state->throwPoints, $statementResult->getThrowPoints());
$state->impurePoints = array_merge($state->impurePoints, $statementResult->getImpurePoints());
if ($state->alreadyTerminated || !$statementResult->isAlwaysTerminating()) {
return;
}
$state->alreadyTerminated = true;
$nextStmts = $this->getNextUnreachableStatements(array_slice($stmts, $i + 1), $parentNode instanceof Node\Stmt\Namespace_);
$this->processUnreachableStatement($nodeScopeResolver, $nextStmts, $state->scope, $storage, $nodeCallback);
}
/**
* The result of the expression an ending statement evaluated, for
* ExecutionEndNode. Null when the statement is not an expression statement,
* and when its expression was not processed into this storage - an end
* statement is collected from wherever execution ended, which can be a
* nested walk whose results never reach the frame the end node is built in.
*/
private function readEndStatementExprResult(Node\Stmt $stmt, ExpressionResultStorage $storage): ?ExpressionResult
{
if (!$stmt instanceof Node\Stmt\Expression) {
return null;
}
return $storage->findExpressionResult($stmt->expr);
}
/**
* A function-like body under the unresolvedTemplateArguments toggle is
* walked in two passes. The observation pass walks every statement
* recording rule-facing emissions and threading immutable constraints
* through the scopes returned by expressions and statements. A body that
* created no unresolved template argument simply replays the recording.
* Otherwise TemplateArgumentResolver builds a new resolved frame for the
* second pass, which re-walks only the statements the resolutions can
* influence. Recorded scopes retain their original collection context.
*
* The outer gatherer frames (the method's return statements, execution
* ends, impure points) are suspended during the observation pass and fed
* by the replay and the re-walk, so each emission reaches them once.
*
* @param Node\Stmt[] $stmts
* @param callable(Node $node, Scope $scope): void $nodeCallback
*/
private function processBodyStmtNodesTwoPass(
NodeScopeResolver $nodeScopeResolver,
Node $parentNode,
array $stmts,
MutatingScope $scope,
ExpressionResultStorage $storage,
callable $nodeCallback,
StatementContext $context,
): InternalStatementResult
{
$statementStartTokenPositions = [];
foreach ($stmts as $stmt) {
$statementStartTokenPositions[] = $stmt->getStartTokenPos();
}
$parentFrame = $scope->getCurrentTemplateArgumentFrame();
$parentConstraints = $scope->getTemplateArgumentConstraints();
$frame = new TemplateArgumentFrame($parentFrame, closureSignatureBody: $parentNode, closureSignatureStmts: $stmts);
if (TemplateArgumentStats::$enabled) {
TemplateArgumentStats::increment('bodiesWalked');
TemplateArgumentStats::increment('statementsTotal', count($stmts));
}
$scope = $scope->withTemplateArgumentFrame($frame)->withTemplateArgumentConstraints(null);
$recording = new RecordingNodeCallback();
$state = new StatementListWalkState($scope);
/** @var list<array{StatementListWalkState, int}> $entries the state and recording offset before each statement, plus the final ones */
$entries = [];
$observationContext = $context->withoutTemplateArgumentResolution();
$suspendedGatherers = $nodeScopeResolver->suspendNodeGatherers();
try {
foreach ($stmts as $i => $stmt) {
$entries[$i] = [clone $state, $recording->count()];
$this->processStatementStep($nodeScopeResolver, $parentNode, $stmts, $i, $stmt, $state, $storage, $recording, $observationContext, true);
}
} finally {
$nodeScopeResolver->restoreNodeGatherers($suspendedGatherers);
}
$stmtCount = count($stmts);
$entries[$stmtCount] = [clone $state, $recording->count()];
$constraints = $state->scope->getTemplateArgumentConstraints() ?? TemplateArgumentConstraints::createEmpty();
$staticSites = $this->staticVariableInference->getSites($parentNode, $stmts);
$staticVariableTypes = [];
$staticVariableConditionalExpressions = [];
$staticStatementIndexes = [];
$staticWalk = null;
if ($staticSites !== []) {
foreach ($staticSites as [, $index]) {
$staticStatementIndexes[$index] = true;
}
[$staticVariableTypes, $staticVariableConditionalExpressions, $constraints, $staticWalk] = $this->inferStaticVariableTypes($nodeScopeResolver, $parentNode, $stmts, $staticSites, $staticStatementIndexes, $parentFrame, $entries, $recording, $storage, $observationContext);
}
$frame = $this->templateArgumentResolver->resolve($constraints, $parentFrame, $statementStartTokenPositions, $parentNode, $stmts);
if ($staticVariableTypes !== []) {
$frame = $frame->withStaticVariableTypes($staticVariableTypes, $staticStatementIndexes, $staticVariableConditionalExpressions);
}
if (
$staticWalk !== null
&& $constraints->isEmpty()
&& !$this->staticVariableInference->hasFunctionLikeFrom($parentNode, $stmts, $staticWalk[0])
) {
return $this->replayStaticVariableWalk($nodeScopeResolver, $stmts, $entries, $recording, $staticWalk, $frame, $parentFrame, $parentConstraints, $storage, $nodeCallback, $scope);
}
if ($frame->isObservingClosures()) {
$frame = $this->observeClosureSignatures($nodeScopeResolver, $parentNode, $stmts, $frame, $entries, $storage, $observationContext, $statementStartTokenPositions);
}
$firstSiteStatementIndex = $frame->firstSiteStatementIndex();
if ($firstSiteStatementIndex === null) {
$nodeScopeResolver->replayRecordingRange($recording, 0, $recording->count(), $nodeCallback, $storage, $scope);
$state->scope = $state->scope->withTemplateArgumentFrame($parentFrame)->withTemplateArgumentConstraints($parentConstraints);
return $state->toResult();
}
if (TemplateArgumentStats::$enabled) {
TemplateArgumentStats::increment('bodiesWithSites');
TemplateArgumentStats::increment('statementsReplayed', $firstSiteStatementIndex);
}
// the second pass: the statements before the first site stand as
// recorded; from there on a statement is re-walked only when it
// created a site or mentions a variable whose tracked state the
// resolutions changed - the rest replay their recording and carry
// their recorded effect onto the re-walked scope
$nodeScopeResolver->replayRecordingRange($recording, 0, $entries[$firstSiteStatementIndex][1], $nodeCallback, $storage, $scope);
$hasLabels = $this->containsLabels($stmts);
$state = clone $entries[$firstSiteStatementIndex][0];
$state->scope = $state->scope->withTemplateArgumentFrame($frame)->withTemplateArgumentConstraints(null);
for ($i = $firstSiteStatementIndex; $i < $stmtCount; $i++) {
[$recordedEntry, $offset] = $entries[$i];
[$recordedExit, $nextOffset] = $entries[$i + 1];
$differingRoots = $state->alreadyTerminated === $recordedEntry->alreadyTerminated
? $state->scope->getDifferingVariableRoots($recordedEntry->scope)
: null;
if ($differingRoots === [] && !$frame->hasSiteAtOrAfter($i)) {
// converged with the observation pass: the rest of its recording stands
if (TemplateArgumentStats::$enabled) {
TemplateArgumentStats::increment('earlyExits');
TemplateArgumentStats::increment('statementsReplayed', $stmtCount - $i);
}
$nodeScopeResolver->replayRecordingRange($recording, $offset, $recording->count(), $nodeCallback, $storage, $scope);
$this->appendRecordedStatementResults($state, $recordedEntry, $entries[$stmtCount][0]);
// the recorded end scope, with what this pass collected
$state->scope = $entries[$stmtCount][0]->scope->withTemplateArgumentConstraints($state->scope->getTemplateArgumentConstraints());
$this->processDeferredByRefClosureBodies($nodeScopeResolver, $frame, $state, $storage, $nodeCallback);
$state->scope = $state->scope->withTemplateArgumentFrame($parentFrame)->withTemplateArgumentConstraints($parentConstraints);
return $state->toResult();
}
$stmt = $stmts[$i];
$reWalk = $differingRoots === null
|| $hasLabels
|| $frame->ownsSiteInStatement($i)
|| $this->statementMentionsAnyVariable($stmt, $differingRoots);
if ($this->debugTemplateArguments) {
echo sprintf(
"[template-arguments] %s:%d statement %d: %s (differing: %s)\n",
$scope->getFile(),
$stmt->getStartLine(),
$i,
$reWalk ? 're-walk' : 'replay',
$differingRoots === null ? 'non-variable key' : implode(', ', $differingRoots),
);
}
if ($reWalk) {
if (TemplateArgumentStats::$enabled) {
TemplateArgumentStats::increment('statementsReWalked');
}
$this->processStatementStep($nodeScopeResolver, $parentNode, $stmts, $i, $stmt, $state, $storage, $nodeCallback, $context, true);
continue;
}
if (TemplateArgumentStats::$enabled) {
TemplateArgumentStats::increment('statementsReplayed');
}
$nodeScopeResolver->replayRecordingRange($recording, $offset, $nextOffset, $nodeCallback, $storage, $scope);
$this->appendRecordedStatementResults($state, $recordedEntry, $recordedExit);
$state->scope = $state->scope->withRecordedStatementDelta($recordedEntry->scope, $recordedExit->scope);
}
$this->processDeferredByRefClosureBodies($nodeScopeResolver, $frame, $state, $storage, $nodeCallback);
$state->scope = $state->scope->withTemplateArgumentFrame($parentFrame)->withTemplateArgumentConstraints($parentConstraints);
return $state->toResult();
}
/**
* The types the body's `static` variables take (see
* StaticVariableInference): the observation pass walked the body with their
* defaults; from the first `static` statement on, the body is observed again
* with the types collected so far - walking, like the second pass, only the
* statements that read a variable whose type changed - until the type at
* each `static` statement holds every type the variable takes after it,
* generalized like a loop's variables. The facts of the last walk are the
* ones the template arguments and closure signatures are resolved from; the
* walk itself is returned too, see replayStaticVariableWalk().
*
* The variables of a run of `static` statements (see
* StaticVariableInference::getRuns()) hold one of the states a call left
* them in together, so the walks also carry how their types depend on each
* other after the run - until those conditional expressions converge too,
* or are given up.
*
* @param Node\Stmt[] $stmts
* @param non-empty-list<array{Expr\Variable, int, string}> $staticSites
* @param array<int, true> $staticStatementIndexes
* @param array<int, array{StatementListWalkState, int}> $entries
* @return array{array<int, array{Expr\Variable, Type, Type}>, array<int, array{Node\Stmt\Static_, array<string, ConditionalExpressionHolder[]>}>, TemplateArgumentConstraints, array{int, StatementListWalkState, RecordingNodeCallback, ExpressionResultStorage, list<array{int, int, int}>}}
*/
private function inferStaticVariableTypes(
NodeScopeResolver $nodeScopeResolver,
Node $parentNode,
array $stmts,
array $staticSites,
array $staticStatementIndexes,
?TemplateArgumentFrame $parentFrame,
array $entries,
RecordingNodeCallback $recording,
ExpressionResultStorage $storage,
StatementContext $context,
): array
{
$stmtCount = count($stmts);
$bodyScope = $entries[0][0]->scope;
$names = [];
$start = $stmtCount;
foreach ($staticSites as [, $index, $name]) {
$names[$name] = true;
$start = min($start, $index);
}
$names = array_keys($names);
$runs = $this->staticVariableInference->getRuns($parentNode, $stmts);
$types = $this->collectStaticVariableTypes($names, $this->collectStaticVariableScopes($bodyScope, $recording, $entries[$stmtCount][0], []));
$conditionalExpressions = $runs !== []
? $this->collectStaticVariableConditionalExpressions($runs, $this->collectStaticVariableStateScopes($bodyScope, $recording, $entries[$stmtCount][0], []), $storage, null, [], $types)
: [];
$hasLabels = $this->containsLabels($stmts);
$count = 0;
$conditionalExpressionsCount = 0;
while (true) {
$siteTypes = [];
foreach ($staticSites as [$var, , $name]) {
[$type, $nativeType] = $types[$name];
$siteTypes[spl_object_id($var)] = [$var, $type, $nativeType];
}
$frame = (new TemplateArgumentFrame($parentFrame, closureSignatureBody: $parentNode, closureSignatureStmts: $stmts))->withStaticVariableTypes($siteTypes, $staticStatementIndexes, $conditionalExpressions);
$state = clone $entries[$start][0];
$state->scope = $state->scope->withTemplateArgumentFrame($frame);
$walkStorage = $storage->duplicate();
$walkRecording = new RecordingNodeCallback();
/** @var list<array{int, int, int}> $walkLog see replayStaticVariableWalk() */
$walkLog = [];
/** @var list<MutatingScope> $replayedScopes */
$replayedScopes = [];