Repository navigation
Expand file tree
/
Copy pathNodeScopeResolver.php
More file actions
3952 lines (3605 loc) · 153 KB
/
Copy pathNodeScopeResolver.php
File metadata and controls
3952 lines (3605 loc) · 153 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\AttributeGroup;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\AssignRef;
use PhpParser\Node\Expr\CallLike;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\List_;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Expr\StaticPropertyFetch;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Echo_;
use PhpParser\Node\Stmt\Foreach_;
use PhpParser\Node\Stmt\Goto_;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\Stmt\Static_;
use PhpParser\Node\Stmt\Switch_;
use PhpParser\NodeFinder;
use PHPStan\Analyser\ExprHandler\ArrowFunctionHandler;
use PHPStan\Analyser\ExprHandler\AssignHandler;
use PHPStan\Analyser\ExprHandler\ClosureHandler;
use PHPStan\Analyser\ExprHandler\Helper\ClosureParameterResolver;
use PHPStan\Analyser\ExprHandler\Helper\ClosureTypeResolver;
use PHPStan\Analyser\ExprHandler\Helper\NonNullabilityHelper;
use PHPStan\Analyser\ExprHandler\Helper\VirtualExprResultHelper;
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\DependencyInjection\AutowiredExtensions;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\DependencyInjection\Container;
use PHPStan\DependencyInjection\ExtensionsCollection;
use PHPStan\File\FileHelper;
use PHPStan\Node\ClosureReturnStatementsNode;
use PHPStan\Node\ExecutionEndNode;
use PHPStan\Node\Expr\NativeTypeExpr;
use PHPStan\Node\Expr\TypeExpr;
use PHPStan\Node\FunctionCallableNode;
use PHPStan\Node\FunctionCallExpressionNode;
use PHPStan\Node\InArrowFunctionNode;
use PHPStan\Node\InClosureNode;
use PHPStan\Node\InstantiationCallableNode;
use PHPStan\Node\InvalidateExprNode;
use PHPStan\Node\MethodCallableNode;
use PHPStan\Node\MethodCallExpressionNode;
use PHPStan\Node\PropertyAssignNode;
use PHPStan\Node\PropertyHookStatementNode;
use PHPStan\Node\ReturnAfterFinallyNode;
use PHPStan\Node\ReturnStatement;
use PHPStan\Node\StaticMethodCallableNode;
use PHPStan\Node\StaticMethodCallExpressionNode;
use PHPStan\Node\UnreachableStatementNode;
use PHPStan\Node\VarTagChangedExpressionTypeNode;
use PHPStan\Parser\ArrowFunctionArgVisitor;
use PHPStan\Parser\ClosureArgVisitor;
use PHPStan\Parser\GotoLabelVisitor;
use PHPStan\Parser\ImmediatelyInvokedClosureVisitor;
use PHPStan\PhpDoc\Tag\VarTag;
use PHPStan\Reflection\Callables\SimpleImpurePoint;
use PHPStan\Reflection\Callables\SimpleThrowPoint;
use PHPStan\Reflection\ExtendedMethodReflection;
use PHPStan\Reflection\ExtendedParameterReflection;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Reflection\Native\NativeMethodReflection;
use PHPStan\Reflection\Native\NativeParameterReflection;
use PHPStan\Reflection\ParameterReflection;
use PHPStan\Reflection\ParametersAcceptor;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Reflection\Php\PhpMethodReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Reflection\ResolvedFunctionVariant;
use PHPStan\Rules\Properties\ReadWritePropertiesExtension;
use PHPStan\ShouldNotHappenException;
use PHPStan\TrinaryLogic;
use PHPStan\Type\ClosureType;
use PHPStan\Type\ErrorType;
use PHPStan\Type\FileTypeMapper;
use PHPStan\Type\FunctionParameterClosureThisExtension;
use PHPStan\Type\FunctionParameterClosureTypeExtension;
use PHPStan\Type\FunctionParameterOutTypeExtension;
use PHPStan\Type\Generic\TemplateTypeHelper;
use PHPStan\Type\Generic\TemplateTypeMap;
use PHPStan\Type\Generic\TemplateTypeVariance;
use PHPStan\Type\MethodParameterClosureThisExtension;
use PHPStan\Type\MethodParameterClosureTypeExtension;
use PHPStan\Type\MethodParameterOutTypeExtension;
use PHPStan\Type\MixedType;
use PHPStan\Type\NullType;
use PHPStan\Type\ObjectWithoutClassType;
use PHPStan\Type\ResourceType;
use PHPStan\Type\StaticMethodParameterClosureThisExtension;
use PHPStan\Type\StaticMethodParameterClosureTypeExtension;
use PHPStan\Type\StaticMethodParameterOutTypeExtension;
use PHPStan\Type\ThisType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeUtils;
use PHPStan\Type\UnionType;
use function array_filter;
use function array_key_exists;
use function array_keys;
use function array_last;
use function array_map;
use function array_merge;
use function array_pop;
use function array_slice;
use function array_values;
use function count;
use function get_class;
use function getenv;
use function implode;
use function in_array;
use function is_array;
use function is_int;
use function is_string;
use function max;
use function spl_object_id;
use function sprintf;
use function usort;
#[AutowiredService]
class NodeScopeResolver
{
public const LOOP_SCOPE_ITERATIONS = 3;
public const GENERALIZE_AFTER_ITERATION = 1;
/** @var array<string, true> filePath(string) => bool(true) */
private array $analysedFiles = [];
/**
* When processing a synthetic node on demand, real AST
* nodes contained in it were already processed and must not be processed again.
*/
protected bool $returnStoredExpressionResults = false;
/**
* Consume-stored mode: a walk that deliberately re-enters an
* already-walked subtree (the nullsafe plain twin re-walking its
* receiver) consumes stored results unconditionally instead of
* re-processing - node callbacks fired during the original walk.
*/
private bool $consumeStoredExpressionResults = false;
private ?NonNullabilityHelper $nonNullabilityHelper = null;
/**
* Engine-feeding gatherer frames (return statements, execution ends,
* impure points, ...), innermost last. callNodeCallback() feeds every
* frame the raw walk scope at the emission position - gatherers are
* engine code and never ask about types, and their arrays are read as
* soon as the enclosing body walk returns.
*
* @var list<callable(Node, Scope): void>
*/
private array $nodeGatherers = [];
/** Whether the PHPSTAN_GUARD_NW diagnostic is enabled (cached from the env). */
public static bool $guardNewWorld = false;
/** PHPSTAN_TEMPLATE_ARGUMENTS_DEBUG=1 prints every second-pass re-walk/replay decision. */
private static bool $debugTemplateArguments = false;
/**
* spl_object_id => true of every Expr in the file's parsed AST. Populated
* only when the PHPSTAN_GUARD_NW diagnostic is enabled, so the guards can
* tell a real AST node from a node a rule built during analysis (which
* legitimately resolves on demand). Static so MutatingScope can read it.
*
* @var array<int, true>
*/
public static array $guardRealExprIds = [];
/**
* spl_object_id => true of every Expr already processed by processExprNode
* in the current file. Used by the MutatingScope::getType guard to detect a
* real AST node whose type is asked before it was processed.
*
* @var array<int, true>
*/
public static array $guardProcessedExprIds = [];
/**
* @param ExtensionsCollection<FunctionParameterOutTypeExtension> $functionParameterOutTypeExtensions
* @param ExtensionsCollection<MethodParameterOutTypeExtension> $methodParameterOutTypeExtensions
* @param ExtensionsCollection<StaticMethodParameterOutTypeExtension> $staticMethodParameterOutTypeExtensions
* @param ExtensionsCollection<ReadWritePropertiesExtension> $readWritePropertiesExtensions
* @param ExtensionsCollection<FunctionParameterClosureThisExtension> $functionParameterClosureThisExtensions
* @param ExtensionsCollection<MethodParameterClosureThisExtension> $methodParameterClosureThisExtensions
* @param ExtensionsCollection<StaticMethodParameterClosureThisExtension> $staticMethodParameterClosureThisExtensions
* @param ExtensionsCollection<FunctionParameterClosureTypeExtension> $functionParameterClosureTypeExtensions
* @param ExtensionsCollection<MethodParameterClosureTypeExtension> $methodParameterClosureTypeExtensions
* @param ExtensionsCollection<StaticMethodParameterClosureTypeExtension> $staticMethodParameterClosureTypeExtensions
* @param ExtensionsCollection<PerFileAnalysisResettable> $perFileAnalysisResettables
*/
public function __construct(
private readonly Container $container,
private readonly TemplateArgumentObserver $templateArgumentObserver,
private readonly TemplateArgumentResolver $templateArgumentResolver,
private readonly ReflectionProvider $reflectionProvider,
private readonly FileHelper $fileHelper,
#[AutowiredExtensions(of: FunctionParameterOutTypeExtension::class)]
private readonly ExtensionsCollection $functionParameterOutTypeExtensions,
#[AutowiredExtensions(of: MethodParameterOutTypeExtension::class)]
private readonly ExtensionsCollection $methodParameterOutTypeExtensions,
#[AutowiredExtensions(of: StaticMethodParameterOutTypeExtension::class)]
private readonly ExtensionsCollection $staticMethodParameterOutTypeExtensions,
private readonly FileTypeMapper $fileTypeMapper,
#[AutowiredExtensions(of: ReadWritePropertiesExtension::class)]
private readonly ExtensionsCollection $readWritePropertiesExtensions,
#[AutowiredExtensions(of: FunctionParameterClosureThisExtension::class)]
private readonly ExtensionsCollection $functionParameterClosureThisExtensions,
#[AutowiredExtensions(of: MethodParameterClosureThisExtension::class)]
private readonly ExtensionsCollection $methodParameterClosureThisExtensions,
#[AutowiredExtensions(of: StaticMethodParameterClosureThisExtension::class)]
private readonly ExtensionsCollection $staticMethodParameterClosureThisExtensions,
#[AutowiredExtensions(of: FunctionParameterClosureTypeExtension::class)]
private readonly ExtensionsCollection $functionParameterClosureTypeExtensions,
#[AutowiredExtensions(of: MethodParameterClosureTypeExtension::class)]
private readonly ExtensionsCollection $methodParameterClosureTypeExtensions,
#[AutowiredExtensions(of: StaticMethodParameterClosureTypeExtension::class)]
private readonly ExtensionsCollection $staticMethodParameterClosureTypeExtensions,
#[AutowiredExtensions(of: PerFileAnalysisResettable::class)]
private readonly ExtensionsCollection $perFileAnalysisResettables,
#[AutowiredParameter]
private readonly bool $polluteScopeWithLoopInitialAssignments,
#[AutowiredParameter]
private readonly bool $polluteScopeWithAlwaysIterableForeach,
#[AutowiredParameter(ref: '%exceptions.implicitThrows%')]
private readonly bool $implicitThrows,
#[AutowiredParameter]
private readonly bool $treatPhpDocTypesAsCertain,
private readonly ExpressionResultFactory $expressionResultFactory,
#[AutowiredParameter(ref: '%featureToggles.unresolvedTemplateArguments%')]
private readonly bool $unresolvedTemplateArguments,
)
{
self::$guardNewWorld = getenv('PHPSTAN_GUARD_NW') === '1';
self::$debugTemplateArguments = getenv('PHPSTAN_TEMPLATE_ARGUMENTS_DEBUG') === '1';
TemplateArgumentStats::enableFromEnvironment();
}
/**
* The lookups (isAnalysedFile()) are keyed by normalized paths, so the
* given paths are normalized here - a caller-provided unnormalized path
* (mixed directory separators on Windows) must not silently skip the
* in-class-context analysis of a trait.
*
* @api
* @param string[] $files
*/
public function setAnalysedFiles(array $files): void
{
$analysedFiles = [];
foreach ($files as $file) {
$analysedFiles[$this->fileHelper->normalizePath($file)] = true;
}
$this->analysedFiles = $analysedFiles;
}
/**
* Releases the previous file's node-keyed captures: the parser cache
* retains ASTs, so node-keyed cache entries never die on
* their own and would hold that file's whole result graph alive.
*
* Called at the per-file boundary (FileAnalyser), NOT in processNodes():
* extensions start nested processNodes() walks mid-file (phpstan-doctrine
* parsing a query-builder method, rule tooling re-analysing a callee) and
* wiping the per-file caches there forces the outer file to rebuild them -
* closure types re-converge, narrowing memos recompute.
*/
private function getNonNullabilityHelper(): NonNullabilityHelper
{
return $this->nonNullabilityHelper ??= $this->container->getByType(NonNullabilityHelper::class);
}
public function resetPerFileAnalysisState(): void
{
foreach ($this->perFileAnalysisResettables->getAll() as $resettableService) {
$resettableService->resetFileAnalysisState();
}
}
/**
* @api
* @param Node[] $nodes
* @param callable(Node $node, Scope $scope): void $nodeCallback
*/
public function processNodes(
array $nodes,
MutatingScope $scope,
callable $nodeCallback,
): void
{
$scope = $scope->toWalkScope();
if (self::$guardNewWorld) {
self::$guardRealExprIds = [];
self::$guardProcessedExprIds = [];
foreach ((new NodeFinder())->findInstanceOf($nodes, Expr::class) as $realExpr) {
self::$guardRealExprIds[spl_object_id($realExpr)] = true;
}
}
$expressionResultStorage = new ExpressionResultStorage();
$scope->pushExpressionResultStorage($expressionResultStorage);
// a fresh walk an extension starts mid-analysis must not feed the
// interrupted walk's gatherer frames (see processStmtNodes())
$gatherers = $this->nodeGatherers;
$this->nodeGatherers = [];
try {
$this->processNodesWithStorage($nodes, $scope, $expressionResultStorage, $nodeCallback);
} finally {
$this->nodeGatherers = $gatherers;
$scope->popExpressionResultStorage();
}
}
/**
* @param Node[] $nodes
* @param callable(Node $node, Scope $scope): void $nodeCallback
*/
private function processNodesWithStorage(
array $nodes,
MutatingScope $scope,
ExpressionResultStorage $expressionResultStorage,
callable $nodeCallback,
): void
{
$alreadyTerminated = false;
$exitPoints = [];
$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(
$dummyParent,
[$node],
$scope,
$expressionResultStorage,
StatementContext::createDeep(),
static fn (string $name): bool => isset($nestedLabelNames[$name]),
false,
);
}
$statementResult = $this->processStmtNode($node, $scope, $expressionResultStorage, $nodeCallback, StatementContext::createTopLevel());
$scope = $statementResult->getScope();
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(
$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($nextStmts, $scope, $expressionResultStorage, $nodeCallback);
}
}
/** The stored result an outside asker may consume. */
public function findSettledExpressionResult(ExpressionResultStorage $storage, Expr $expr): ?ExpressionResult
{
return $storage->findExpressionResult($expr);
}
/** An effect-free result carrying eagerly known types, positioned at the given scope. */
protected function createEagerExpressionResult(MutatingScope $scope, Expr $expr, Type $type, Type $nativeType): ExpressionResult
{
return $this->expressionResultFactory->create(
$scope,
beforeScope: $scope,
expr: $expr,
hasYield: false,
isAlwaysTerminating: false,
throwPoints: [],
impurePoints: [],
typeCallback: null,
specifyTypesCallback: SpecifiedTypes::emptySpecifyCallback(),
type: $type,
nativeType: $nativeType,
);
}
public function storeExpressionResult(ExpressionResultStorage $storage, Expr $expr, ExpressionResult $expressionResult): void
{
if (self::$guardNewWorld) {
self::$guardProcessedExprIds[spl_object_id($expr)] = true;
}
// handlers are answered from stored results in both worlds
$storage->storeExpressionResult($expr, $expressionResult);
}
/**
* @param Node\Stmt[] $bodyStmts
* @param Closure(string): bool $gotoNameMatcher
*/
/**
* Narrows a scope by a (often synthetic) control-flow condition the new-world
* way: resolve its narrowing through the scope's on-demand dispatcher and apply
* it via applySpecifiedTypes, instead of the old-world filterBy*Value().
*/
public function narrowScopeWithCondition(MutatingScope $scope, Expr $expr, TypeSpecifierContext $context): MutatingScope
{
$specifiedTypes = $scope->specifyTypesOfNewWorldHandlerNode($expr, $context);
return $scope->applySpecifiedTypes($specifiedTypes);
}
/**
* @param Node\Stmt[] $bodyStmts
* @param Closure(string): bool $gotoNameMatcher
*/
private function resolveBackwardGotoScope(
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 = $this->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 >= self::GENERALIZE_AFTER_ITERATION) {
$bodyScope = $prevScope->generalizeWith($bodyScope);
}
$count++;
} while ($count < self::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(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;
}
$this->callNodeCallback($nodeCallback, new UnreachableStatementNode($unreachableStatement, $nextStatements), $scope, $storage);
}
/**
* @api
* @param Node\Stmt[] $stmts
* @param callable(Node $node, Scope $scope): void $nodeCallback
*/
public function processStmtNodes(
Node $parentNode,
array $stmts,
MutatingScope $scope,
callable $nodeCallback,
StatementContext $context,
): StatementResult
{
// a rule may pass the scope it was handed - the rule-facing NodeCallbackScope -
// as the walk's initial scope; the walk must anchor its results to the
// state-identical MutatingScope or their consumption re-enters the
// rule-facing ask paths
$scope = $scope->toWalkScope();
$storage = new ExpressionResultStorage();
$scope->pushExpressionResultStorage($storage);
// a fresh walk an extension starts mid-analysis must not feed the
// interrupted walk's gatherer frames - they describe the body walk
// that was interrupted, not the nested one
$gatherers = $this->nodeGatherers;
$this->nodeGatherers = [];
try {
return $this->processStmtNodesInternal(
$parentNode,
$stmts,
$scope,
$storage,
$nodeCallback,
$context,
)->toPublic();
} finally {
$this->nodeGatherers = $gatherers;
$scope->popExpressionResultStorage();
}
}
/**
* @param Node\Stmt[] $stmts
* @param callable(Node $node, Scope $scope): void $nodeCallback
*/
public function processStmtNodesInternal(
Node $parentNode,
array $stmts,
MutatingScope $scope,
ExpressionResultStorage $storage,
callable $nodeCallback,
StatementContext $context,
): InternalStatementResult
{
// make the storage this walk writes into scope-visible: loop-convergence
// passes (including the closure by-ref convergence, which calls this
// method directly) thread a throwaway duplicate that would otherwise
// never reach the storage stack, so every in-pass ask
// (applySpecifiedTypes pricing, rules via Scope::getType) would miss the
// pass's own results and re-process real nodes on demand
$pushStorage = $scope->getCurrentExpressionResultStorage() !== $storage;
if ($pushStorage) {
$scope->pushExpressionResultStorage($storage);
}
try {
return $this->doProcessStmtNodes($parentNode, $stmts, $scope, $storage, $nodeCallback, $context);
} finally {
if ($pushStorage) {
$scope->popExpressionResultStorage();
}
}
}
/**
* @param Node\Stmt[] $stmts
* @param callable(Node $node, Scope $scope): void $nodeCallback
*/
private function doProcessStmtNodes(
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($parentNode, $stmts, $scope, $storage, $nodeCallback, $context);
}
$state = new StatementListWalkState($scope);
foreach ($stmts as $i => $stmt) {
$this->processStatementStep($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
$this->callNodeCallback($nodeCallback, new ExecutionEndNode(
$parentNode,
$statementResult->toPublic(),
$returnTypeNode !== null,
), $scope, $storage);
}
return $statementResult;
}
/**
* 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(
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(
$parentNode,
[$stmt],
$state->scope,
$storage,
$context->enterDeep(),
static fn (string $name): bool => isset($nestedLabelNames[$name]),
false,
);
}
$statementResult = $this->processStmtNode(
$stmt,
$state->scope,
$storage,
$nodeCallback,
$context,
);
$state->variableFlows[$i] = $statementResult->getVariableFlow();
$state->scope = $statementResult->getScope();
$state->hasYield = $state->hasYield || $statementResult->hasYield();
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(
$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();
$this->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 {
$this->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($nextStmts, $state->scope, $storage, $nodeCallback);
}
/**
* 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(
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);
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 = $this->nodeGatherers;
$this->nodeGatherers = [];
try {
foreach ($stmts as $i => $stmt) {
$entries[$i] = [clone $state, $recording->count()];
$this->processStatementStep($parentNode, $stmts, $i, $stmt, $state, $storage, $recording, $observationContext, true);
}
} finally {
$this->nodeGatherers = $suspendedGatherers;
}
$frame = $this->templateArgumentResolver->resolve($state->scope->getTemplateArgumentConstraints() ?? TemplateArgumentConstraints::createEmpty(), $parentFrame, $statementStartTokenPositions);
$stmtCount = count($stmts);
$entries[$stmtCount] = [clone $state, $recording->count()];
$firstSiteStatementIndex = $frame->firstSiteStatementIndex();
if ($firstSiteStatementIndex === null) {
$this->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
$this->replayRecordingRange($recording, 0, $entries[$firstSiteStatementIndex][1], $nodeCallback, $storage, $scope);
$hasLabels = false;
foreach ($stmts as $stmt) {
if (!$stmt instanceof Node\Stmt\Label && $stmt->getAttribute(GotoLabelVisitor::NESTED_BACKWARD_GOTO_LABELS_ATTRIBUTE) === null) {
continue;
}
$hasLabels = true;
break;
}
$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);
}
$this->replayRecordingRange($recording, $offset, $recording->count(), $nodeCallback, $storage, $scope);
$this->appendRecordedStatementResults($state, $recordedEntry, $entries[$stmtCount][0]);
$state->scope = $entries[$stmtCount][0]->scope;
$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 (self::$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($parentNode, $stmts, $i, $stmt, $state, $storage, $nodeCallback, $context, true);
continue;
}
if (TemplateArgumentStats::$enabled) {
TemplateArgumentStats::increment('statementsReplayed');
}
$this->replayRecordingRange($recording, $offset, $nextOffset, $nodeCallback, $storage, $scope);
$this->appendRecordedStatementResults($state, $recordedEntry, $recordedExit);
$state->scope = $state->scope->withRecordedStatementDelta($recordedEntry->scope, $recordedExit->scope);
}
$state->scope = $state->scope->withTemplateArgumentFrame($parentFrame)->withTemplateArgumentConstraints($parentConstraints);
return $state->toResult();
}
/**
* The parameter type an argument is observed against: the declared one with
* the template types the call already decided substituted - the receiver's
* class-level arguments, a template an earlier argument inferred - while a
* template still open (ErrorType in the resolved map, typically the one this
* very argument decides) stays a TemplateType, which the observer ignores.
* The resolved parameter type would carry such a template's bound instead.
*/
private function findOriginalParameterType(ParametersAcceptor $acceptor, ParameterReflection $parameter): ?Type
{
if (!$acceptor instanceof ResolvedFunctionVariant) {
return $parameter->getType();
}
$originalParameters = $acceptor->getOriginalParametersAcceptor()->getParameters();
foreach ($acceptor->getParameters() as $index => $resolvedParameter) {
if ($resolvedParameter !== $parameter) {
continue;