1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Analyser;
4:
5: use Closure;
6: use PhpParser\Node;
7: use PhpParser\Node\Expr;
8: use PhpParser\Node\Expr\ArrayDimFetch;
9: use PhpParser\Node\Expr\FuncCall;
10: use PhpParser\Node\Expr\List_;
11: use PhpParser\Node\Expr\MethodCall;
12: use PhpParser\Node\Expr\New_;
13: use PhpParser\Node\Expr\PropertyFetch;
14: use PhpParser\Node\Expr\StaticCall;
15: use PhpParser\Node\Expr\StaticPropertyFetch;
16: use PhpParser\Node\Expr\Variable;
17: use PhpParser\Node\Identifier;
18: use PhpParser\Node\Stmt\Class_;
19: use PhpParser\Node\Stmt\Echo_;
20: use PhpParser\Node\Stmt\Foreach_;
21: use PhpParser\Node\Stmt\If_;
22: use PhpParser\Node\Stmt\Return_;
23: use PhpParser\Node\Stmt\Static_;
24: use PhpParser\Node\Stmt\Switch_;
25: use PhpParser\NodeFinder;
26: use PHPStan\Analyser\ExprHandler\Helper\NonNullabilityHelper;
27: use PHPStan\Analyser\Generics\TemplateArgumentConstraints;
28: use PHPStan\Analyser\Generics\TemplateArgumentFrame;
29: use PHPStan\Analyser\Generics\TemplateArgumentObserver;
30: use PHPStan\Analyser\Generics\TemplateArgumentStats;
31: use PHPStan\Dependency\Dependencies;
32: use PHPStan\DependencyInjection\AutowiredExtensions;
33: use PHPStan\DependencyInjection\AutowiredService;
34: use PHPStan\DependencyInjection\Container;
35: use PHPStan\DependencyInjection\ExtensionsCollection;
36: use PHPStan\File\FileHelper;
37: use PHPStan\Node\FunctionCallableNode;
38: use PHPStan\Node\FunctionCallExpressionNode;
39: use PHPStan\Node\InstantiationCallableNode;
40: use PHPStan\Node\MethodCallableNode;
41: use PHPStan\Node\MethodCallExpressionNode;
42: use PHPStan\Node\StaticMethodCallableNode;
43: use PHPStan\Node\StaticMethodCallExpressionNode;
44: use PHPStan\Reflection\Php\PhpMethodFromParserNodeReflection;
45: use PHPStan\Reflection\Php\PhpPropertyReflection;
46: use PHPStan\ShouldNotHappenException;
47: use PHPStan\Turbo\ShadowedByTurboExtension;
48: use PHPStan\Type\ErrorType;
49: use PHPStan\Type\MixedType;
50: use PHPStan\Type\Type;
51: use PHPStan\Type\TypeUtils;
52: use function array_merge;
53: use function array_pop;
54: use function get_class;
55: use function getenv;
56: use function is_array;
57: use function is_string;
58: use function spl_object_id;
59: use function sprintf;
60:
61: #[AutowiredService]
62: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/NodeScopeResolver.cpp')]
63: class NodeScopeResolver
64: {
65:
66: public const LOOP_SCOPE_ITERATIONS = 10;
67: public const GENERALIZE_AFTER_ITERATION = 1;
68:
69: /** Passes a loop that reached LOOP_SCOPE_ITERATIONS makes forgetting its still-changing variables before it forgets everything it writes. */
70: public const LOOP_SCOPE_FORGETTING_ITERATIONS_LIMIT = 10;
71:
72: /** @var array<string, true> filePath(string) => bool(true) */
73: private array $analysedFiles = [];
74:
75: /**
76: * When processing a synthetic node on demand, real AST
77: * nodes contained in it were already processed and must not be processed again.
78: */
79: protected bool $returnStoredExpressionResults = false;
80:
81: /**
82: * Consume-stored mode: a walk that deliberately re-enters an
83: * already-walked subtree (the nullsafe plain twin re-walking its
84: * receiver) consumes this node's stored result unconditionally instead
85: * of re-processing it - node callbacks fired during the original walk.
86: * Only this exact node is consumed: the rest of the twin (arguments,
87: * a dynamic name) is walked normally, even when the storage was seeded
88: * with results of an earlier loop convergence pass.
89: */
90: private ?Expr $consumeStoredExpression = null;
91:
92: private ?NonNullabilityHelper $nonNullabilityHelper = null;
93:
94: /**
95: * Engine-feeding gatherer frames (return statements, execution ends,
96: * impure points, ...), innermost last. callNodeCallback() feeds every
97: * frame the raw walk scope at the emission position - gatherers are
98: * engine code and never ask about types, and their arrays are read as
99: * soon as the enclosing body walk returns.
100: *
101: * @var list<callable(Node, Scope): void>
102: */
103: private array $nodeGatherers = [];
104:
105: /** Whether the PHPSTAN_GUARD_NW diagnostic is enabled (cached from the env). */
106: public static bool $guardNewWorld = false;
107:
108: /**
109: * spl_object_id => true of every Expr in the file's parsed AST. Populated
110: * only when the PHPSTAN_GUARD_NW diagnostic is enabled, so the guards can
111: * tell a real AST node from a node a rule built during analysis (which
112: * legitimately resolves on demand). Static so MutatingScope can read it.
113: *
114: * @var array<int, true>
115: */
116: public static array $guardRealExprIds = [];
117:
118: /**
119: * spl_object_id => true of every Expr already processed by processExprNode
120: * in the current file. Used by the MutatingScope::getType guard to detect a
121: * real AST node whose type is asked before it was processed.
122: *
123: * @var array<int, true>
124: */
125: public static array $guardProcessedExprIds = [];
126:
127: /**
128: * @param ExtensionsCollection<PerFileAnalysisResettable> $perFileAnalysisResettables
129: */
130: public function __construct(
131: private readonly Container $container,
132: private readonly TemplateArgumentObserver $templateArgumentObserver,
133: private readonly FileHelper $fileHelper,
134: #[AutowiredExtensions(of: PerFileAnalysisResettable::class)]
135: private readonly ExtensionsCollection $perFileAnalysisResettables,
136: private readonly ExpressionResultFactory $expressionResultFactory,
137: private readonly StatementsHandler $statementsHandler,
138: )
139: {
140: self::$guardNewWorld = getenv('PHPSTAN_GUARD_NW') === '1';
141: TemplateArgumentStats::enableFromEnvironment();
142: }
143:
144: /**
145: * The lookups (isAnalysedFile()) are keyed by normalized paths, so the
146: * given paths are normalized here - a caller-provided unnormalized path
147: * (mixed directory separators on Windows) must not silently skip the
148: * in-class-context analysis of a trait.
149: *
150: * @api
151: * @param string[] $files
152: */
153: public function setAnalysedFiles(array $files): void
154: {
155: $analysedFiles = [];
156: foreach ($files as $file) {
157: $analysedFiles[$this->fileHelper->normalizePath($file)] = true;
158: }
159: $this->analysedFiles = $analysedFiles;
160: }
161:
162: /**
163: * Releases the previous file's node-keyed captures: the parser cache
164: * retains ASTs, so node-keyed cache entries never die on
165: * their own and would hold that file's whole result graph alive.
166: *
167: * Called at the per-file boundary (FileAnalyser), NOT in processNodes():
168: * extensions start nested processNodes() walks mid-file (phpstan-doctrine
169: * parsing a query-builder method, rule tooling re-analysing a callee) and
170: * wiping the per-file caches there forces the outer file to rebuild them -
171: * closure types re-converge, narrowing memos recompute.
172: */
173: private function getNonNullabilityHelper(): NonNullabilityHelper
174: {
175: return $this->nonNullabilityHelper ??= $this->container->getByType(NonNullabilityHelper::class);
176: }
177:
178: public function resetPerFileAnalysisState(): void
179: {
180: foreach ($this->perFileAnalysisResettables->getAll() as $resettableService) {
181: $resettableService->resetFileAnalysisState();
182: }
183: }
184:
185: /**
186: * @api
187: * @param Node[] $nodes
188: * @param callable(Node $node, Scope $scope): void $nodeCallback
189: */
190: public function processNodes(
191: array $nodes,
192: MutatingScope $scope,
193: callable $nodeCallback,
194: ): void
195: {
196: $this->processFileNodes($nodes, $scope, $nodeCallback);
197: }
198:
199: /**
200: * processNodes() for the analysis of a file: returns what the file depends on besides itself.
201: *
202: * @param Node[] $nodes
203: * @param callable(Node $node, Scope $scope): void $nodeCallback
204: */
205: public function processFileNodes(
206: array $nodes,
207: MutatingScope $scope,
208: callable $nodeCallback,
209: ): ?Dependencies
210: {
211: $scope = $scope->toWalkScope();
212: if (self::$guardNewWorld) {
213: self::$guardRealExprIds = [];
214: self::$guardProcessedExprIds = [];
215: foreach ((new NodeFinder())->findInstanceOf($nodes, Expr::class) as $realExpr) {
216: self::$guardRealExprIds[spl_object_id($realExpr)] = true;
217: }
218: }
219:
220: $expressionResultStorage = new ExpressionResultStorage();
221: $scope->pushExpressionResultStorage($expressionResultStorage);
222: // a fresh walk an extension starts mid-analysis must not feed the
223: // interrupted walk's gatherer frames (see processStmtNodes())
224: $gatherers = $this->suspendNodeGatherers();
225: try {
226: return $this->statementsHandler->processNodesWithStorage($this, $nodes, $scope, $expressionResultStorage, $nodeCallback);
227: } finally {
228: $this->restoreNodeGatherers($gatherers);
229: $scope->popExpressionResultStorage();
230: }
231: }
232:
233: public function storeExpressionResult(ExpressionResultStorage $storage, Expr $expr, ExpressionResult $expressionResult): void
234: {
235: if (self::$guardNewWorld) {
236: self::$guardProcessedExprIds[spl_object_id($expr)] = true;
237: }
238: // handlers are answered from stored results in both worlds
239: $storage->storeExpressionResult($expr, $expressionResult);
240: }
241:
242: /**
243: * Narrows a scope by a (often synthetic) control-flow condition the new-world
244: * way: resolve its narrowing through the scope's on-demand dispatcher and apply
245: * it via applySpecifiedTypes, instead of the old-world filterBy*Value().
246: */
247: public function narrowScopeWithCondition(MutatingScope $scope, Expr $expr, TypeSpecifierContext $context): MutatingScope
248: {
249: $specifiedTypes = $scope->specifyTypesOfNewWorldHandlerNode($expr, $context);
250:
251: return $scope->applySpecifiedTypes($specifiedTypes);
252: }
253:
254: /**
255: * @api
256: * @param Node\Stmt[] $stmts
257: * @param callable(Node $node, Scope $scope): void $nodeCallback
258: */
259: public function processStmtNodes(
260: Node $parentNode,
261: array $stmts,
262: MutatingScope $scope,
263: callable $nodeCallback,
264: StatementContext $context,
265: ): StatementResult
266: {
267: // a rule may pass the scope it was handed - the rule-facing NodeCallbackScope -
268: // as the walk's initial scope; the walk must anchor its results to the
269: // state-identical MutatingScope or their consumption re-enters the
270: // rule-facing ask paths
271: $scope = $scope->toWalkScope();
272: $storage = new ExpressionResultStorage();
273: $scope->pushExpressionResultStorage($storage);
274: // a fresh walk an extension starts mid-analysis must not feed the
275: // interrupted walk's gatherer frames - they describe the body walk
276: // that was interrupted, not the nested one
277: $gatherers = $this->suspendNodeGatherers();
278: try {
279: return $this->processStmtNodesInternal(
280: $parentNode,
281: $stmts,
282: $scope,
283: $storage,
284: $nodeCallback,
285: $context,
286: )->toPublic();
287: } finally {
288: $this->restoreNodeGatherers($gatherers);
289: $scope->popExpressionResultStorage();
290: }
291: }
292:
293: /**
294: * The final walk of a loop body against its last convergence pass (see
295: * StatementsHandler::processLoopFinalStmtNodes()).
296: *
297: * @param Node\Stmt[] $stmts
298: * @param callable(Node $node, Scope $scope): void $nodeCallback
299: * @param array{array<int, array{StatementListWalkState, int}>, RecordingNodeCallback} $lastPass
300: */
301: public function processLoopFinalStmtNodes(
302: Node $parentNode,
303: array $stmts,
304: MutatingScope $scope,
305: ExpressionResultStorage $storage,
306: callable $nodeCallback,
307: StatementContext $context,
308: array $lastPass,
309: ): InternalStatementResult
310: {
311: $pushStorage = $scope->getCurrentExpressionResultStorage() !== $storage;
312: if ($pushStorage) {
313: $scope->pushExpressionResultStorage($storage);
314: }
315: try {
316: return $this->statementsHandler->processLoopFinalStmtNodes($this, $parentNode, $stmts, $scope, $storage, $nodeCallback, $context, $lastPass);
317: } finally {
318: if ($pushStorage) {
319: $scope->popExpressionResultStorage();
320: }
321: }
322: }
323:
324: /**
325: * One loop convergence pass over $stmts, re-walking only what differs from
326: * $previous, the previous pass (see StatementsHandler::processLoopPassStmtNodes()).
327: *
328: * @param Node\Stmt[] $stmts
329: * @param callable(Node $node, Scope $scope): void $nodeCallback
330: * @param array{array<int, array{StatementListWalkState, int}>, ?RecordingNodeCallback}|null $previous
331: * @param array{array<int, array{StatementListWalkState, int}>, ?RecordingNodeCallback}|null $record
332: */
333: public function processLoopPassStmtNodes(
334: Node $parentNode,
335: array $stmts,
336: MutatingScope $scope,
337: ExpressionResultStorage $storage,
338: callable $nodeCallback,
339: StatementContext $context,
340: ?array $previous,
341: ?array &$record,
342: ): InternalStatementResult
343: {
344: $pushStorage = $scope->getCurrentExpressionResultStorage() !== $storage;
345: if ($pushStorage) {
346: $scope->pushExpressionResultStorage($storage);
347: }
348: try {
349: return $this->statementsHandler->processLoopPassStmtNodes($this, $parentNode, $stmts, $scope, $storage, $nodeCallback, $context, $previous, $record);
350: } finally {
351: if ($pushStorage) {
352: $scope->popExpressionResultStorage();
353: }
354: }
355: }
356:
357: /**
358: * @param Node\Stmt[] $stmts
359: * @param callable(Node $node, Scope $scope): void $nodeCallback
360: */
361: public function processStmtNodesInternal(
362: Node $parentNode,
363: array $stmts,
364: MutatingScope $scope,
365: ExpressionResultStorage $storage,
366: callable $nodeCallback,
367: StatementContext $context,
368: ): InternalStatementResult
369: {
370: // make the storage this walk writes into scope-visible: loop-convergence
371: // passes (including the closure by-ref convergence, which calls this
372: // method directly) thread a throwaway duplicate that would otherwise
373: // never reach the storage stack, so every in-pass ask
374: // (applySpecifiedTypes pricing, rules via Scope::getType) would miss the
375: // pass's own results and re-process real nodes on demand
376: $pushStorage = $scope->getCurrentExpressionResultStorage() !== $storage;
377: if ($pushStorage) {
378: $scope->pushExpressionResultStorage($storage);
379: }
380: try {
381: return $this->statementsHandler->doProcessStmtNodes($this, $parentNode, $stmts, $scope, $storage, $nodeCallback, $context);
382: } finally {
383: if ($pushStorage) {
384: $scope->popExpressionResultStorage();
385: }
386: }
387: }
388:
389: /**
390: * @param callable(Node $node, Scope $scope): void $nodeCallback
391: */
392: public function processStmtNode(
393: Node\Stmt $stmt,
394: MutatingScope $scope,
395: ExpressionResultStorage $storage,
396: callable $nodeCallback,
397: StatementContext $context,
398: ): InternalStatementResult
399: {
400: $overridingThrowPoints = null;
401: if (
402: !$stmt instanceof Static_
403: && !$stmt instanceof Node\Stmt\Global_
404: && !$stmt instanceof Node\Stmt\Property
405: && !$stmt instanceof Node\Stmt\ClassConst
406: && !$stmt instanceof Node\Stmt\Const_
407: && !$stmt instanceof Node\Stmt\ClassLike
408: && !$stmt instanceof Node\Stmt\Function_
409: && !$stmt instanceof Node\Stmt\ClassMethod
410: ) {
411: if (!$stmt instanceof Foreach_) {
412: $scope = $this->statementsHandler->processStmtVarAnnotation($this, $scope, $storage, $stmt, null, $nodeCallback);
413: }
414: $overridingThrowPoints = $this->statementsHandler->getOverridingThrowPoints($stmt, $scope);
415: }
416: $varTagDependencies = $this->statementsHandler->getVarTagDependencies($stmt, $scope);
417:
418: if ($stmt instanceof Node\Stmt\ClassMethod) {
419: // a trait method the using class overrides is not analysed here at all -
420: // decided before the node callback is emitted; the override can be the
421: // class's own method, another trait's, or an engine-provided one like
422: // enum cases(), from() and tryFrom(), so it is told by the declaring
423: // class of the native method, not by the kind of its method reflection
424: if (!$scope->isInClass()) {
425: throw new ShouldNotHappenException();
426: }
427: if ($scope->isInTrait()) {
428: $nativeClassReflection = $scope->getClassReflection()->getNativeReflection();
429: $methodName = $stmt->name->toString();
430: if (
431: $nativeClassReflection->hasMethod($methodName)
432: && $nativeClassReflection->getMethod($methodName)->getBetterReflection()->getDeclaringClass()->getName() !== $scope->getTraitReflection()->getName()
433: ) {
434: return new InternalStatementResult($scope, hasYield: false, isAlwaysTerminating: false, exitPoints: [], throwPoints: [], impurePoints: []);
435: }
436: }
437: }
438:
439: // Statements whose work is processing their expressions emit their node
440: // callback AFTER that processing, inside their branches below, with the
441: // entry scope - a synchronously invoked rule (the plain resolver,
442: // PHP < 8.1) then finds the expressions' results in the storage instead
443: // of re-walking them on demand, mirroring processExprNodeInternal().
444: $deferredStmtCallback = $stmt instanceof Return_ || $stmt instanceof Node\Stmt\Expression || $stmt instanceof Echo_
445: || $stmt instanceof If_ || $stmt instanceof Switch_ || $stmt instanceof Foreach_
446: || $stmt instanceof Node\Stmt\Unset_ || $stmt instanceof Node\Stmt\ClassConst
447: || $stmt instanceof Node\Stmt\Const_ || $stmt instanceof Node\Stmt\While_
448: || $stmt instanceof Node\Stmt\Do_;
449: if (!$deferredStmtCallback) {
450: $this->callNodeCallback($nodeCallback, $stmt, $scope, $storage);
451: }
452:
453: $stmtHandler = StmtHandlerRegistry::resolve($stmt, $this->container);
454: if ($stmtHandler !== null) {
455: $stmtResult = $stmtHandler->processStmt($this, $stmt, $scope, $storage, $nodeCallback, $context);
456: if ($varTagDependencies !== null) {
457: $stmtResult = $stmtResult->withDependencies(Dependencies::merge($stmtResult->getDependencies(), $varTagDependencies));
458: }
459: if ($overridingThrowPoints !== null) {
460: // the overriding throw points use the scope before the statement,
461: // so the variable flow throws before the statement does its work
462: $overridingThrowFlows = [];
463: foreach ($overridingThrowPoints as $overridingThrowPoint) {
464: $overridingThrowFlows[] = VariableFlow::throwing($overridingThrowPoint->getType(), true, $overridingThrowPoint->canContainAnyThrowable());
465: }
466:
467: return new InternalStatementResult(
468: $stmtResult->getScope(),
469: hasYield: $stmtResult->hasYield(),
470: isAlwaysTerminating: $stmtResult->isAlwaysTerminating(),
471: exitPoints: $stmtResult->getExitPoints(),
472: throwPoints: $overridingThrowPoints,
473: impurePoints: $stmtResult->getImpurePoints(),
474: endStatements: $stmtResult->getEndStatements(),
475: variableFlow: VariableFlow::sequence(...$overridingThrowFlows, ...[$stmtResult->getVariableFlow()]),
476: dependencies: $stmtResult->getDependencies(),
477: );
478: }
479:
480: return $stmtResult;
481: }
482:
483: // statements with no analysis of their own (e.g. HaltCompiler)
484: return new InternalStatementResult($scope, hasYield: false, isAlwaysTerminating: false, exitPoints: [], throwPoints: $overridingThrowPoints ?? [], impurePoints: [], dependencies: $varTagDependencies);
485: }
486:
487: public function isAnalysedFile(string $fileName): bool
488: {
489: return isset($this->analysedFiles[$fileName]);
490: }
491:
492: /** Whether an on-demand walk answers already processed real nodes from their stored results (see processExprOnDemand()). */
493: public function isReturningStoredExpressionResults(): bool
494: {
495: return $this->returnStoredExpressionResults;
496: }
497:
498: public function lookForSetAllowedUndefinedExpressions(MutatingScope $scope, Expr $expr): MutatingScope
499: {
500: return $this->lookForExpressionCallback($scope, $expr, static fn (MutatingScope $scope, Expr $expr): MutatingScope => $scope->setAllowedUndefinedExpression($expr));
501: }
502:
503: public function lookForUnsetAllowedUndefinedExpressions(MutatingScope $scope, Expr $expr): MutatingScope
504: {
505: return $this->lookForExpressionCallback($scope, $expr, static fn (MutatingScope $scope, Expr $expr): MutatingScope => $scope->unsetAllowedUndefinedExpression($expr));
506: }
507:
508: /**
509: * @param Closure(MutatingScope $scope, Expr $expr): MutatingScope $callback
510: */
511: private function lookForExpressionCallback(MutatingScope $scope, Expr $expr, Closure $callback): MutatingScope
512: {
513: if (!$expr instanceof ArrayDimFetch || $expr->dim !== null) {
514: $scope = $callback($scope, $expr);
515: }
516:
517: if ($expr instanceof ArrayDimFetch) {
518: $scope = $this->lookForExpressionCallback($scope, $expr->var, $callback);
519: } elseif ($expr instanceof PropertyFetch || $expr instanceof Expr\NullsafePropertyFetch || $expr instanceof Expr\NullsafeMethodCall) {
520: $scope = $this->lookForExpressionCallback($scope, $expr->var, $callback);
521: } elseif ($expr instanceof StaticPropertyFetch && $expr->class instanceof Expr) {
522: $scope = $this->lookForExpressionCallback($scope, $expr->class, $callback);
523: } elseif ($expr instanceof List_) {
524: foreach ($expr->items as $item) {
525: if ($item === null) {
526: continue;
527: }
528:
529: $scope = $this->lookForExpressionCallback($scope, $item->value, $callback);
530: }
531: }
532:
533: return $scope;
534: }
535:
536: /**
537: * Processes an expression outside the normal AST traversal - e.g. a synthetic
538: * node a rule or extension asks about. Real AST nodes contained in it return
539: * their already-stored results instead of being processed again. New results
540: * are stored into the given storage - pass a duplicate to keep them isolated.
541: */
542: /**
543: * Processes an expression whose already-walked receiver must be CONSUMED
544: * from its stored result instead of re-walked: the nullsafe handlers
545: * process the receiver once (real callbacks) and then walk the plain twin,
546: * whose receiver answers from storage, re-anchored to the twin's
547: * (ensured) scope.
548: *
549: * @param callable(Node $node, Scope $scope): void $nodeCallback
550: */
551: public function processExprNodeConsumingStored(Node\Stmt $stmt, Expr $expr, Expr $consumedExpr, MutatingScope $scope, ExpressionResultStorage $storage, callable $nodeCallback, ExpressionContext $context): ExpressionResult
552: {
553: $previous = $this->consumeStoredExpression;
554: $this->consumeStoredExpression = $consumedExpr;
555: try {
556: return $this->processExprNode($stmt, $expr, $scope, $storage, $nodeCallback, $context);
557: } finally {
558: $this->consumeStoredExpression = $previous;
559: }
560: }
561:
562: public function processExprOnDemand(Expr $expr, MutatingScope $scope, ExpressionResultStorage $storage): ExpressionResult
563: {
564: // A node no handler supports - a virtual node (BooleanOrNode, ...) a
565: // rule asked the type of - degrades to mixed, mirroring
566: // MutatingScope::resolveType()'s fallback. The main walk's unhandled
567: // throw stays: real source nodes must have a handler.
568: if (
569: ExprHandlerRegistry::resolve($expr, $this->container) === null
570: && !($expr instanceof Expr\CallLike && $expr->isPartialFunctionApplication())
571: ) {
572: $mixed = new MixedType();
573: return $this->expressionResultFactory->create(
574: $scope,
575: beforeScope: $scope,
576: expr: $expr,
577: hasYield: false,
578: isAlwaysTerminating: false,
579: throwPoints: [],
580: impurePoints: [],
581: typeCallback: null,
582: specifyTypesCallback: SpecifiedTypes::emptySpecifyCallback(),
583: type: $mixed,
584: nativeType: $mixed,
585: );
586: }
587:
588: // save/restore, never reset: on-demand walks nest (a typeCallback
589: // evaluated mid-walk prices another synthetic node) and a hard reset
590: // would turn stored-result consumption off for the rest of the outer
591: // walk - re-processing every remaining subtree and bypassing the
592: // closure-argument consume guards in ArgumentsHandler::processArgs()
593: $previous = $this->returnStoredExpressionResults;
594: $this->returnStoredExpressionResults = true;
595: $scope->pushExpressionResultStorage($storage);
596: try {
597: return $this->processExprNode(
598: new Node\Stmt\Expression($expr),
599: $expr,
600: $scope,
601: $storage,
602: new NoopNodeCallback(),
603: ExpressionContext::createTopLevel(resolveTemplateArguments: false),
604: );
605: } finally {
606: $scope->popExpressionResultStorage();
607: $this->returnStoredExpressionResults = $previous;
608: }
609: }
610:
611: /**
612: * The stored ExpressionResult of a node processExprNode() already processed
613: * into the given storage - the caller asserts the processing order by
614: * holding the very storage it processed the node into (a scope-based lookup
615: * would miss loop-convergence storages, which are never scope-visible).
616: * Throws when the node has no stored result.
617: */
618: public function readStoredResult(Expr $expr, ExpressionResultStorage $storage): ExpressionResult
619: {
620: $result = $storage->findExpressionResult($expr);
621: if ($result === null) {
622: throw new ShouldNotHappenException(sprintf(
623: '%s on line %d has no stored ExpressionResult - it was not processed by processExprNode().',
624: get_class($expr),
625: $expr->getStartLine(),
626: ));
627: }
628:
629: return $result;
630: }
631:
632: /**
633: * The type, on the given scope, of a node that may or may not have a stored
634: * ExpressionResult. Every call site of this method is UNDECIDED about whether
635: * the node was already analysed - each should eventually either consume the
636: * node's ExpressionResult where it was processed or be a synthetic node
637: * (processSyntheticOnDemand()).
638: */
639: public function readTypeOfMaybeStored(Expr $expr, MutatingScope $scope): Type
640: {
641: $storage = $scope->getCurrentExpressionResultStorage();
642: $result = $storage?->findExpressionResult($expr);
643: if ($result !== null) {
644: return $result->getTypeOnScope($scope, $scope->nativeTypesPromoted);
645: }
646:
647: return $this->readScopeStateOrSyntheticType($expr, $scope);
648: }
649:
650: /**
651: * The type the scope itself knows for the expression, without any node
652: * processing: a string-named variable read is scope state (mirrors
653: * VariableHandler's typeCallback), and a type tracked for the whole
654: * expression answers directly - an on-demand walk would return that very
655: * holder anyway (the fresh result's beforeScope is the asking scope),
656: * after paying the walk. Null when the scope has no answer; the caller
657: * decides whether that means a synthetic walk (processSyntheticOnDemand())
658: * or an invariant violation.
659: */
660: public function findScopeStateType(Expr $expr, MutatingScope $scope): ?Type
661: {
662: if ($expr instanceof Expr\Variable && is_string($expr->name)) {
663: if ($scope->hasVariableType($expr->name)->no()) {
664: return new ErrorType();
665: }
666:
667: return $scope->getVariableType($expr->name);
668: }
669:
670: // a literal is position-independent: the scope prices it without a walk,
671: // so an argument the walk reaches only later (an IIFE's or a pipe's
672: // operand) never has to be processed ahead of its turn
673: if ($expr instanceof Node\Scalar\String_ || $expr instanceof Node\Scalar\Int_ || $expr instanceof Node\Scalar\Float_) {
674: return $scope->getStateType($expr);
675: }
676:
677: // A variable whose name is an expression ($$name) never reaches the read
678: // above, and the scope tracks it like any other expression - so it belongs
679: // here rather than falling through to a walk.
680: if (
681: !$expr instanceof Expr\Closure
682: && !$expr instanceof Expr\ArrowFunction
683: && $scope->hasExpressionType($expr)->yes()
684: ) {
685: return TypeUtils::resolveLateResolvableTypes($scope->getTrackedExpressionType($expr));
686: }
687:
688: return null;
689: }
690:
691: /**
692: * The type, on the given scope, of a node the caller knows has no stored
693: * ExpressionResult in its walk: scope state (variable read / tracked
694: * holder) answers without a walk, anything else is priced as a synthetic
695: * node.
696: */
697: public function readScopeStateOrSyntheticType(Expr $expr, MutatingScope $scope): Type
698: {
699: return $this->findScopeStateType($expr, $scope) ?? $this->processSyntheticOnDemand($expr, $scope)->getTypeOnScope($scope, $scope->nativeTypesPromoted);
700: }
701:
702: /**
703: * The type the scope knows for an expression the caller has already pinned as
704: * tracked there (hasExpressionType() yes, or a string-named variable). Unlike
705: * readScopeStateOrSyntheticType() this never falls back to a synthetic walk -
706: * the caller decided that the scope answers.
707: */
708: public function requireScopeStateType(Expr $expr, MutatingScope $scope): Type
709: {
710: $type = $this->findScopeStateType($expr, $scope);
711: if ($type === null) {
712: throw new ShouldNotHappenException(sprintf(
713: '%s on line %d is not tracked on the scope it was pinned as tracked on.',
714: get_class($expr),
715: $expr->getStartLine(),
716: ));
717: }
718:
719: return $type;
720: }
721:
722: /**
723: * Fires the PHPSTAN_GUARD_NW diagnostic when a real (non-synthetic) AST node
724: * reaches an on-demand pricing path without having been processed and stored
725: * by processExprNode() first. Mirrors the guard in MutatingScope::getType():
726: * such a node should be answered from its stored ExpressionResult, never
727: * re-priced as if it were synthetic. Dormant unless PHPSTAN_GUARD_NW=1.
728: */
729: private function guardAgainstUnprocessedRealNode(Expr $expr, string $caller): void
730: {
731: if (
732: !self::$guardNewWorld
733: || !isset(self::$guardRealExprIds[spl_object_id($expr)])
734: || isset(self::$guardProcessedExprIds[spl_object_id($expr)])
735: ) {
736: return;
737: }
738:
739: throw new ShouldNotHappenException(sprintf(
740: '%s() asked about non-synthetic %s on line %d before it was processed by processExprNode() - it should consume the node\'s ExpressionResult instead.',
741: $caller,
742: get_class($expr),
743: $expr->getStartLine(),
744: ));
745: }
746:
747: /**
748: * Processes a synthetic node (one an ExprHandler built itself) on a duplicate
749: * of the storage of the analysis currently in progress, mirroring
750: * MutatingScope::resolveTypeOfNewWorldHandlerNode(): the duplicate isolates
751: * the synthetic node's own stored result from the live storage while its real
752: * subnodes still resolve from the fallback.
753: */
754: public function processSyntheticOnDemand(Expr $expr, MutatingScope $scope): ExpressionResult
755: {
756: $this->guardAgainstUnprocessedRealNode($expr, __FUNCTION__);
757: $current = $scope->getCurrentExpressionResultStorage() ?? new ExpressionResultStorage();
758:
759: return $this->processExprOnDemand($expr, $scope, $current->duplicate());
760: }
761:
762: /**
763: * @param callable(Node $node, Scope $scope): void $nodeCallback
764: */
765: public function processExprNode(
766: Node\Stmt $stmt,
767: Expr $expr,
768: MutatingScope $scope,
769: ExpressionResultStorage $storage,
770: callable $nodeCallback,
771: ExpressionContext $context,
772: ): ExpressionResult
773: {
774: $consume = $this->consumeStoredExpression === $expr;
775: if ($this->returnStoredExpressionResults || $consume) {
776: $storedResult = $storage->findExpressionResult($expr);
777: // a stored result only answers when the current scope agrees with its
778: // evaluation position on the variables the expression reads - a
779: // counterfactual walk (an extension re-binding a variable and pricing
780: // a real subtree, e.g. array_filter's per-element callback evaluation)
781: // re-processes the node on its own scope instead. In CONSUME mode the
782: // divergence is intentional (an ensured-non-null device) and the
783: // stored result is consumed unconditionally, re-anchored below.
784: if ($storedResult !== null && ($consume || $storedResult->askScopeVariableStateMatches($scope, $scope->nativeTypesPromoted))) {
785: // a foreign-position answer must not thread its original walk
786: // scopes into THIS walk - re-anchor it to the asking position so
787: // subsequent operands keep evaluating on the asking scope
788: if ($storedResult->getBeforeScope() === $scope) {
789: return $storedResult;
790: }
791:
792: $reanchored = $storedResult->atAskPosition($scope);
793: if ($consume) {
794: // the re-anchored view IS this walk's result for the node
795: // (the nullsafe twin's receiver at the ensured position) -
796: // store it so later asks (rules' storage reads) see the same
797: // result the twin walk itself consumed, exactly like the
798: // receiver walked inside the twin used to be stored
799: $this->storeExpressionResult($storage, $expr, $reanchored);
800: }
801:
802: return $reanchored;
803: }
804: }
805:
806: return $this->processExprNodeInternal($stmt, $expr, $scope, $storage, $nodeCallback, $context);
807: }
808:
809: /**
810: * @param callable(Node $node, Scope $scope): void $nodeCallback
811: */
812: private function processExprNodeInternal(
813: Node\Stmt $stmt,
814: Expr $expr,
815: MutatingScope $scope,
816: ExpressionResultStorage $storage,
817: callable $nodeCallback,
818: ExpressionContext $context,
819: ): ExpressionResult
820: {
821: // a nullsafe first-class callable is a compile error; its handler turns it
822: // into a plain MethodCall, which then lands here
823: if ($expr instanceof Expr\CallLike && !$expr instanceof Expr\NullsafeMethodCall && $expr->isPartialFunctionApplication()) {
824: if ($expr instanceof FuncCall) {
825: $newExpr = new FunctionCallableNode($expr->name, $expr);
826: } elseif ($expr instanceof MethodCall) {
827: $newExpr = new MethodCallableNode($expr->var, $expr->name, $expr);
828: } elseif ($expr instanceof StaticCall) {
829: $newExpr = new StaticMethodCallableNode($expr->class, $expr->name, $expr);
830: } elseif ($expr instanceof New_ && !$expr->class instanceof Class_) {
831: $newExpr = new InstantiationCallableNode($expr->class, $expr);
832: } else {
833: throw new ShouldNotHappenException();
834: }
835:
836: $newExprResult = $this->processExprNode($stmt, $newExpr, $scope, $storage, $nodeCallback, $context);
837: $expressionResult = $this->expressionResultFactory->create(
838: $newExprResult->getScope(),
839: beforeScope: $scope,
840: expr: $expr,
841: hasYield: $newExprResult->hasYield(),
842: isAlwaysTerminating: $newExprResult->isAlwaysTerminating(),
843: throwPoints: $newExprResult->getThrowPoints(),
844: impurePoints: $newExprResult->getImpurePoints(),
845: variableFlow: $newExprResult->getVariableFlow(),
846: // the first-class callable closure type lives on the *CallableNode
847: // result; delegate so getType() of the original CallLike answers from it
848: typeCallback: static fn (bool $nativeTypesPromoted): Type => ($nativeTypesPromoted ? $newExprResult->getNativeType() : $newExprResult->getType()),
849: specifyTypesCallback: SpecifiedTypes::emptySpecifyCallback(),
850: dependencies: $newExprResult->getDependencies(),
851: );
852: $this->storeExpressionResult($storage, $expr, $expressionResult);
853: return $expressionResult;
854: }
855:
856: $exprHandler = ExprHandlerRegistry::resolve($expr, $this->container);
857: if ($exprHandler !== null) {
858: $expressionResult = $exprHandler->processExpr($this, $stmt, $expr, $scope, $storage, $nodeCallback, $context);
859: // a chain link an enclosing isset/empty/?? could not device ahead
860: // of its walk (an untracked call) is deviced now, from the type
861: // the walk produced
862: $expressionResult = $this->getNonNullabilityHelper()->applyPendingEnsure($expr, $expressionResult);
863: $this->storeExpressionResult($storage, $expr, $expressionResult);
864: // Force potential producers before collecting the body's constraints.
865: // Type reads only construct markers; they never register sites as a side effect.
866: $frame = $scope->getCurrentTemplateArgumentFrame();
867: if (
868: $frame !== null && $frame->isObserving()
869: && $expr instanceof Expr\CallLike
870: ) {
871: $constraints = $this->templateArgumentObserver->collectSites($expressionResult->getType());
872: $expressionResult = $expressionResult->withScope($expressionResult->getScope()->addTemplateArgumentConstraints($constraints));
873: $this->storeExpressionResult($storage, $expr, $expressionResult);
874: }
875: // The node's own callback fires AFTER its result is stored, with the
876: // scope captured before processing. Rules observe the same (scope,
877: // answer) pair as at a pre-order emission - previously a pre-order
878: // rule parks on its first ask and resumes at this store anyway - but
879: // a synchronously invoked rule (the plain resolver, PHP < 8.1) now
880: // finds the node's and its subtree's results in the storage instead
881: // of re-walking them on demand.
882: $this->callNodeCallbackWithExpression($nodeCallback, $expr, $scope, $storage, $context);
883: // the call is now processed and stored; emit a virtual node so
884: // impossible-check rules read its specified types from the result
885: // instead of asking the scope before the call node is processed
886: if ($expr instanceof FuncCall) {
887: $this->callNodeCallbackWithExpression($nodeCallback, new FunctionCallExpressionNode($expr, $expressionResult, $expressionResult->getArgsResult()), $scope, $storage, $context);
888: } elseif ($expr instanceof MethodCall) {
889: $this->callNodeCallbackWithExpression($nodeCallback, new MethodCallExpressionNode($expr, $expressionResult, $expressionResult->getArgsResult()), $scope, $storage, $context);
890: } elseif ($expr instanceof StaticCall) {
891: $this->callNodeCallbackWithExpression($nodeCallback, new StaticMethodCallExpressionNode($expr, $expressionResult, $expressionResult->getArgsResult()), $scope, $storage, $context);
892: }
893: return $expressionResult;
894: }
895:
896: throw new ShouldNotHappenException(sprintf('Unhandled expr: %s', get_class($expr)));
897: }
898:
899: /**
900: * Unlike a method call, a property read defaults to pure: only a hook we're
901: * certain about and that is certainly side-effecting makes the read impure.
902: *
903: * The reset is assumed pure as reporting those would make accessing them
904: * unreasonably annoying.
905: *
906: * @param 'get'|'set' $hookName
907: * @return ImpurePoint[]
908: */
909: public function getImpurePointsFromPropertyHook(
910: MutatingScope $scope,
911: PropertyFetch $propertyFetch,
912: PhpPropertyReflection $propertyReflection,
913: string $hookName,
914: ): array
915: {
916: if ($this->isPropertyHookBackingValueAccess($scope, $propertyFetch)) {
917: return [];
918: }
919:
920: if (!$propertyReflection->hasHook($hookName)) {
921: return [];
922: }
923:
924: if (!$propertyReflection->getHook($hookName)->hasSideEffects()->yes()) {
925: return [];
926: }
927:
928: return [
929: new ImpurePoint(
930: $scope,
931: $propertyFetch,
932: 'propertyHookCall',
933: sprintf(
934: 'call to %s hook of property %s::$%s',
935: $hookName,
936: $propertyReflection->getDeclaringClass()->getDisplayName(),
937: $propertyReflection->getName(),
938: ),
939: true,
940: ),
941: ];
942: }
943:
944: /**
945: * Inside a hook of the same property, $this->prop is the backing value, not
946: * a re-entrant hook call.
947: */
948: private function isPropertyHookBackingValueAccess(MutatingScope $scope, PropertyFetch $propertyFetch): bool
949: {
950: $scopeFunction = $scope->getFunction();
951:
952: return $scopeFunction instanceof PhpMethodFromParserNodeReflection
953: && $scopeFunction->isPropertyHook()
954: && $propertyFetch->var instanceof Variable
955: && $propertyFetch->var->name === 'this'
956: && $propertyFetch->name instanceof Identifier
957: && $propertyFetch->name->toString() === $scopeFunction->getHookedPropertyName();
958: }
959:
960: /**
961: * @return string[]
962: */
963: public function getAssignedVariables(Expr $expr): array
964: {
965: if ($expr instanceof Expr\Variable) {
966: if (is_string($expr->name)) {
967: return [$expr->name];
968: }
969:
970: return [];
971: }
972:
973: if ($expr instanceof Expr\List_) {
974: $names = [];
975: foreach ($expr->items as $item) {
976: if ($item === null) {
977: continue;
978: }
979:
980: $names = array_merge($names, $this->getAssignedVariables($item->value));
981: }
982:
983: return $names;
984: }
985:
986: if ($expr instanceof ArrayDimFetch) {
987: return $this->getAssignedVariables($expr->var);
988: }
989:
990: return [];
991: }
992:
993: private const REPLAYABLE_BODY_ATTRIBUTE = 'convergenceReplayableBody';
994:
995: private const CONTEXT_SENSITIVE_STATEMENT_ATTRIBUTE = 'convergenceContextSensitiveStatement';
996:
997: /**
998: * Whether a recorded convergence pass over the loop body can replace the
999: * final walk. A pass runs at deep statement context, the final walk at top
1000: * level - constructs that analyse differently between the two (nested
1001: * loop/label fixpoints run only at top level, statement-level classes are
1002: * skipped at deep context) disqualify the body. Closure bodies process
1003: * context-independently and are not traversed.
1004: *
1005: * @param Node\Stmt[] $bodyStmts
1006: */
1007: public function isReplayableConvergenceBody(Node $loopNode, array $bodyStmts): bool
1008: {
1009: $cached = $loopNode->getAttribute(self::REPLAYABLE_BODY_ATTRIBUTE);
1010: if ($cached !== null) {
1011: return $cached;
1012: }
1013:
1014: $replayable = true;
1015: foreach ($bodyStmts as $bodyStmt) {
1016: if ($this->hasContextSensitiveConstruct($bodyStmt)) {
1017: $replayable = false;
1018: break;
1019: }
1020: }
1021: $loopNode->setAttribute(self::REPLAYABLE_BODY_ATTRIBUTE, $replayable);
1022:
1023: return $replayable;
1024: }
1025:
1026: /** A statement that walks differently in a convergence pass than in the final walk. */
1027: public function isContextSensitiveStatement(Node\Stmt $stmt): bool
1028: {
1029: $cached = $stmt->getAttribute(self::CONTEXT_SENSITIVE_STATEMENT_ATTRIBUTE);
1030: if ($cached !== null) {
1031: return $cached;
1032: }
1033:
1034: $sensitive = $this->hasContextSensitiveConstruct($stmt);
1035: $stmt->setAttribute(self::CONTEXT_SENSITIVE_STATEMENT_ATTRIBUTE, $sensitive);
1036:
1037: return $sensitive;
1038: }
1039:
1040: private function hasContextSensitiveConstruct(Node $node): bool
1041: {
1042: if ($node instanceof Expr\Closure) {
1043: return false;
1044: }
1045: if (
1046: $node instanceof Node\Stmt\While_
1047: || $node instanceof Node\Stmt\Do_
1048: || $node instanceof Node\Stmt\For_
1049: || $node instanceof Foreach_
1050: || $node instanceof Node\Stmt\Label
1051: || $node instanceof Node\Stmt\ClassLike
1052: ) {
1053: return true;
1054: }
1055:
1056: foreach ($node->getSubNodeNames() as $subNodeName) {
1057: $subNode = $node->$subNodeName;
1058: if ($subNode instanceof Node) {
1059: if ($this->hasContextSensitiveConstruct($subNode)) {
1060: return true;
1061: }
1062: } elseif (is_array($subNode)) {
1063: foreach ($subNode as $item) {
1064: if ($item instanceof Node && $this->hasContextSensitiveConstruct($item)) {
1065: return true;
1066: }
1067: }
1068: }
1069: }
1070:
1071: return false;
1072: }
1073:
1074: /**
1075: * Opens an engine-feeding gatherer frame for the duration of a body walk.
1076: * The caller closes it in a finally block via popNodeGatherer().
1077: *
1078: * @param callable(Node, Scope): void $gatherer
1079: */
1080: public function pushNodeGatherer(callable $gatherer): void
1081: {
1082: $this->nodeGatherers[] = $gatherer;
1083: }
1084:
1085: public function popNodeGatherer(): void
1086: {
1087: array_pop($this->nodeGatherers);
1088: }
1089:
1090: /**
1091: * Detaches all gatherer frames for a walk that must not feed them. The
1092: * caller reattaches them in a finally block via restoreNodeGatherers().
1093: *
1094: * @return list<callable(Node, Scope): void>
1095: */
1096: public function suspendNodeGatherers(): array
1097: {
1098: $gatherers = $this->nodeGatherers;
1099: $this->nodeGatherers = [];
1100:
1101: return $gatherers;
1102: }
1103:
1104: /**
1105: * @param list<callable(Node, Scope): void> $gatherers
1106: */
1107: public function restoreNodeGatherers(array $gatherers): void
1108: {
1109: $this->nodeGatherers = $gatherers;
1110: }
1111:
1112: /**
1113: * @param callable(Node $node, Scope $scope): void $nodeCallback
1114: */
1115: public function replayRecording(RecordingNodeCallback $recording, callable $nodeCallback, ExpressionResultStorage $storage, MutatingScope $scope): void
1116: {
1117: $this->replayRecordingRange($recording, 0, $recording->count(), $nodeCallback, $storage, $scope);
1118: }
1119:
1120: /**
1121: * Replays the recorded pairs [$from, $to) the way callNodeCallback() would
1122: * have emitted them: gatherer frames observe them exactly like live ones
1123: * (with the raw walk scope), a real callback gets the callback scope - and
1124: * a recording callback records them again (a loop's fixpoint replay running
1125: * inside a body's observation pass).
1126: *
1127: * @param callable(Node $node, Scope $scope): void $nodeCallback
1128: */
1129: public function replayRecordingRange(RecordingNodeCallback $recording, int $from, int $to, callable $nodeCallback, ExpressionResultStorage $storage, MutatingScope $scope): void
1130: {
1131: $pairs = $recording->getPairs();
1132: $scope->pushExpressionResultStorage($storage);
1133: try {
1134: for ($i = $from; $i < $to; $i++) {
1135: [$node, $pairScope] = $pairs[$i];
1136: if (!$pairScope instanceof MutatingScope) {
1137: throw new ShouldNotHappenException();
1138: }
1139: $this->callNodeCallback($nodeCallback, $node, $pairScope, $storage);
1140: }
1141: } finally {
1142: $scope->popExpressionResultStorage();
1143: }
1144: }
1145:
1146: /**
1147: * @param callable(Node $node, Scope $scope): void $nodeCallback
1148: */
1149: public function callNodeCallbackWithExpression(
1150: callable $nodeCallback,
1151: Node $expr,
1152: MutatingScope $scope,
1153: ExpressionResultStorage $storage,
1154: ExpressionContext $context,
1155: ): void
1156: {
1157: if ($context->isDeep()) {
1158: $scope = $scope->exitFirstLevelStatements();
1159: }
1160: $this->callNodeCallback($nodeCallback, $expr, $scope, $storage);
1161: }
1162:
1163: /**
1164: * @param callable(Node $node, Scope $scope): void $nodeCallback
1165: */
1166: public function callNodeCallback(
1167: callable $nodeCallback,
1168: Node $node,
1169: MutatingScope $scope,
1170: ExpressionResultStorage $storage,
1171: ): void
1172: {
1173: // Engine-feeding gatherer frames observe the node at the emission
1174: // position - their arrays are read as soon as the enclosing body walk
1175: // returns. Gatherers are engine code and never ask about types -
1176: // handing them the raw scope skips a NodeCallbackScope construction per
1177: // emission; the scopes they capture (return statements, impure points)
1178: // answer later asks through the storage hub like any MutatingScope.
1179: foreach ($this->nodeGatherers as $gatherer) {
1180: $gatherer($node, $scope);
1181: }
1182:
1183: if ($nodeCallback instanceof NoopNodeCallback) {
1184: return;
1185: }
1186:
1187: if ($nodeCallback instanceof RecordingNodeCallback) {
1188: // recording never asks about types - the pairs are wrapped and
1189: // bound to the storage at replay time instead
1190: $nodeCallback($node, $scope);
1191: return;
1192: }
1193:
1194: // post-order emission means the node's own result and every subnode
1195: // result are already stored when the callback fires - NodeCallbackScope
1196: // answers every ask synchronously from the storage
1197: $nodeCallback($node, $scope->toNodeCallbackScope());
1198: }
1199:
1200: /**
1201: * The template argument frame of the body being walked while it observes
1202: * a body that created unresolved template arguments (or, in the closure
1203: * observation pass, closure signatures) - null otherwise, so every
1204: * observation hook costs a null check outside the observation passes.
1205: */
1206: public function observingTemplateArgumentFrame(MutatingScope $scope): ?TemplateArgumentFrame
1207: {
1208: $frame = $scope->getCurrentTemplateArgumentFrame();
1209: if ($frame === null || !$frame->isObservingClosures() || $scope->getTemplateArgumentConstraints() === null) {
1210: return null;
1211: }
1212:
1213: return $frame;
1214: }
1215:
1216: /**
1217: * A value leaves the function: the declared return type is a send target for
1218: * the unresolved template arguments it carries.
1219: */
1220: public function collectReturnSend(MutatingScope $scope, ExpressionResult $returnedResult): TemplateArgumentConstraints
1221: {
1222: $frame = $this->observingTemplateArgumentFrame($returnedResult->getScope());
1223: if ($frame === null) {
1224: return TemplateArgumentConstraints::createEmpty();
1225: }
1226: $declaredReturnType = self::getDeclaredReturnType($scope);
1227: if ($declaredReturnType === null) {
1228: return TemplateArgumentConstraints::createEmpty();
1229: }
1230:
1231: return $this->templateArgumentObserver->collectSend($declaredReturnType, $returnedResult->getType());
1232: }
1233:
1234: /**
1235: * A generator hands out a key and a value: the key and value types of the
1236: * declared return type (Generator<TKey, TValue>, iterable<K, V>) are send
1237: * targets for the unresolved template arguments and the closures they carry.
1238: * A return type that describes no iterable lets the closures escape.
1239: */
1240: public function collectYieldSend(MutatingScope $scope, ?Type $keyType, ?Type $valueType): TemplateArgumentConstraints
1241: {
1242: $constraints = TemplateArgumentConstraints::createEmpty();
1243: if ($this->observingTemplateArgumentFrame($scope) === null) {
1244: return $constraints;
1245: }
1246: $declaredReturnType = self::getDeclaredReturnType($scope);
1247: if ($declaredReturnType === null || !$declaredReturnType->isIterable()->yes()) {
1248: foreach ([$keyType, $valueType] as $yieldedType) {
1249: if ($yieldedType === null) {
1250: continue;
1251: }
1252: $constraints = $constraints->merge($this->templateArgumentObserver->collectEscape($yieldedType));
1253: }
1254:
1255: return $constraints;
1256: }
1257: if ($keyType !== null) {
1258: $constraints = $constraints->merge($this->templateArgumentObserver->collectSend($declaredReturnType->getIterableKeyType(), $keyType));
1259: }
1260: if ($valueType !== null) {
1261: $constraints = $constraints->merge($this->templateArgumentObserver->collectSend($declaredReturnType->getIterableValueType(), $valueType));
1262: }
1263:
1264: return $constraints;
1265: }
1266:
1267: /**
1268: * `yield from` hands out the keys and values of the iterable it delegates to.
1269: */
1270: public function collectYieldFromSend(MutatingScope $scope, Type $delegatedType): TemplateArgumentConstraints
1271: {
1272: if ($this->observingTemplateArgumentFrame($scope) === null) {
1273: return TemplateArgumentConstraints::createEmpty();
1274: }
1275: if (!$delegatedType->isIterable()->yes()) {
1276: return $this->templateArgumentObserver->collectEscape($delegatedType);
1277: }
1278:
1279: return $this->collectYieldSend($scope, $delegatedType->getIterableKeyType(), $delegatedType->getIterableValueType());
1280: }
1281:
1282: private static function getDeclaredReturnType(MutatingScope $scope): ?Type
1283: {
1284: if ($scope->isInAnonymousFunction()) {
1285: return $scope->getAnonymousFunctionReturnType();
1286: }
1287:
1288: $function = $scope->getFunction();
1289:
1290: return $function?->getReturnType();
1291: }
1292:
1293: }
1294: