1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Analyser;
4:
5: use PhpParser\Node;
6: use PhpParser\Node\Arg;
7: use PhpParser\Node\ComplexType;
8: use PhpParser\Node\Expr;
9: use PhpParser\Node\Expr\Array_;
10: use PhpParser\Node\Expr\ClassConstFetch;
11: use PhpParser\Node\Expr\ConstFetch;
12: use PhpParser\Node\Expr\FuncCall;
13: use PhpParser\Node\Expr\Match_;
14: use PhpParser\Node\Expr\MethodCall;
15: use PhpParser\Node\Expr\PropertyFetch;
16: use PhpParser\Node\Expr\Variable;
17: use PhpParser\Node\Identifier;
18: use PhpParser\Node\Name;
19: use PhpParser\Node\Name\FullyQualified;
20: use PhpParser\Node\PropertyHook;
21: use PhpParser\Node\Scalar;
22: use PhpParser\Node\Scalar\String_;
23: use PhpParser\Node\Stmt\ClassMethod;
24: use PhpParser\Node\Stmt\Function_;
25: use PhpParser\NodeFinder;
26: use PHPStan\Analyser\ExprHandler\Helper\ClosureTypeResolver;
27: use PHPStan\Analyser\Generics\ClosureSignatureInference;
28: use PHPStan\Analyser\Generics\TemplateArgumentConstraints;
29: use PHPStan\Analyser\Generics\TemplateArgumentFrame;
30: use PHPStan\Analyser\Traverser\TransformStaticTypeTraverser;
31: use PHPStan\Collectors\Collector;
32: use PHPStan\Node\EmitCollectedDataNode;
33: use PHPStan\Node\Expr\AlwaysRememberedExpr;
34: use PHPStan\Node\Expr\CloneReinitializationExpr;
35: use PHPStan\Node\Expr\IntertwinedVariableByReferenceWithExpr;
36: use PHPStan\Node\Expr\NativeTypeExpr;
37: use PHPStan\Node\Expr\OriginalForeachKeyExpr;
38: use PHPStan\Node\Expr\OriginalForeachValueExpr;
39: use PHPStan\Node\Expr\ParameterVariableOriginalValueExpr;
40: use PHPStan\Node\Expr\PropertyInitializationExpr;
41: use PHPStan\Node\Expr\SetExistingOffsetValueTypeExpr;
42: use PHPStan\Node\IssetExpr;
43: use PHPStan\Node\Printer\ExprPrinter;
44: use PHPStan\Node\VirtualNode;
45: use PHPStan\Php\PhpVersionFactory;
46: use PHPStan\Php\PhpVersions;
47: use PHPStan\PhpDoc\ResolvedPhpDocBlock;
48: use PHPStan\Reflection\Assertions;
49: use PHPStan\Reflection\AttributeReflection;
50: use PHPStan\Reflection\ClassConstantReflection;
51: use PHPStan\Reflection\ClassMemberReflection;
52: use PHPStan\Reflection\ClassReflection;
53: use PHPStan\Reflection\ExtendedMethodReflection;
54: use PHPStan\Reflection\ExtendedParametersAcceptor;
55: use PHPStan\Reflection\ExtendedPropertyReflection;
56: use PHPStan\Reflection\FunctionReflection;
57: use PHPStan\Reflection\InitializerExprContext;
58: use PHPStan\Reflection\MethodReflection;
59: use PHPStan\Reflection\ParameterReflection;
60: use PHPStan\Reflection\ParametersAcceptorSelector;
61: use PHPStan\Reflection\Php\PhpFunctionFromParserNodeReflection;
62: use PHPStan\Reflection\Php\PhpMethodFromParserNodeReflection;
63: use PHPStan\Reflection\PropertyReflection;
64: use PHPStan\ShouldNotHappenException;
65: use PHPStan\TrinaryLogic;
66: use PHPStan\Turbo\ShadowedByTurboExtension;
67: use PHPStan\Type\Accessory\AccessoryArrayListType;
68: use PHPStan\Type\Accessory\HasOffsetValueType;
69: use PHPStan\Type\Accessory\NonEmptyArrayType;
70: use PHPStan\Type\Accessory\OversizedArrayType;
71: use PHPStan\Type\ArrayType;
72: use PHPStan\Type\BenevolentUnionType;
73: use PHPStan\Type\ClosureType;
74: use PHPStan\Type\ConditionalTypeForParameter;
75: use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
76: use PHPStan\Type\Constant\ConstantBooleanType;
77: use PHPStan\Type\Constant\ConstantFloatType;
78: use PHPStan\Type\Constant\ConstantIntegerType;
79: use PHPStan\Type\Constant\ConstantStringType;
80: use PHPStan\Type\ConstantTypeHelper;
81: use PHPStan\Type\ErrorType;
82: use PHPStan\Type\GeneralizePrecision;
83: use PHPStan\Type\Generic\TemplateTypeHelper;
84: use PHPStan\Type\Generic\TemplateTypeMap;
85: use PHPStan\Type\IntegerRangeType;
86: use PHPStan\Type\IntegerType;
87: use PHPStan\Type\IntersectionType;
88: use PHPStan\Type\MixedType;
89: use PHPStan\Type\NeverType;
90: use PHPStan\Type\NullType;
91: use PHPStan\Type\ObjectType;
92: use PHPStan\Type\StaticType;
93: use PHPStan\Type\StaticTypeFactory;
94: use PHPStan\Type\StringType;
95: use PHPStan\Type\ThisType;
96: use PHPStan\Type\Type;
97: use PHPStan\Type\TypeCombinator;
98: use PHPStan\Type\TypeTraverser;
99: use PHPStan\Type\TypeUtils;
100: use PHPStan\Type\TypeWithClassName;
101: use PHPStan\Type\UnionType;
102: use PHPStan\Type\VerbosityLevel;
103: use PHPStan\Type\VoidType;
104: use Serializable;
105: use Throwable;
106: use function abs;
107: use function array_diff_key;
108: use function array_filter;
109: use function array_intersect_key;
110: use function array_key_exists;
111: use function array_keys;
112: use function array_last;
113: use function array_map;
114: use function array_merge;
115: use function array_pop;
116: use function array_shift;
117: use function array_slice;
118: use function array_values;
119: use function count;
120: use function ctype_alnum;
121: use function explode;
122: use function get_class;
123: use function implode;
124: use function in_array;
125: use function is_string;
126: use function ltrim;
127: use function md5;
128: use function min;
129: use function preg_match;
130: use function preg_match_all;
131: use function spl_object_id;
132: use function sprintf;
133: use function str_starts_with;
134: use function strlen;
135: use function strtolower;
136: use function substr;
137: use function uksort;
138: use function usort;
139: use const PHP_INT_MAX;
140: use const PHP_INT_MIN;
141:
142: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/MutatingScope.cpp')]
143: class MutatingScope implements Scope, NodeCallbackInvoker, CollectedDataEmitter, DependencyTracker
144: {
145:
146: private const COMPLEX_UNION_TYPE_MEMBER_LIMIT = 8;
147:
148: /** Distinct name/namespace combinations getGlobalConstantType() remembers the expression keys of. */
149: private const GLOBAL_CONSTANT_FETCH_KEYS_LIMIT = 8192;
150:
151: /** Magic methods that let the author decide which properties survive a serialize()/unserialize() round trip. */
152: private const CUSTOM_SERIALIZATION_METHODS = ['__sleep', '__serialize', '__unserialize'];
153:
154: /**
155: * Expression keys the constant-fetch nodes of a global constant lookup print
156: * as, by the name class, name and namespace they are built from. The nodes
157: * exist only to produce those keys, and a freshly built node can never hit
158: * the printer's node-attribute cache - so without this every lookup printed
159: * two or three of them again. PHP_VERSION_ID alone accounted for ~30% of all
160: * expression-key prints in a self-analysis run.
161: *
162: * @var array<string, list<string>>
163: */
164: private static array $globalConstantFetchKeys = [];
165:
166: /**
167: * Keys of the merged calls findUninformativeMergedCalls() is resolving.
168: * Resolving a call processes its arguments again, and merging a ternary
169: * among them can make the same call a candidate again, e.g. when
170: * conditional expressions tie the call's type to the ternary's condition
171: * after `$s = strlen($s ?: '') ?: 0;`. Such a nested check keeps the
172: * merged entry instead of resolving the call once more.
173: *
174: * @var array<string, true>
175: */
176: private static array $resolvingMergedCalls = [];
177:
178: /**
179: * @internal accessed by ScopeOps (native and PHP implementations)
180: * @var array<string, Type>
181: */
182: public array $resolvedTypes = [];
183:
184: private ?self $nodeCallbackScope = null;
185:
186: /** @var non-empty-string|null */
187: private ?string $namespace;
188:
189: private ?self $scopeOutOfFirstLevelStatement = null;
190:
191: private ?self $scopeWithPromotedNativeTypes = null;
192:
193: /** What getPhpVersion() answered for the expression types in $phpVersionExpressionTypes. */
194: private ?PhpVersions $phpVersion = null;
195:
196: /** @var array<string, ExpressionTypeHolder> */
197: private array $phpVersionExpressionTypes = [];
198:
199: /**
200: * @param array<string, ExpressionTypeHolder> $expressionTypes
201: * @param array<string, ConditionalExpressionHolder[]> $conditionalExpressions
202: * @param list<non-empty-string> $inClosureBindScopeClasses
203: * @param array<string, bool> $currentlyAssignedExpressions true when the expression is a plain write target (its writable type applies), false when it is read-modified in place (e.g. the base of `$prop[] = ...`), where its readable type applies
204: * @param array<string, true> $currentlyAllowedUndefinedExpressions
205: * @param array<string, ExpressionTypeHolder> $nativeExpressionTypes
206: * @param list<array{MethodReflection|FunctionReflection|null, ParameterReflection|null}> $inFunctionCallsStack
207: */
208: public function __construct(
209: private ScopeServices $services,
210: protected InternalScopeFactory $scopeFactory,
211: protected ScopeContext $context,
212: private bool $declareStrictTypes = false,
213: private PhpFunctionFromParserNodeReflection|null $function = null,
214: ?string $namespace = null,
215: public array $expressionTypes = [],
216: protected array $nativeExpressionTypes = [],
217: protected array $conditionalExpressions = [],
218: protected array $inClosureBindScopeClasses = [],
219: private ?ClosureType $anonymousFunctionReflection = null,
220: private bool $inFirstLevelStatement = true,
221: protected array $currentlyAssignedExpressions = [],
222: protected array $currentlyAllowedUndefinedExpressions = [],
223: public array $inFunctionCallsStack = [],
224: protected bool $afterExtractCall = false,
225: private ?self $parentScope = null,
226: public bool $nativeTypesPromoted = false,
227: protected ?TemplateArgumentFrame $templateArgumentFrame = null,
228: protected ?TemplateArgumentConstraints $templateArgumentConstraints = null,
229: )
230: {
231: if ($namespace === '') {
232: $namespace = null;
233: }
234:
235: $this->namespace = $namespace;
236: }
237:
238: public function toNodeCallbackScope(): self
239: {
240: if ($this->nodeCallbackScope !== null) {
241: return $this->nodeCallbackScope;
242: }
243:
244: $nodeCallbackScope = $this->scopeFactory->toNodeCallbackScopeFactory()->create(
245: $this->context,
246: $this->isDeclareStrictTypes(),
247: $this->getFunction(),
248: $this->getNamespace(),
249: $this->expressionTypes,
250: $this->nativeExpressionTypes,
251: $this->conditionalExpressions,
252: $this->inClosureBindScopeClasses,
253: $this->anonymousFunctionReflection,
254: $this->isInFirstLevelStatement(),
255: $this->currentlyAssignedExpressions,
256: $this->currentlyAllowedUndefinedExpressions,
257: $this->inFunctionCallsStack,
258: $this->afterExtractCall,
259: $this->parentScope,
260: $this->nativeTypesPromoted,
261: $this->templateArgumentFrame,
262: $this->templateArgumentConstraints,
263: );
264: if ($nodeCallbackScope instanceof NodeCallbackScope) {
265: $nodeCallbackScope->seedWalkScope($this);
266: }
267:
268: return $this->nodeCallbackScope = $nodeCallbackScope;
269: }
270:
271: public function toWalkScope(): self
272: {
273: return $this;
274: }
275:
276: /** @deprecated */
277: public function toMutatingScope(): self
278: {
279: return $this;
280: }
281:
282: /** @api */
283: public function getFile(): string
284: {
285: return $this->context->getFile();
286: }
287:
288: /** @api */
289: public function getFileDescription(): string
290: {
291: if ($this->context->getTraitReflection() === null) {
292: return $this->getFile();
293: }
294:
295: /** @var ClassReflection $classReflection */
296: $classReflection = $this->context->getClassReflection();
297:
298: $className = $classReflection->getDisplayName();
299: if (!$classReflection->isAnonymous()) {
300: $className = sprintf('class %s', $className);
301: }
302:
303: $traitReflection = $this->context->getTraitReflection();
304: if ($traitReflection->getFileName() === null) {
305: throw new ShouldNotHappenException();
306: }
307:
308: return sprintf(
309: '%s (in context of %s)',
310: $traitReflection->getFileName(),
311: $className,
312: );
313: }
314:
315: /** @api */
316: public function isDeclareStrictTypes(): bool
317: {
318: return $this->declareStrictTypes;
319: }
320:
321: public function enterDeclareStrictTypes(): self
322: {
323: return $this->scopeFactory->create(
324: $this->context,
325: true,
326: null,
327: null,
328: $this->expressionTypes,
329: $this->nativeExpressionTypes,
330: templateArgumentFrame: $this->templateArgumentFrame,
331: templateArgumentConstraints: $this->templateArgumentConstraints,
332: );
333: }
334:
335: /**
336: * @param array<string, ExpressionTypeHolder> $currentExpressionTypes
337: * @return array<string, ExpressionTypeHolder>
338: */
339: private function rememberConstructorExpressions(array $currentExpressionTypes): array
340: {
341: $rememberPropertyState = !$this->classHasCustomSerialization();
342: $expressionTypes = [];
343: foreach ($currentExpressionTypes as $exprString => $expressionTypeHolder) {
344: $expr = $expressionTypeHolder->getExpr();
345: if ($expr instanceof FuncCall) {
346: if (
347: !$expr->name instanceof Name
348: // interface_exists() etc. imply class_exists() therefore not listed here
349: || !in_array($expr->name->name, ['class_exists', 'function_exists'], true)
350: ) {
351: continue;
352: }
353: } elseif ($expr instanceof PropertyFetch) {
354: if (!$rememberPropertyState || !$this->isReadonlyPropertyFetch($expr, true)) {
355: continue;
356: }
357: } elseif ($expr instanceof PropertyInitializationExpr) {
358: if (!$rememberPropertyState) {
359: continue;
360: }
361: } elseif (!$expr instanceof ConstFetch) {
362: continue;
363: }
364:
365: $expressionTypes[$exprString] = $expressionTypeHolder;
366: }
367:
368: if (array_key_exists('$this', $currentExpressionTypes)) {
369: $expressionTypes['$this'] = $currentExpressionTypes['$this'];
370: }
371:
372: return $expressionTypes;
373: }
374:
375: /**
376: * A class with custom serialization logic can be rebuilt by unserialize()
377: * without the constructor ever running, and the author decides which properties
378: * make the round trip - so nothing the constructor established can be relied upon
379: * in the other methods.
380: */
381: private function classHasCustomSerialization(): bool
382: {
383: if (!$this->isInClass()) {
384: return false;
385: }
386:
387: $classReflection = $this->getClassReflection();
388: foreach (self::CUSTOM_SERIALIZATION_METHODS as $methodName) {
389: if ($classReflection->hasNativeMethod($methodName)) {
390: return true;
391: }
392: }
393:
394: return $classReflection->implementsInterface(Serializable::class)
395: && $classReflection->hasNativeMethod('unserialize');
396: }
397:
398: public function rememberConstructorScope(): self
399: {
400: return $this->scopeFactory->create(
401: $this->context,
402: $this->isDeclareStrictTypes(),
403: null,
404: $this->getNamespace(),
405: $this->rememberConstructorExpressions($this->expressionTypes),
406: $this->rememberConstructorExpressions($this->nativeExpressionTypes),
407: $this->conditionalExpressions,
408: $this->inClosureBindScopeClasses,
409: $this->anonymousFunctionReflection,
410: $this->inFirstLevelStatement,
411: [],
412: [],
413: $this->inFunctionCallsStack,
414: $this->afterExtractCall,
415: $this->parentScope,
416: $this->nativeTypesPromoted,
417: $this->templateArgumentFrame,
418: $this->templateArgumentConstraints,
419: );
420: }
421:
422: /** @internal called by ScopeOps */
423: public function isReadonlyPropertyFetch(PropertyFetch $expr, bool $allowOnlyOnThis): bool
424: {
425: while ($expr instanceof PropertyFetch) {
426: if ($expr->var instanceof Variable) {
427: if (
428: $allowOnlyOnThis
429: && (
430: ! $expr->name instanceof Node\Identifier
431: || !is_string($expr->var->name)
432: || $expr->var->name !== 'this'
433: )
434: ) {
435: return false;
436: }
437: } elseif (!$expr->var instanceof PropertyFetch) {
438: return false;
439: }
440:
441: $propertyReflection = $this->services->propertyReflectionFinder->findPropertyReflectionFromNode($expr, $this);
442: if ($propertyReflection === null) {
443: return false;
444: }
445:
446: $nativePropertyReflection = $propertyReflection->getNativeReflection();
447: if ($nativePropertyReflection === null || !$nativePropertyReflection->isReadOnly()) {
448: return false;
449: }
450:
451: $expr = $expr->var;
452: }
453:
454: $supportsReadOnlyProperties = $this->getPhpVersion()->supportsReadOnlyProperties();
455: return $this->services->checkWholePhpVersionRange ? !$supportsReadOnlyProperties->no() : $supportsReadOnlyProperties->yes();
456: }
457:
458: /** @api */
459: public function isInClass(): bool
460: {
461: return $this->context->getClassReflection() !== null;
462: }
463:
464: /** @api */
465: public function isInTrait(): bool
466: {
467: return $this->context->getTraitReflection() !== null;
468: }
469:
470: /** @api */
471: public function getClassReflection(): ?ClassReflection
472: {
473: return $this->context->getClassReflection();
474: }
475:
476: /** @api */
477: public function getTraitReflection(): ?ClassReflection
478: {
479: return $this->context->getTraitReflection();
480: }
481:
482: /**
483: * @api
484: */
485: public function getFunction(): ?PhpFunctionFromParserNodeReflection
486: {
487: return $this->function;
488: }
489:
490: /** @api */
491: public function getFunctionName(): ?string
492: {
493: return $this->function?->getName();
494: }
495:
496: /** @api */
497: public function getNamespace(): ?string
498: {
499: return $this->namespace;
500: }
501:
502: /** @api */
503: public function getParentScope(): ?self
504: {
505: return $this->parentScope;
506: }
507:
508: /** @api */
509: public function canAnyVariableExist(): bool
510: {
511: return ($this->function === null && !$this->isInAnonymousFunction()) || $this->afterExtractCall;
512: }
513:
514: public function afterExtractCall(): self
515: {
516: return $this->scopeFactory->create(
517: $this->context,
518: $this->isDeclareStrictTypes(),
519: $this->getFunction(),
520: $this->getNamespace(),
521: $this->expressionTypes,
522: $this->nativeExpressionTypes,
523: [],
524: $this->inClosureBindScopeClasses,
525: $this->anonymousFunctionReflection,
526: $this->isInFirstLevelStatement(),
527: $this->currentlyAssignedExpressions,
528: $this->currentlyAllowedUndefinedExpressions,
529: $this->inFunctionCallsStack,
530: true,
531: $this->parentScope,
532: $this->nativeTypesPromoted,
533: $this->templateArgumentFrame,
534: $this->templateArgumentConstraints,
535: );
536: }
537:
538: public function afterClearstatcacheCall(): self
539: {
540: $changed = false;
541:
542: $expressionTypes = $this->expressionTypes;
543: $nativeExpressionTypes = $this->nativeExpressionTypes;
544: foreach (array_keys($expressionTypes) as $exprString) {
545: // list from https://www.php.net/manual/en/function.clearstatcache.php
546:
547: // stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), and fileperms().
548: foreach ([
549: 'stat',
550: 'lstat',
551: 'file_exists',
552: 'is_writable',
553: 'is_writeable',
554: 'is_readable',
555: 'is_executable',
556: 'is_file',
557: 'is_dir',
558: 'is_link',
559: 'filectime',
560: 'fileatime',
561: 'filemtime',
562: 'fileinode',
563: 'filegroup',
564: 'fileowner',
565: 'filesize',
566: 'filetype',
567: 'fileperms',
568: ] as $functionName) {
569: if (!str_starts_with($exprString, $functionName . '(') && !str_starts_with($exprString, '\\' . $functionName . '(')) {
570: continue;
571: }
572:
573: unset($expressionTypes[$exprString]);
574: unset($nativeExpressionTypes[$exprString]);
575: $changed = true;
576: continue 2;
577: }
578: }
579:
580: if (!$changed) {
581: return $this;
582: }
583:
584: return $this->scopeFactory->create(
585: $this->context,
586: $this->isDeclareStrictTypes(),
587: $this->getFunction(),
588: $this->getNamespace(),
589: $expressionTypes,
590: $nativeExpressionTypes,
591: $this->conditionalExpressions,
592: $this->inClosureBindScopeClasses,
593: $this->anonymousFunctionReflection,
594: $this->isInFirstLevelStatement(),
595: $this->currentlyAssignedExpressions,
596: $this->currentlyAllowedUndefinedExpressions,
597: $this->inFunctionCallsStack,
598: $this->afterExtractCall,
599: $this->parentScope,
600: $this->nativeTypesPromoted,
601: $this->templateArgumentFrame,
602: $this->templateArgumentConstraints,
603: );
604: }
605:
606: public function afterOpenSslCall(string $openSslFunctionName): self
607: {
608: $expressionTypes = $this->expressionTypes;
609: $nativeExpressionTypes = $this->nativeExpressionTypes;
610:
611: $errorStringFunction = '\openssl_error_string()';
612: if (
613: !array_key_exists($errorStringFunction, $expressionTypes)
614: && !array_key_exists($errorStringFunction, $nativeExpressionTypes)
615: ) {
616: return $this;
617: }
618:
619: $changed = false;
620: if (in_array($openSslFunctionName, [
621: 'openssl_cipher_iv_length',
622: 'openssl_cms_decrypt',
623: 'openssl_cms_encrypt',
624: 'openssl_cms_read',
625: 'openssl_cms_sign',
626: 'openssl_cms_verify',
627: 'openssl_csr_export_to_file',
628: 'openssl_csr_export',
629: 'openssl_csr_get_public_key',
630: 'openssl_csr_get_subject',
631: 'openssl_csr_new',
632: 'openssl_csr_sign',
633: 'openssl_decrypt',
634: 'openssl_dh_compute_key',
635: 'openssl_digest',
636: 'openssl_encrypt',
637: 'openssl_get_curve_names',
638: 'openssl_get_privatekey',
639: 'openssl_get_publickey',
640: 'openssl_open',
641: 'openssl_pbkdf2',
642: 'openssl_pkcs12_export_to_file',
643: 'openssl_pkcs12_export',
644: 'openssl_pkcs12_read',
645: 'openssl_pkcs7_decrypt',
646: 'openssl_pkcs7_encrypt',
647: 'openssl_pkcs7_read',
648: 'openssl_pkcs7_sign',
649: 'openssl_pkcs7_verify',
650: 'openssl_pkey_derive',
651: 'openssl_pkey_export_to_file',
652: 'openssl_pkey_export',
653: 'openssl_pkey_get_private',
654: 'openssl_pkey_get_public',
655: 'openssl_pkey_new',
656: 'openssl_private_decrypt',
657: 'openssl_private_encrypt',
658: 'openssl_public_decrypt',
659: 'openssl_public_encrypt',
660: 'openssl_random_pseudo_bytes',
661: 'openssl_seal',
662: 'openssl_sign',
663: 'openssl_spki_export_challenge',
664: 'openssl_spki_export',
665: 'openssl_spki_new',
666: 'openssl_spki_verify',
667: 'openssl_verify',
668: 'openssl_x509_checkpurpose',
669: 'openssl_x509_export_to_file',
670: 'openssl_x509_export',
671: 'openssl_x509_fingerprint',
672: 'openssl_x509_read',
673: 'openssl_x509_verify',
674: ], true)) {
675: unset($expressionTypes[$errorStringFunction]);
676: unset($nativeExpressionTypes[$errorStringFunction]);
677: $changed = true;
678: }
679:
680: if (!$changed) {
681: return $this;
682: }
683:
684: return $this->scopeFactory->create(
685: $this->context,
686: $this->isDeclareStrictTypes(),
687: $this->getFunction(),
688: $this->getNamespace(),
689: $expressionTypes,
690: $nativeExpressionTypes,
691: $this->conditionalExpressions,
692: $this->inClosureBindScopeClasses,
693: $this->anonymousFunctionReflection,
694: $this->isInFirstLevelStatement(),
695: $this->currentlyAssignedExpressions,
696: $this->currentlyAllowedUndefinedExpressions,
697: $this->inFunctionCallsStack,
698: $this->afterExtractCall,
699: $this->parentScope,
700: $this->nativeTypesPromoted,
701: $this->templateArgumentFrame,
702: $this->templateArgumentConstraints,
703: );
704: }
705:
706: /**
707: * Forgets every tracked volatile global-state expression: argument-less
708: * function-call expressions whose value reflects mutable global/output-buffer
709: * state rather than just their arguments, superglobal variables and their offsets
710: * and negative results of existence checks (function_exists(), class_exists(), ...)
711: * because the invalidating code may define the missing function/class/etc.
712: */
713: public function invalidateVolatileExpressions(): self
714: {
715: $expressionTypes = $this->expressionTypes;
716: $nativeExpressionTypes = $this->nativeExpressionTypes;
717:
718: $changed = VolatileExpressionHelper::invalidateVolatileFunctionCalls($expressionTypes, $nativeExpressionTypes);
719: $changed = VolatileExpressionHelper::invalidateSuperglobals($expressionTypes, $nativeExpressionTypes) || $changed;
720: $changed = VolatileExpressionHelper::invalidateNegativeExistenceChecks($this, $expressionTypes, $nativeExpressionTypes) || $changed;
721:
722: if (!$changed) {
723: return $this;
724: }
725:
726: return $this->scopeFactory->create(
727: $this->context,
728: $this->isDeclareStrictTypes(),
729: $this->getFunction(),
730: $this->getNamespace(),
731: $expressionTypes,
732: $nativeExpressionTypes,
733: $this->conditionalExpressions,
734: $this->inClosureBindScopeClasses,
735: $this->anonymousFunctionReflection,
736: $this->isInFirstLevelStatement(),
737: $this->currentlyAssignedExpressions,
738: $this->currentlyAllowedUndefinedExpressions,
739: $this->inFunctionCallsStack,
740: $this->afterExtractCall,
741: $this->parentScope,
742: $this->nativeTypesPromoted,
743: $this->templateArgumentFrame,
744: $this->templateArgumentConstraints,
745: );
746: }
747:
748: /**
749: * Forgets negative results of the given existence checks (function_exists(),
750: * class_exists(), ...) because declaring a symbol may define the previously-missing one.
751: *
752: * @param list<'class_exists'|'interface_exists'|'trait_exists'|'enum_exists'|'function_exists'> $functionNames existence-check function names to forget
753: */
754: public function invalidateExistenceCheckExpressions(array $functionNames, ?string $declaredSymbolName): self
755: {
756: $expressionTypes = $this->expressionTypes;
757: $nativeExpressionTypes = $this->nativeExpressionTypes;
758:
759: if (!VolatileExpressionHelper::invalidateNegativeExistenceChecks($this, $expressionTypes, $nativeExpressionTypes, $functionNames, $declaredSymbolName)) {
760: return $this;
761: }
762:
763: return $this->scopeFactory->create(
764: $this->context,
765: $this->isDeclareStrictTypes(),
766: $this->getFunction(),
767: $this->getNamespace(),
768: $expressionTypes,
769: $nativeExpressionTypes,
770: $this->conditionalExpressions,
771: $this->inClosureBindScopeClasses,
772: $this->anonymousFunctionReflection,
773: $this->isInFirstLevelStatement(),
774: $this->currentlyAssignedExpressions,
775: $this->currentlyAllowedUndefinedExpressions,
776: $this->inFunctionCallsStack,
777: $this->afterExtractCall,
778: $this->parentScope,
779: $this->nativeTypesPromoted,
780: $this->templateArgumentFrame,
781: $this->templateArgumentConstraints,
782: );
783: }
784:
785: /** @api */
786: public function hasVariableType(string $variableName): TrinaryLogic
787: {
788: return ScopeOps::hasVariableType($this, $variableName);
789: }
790:
791: /** @api */
792: public function getVariableType(string $variableName): Type
793: {
794: // a certainly defined variable, the common case, does not need the rest
795: $holder = $this->expressionTypes['$' . $variableName] ?? null;
796: if ($holder !== null && $holder->getCertainty()->yes()) {
797: return $holder->getType();
798: }
799:
800: $hasVariableType = $this->hasVariableType($variableName);
801:
802: if ($hasVariableType->maybe()) {
803: if ($variableName === 'argc') {
804: return StaticTypeFactory::argc();
805: }
806: if ($variableName === 'argv') {
807: return StaticTypeFactory::argv();
808: }
809: if ($this->canAnyVariableExist()) {
810: return new MixedType();
811: }
812: }
813:
814: if ($hasVariableType->no()) {
815: throw new UndefinedVariableException($this, $variableName);
816: }
817:
818: $varExprString = '$' . $variableName;
819: if (!array_key_exists($varExprString, $this->expressionTypes)) {
820: if ($this->isGlobalVariable($variableName)) {
821: return new ArrayType(new BenevolentUnionType([new IntegerType(), new StringType()]), new MixedType(true));
822: }
823: return new MixedType();
824: }
825:
826: return $this->expressionTypes[$varExprString]->getType();
827: }
828:
829: /**
830: * @api
831: * @return list<string>
832: */
833: public function getDefinedVariables(): array
834: {
835: $variables = [];
836: foreach ($this->expressionTypes as $exprString => $holder) {
837: if (!$holder->getExpr() instanceof Variable) {
838: continue;
839: }
840: if (!$holder->getCertainty()->yes()) {
841: continue;
842: }
843:
844: $variables[] = substr($exprString, 1);
845: }
846:
847: return $variables;
848: }
849:
850: /**
851: * @api
852: * @return list<string>
853: */
854: public function getMaybeDefinedVariables(): array
855: {
856: $variables = [];
857: foreach ($this->expressionTypes as $exprString => $holder) {
858: if (!$holder->getExpr() instanceof Variable) {
859: continue;
860: }
861: if (!$holder->getCertainty()->maybe()) {
862: continue;
863: }
864:
865: $variables[] = substr($exprString, 1);
866: }
867:
868: return $variables;
869: }
870:
871: private function isGlobalVariable(string $variableName): bool
872: {
873: return in_array($variableName, self::SUPERGLOBAL_VARIABLES, true);
874: }
875:
876: /** @api */
877: public function hasConstant(Name $name): bool
878: {
879: $isCompilerHaltOffset = $name->toString() === '__COMPILER_HALT_OFFSET__';
880: if ($isCompilerHaltOffset) {
881: return $this->fileHasCompilerHaltStatementCalls();
882: }
883:
884: if ($this->getGlobalConstantType($name) !== null) {
885: return true;
886: }
887:
888: return $this->services->reflectionProvider->hasConstant($name, $this);
889: }
890:
891: private function fileHasCompilerHaltStatementCalls(): bool
892: {
893: $nodes = $this->services->parser->parseFile($this->getFile());
894: foreach ($nodes as $node) {
895: if ($node instanceof Node\Stmt\HaltCompiler) {
896: return true;
897: }
898: }
899:
900: return false;
901: }
902:
903: /** @api */
904: public function isInAnonymousFunction(): bool
905: {
906: return $this->anonymousFunctionReflection !== null;
907: }
908:
909: /** @api */
910: public function getAnonymousFunctionReflection(): ?ClosureType
911: {
912: return $this->anonymousFunctionReflection;
913: }
914:
915: /** @api */
916: public function getAnonymousFunctionReturnType(): ?Type
917: {
918: if ($this->anonymousFunctionReflection === null) {
919: return null;
920: }
921:
922: return $this->anonymousFunctionReflection->getReturnType();
923: }
924:
925: /**
926: * Returns a scope identical to this one but with the anonymous function
927: * reflection replaced. The scope entered at a closure/arrow carries only a
928: * shallow reflection (parameters + declared return); once the single body
929: * walk has gathered the returns, the engine builds the refined ClosureType and
930: * swaps it in here so the closure/arrow return-type node and its rules see the
931: * refined expected return.
932: */
933: public function withAnonymousFunctionReflection(ClosureType $anonymousFunctionReflection): self
934: {
935: return $this->scopeFactory->create(
936: $this->context,
937: $this->isDeclareStrictTypes(),
938: $this->getFunction(),
939: $this->getNamespace(),
940: $this->expressionTypes,
941: $this->nativeExpressionTypes,
942: $this->conditionalExpressions,
943: $this->inClosureBindScopeClasses,
944: $anonymousFunctionReflection,
945: $this->isInFirstLevelStatement(),
946: $this->currentlyAssignedExpressions,
947: $this->currentlyAllowedUndefinedExpressions,
948: $this->inFunctionCallsStack,
949: $this->afterExtractCall,
950: $this->parentScope,
951: $this->nativeTypesPromoted,
952: $this->templateArgumentFrame,
953: $this->templateArgumentConstraints,
954: );
955: }
956:
957: /** @api */
958: public function getType(Expr $node): Type
959: {
960: // a variable read is scope state and a literal is a constant - neither
961: // needs the node walked, so asking about them ahead of the walk is not
962: // the on-demand pricing the guard exists to catch
963: if (
964: NodeScopeResolver::$guardNewWorld
965: && isset(NodeScopeResolver::$guardRealExprIds[spl_object_id($node)])
966: && !isset(NodeScopeResolver::$guardProcessedExprIds[spl_object_id($node)])
967: && !($node instanceof Variable && is_string($node->name))
968: && !$node instanceof Node\Scalar\String_
969: && !$node instanceof Node\Scalar\Int_
970: && !$node instanceof Node\Scalar\Float_
971: ) {
972: throw new ShouldNotHappenException(sprintf(
973: 'getType() asked about non-synthetic %s on line %d before it was processed by processExprNode() - it should consume the node\'s ExpressionResult instead.',
974: get_class($node),
975: $node->getStartLine(),
976: ));
977: }
978:
979: $type = ScopeOps::getTypeFromCache($this, $node, $key);
980: if ($type !== null) {
981: return $type;
982: }
983:
984: return $this->resolvedTypes[$key] = TypeUtils::resolveLateResolvableTypes($this->resolveType($key, $node));
985: }
986:
987: public function getScopeType(Expr $expr): Type
988: {
989: return $this->getType($expr);
990: }
991:
992: public function getScopeNativeType(Expr $expr): Type
993: {
994: return $this->getNativeType($expr);
995: }
996:
997: public function getNodeKey(Expr $node): string
998: {
999: // ScopeOps::nodeKey() has the same fast path, but this method is hot enough
1000: // that the static call and the services fetch before it are measurable
1001: if ($node instanceof Variable && !$node->name instanceof Expr) {
1002: return '$' . $node->name;
1003: }
1004:
1005: return ScopeOps::nodeKey($node, $this->services->exprPrinter);
1006: }
1007:
1008: /** @internal */
1009: public function getExprPrinter(): ExprPrinter
1010: {
1011: return $this->services->exprPrinter;
1012: }
1013:
1014: /**
1015: * Creates a copy of this scope with the given expression tables and flags
1016: * replaced, keeping context, function, namespace and everything else.
1017: *
1018: * @internal called by ScopeOps
1019: * @param array<string, ExpressionTypeHolder> $expressionTypes
1020: * @param array<string, ExpressionTypeHolder> $nativeExpressionTypes
1021: * @param array<string, ConditionalExpressionHolder[]> $conditionalExpressions
1022: * @param array<string, bool> $currentlyAssignedExpressions
1023: * @param array<string, true> $currentlyAllowedUndefinedExpressions
1024: * @param list<array{FunctionReflection|MethodReflection|null, ParameterReflection|null}> $inFunctionCallsStack
1025: */
1026: public function duplicateWith(
1027: array $expressionTypes,
1028: array $nativeExpressionTypes,
1029: array $conditionalExpressions,
1030: array $currentlyAssignedExpressions,
1031: array $currentlyAllowedUndefinedExpressions,
1032: array $inFunctionCallsStack,
1033: bool $inFirstLevelStatement,
1034: bool $afterExtractCall,
1035: ): self
1036: {
1037: return $this->scopeFactory->create(
1038: $this->context,
1039: $this->isDeclareStrictTypes(),
1040: $this->getFunction(),
1041: $this->getNamespace(),
1042: $expressionTypes,
1043: $nativeExpressionTypes,
1044: $conditionalExpressions,
1045: $this->inClosureBindScopeClasses,
1046: $this->anonymousFunctionReflection,
1047: $inFirstLevelStatement,
1048: $currentlyAssignedExpressions,
1049: $currentlyAllowedUndefinedExpressions,
1050: $inFunctionCallsStack,
1051: $afterExtractCall,
1052: $this->parentScope,
1053: $this->nativeTypesPromoted,
1054: $this->templateArgumentFrame,
1055: $this->templateArgumentConstraints,
1056: );
1057: }
1058:
1059: /**
1060: * A cache key of the scope state a closure's type can depend on. With
1061: * $relevantRoots (the closure's free variables, '$this' included) only
1062: * the expression types rooted in them contribute - narrow enough that
1063: * loop-local churn does not invalidate the closure's cached type. Null
1064: * means everything contributes (dynamic variable access in the body).
1065: *
1066: * @param list<string>|null $relevantRoots
1067: */
1068: public function getClosureScopeCacheKey(?array $relevantRoots = null): string
1069: {
1070: $parts = [];
1071: foreach ($this->expressionTypes as $exprString => $expressionTypeHolder) {
1072: if ($expressionTypeHolder->getExpr() instanceof VirtualNode) {
1073: continue;
1074: }
1075: if ($relevantRoots !== null && !self::exprStringIsRootedIn($exprString, $relevantRoots)) {
1076: continue;
1077: }
1078: $parts[] = sprintf('%s::%s', $exprString, $expressionTypeHolder->getType()->describe(VerbosityLevel::cache()));
1079: }
1080: $parts[] = '---';
1081:
1082: $parts[] = sprintf(':%d', count($this->inFunctionCallsStack));
1083: foreach ($this->inFunctionCallsStack as [, $parameter]) {
1084: if ($parameter === null) {
1085: $parts[] = ',null';
1086: continue;
1087: }
1088:
1089: $parts[] = sprintf(',%s', $parameter->getType()->describe(VerbosityLevel::cache()));
1090: }
1091:
1092: return md5(implode("\n", $parts));
1093: }
1094:
1095: /** @param list<string> $roots */
1096: private static function exprStringIsRootedIn(string $exprString, array $roots): bool
1097: {
1098: foreach ($roots as $root) {
1099: if ($exprString === $root) {
1100: return true;
1101: }
1102: if (!str_starts_with($exprString, $root)) {
1103: continue;
1104: }
1105:
1106: $next = $exprString[strlen($root)];
1107: if ($next !== '_' && !ctype_alnum($next)) {
1108: return true;
1109: }
1110: }
1111:
1112: return false;
1113: }
1114:
1115: private function resolveType(string $exprString, Expr $node): Type
1116: {
1117: foreach ($this->services->expressionTypeResolverExtensions->getAll() as $extension) {
1118: $type = $extension->getType($node, $this);
1119: if ($type !== null) {
1120: return $type;
1121: }
1122: }
1123:
1124: $expressionType = ScopeOps::expressionTypeByKey($this, $node, $exprString);
1125: if ($expressionType !== null) {
1126: return $expressionType;
1127: }
1128:
1129: // NodeScopeResolver intercepts a first-class callable CallLike before the
1130: // ExprHandler dispatch - no handler supports the original node, its closure
1131: // type lives on the stored result's typeCallback (see the *CallableNode
1132: // handlers), mirroring TypeSpecifier::specifyTypesInCondition().
1133: if ($node instanceof Expr\CallLike && $node->isPartialFunctionApplication()) {
1134: return $this->resolveTypeOfNewWorldHandlerNode($node);
1135: }
1136:
1137: $exprHandler = ExprHandlerRegistry::resolve($node, $this->services->container);
1138: if ($exprHandler !== null) {
1139: return $this->resolveTypeOfNewWorldHandlerNode($node);
1140: }
1141:
1142: return new MixedType();
1143: }
1144:
1145: /**
1146: * Resolves the type of a node whose ExprHandler produced an ExpressionResult.
1147: * The answer comes from the ExpressionResult stored during the analysis
1148: * currently in progress (its eager type or typeCallback), or from processing
1149: * the node on demand (synthetic nodes, or no analysis in progress at all).
1150: *
1151: * The scope deliberately does not reference the storage - that would create
1152: * a reference cycle that never gets collected (see ExpressionResultStorageStack).
1153: */
1154: private function resolveTypeOfNewWorldHandlerNode(Expr $node): Type
1155: {
1156: // the hooks are the boundary between the rule-facing world and the
1157: // engine - a rule's NodeCallbackScope must not flow into result
1158: // callbacks or on-demand processing
1159: $scope = $this->toWalkScope();
1160: $storage = $this->services->expressionResultStorageStack->getCurrent();
1161: $counterfactualAsk = false;
1162: if ($storage !== null) {
1163: $result = $storage->findExpressionResult($node);
1164: if ($result !== null && $result->canResolveOwnType()) {
1165: // a counterfactual ask (the asking scope re-binds a variable the
1166: // expression reads, e.g. array_filter pricing its callback body
1167: // per constant element) must re-price the node on that scope -
1168: // the memoized walk-position type answers a different question
1169: $counterfactualAsk = !$result->askScopeVariableStateMatches($scope, $scope->nativeTypesPromoted);
1170: if (!$counterfactualAsk) {
1171: return $result->getTypeOnScope($scope, $scope->nativeTypesPromoted);
1172: }
1173: }
1174: }
1175:
1176: // A closure/arrow function type is computed directly (as
1177: // resolveCallableTypeForScope() also does) - never by processing it on
1178: // demand, which would re-enter ClosureHandler::processExpr() endlessly.
1179: // This answers both a closure whose result is not stored yet (its own
1180: // body walk asks for its type, and a callable parameter is derived from
1181: // it while it is being processed) and a closure passed as a call argument,
1182: // whose result NodeScopeResolver stores without an eager type.
1183: // getClosureType()'s own depth guard answers the self-by-ref ask.
1184: if ($node instanceof Expr\Closure || $node instanceof Expr\ArrowFunction) {
1185: return $this->services->container->getByType(ClosureTypeResolver::class)->getClosureType($scope, $node, false, $storage);
1186: }
1187:
1188: if (!$counterfactualAsk && $storage !== null && $storage->findExpressionResult($node) !== null) {
1189: throw new ShouldNotHappenException(sprintf(
1190: 'ExpressionResult of %s cannot resolve its own type (no eager type, no typeCallback).',
1191: get_class($node),
1192: ));
1193: }
1194:
1195: // a synthetic node, or no analysis in progress
1196: $onDemandResult = $this->services->container->getByType(NodeScopeResolver::class)->processExprOnDemand(
1197: $node,
1198: $scope,
1199: $storage !== null ? $storage->duplicate() : new ExpressionResultStorage(),
1200: );
1201:
1202: return $onDemandResult->getTypeOnScope($scope, $scope->nativeTypesPromoted);
1203: }
1204:
1205: /**
1206: * Prices the current (phpdoc, native) type pair of an expression that
1207: * applySpecifiedTypes() needs to intersect with or subtract from but that
1208: * is not tracked in the scope. Old-world filterBySpecifiedTypes() asked
1209: * Scope::getType() here; pricing from the stored ExpressionResult answers
1210: * through the typeCallback for converted handlers. A synthetic node the
1211: * analysis never processed - e.g. the plain-chain variant a nullsafe
1212: * narrowing emits ($a->b() alongside $a?->b()) - is priced on demand,
1213: * mirroring resolveTypeOfNewWorldHandlerNode(); its real subnodes answer
1214: * from stored results so the on-demand walk terminates. Returns null only
1215: * when there is no analysis in progress to price against.
1216: *
1217: * @return array{Type, Type}|null
1218: */
1219: private function getCurrentTypesOfSpecifiedExpr(Expr $expr): ?array
1220: {
1221: $storage = $this->services->expressionResultStorageStack->getCurrent();
1222: if ($storage === null) {
1223: return null;
1224: }
1225:
1226: // a narrowable expression's scope-view type is derived from tracked
1227: // state - the application-point semantics this method exists for. The
1228: // stored result must NOT win here: a narrowing entry's node sits inside
1229: // the condition (the \$a of `'' !== \$a`, walked on a truthy branch), so
1230: // its walk-position type carries branch narrowing that would poison the
1231: // base the narrowing is applied to. A nullsafe-containing chain is the
1232: // exception: deriving it from tracked state re-prices its links on
1233: // receiver state an active isset/?? ensure devices non-null, losing the
1234: // short-circuit's null - its stored result keeps it.
1235: $exprResult = $storage->findExpressionResult($expr);
1236: if (
1237: (
1238: ($expr instanceof Expr\Variable && is_string($expr->name))
1239: || $expr instanceof PropertyFetch
1240: || $expr instanceof Expr\ArrayDimFetch
1241: || $expr instanceof Expr\StaticPropertyFetch
1242: // argument-less instance calls: the shape @phpstan-assert subjects
1243: // take (synthetic per-build nodes, never stored - a walk per
1244: // application otherwise)
1245: || ($expr instanceof Expr\MethodCall && $expr->name instanceof Identifier && !$expr->isPartialFunctionApplication() && $expr->getArgs() === [])
1246: )
1247: && ($exprResult === null || !$exprResult->containsNullsafe())
1248: ) {
1249: return [
1250: $this->resolveScopeStateType($expr, $this->nativeTypesPromoted),
1251: $this->resolveScopeStateType($expr, true),
1252: ];
1253: }
1254:
1255: $result = $exprResult;
1256: if ($result === null) {
1257: // a call subject (or a synthetic plain-chain variant) is priced on
1258: // demand: one walk answers both flavours. Not memoized - a census
1259: // showed repeat asks for the same unstored subject on one scope
1260: // never happen (0 hits across corpora)
1261: $scope = $this->toWalkScope();
1262: $result = $this->services->container->getByType(NodeScopeResolver::class)->processExprOnDemand(
1263: $expr,
1264: $scope,
1265: $storage->duplicate(),
1266: );
1267:
1268: return [
1269: $result->getTypeOnScope($scope, $scope->nativeTypesPromoted),
1270: $result->getTypeOnScope($scope, true),
1271: ];
1272: }
1273:
1274: // a type tracked for the whole expression on the asking scope wins over
1275: // the stored result's own type: a handler (e.g. isset/empty via
1276: // NonNullabilityHelper) may have processed the inner expression on a
1277: // scope that strips null, so the result's type would be stale for the
1278: // narrowing the caller is applying
1279: return [
1280: $result->getTypeOnScope($this, $this->nativeTypesPromoted),
1281: $result->getTypeOnScope($this, true),
1282: ];
1283: }
1284:
1285: /**
1286: * Narrowing counterpart of resolveTypeOfNewWorldHandlerNode() - the old-world
1287: * TypeSpecifier dispatcher asks here for a node's narrowing. Returns null when
1288: * the ExpressionResult carries no specifyTypesCallback - the dispatcher falls
1289: * back to default truthy/falsey narrowing.
1290: *
1291: * @internal
1292: */
1293: public function specifyTypesOfNewWorldHandlerNode(Expr $node, TypeSpecifierContext $context): SpecifiedTypes
1294: {
1295: return $this->obtainResultForNode($node)->getSpecifiedTypesForScope($this->toWalkScope(), $context);
1296: }
1297:
1298: /**
1299: * Obtains the ExpressionResult of a node so its narrowing/type can be asked
1300: * (getSpecifiedTypesForScope()/getTypeOnScope()): the stored result of an
1301: * already-processed node, or - for a synthetic node (or with no analysis in
1302: * progress) - the result of processing it on demand against a duplicate of
1303: * the current storage, so the throwaway walk never pollutes the live one.
1304: */
1305: public function obtainResultForNode(Expr $node): ExpressionResult
1306: {
1307: $storage = $this->services->expressionResultStorageStack->getCurrent();
1308: if ($storage !== null) {
1309: $result = $storage->findExpressionResult($node);
1310: if ($result !== null) {
1311: return $result;
1312: }
1313: }
1314:
1315: if (
1316: NodeScopeResolver::$guardNewWorld
1317: && isset(NodeScopeResolver::$guardRealExprIds[spl_object_id($node)])
1318: && !isset(NodeScopeResolver::$guardProcessedExprIds[spl_object_id($node)])
1319: ) {
1320: throw new ShouldNotHappenException(sprintf(
1321: 'obtainResultForNode() asked about non-synthetic %s on line %d before it was processed by processExprNode() - it should consume the node\'s ExpressionResult instead.',
1322: get_class($node),
1323: $node->getStartLine(),
1324: ));
1325: }
1326:
1327: // see resolveTypeOfNewWorldHandlerNode() - rules ask the dispatcher
1328: // with their NodeCallbackScope (e.g. ImpossibleCheckTypeHelper), the engine
1329: // side of the boundary works with the mutating flavor
1330: $scope = $this->toWalkScope();
1331:
1332: // a synthetic node, or no analysis in progress
1333: return $this->services->container->getByType(NodeScopeResolver::class)->processExprOnDemand(
1334: $node,
1335: $scope,
1336: $storage !== null ? $storage->duplicate() : new ExpressionResultStorage(),
1337: );
1338: }
1339:
1340: /**
1341: * Makes the storage answer type questions asked on this scope (and every
1342: * scope sharing its ExpressionResultStorageStack) for the duration of an
1343: * analysis. The caller must pop in a finally block.
1344: */
1345: public function pushExpressionResultStorage(ExpressionResultStorage $storage): void
1346: {
1347: $this->services->expressionResultStorageStack->push($storage);
1348: }
1349:
1350: public function popExpressionResultStorage(): void
1351: {
1352: $this->services->expressionResultStorageStack->pop();
1353: }
1354:
1355: /**
1356: * The ExpressionResultStorage of the analysis currently in progress, the one
1357: * resolveTypeOfNewWorldHandlerNode() prices synthetic nodes against. A handler
1358: * pricing a synthetic node from a lazily-invoked typeCallback must use this
1359: * (not a storage captured at processExpr() time): a later re-evaluation
1360: * (e.g. findEarlyTerminatingExpr()) runs under a different current storage,
1361: * and the captured one would resolve the synthetic node's real subnodes from
1362: * stale stored results.
1363: *
1364: * @internal
1365: */
1366: /** The settled stored result of the current storage - NodeCallbackScope's no-switch fast path. */
1367: protected function findSettledStoredResult(Expr $node): ?ExpressionResult
1368: {
1369: $storage = $this->services->expressionResultStorageStack->getCurrent();
1370: if ($storage === null) {
1371: return null;
1372: }
1373:
1374: return $storage->findExpressionResult($node);
1375: }
1376:
1377: public function getCurrentExpressionResultStorage(): ?ExpressionResultStorage
1378: {
1379: return $this->services->expressionResultStorageStack->getCurrent();
1380: }
1381:
1382: public function withTemplateArgumentFrame(?TemplateArgumentFrame $frame): self
1383: {
1384: $scope = $this->withoutMemoizedTypes();
1385: $scope->templateArgumentFrame = $frame;
1386: return $scope;
1387: }
1388:
1389: public function getCurrentTemplateArgumentFrame(): ?TemplateArgumentFrame
1390: {
1391: return $this->templateArgumentFrame;
1392: }
1393:
1394: public function getTemplateArgumentConstraints(): ?TemplateArgumentConstraints
1395: {
1396: return $this->templateArgumentConstraints;
1397: }
1398:
1399: public function withTemplateArgumentConstraints(?TemplateArgumentConstraints $constraints): self
1400: {
1401: if ($constraints === $this->templateArgumentConstraints) {
1402: return $this;
1403: }
1404: $scope = clone $this;
1405: $scope->nodeCallbackScope = null;
1406: $scope->scopeOutOfFirstLevelStatement = null;
1407: $scope->scopeWithPromotedNativeTypes = null;
1408: $scope->templateArgumentConstraints = $constraints;
1409: return $scope;
1410: }
1411:
1412: /** Inference facts join independently of variable-state convergence and branch termination. */
1413: public function addTemplateArgumentConstraints(?TemplateArgumentConstraints $constraints): self
1414: {
1415: if ($constraints === null || $constraints->isEmpty()) {
1416: return $this;
1417: }
1418:
1419: return $this->withTemplateArgumentConstraints($this->templateArgumentConstraints === null ? $constraints : $this->templateArgumentConstraints->merge($constraints));
1420: }
1421:
1422: /**
1423: * A copy of this scope without its memoized type answers: the recorded
1424: * entry scope of a statement the second pass re-walks answered questions
1425: * during the observation pass with unresolved template arguments in them.
1426: */
1427: public function withoutMemoizedTypes(): self
1428: {
1429: return $this->duplicateWith(
1430: $this->expressionTypes,
1431: $this->nativeExpressionTypes,
1432: $this->conditionalExpressions,
1433: $this->currentlyAssignedExpressions,
1434: $this->currentlyAllowedUndefinedExpressions,
1435: $this->inFunctionCallsStack,
1436: $this->inFirstLevelStatement,
1437: $this->afterExtractCall,
1438: );
1439: }
1440:
1441: /**
1442: * The variables spelled by the tracked expressions whose state differs
1443: * between this scope and $other - a statement mentioning none of them walks
1444: * the same on both - or null when a differing entry has no variable root (a
1445: * static property, a class constant fetch). Every variable of an entry counts,
1446: * not just its root: assigning $b invalidates $a->get($b).
1447: *
1448: * @return list<string>|null
1449: */
1450: public function getDifferingVariableRoots(self $other): ?array
1451: {
1452: $roots = [];
1453: $tables = [
1454: [$this->expressionTypes, $other->expressionTypes],
1455: [$this->nativeExpressionTypes, $other->nativeExpressionTypes],
1456: ];
1457: foreach ($tables as [$ours, $theirs]) {
1458: foreach ($ours as $key => $holder) {
1459: $theirHolder = $theirs[$key] ?? null;
1460: if ($theirHolder !== null && ($theirHolder === $holder || $holder->equals($theirHolder))) {
1461: continue;
1462: }
1463: $variables = self::getVariablesOfExpressionKey($key);
1464: if ($variables === null) {
1465: return null;
1466: }
1467: foreach ($variables as $variable) {
1468: $roots[$variable] = true;
1469: }
1470: }
1471: foreach ($theirs as $key => $holder) {
1472: if (isset($ours[$key])) {
1473: continue;
1474: }
1475: $variables = self::getVariablesOfExpressionKey($key);
1476: if ($variables === null) {
1477: return null;
1478: }
1479: foreach ($variables as $variable) {
1480: $roots[$variable] = true;
1481: }
1482: }
1483: }
1484: $conditionalTables = [
1485: [$this->conditionalExpressions, $other->conditionalExpressions],
1486: [$other->conditionalExpressions, $this->conditionalExpressions],
1487: ];
1488: foreach ($conditionalTables as [$ours, $theirs]) {
1489: foreach ($ours as $key => $holders) {
1490: if (isset($theirs[$key]) && $theirs[$key] === $holders) {
1491: continue;
1492: }
1493: $variables = self::getVariablesOfExpressionKey($key);
1494: if ($variables === null) {
1495: return null;
1496: }
1497: foreach ($variables as $variable) {
1498: $roots[$variable] = true;
1499: }
1500: }
1501: }
1502:
1503: return array_keys($roots);
1504: }
1505:
1506: /**
1507: * The variables an expression key spells, or null when the key is not
1508: * rooted in a variable.
1509: *
1510: * @return list<string>|null
1511: */
1512: private static function getVariablesOfExpressionKey(string $key): ?array
1513: {
1514: if (preg_match('/^\$[a-zA-Z_\x80-\xff]/', $key) !== 1) {
1515: return null;
1516: }
1517:
1518: preg_match_all('/\$([a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)/', $key, $matches);
1519:
1520: return $matches[1];
1521: }
1522:
1523: /**
1524: * This scope after a statement whose recorded walk stands: the entries the
1525: * statement changed or removed between its recorded entry and exit scopes
1526: * are carried over, everything else keeps this scope's state.
1527: */
1528: public function withRecordedStatementDelta(self $recordedEntry, self $recordedExit): self
1529: {
1530: $conditionalExpressions = $this->conditionalExpressions;
1531: foreach (array_keys($recordedExit->conditionalExpressions + $recordedEntry->conditionalExpressions) as $key) {
1532: $entryHolders = $recordedEntry->conditionalExpressions[$key] ?? [];
1533: $exitHolders = $recordedExit->conditionalExpressions[$key] ?? [];
1534: if ($entryHolders === $exitHolders) {
1535: continue;
1536: }
1537: $currentHolders = $conditionalExpressions[$key] ?? [];
1538: if ($currentHolders !== $entryHolders) {
1539: // the statement changed the holders of an expression whose holders
1540: // differ here (e.g. it assigned the guard of one): the recorded
1541: // exit's holders describe the recorded state, so keep only this
1542: // scope's holders that the recorded walk kept
1543: $exitHolders = array_intersect_key($currentHolders, $entryHolders, $exitHolders);
1544: }
1545: if ($exitHolders === []) {
1546: unset($conditionalExpressions[$key]);
1547: continue;
1548: }
1549: $conditionalExpressions[$key] = $exitHolders;
1550: }
1551:
1552: return $this->duplicateWith(
1553: self::applyRecordedHolderDelta($this->expressionTypes, $recordedEntry->expressionTypes, $recordedExit->expressionTypes),
1554: self::applyRecordedHolderDelta($this->nativeExpressionTypes, $recordedEntry->nativeExpressionTypes, $recordedExit->nativeExpressionTypes),
1555: $conditionalExpressions,
1556: [],
1557: [],
1558: [],
1559: $this->inFirstLevelStatement,
1560: $recordedExit->afterExtractCall,
1561: );
1562: }
1563:
1564: /**
1565: * @param array<string, ExpressionTypeHolder> $current
1566: * @param array<string, ExpressionTypeHolder> $recordedEntry
1567: * @param array<string, ExpressionTypeHolder> $recordedExit
1568: * @return array<string, ExpressionTypeHolder>
1569: */
1570: private static function applyRecordedHolderDelta(array $current, array $recordedEntry, array $recordedExit): array
1571: {
1572: foreach ($recordedExit as $key => $holder) {
1573: $entryHolder = $recordedEntry[$key] ?? null;
1574: if ($entryHolder !== null && ($entryHolder === $holder || $entryHolder->equals($holder))) {
1575: continue;
1576: }
1577: $current[$key] = $holder;
1578: }
1579: foreach (array_keys($recordedEntry) as $key) {
1580: if (isset($recordedExit[$key])) {
1581: continue;
1582: }
1583: unset($current[$key]);
1584: }
1585:
1586: return $current;
1587: }
1588:
1589: /** @api */
1590: public function getNativeType(Expr $expr): Type
1591: {
1592: return $this->promoteNativeTypes()->getType($expr);
1593: }
1594:
1595: public function getKeepVoidType(Expr $node): Type
1596: {
1597: if (
1598: !$node instanceof Match_
1599: && !$node instanceof Expr\Yield_
1600: && !$node instanceof Expr\YieldFrom
1601: && (
1602: (
1603: !$node instanceof FuncCall
1604: && !$node instanceof MethodCall
1605: && !$node instanceof Expr\NullsafeMethodCall
1606: && !$node instanceof Expr\StaticCall
1607: ) || $node->isPartialFunctionApplication()
1608: )
1609: ) {
1610: return $this->getScopeStateType($node);
1611: }
1612:
1613: $originalType = $this->getScopeStateType($node);
1614: if (!TypeCombinator::containsNull($originalType)) {
1615: return $originalType;
1616: }
1617:
1618: // the null may be a projected void: read the call's/match's raw
1619: // (void-kept) own type. A result already stored in the current frame is
1620: // read directly; a node evaluated on a different scope - e.g. an arrow
1621: // body typed on the closure scope - is processed on demand there, its
1622: // raw own type keeping void without any keep-void marker on the node.
1623: $storage = $this->services->expressionResultStorageStack->getCurrent();
1624: $result = $storage?->findExpressionResult($node);
1625: if ($result === null) {
1626: $result = $this->services->container->getByType(NodeScopeResolver::class)->processExprOnDemand(
1627: $node,
1628: $this->toWalkScope(),
1629: $storage !== null ? $storage->duplicate() : new ExpressionResultStorage(),
1630: );
1631: }
1632:
1633: return $result->getKeepVoidType($this->nativeTypesPromoted);
1634: }
1635:
1636: public function doNotTreatPhpDocTypesAsCertain(): self
1637: {
1638: return $this->promoteNativeTypes();
1639: }
1640:
1641: private function promoteNativeTypes(): self
1642: {
1643: if ($this->nativeTypesPromoted) {
1644: return $this;
1645: }
1646:
1647: if ($this->scopeWithPromotedNativeTypes !== null) {
1648: return $this->scopeWithPromotedNativeTypes;
1649: }
1650:
1651: return $this->scopeWithPromotedNativeTypes = $this->scopeFactory->create(
1652: $this->context,
1653: $this->declareStrictTypes,
1654: $this->function,
1655: $this->namespace,
1656: $this->nativeExpressionTypes,
1657: [],
1658: [],
1659: $this->inClosureBindScopeClasses,
1660: $this->anonymousFunctionReflection,
1661: $this->inFirstLevelStatement,
1662: $this->currentlyAssignedExpressions,
1663: $this->currentlyAllowedUndefinedExpressions,
1664: $this->inFunctionCallsStack,
1665: $this->afterExtractCall,
1666: $this->parentScope,
1667: true,
1668: templateArgumentFrame: $this->templateArgumentFrame,
1669: templateArgumentConstraints: $this->templateArgumentConstraints,
1670: );
1671: }
1672:
1673: /** @api */
1674: public function resolveName(Name $name): string
1675: {
1676: $originalClass = (string) $name;
1677: if ($this->isInClass()) {
1678: $lowerClass = strtolower($originalClass);
1679: if (in_array($lowerClass, [
1680: 'self',
1681: 'static',
1682: ], true)) {
1683: if ($this->inClosureBindScopeClasses !== [] && $this->inClosureBindScopeClasses !== ['static']) {
1684: return $this->inClosureBindScopeClasses[0];
1685: }
1686: return $this->getClassReflection()->getName();
1687: } elseif ($lowerClass === 'parent') {
1688: $currentClassReflection = $this->getClassReflection();
1689: if ($currentClassReflection->getParentClass() !== null) {
1690: return $currentClassReflection->getParentClass()->getName();
1691: }
1692: }
1693: }
1694:
1695: return $originalClass;
1696: }
1697:
1698: /** @api */
1699: public function resolveTypeByName(Name $name): TypeWithClassName
1700: {
1701: if ($name->toLowerString() === 'static' && $this->isInClass()) {
1702: if ($this->inClosureBindScopeClasses !== [] && $this->inClosureBindScopeClasses !== ['static']) {
1703: if ($this->services->reflectionProvider->hasClass($this->inClosureBindScopeClasses[0])) {
1704: return new StaticType($this->services->reflectionProvider->getClass($this->inClosureBindScopeClasses[0]));
1705: }
1706: }
1707:
1708: return new StaticType($this->getClassReflection());
1709: }
1710:
1711: $originalClass = $this->resolveName($name);
1712: if ($this->isInClass()) {
1713: if ($this->inClosureBindScopeClasses === [$originalClass]) {
1714: if ($this->services->reflectionProvider->hasClass($originalClass)) {
1715: return new ThisType($this->services->reflectionProvider->getClass($originalClass));
1716: }
1717: return new ObjectType($originalClass);
1718: }
1719:
1720: $thisType = new ThisType($this->getClassReflection());
1721: $ancestor = $thisType->getAncestorWithClassName($originalClass);
1722: if ($ancestor !== null) {
1723: return $ancestor;
1724: }
1725: }
1726:
1727: return new ObjectType($originalClass);
1728: }
1729:
1730: /**
1731: * @api
1732: * @param mixed $value
1733: */
1734: public function getTypeFromValue($value): Type
1735: {
1736: return ConstantTypeHelper::getTypeFromValue($value);
1737: }
1738:
1739: /** @api */
1740: public function hasExpressionType(Expr $node): TrinaryLogic
1741: {
1742: return ScopeOps::hasExpressionType($this, $node, $this->services->exprPrinter);
1743: }
1744:
1745: /**
1746: * Reads the type tracked for an expression straight from its holder, skipping
1747: * the extension/dispatch/cache machinery that getType() runs. Only valid when
1748: * hasExpressionType($node) is yes - mirrors resolveType()'s tracked-holder
1749: * early return and is what ExpressionResult uses on its tracked-holder path.
1750: *
1751: * @internal
1752: */
1753: public function getTrackedExpressionType(Expr $node): Type
1754: {
1755: return $this->expressionTypes[$this->getNodeKey($node)]->getType();
1756: }
1757:
1758: /**
1759: * @param MethodReflection|FunctionReflection|null $reflection
1760: */
1761: public function pushInFunctionCall($reflection, ?ParameterReflection $parameter, bool $rememberTypes): self
1762: {
1763: $stack = $this->inFunctionCallsStack;
1764: $stack[] = [$reflection, $parameter];
1765:
1766: $functionScope = $this->scopeFactory->create(
1767: $this->context,
1768: $this->isDeclareStrictTypes(),
1769: $this->getFunction(),
1770: $this->getNamespace(),
1771: $this->expressionTypes,
1772: $this->nativeExpressionTypes,
1773: $this->conditionalExpressions,
1774: $this->inClosureBindScopeClasses,
1775: $this->anonymousFunctionReflection,
1776: $this->isInFirstLevelStatement(),
1777: $this->currentlyAssignedExpressions,
1778: $this->currentlyAllowedUndefinedExpressions,
1779: $stack,
1780: $this->afterExtractCall,
1781: $this->parentScope,
1782: $this->nativeTypesPromoted,
1783: $this->templateArgumentFrame,
1784: $this->templateArgumentConstraints,
1785: );
1786:
1787: if ($rememberTypes) {
1788: $functionScope->resolvedTypes = $this->resolvedTypes;
1789: }
1790:
1791: return $functionScope;
1792: }
1793:
1794: public function popInFunctionCall(): self
1795: {
1796: $stack = $this->inFunctionCallsStack;
1797: array_pop($stack);
1798:
1799: $parentScope = $this->scopeFactory->create(
1800: $this->context,
1801: $this->isDeclareStrictTypes(),
1802: $this->getFunction(),
1803: $this->getNamespace(),
1804: $this->expressionTypes,
1805: $this->nativeExpressionTypes,
1806: $this->conditionalExpressions,
1807: $this->inClosureBindScopeClasses,
1808: $this->anonymousFunctionReflection,
1809: $this->isInFirstLevelStatement(),
1810: $this->currentlyAssignedExpressions,
1811: $this->currentlyAllowedUndefinedExpressions,
1812: $stack,
1813: $this->afterExtractCall,
1814: $this->parentScope,
1815: $this->nativeTypesPromoted,
1816: $this->templateArgumentFrame,
1817: $this->templateArgumentConstraints,
1818: );
1819:
1820: $parentScope->resolvedTypes = $this->resolvedTypes;
1821:
1822: return $parentScope;
1823: }
1824:
1825: /** @api */
1826: public function isInClassExists(string $className): bool
1827: {
1828: foreach ($this->inFunctionCallsStack as [$inFunctionCall]) {
1829: if (!$inFunctionCall instanceof FunctionReflection) {
1830: continue;
1831: }
1832:
1833: if (in_array($inFunctionCall->getName(), [
1834: 'class_exists',
1835: 'interface_exists',
1836: 'trait_exists',
1837: 'enum_exists',
1838: ], true)) {
1839: return true;
1840: }
1841: }
1842:
1843: // interface_exists() etc. imply class_exists() therefore not listed here
1844: $expr = new FuncCall(new FullyQualified('class_exists'), [
1845: new Arg(new String_(ltrim($className, '\\'))),
1846: ]);
1847:
1848: return $this->getType($expr)->isTrue()->yes();
1849: }
1850:
1851: public function getFunctionCallStack(): array
1852: {
1853: return array_values(array_filter(
1854: array_map(static fn ($values) => $values[0], $this->inFunctionCallsStack),
1855: static fn (FunctionReflection|MethodReflection|null $reflection) => $reflection !== null,
1856: ));
1857: }
1858:
1859: public function getFunctionCallStackWithParameters(): array
1860: {
1861: return array_values(array_filter(
1862: $this->inFunctionCallsStack,
1863: static fn ($item) => $item[0] !== null,
1864: ));
1865: }
1866:
1867: /** @api */
1868: public function isInFunctionExists(string $functionName): bool
1869: {
1870: $expr = new FuncCall(new FullyQualified('function_exists'), [
1871: new Arg(new String_(ltrim($functionName, '\\'))),
1872: ]);
1873:
1874: return $this->getType($expr)->isTrue()->yes();
1875: }
1876:
1877: /** @api */
1878: public function enterClass(ClassReflection $classReflection): self
1879: {
1880: $thisHolder = ExpressionTypeHolder::createYes(new Variable('this'), new ThisType($classReflection));
1881: $constantTypes = $this->getConstantTypes();
1882: $constantTypes['$this'] = $thisHolder;
1883: $nativeConstantTypes = $this->getNativeConstantTypes();
1884: $nativeConstantTypes['$this'] = $thisHolder;
1885:
1886: return $this->scopeFactory->create(
1887: $this->context->enterClass($classReflection),
1888: $this->isDeclareStrictTypes(),
1889: null,
1890: $this->getNamespace(),
1891: $constantTypes,
1892: $nativeConstantTypes,
1893: [],
1894: [],
1895: null,
1896: true,
1897: [],
1898: [],
1899: [],
1900: false,
1901: $classReflection->isAnonymous() ? $this : null,
1902: templateArgumentFrame: $this->templateArgumentFrame,
1903: templateArgumentConstraints: $this->templateArgumentConstraints,
1904: );
1905: }
1906:
1907: public function enterTrait(ClassReflection $traitReflection): self
1908: {
1909: $namespace = null;
1910: $traitName = $traitReflection->getName();
1911: $traitNameParts = explode('\\', $traitName);
1912: if (count($traitNameParts) > 1) {
1913: $namespace = implode('\\', array_slice($traitNameParts, 0, -1));
1914: }
1915: return $this->scopeFactory->create(
1916: $this->context->enterTrait($traitReflection),
1917: $this->isDeclareStrictTypes(),
1918: $this->getFunction(),
1919: $namespace,
1920: $this->expressionTypes,
1921: $this->nativeExpressionTypes,
1922: [],
1923: $this->inClosureBindScopeClasses,
1924: $this->anonymousFunctionReflection,
1925: templateArgumentFrame: $this->templateArgumentFrame,
1926: templateArgumentConstraints: $this->templateArgumentConstraints,
1927: );
1928: }
1929:
1930: /**
1931: * @api
1932: * @param Type[] $phpDocParameterTypes
1933: * @param Type[] $parameterOutTypes
1934: * @param array<string, bool> $immediatelyInvokedCallableParameters
1935: * @param array<string, Type> $phpDocClosureThisTypeParameters
1936: * @param array<string, bool> $phpDocPureUnlessCallableIsImpureParameters
1937: * @param array<string, bool> $phpDocPureUnlessParameterPassedParameters
1938: */
1939: public function enterClassMethod(
1940: Node\Stmt\ClassMethod $classMethod,
1941: TemplateTypeMap $templateTypeMap,
1942: array $phpDocParameterTypes,
1943: ?Type $phpDocReturnType,
1944: ?Type $throwType,
1945: ?string $deprecatedDescription,
1946: bool $isDeprecated,
1947: bool $isInternal,
1948: bool $isFinal,
1949: ?bool $isPure = null,
1950: bool $acceptsNamedArguments = true,
1951: ?Assertions $asserts = null,
1952: ?Type $selfOutType = null,
1953: ?string $phpDocComment = null,
1954: array $parameterOutTypes = [],
1955: array $immediatelyInvokedCallableParameters = [],
1956: array $phpDocClosureThisTypeParameters = [],
1957: bool $isConstructor = false,
1958: ?ResolvedPhpDocBlock $resolvedPhpDocBlock = null,
1959: array $phpDocPureUnlessCallableIsImpureParameters = [],
1960: array $phpDocPureUnlessParameterPassedParameters = [],
1961: ): self
1962: {
1963: if (!$this->isInClass()) {
1964: throw new ShouldNotHappenException();
1965: }
1966:
1967: return $this->enterFunctionLike(
1968: new PhpMethodFromParserNodeReflection(
1969: $this->getClassReflection(),
1970: $classMethod,
1971: null,
1972: $this->getFile(),
1973: $templateTypeMap,
1974: $this->getRealParameterTypes($classMethod),
1975: array_map(fn (Type $type): Type => $this->transformStaticType(TemplateTypeHelper::toArgument($type)), $phpDocParameterTypes),
1976: $this->getRealParameterDefaultValues($classMethod),
1977: $this->getParameterAttributes($classMethod),
1978: $this->transformStaticType($this->getFunctionType($classMethod->returnType, false, false)),
1979: $phpDocReturnType !== null ? $this->transformStaticType(TemplateTypeHelper::toArgument($phpDocReturnType)) : null,
1980: $throwType !== null ? $this->transformStaticType(TemplateTypeHelper::toArgument($throwType)) : null,
1981: $deprecatedDescription,
1982: $isDeprecated,
1983: $isInternal,
1984: $isFinal,
1985: $isPure,
1986: $acceptsNamedArguments,
1987: $asserts ?? Assertions::createEmpty(),
1988: $selfOutType,
1989: $phpDocComment,
1990: $resolvedPhpDocBlock,
1991: array_map(fn (Type $type): Type => $this->transformStaticType(TemplateTypeHelper::toArgument($type)), $parameterOutTypes),
1992: $immediatelyInvokedCallableParameters,
1993: array_map(fn (Type $type): Type => $this->transformStaticType(TemplateTypeHelper::toArgument($type)), $phpDocClosureThisTypeParameters),
1994: $isConstructor,
1995: $this->services->attributeReflectionFactory->fromAttrGroups($classMethod->attrGroups, InitializerExprContext::fromStubParameter($this->getClassReflection()->getName(), $this->getFile(), $classMethod)),
1996: $phpDocPureUnlessCallableIsImpureParameters,
1997: $phpDocPureUnlessParameterPassedParameters,
1998: ),
1999: !$classMethod->isStatic(),
2000: );
2001: }
2002:
2003: /**
2004: * @param Type[] $phpDocParameterTypes
2005: */
2006: public function enterPropertyHook(
2007: Node\PropertyHook $hook,
2008: string $propertyName,
2009: Identifier|Name|ComplexType|null $nativePropertyTypeNode,
2010: ?Type $phpDocPropertyType,
2011: array $phpDocParameterTypes,
2012: ?Type $throwType,
2013: ?string $deprecatedDescription,
2014: bool $isDeprecated,
2015: ?bool $isPure,
2016: ?string $phpDocComment,
2017: ?ResolvedPhpDocBlock $resolvedPhpDocBlock = null,
2018: ): self
2019: {
2020: if (!$this->isInClass()) {
2021: throw new ShouldNotHappenException();
2022: }
2023:
2024: $phpDocParameterTypes = array_map(fn (Type $type): Type => $this->transformStaticType(TemplateTypeHelper::toArgument($type)), $phpDocParameterTypes);
2025:
2026: $hookName = $hook->name->toLowerString();
2027: if ($hookName === 'set') {
2028: if ($hook->params === []) {
2029: $hook = clone $hook;
2030: $hook->params = [
2031: new Node\Param(new Variable('value'), type: $nativePropertyTypeNode),
2032: ];
2033: }
2034:
2035: $firstParam = $hook->params[0] ?? null;
2036: if (
2037: $firstParam !== null
2038: && $phpDocPropertyType !== null
2039: && $firstParam->var instanceof Variable
2040: && is_string($firstParam->var->name)
2041: ) {
2042: $valueParamPhpDocType = $phpDocParameterTypes[$firstParam->var->name] ?? null;
2043: if ($valueParamPhpDocType === null) {
2044: $phpDocParameterTypes[$firstParam->var->name] = $this->transformStaticType(TemplateTypeHelper::toArgument($phpDocPropertyType));
2045: }
2046: }
2047:
2048: $realReturnType = new VoidType();
2049: $phpDocReturnType = null;
2050: } elseif ($hookName === 'get') {
2051: $realReturnType = $this->getFunctionType($nativePropertyTypeNode, false, false);
2052: $phpDocReturnType = $phpDocPropertyType !== null ? $this->transformStaticType(TemplateTypeHelper::toArgument($phpDocPropertyType)) : null;
2053: } else {
2054: throw new ShouldNotHappenException();
2055: }
2056:
2057: $realParameterTypes = $this->getRealParameterTypes($hook);
2058:
2059: return $this->enterFunctionLike(
2060: new PhpMethodFromParserNodeReflection(
2061: $this->getClassReflection(),
2062: $hook,
2063: $propertyName,
2064: $this->getFile(),
2065: TemplateTypeMap::createEmpty(),
2066: $realParameterTypes,
2067: $phpDocParameterTypes,
2068: [],
2069: $this->getParameterAttributes($hook),
2070: $realReturnType,
2071: $phpDocReturnType,
2072: $throwType !== null ? $this->transformStaticType(TemplateTypeHelper::toArgument($throwType)) : null,
2073: $deprecatedDescription,
2074: $isDeprecated,
2075: false,
2076: false,
2077: $isPure,
2078: true,
2079: Assertions::createEmpty(),
2080: null,
2081: $phpDocComment,
2082: $resolvedPhpDocBlock,
2083: [],
2084: [],
2085: [],
2086: false,
2087: $this->services->attributeReflectionFactory->fromAttrGroups($hook->attrGroups, InitializerExprContext::fromStubParameter($this->getClassReflection()->getName(), $this->getFile(), $hook)),
2088: [],
2089: [],
2090: ),
2091: true,
2092: );
2093: }
2094:
2095: private function transformStaticType(Type $type): Type
2096: {
2097: return TypeTraverser::mapMemoized($type, new TransformStaticTypeTraverser($this));
2098: }
2099:
2100: /**
2101: * @return Type[]
2102: */
2103: private function getRealParameterTypes(Node\FunctionLike $functionLike): array
2104: {
2105: $realParameterTypes = [];
2106: foreach ($functionLike->getParams() as $parameter) {
2107: if (!$parameter->var instanceof Variable || !is_string($parameter->var->name)) {
2108: throw new ShouldNotHappenException();
2109: }
2110: $realParameterTypes[$parameter->var->name] = $this->getFunctionType(
2111: $parameter->type,
2112: $this->isParameterValueNullable($parameter) && $parameter->flags === 0,
2113: false,
2114: );
2115: }
2116:
2117: return $realParameterTypes;
2118: }
2119:
2120: /**
2121: * @return Type[]
2122: */
2123: private function getRealParameterDefaultValues(Node\FunctionLike $functionLike): array
2124: {
2125: $realParameterDefaultValues = [];
2126: foreach ($functionLike->getParams() as $parameter) {
2127: if ($parameter->default === null) {
2128: continue;
2129: }
2130: if (!$parameter->var instanceof Variable || !is_string($parameter->var->name)) {
2131: throw new ShouldNotHappenException();
2132: }
2133: $realParameterDefaultValues[$parameter->var->name] = $this->services->initializerExprTypeResolver->getType($parameter->default, InitializerExprContext::fromScope($this));
2134: }
2135:
2136: return $realParameterDefaultValues;
2137: }
2138:
2139: /**
2140: * @return array<string, list<AttributeReflection>>
2141: */
2142: private function getParameterAttributes(ClassMethod|Function_|PropertyHook $functionLike): array
2143: {
2144: $parameterAttributes = [];
2145: $className = null;
2146: if ($this->isInClass()) {
2147: $className = $this->getClassReflection()->getName();
2148: }
2149: foreach ($functionLike->getParams() as $parameter) {
2150: if (!$parameter->var instanceof Variable || !is_string($parameter->var->name)) {
2151: throw new ShouldNotHappenException();
2152: }
2153:
2154: $parameterAttributes[$parameter->var->name] = $this->services->attributeReflectionFactory->fromAttrGroups($parameter->attrGroups, InitializerExprContext::fromStubParameter($className, $this->getFile(), $functionLike));
2155: }
2156:
2157: return $parameterAttributes;
2158: }
2159:
2160: /**
2161: * @api
2162: * @param Type[] $phpDocParameterTypes
2163: * @param Type[] $parameterOutTypes
2164: * @param array<string, bool> $immediatelyInvokedCallableParameters
2165: * @param array<string, Type> $phpDocClosureThisTypeParameters
2166: * @param array<string, bool> $pureUnlessCallableIsImpureParameters
2167: * @param array<string, bool> $pureUnlessParameterPassedParameters
2168: */
2169: public function enterFunction(
2170: Node\Stmt\Function_ $function,
2171: TemplateTypeMap $templateTypeMap,
2172: array $phpDocParameterTypes,
2173: ?Type $phpDocReturnType,
2174: ?Type $throwType,
2175: ?string $deprecatedDescription,
2176: bool $isDeprecated,
2177: bool $isInternal,
2178: ?bool $isPure = null,
2179: bool $acceptsNamedArguments = true,
2180: ?Assertions $asserts = null,
2181: ?string $phpDocComment = null,
2182: array $parameterOutTypes = [],
2183: array $immediatelyInvokedCallableParameters = [],
2184: array $phpDocClosureThisTypeParameters = [],
2185: array $pureUnlessCallableIsImpureParameters = [],
2186: array $pureUnlessParameterPassedParameters = [],
2187: ): self
2188: {
2189: return $this->enterFunctionLike(
2190: new PhpFunctionFromParserNodeReflection(
2191: $function,
2192: $this->getFile(),
2193: $templateTypeMap,
2194: $this->getRealParameterTypes($function),
2195: array_map(static fn (Type $type): Type => TemplateTypeHelper::toArgument($type), $phpDocParameterTypes),
2196: $this->getRealParameterDefaultValues($function),
2197: $this->getParameterAttributes($function),
2198: $this->getFunctionType($function->returnType, $function->returnType === null, false),
2199: $phpDocReturnType !== null ? TemplateTypeHelper::toArgument($phpDocReturnType) : null,
2200: $throwType,
2201: $deprecatedDescription,
2202: $isDeprecated,
2203: $isInternal,
2204: $isPure,
2205: $acceptsNamedArguments,
2206: $asserts ?? Assertions::createEmpty(),
2207: $phpDocComment,
2208: array_map(static fn (Type $type): Type => TemplateTypeHelper::toArgument($type), $parameterOutTypes),
2209: $immediatelyInvokedCallableParameters,
2210: $phpDocClosureThisTypeParameters,
2211: $this->services->attributeReflectionFactory->fromAttrGroups($function->attrGroups, InitializerExprContext::fromStubParameter(null, $this->getFile(), $function)),
2212: $pureUnlessCallableIsImpureParameters,
2213: $pureUnlessParameterPassedParameters,
2214: ),
2215: false,
2216: );
2217: }
2218:
2219: private function enterFunctionLike(
2220: PhpFunctionFromParserNodeReflection $functionReflection,
2221: bool $preserveConstructorScope,
2222: ): self
2223: {
2224: $parametersByName = [];
2225:
2226: $functionParameters = $functionReflection->getParameters();
2227: foreach ($functionParameters as $parameter) {
2228: $parametersByName[$parameter->getName()] = $parameter;
2229: }
2230:
2231: $expressionTypes = [];
2232: $nativeExpressionTypes = [];
2233: $conditionalTypes = [];
2234:
2235: if ($preserveConstructorScope) {
2236: $expressionTypes = $this->expressionTypes;
2237: $nativeExpressionTypes = $this->nativeExpressionTypes;
2238: }
2239:
2240: foreach ($functionParameters as $parameter) {
2241: $parameterType = $parameter->getType();
2242:
2243: if ($parameterType instanceof ConditionalTypeForParameter) {
2244: $targetParameterName = substr($parameterType->getParameterName(), 1);
2245: if (array_key_exists($targetParameterName, $parametersByName)) {
2246: $targetParameter = $parametersByName[$targetParameterName];
2247:
2248: $ifType = $parameterType->isNegated() ? $parameterType->getElse() : $parameterType->getIf();
2249: $elseType = $parameterType->isNegated() ? $parameterType->getIf() : $parameterType->getElse();
2250:
2251: $holder = new ConditionalExpressionHolder([
2252: $parameterType->getParameterName() => ExpressionTypeHolder::createYes(new Variable($targetParameterName), TypeCombinator::intersect($targetParameter->getType(), $parameterType->getTarget())),
2253: ], ExpressionTypeHolder::createYes(new Variable($parameter->getName()), $ifType));
2254: $conditionalTypes['$' . $parameter->getName()][$holder->getKey()] = $holder;
2255:
2256: $holder = new ConditionalExpressionHolder([
2257: $parameterType->getParameterName() => ExpressionTypeHolder::createYes(new Variable($targetParameterName), TypeCombinator::remove($targetParameter->getType(), $parameterType->getTarget())),
2258: ], ExpressionTypeHolder::createYes(new Variable($parameter->getName()), $elseType));
2259: $conditionalTypes['$' . $parameter->getName()][$holder->getKey()] = $holder;
2260: }
2261: }
2262:
2263: $paramExprString = '$' . $parameter->getName();
2264: if ($parameter->isVariadic()) {
2265: if (!$this->getPhpVersion()->supportsNamedArguments()->no() && $functionReflection->acceptsNamedArguments()->yes()) {
2266: $parameterType = new ArrayType(new UnionType([IntegerRangeType::createAllGreaterThanOrEqualTo(0), new StringType()]), $parameterType);
2267: } else {
2268: $parameterType = new IntersectionType([new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), $parameterType), new AccessoryArrayListType()]);
2269: }
2270: }
2271: $parameterNode = new Variable($parameter->getName());
2272: $expressionTypes[$paramExprString] = ExpressionTypeHolder::createYes($parameterNode, $parameterType);
2273:
2274: $parameterOriginalValueExpr = new ParameterVariableOriginalValueExpr($parameter->getName());
2275: $parameterOriginalValueExprString = $this->getNodeKey($parameterOriginalValueExpr);
2276: $expressionTypes[$parameterOriginalValueExprString] = ExpressionTypeHolder::createYes($parameterOriginalValueExpr, $parameterType);
2277:
2278: $nativeParameterType = $parameter->getNativeType();
2279: if ($parameter->isVariadic()) {
2280: if (!$this->getPhpVersion()->supportsNamedArguments()->no() && $functionReflection->acceptsNamedArguments()->yes()) {
2281: $nativeParameterType = new ArrayType(new UnionType([IntegerRangeType::createAllGreaterThanOrEqualTo(0), new StringType()]), $nativeParameterType);
2282: } else {
2283: $nativeParameterType = new IntersectionType([new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), $nativeParameterType), new AccessoryArrayListType()]);
2284: }
2285: }
2286: $nativeExpressionTypes[$paramExprString] = ExpressionTypeHolder::createYes($parameterNode, $nativeParameterType);
2287: $nativeExpressionTypes[$parameterOriginalValueExprString] = ExpressionTypeHolder::createYes($parameterOriginalValueExpr, $nativeParameterType);
2288: }
2289:
2290: return $this->scopeFactory->create(
2291: $this->context,
2292: $this->isDeclareStrictTypes(),
2293: $functionReflection,
2294: $this->getNamespace(),
2295: array_merge($this->getConstantTypes(), $expressionTypes),
2296: array_merge($this->getNativeConstantTypes(), $nativeExpressionTypes),
2297: $conditionalTypes,
2298: templateArgumentFrame: $this->templateArgumentFrame,
2299: templateArgumentConstraints: $this->templateArgumentConstraints,
2300: );
2301: }
2302:
2303: /** @api */
2304: public function enterNamespace(string $namespaceName): self
2305: {
2306: return $this->scopeFactory->create(
2307: $this->context->beginFile(),
2308: $this->isDeclareStrictTypes(),
2309: null,
2310: $namespaceName,
2311: templateArgumentFrame: $this->templateArgumentFrame,
2312: templateArgumentConstraints: $this->templateArgumentConstraints,
2313: );
2314: }
2315:
2316: /**
2317: * @param list<non-empty-string> $scopeClasses
2318: */
2319: public function enterClosureBind(?Type $thisType, ?Type $nativeThisType, array $scopeClasses): self
2320: {
2321: $expressionTypes = $this->expressionTypes;
2322: if ($thisType !== null) {
2323: $expressionTypes['$this'] = ExpressionTypeHolder::createYes(new Variable('this'), $thisType);
2324: } else {
2325: unset($expressionTypes['$this']);
2326: }
2327:
2328: $nativeExpressionTypes = $this->nativeExpressionTypes;
2329: if ($nativeThisType !== null) {
2330: $nativeExpressionTypes['$this'] = ExpressionTypeHolder::createYes(new Variable('this'), $nativeThisType);
2331: } else {
2332: unset($nativeExpressionTypes['$this']);
2333: }
2334:
2335: if ($scopeClasses === ['static'] && $this->isInClass()) {
2336: $scopeClasses = [$this->getClassReflection()->getName()];
2337: }
2338:
2339: return $this->scopeFactory->create(
2340: $this->context,
2341: $this->isDeclareStrictTypes(),
2342: $this->getFunction(),
2343: $this->getNamespace(),
2344: $expressionTypes,
2345: $nativeExpressionTypes,
2346: $this->conditionalExpressions,
2347: $scopeClasses,
2348: $this->anonymousFunctionReflection,
2349: templateArgumentFrame: $this->templateArgumentFrame,
2350: templateArgumentConstraints: $this->templateArgumentConstraints,
2351: );
2352: }
2353:
2354: public function restoreOriginalScopeAfterClosureBind(self $originalScope): self
2355: {
2356: $expressionTypes = $this->expressionTypes;
2357: if (isset($originalScope->expressionTypes['$this'])) {
2358: $expressionTypes['$this'] = $originalScope->expressionTypes['$this'];
2359: } else {
2360: unset($expressionTypes['$this']);
2361: }
2362:
2363: $nativeExpressionTypes = $this->nativeExpressionTypes;
2364: if (isset($originalScope->nativeExpressionTypes['$this'])) {
2365: $nativeExpressionTypes['$this'] = $originalScope->nativeExpressionTypes['$this'];
2366: } else {
2367: unset($nativeExpressionTypes['$this']);
2368: }
2369:
2370: return $this->scopeFactory->create(
2371: $this->context,
2372: $this->isDeclareStrictTypes(),
2373: $this->getFunction(),
2374: $this->getNamespace(),
2375: $expressionTypes,
2376: $nativeExpressionTypes,
2377: $this->conditionalExpressions,
2378: $originalScope->inClosureBindScopeClasses,
2379: $this->anonymousFunctionReflection,
2380: templateArgumentFrame: $this->templateArgumentFrame,
2381: templateArgumentConstraints: $this->templateArgumentConstraints,
2382: );
2383: }
2384:
2385: public function restoreThis(self $restoreThisScope): self
2386: {
2387: $expressionTypes = $this->expressionTypes;
2388: $nativeExpressionTypes = $this->nativeExpressionTypes;
2389:
2390: if ($restoreThisScope->isInClass()) {
2391: foreach ($restoreThisScope->expressionTypes as $exprString => $expressionTypeHolder) {
2392: if (!str_starts_with($exprString, '$this')) {
2393: continue;
2394: }
2395:
2396: $expressionTypes[$exprString] = $expressionTypeHolder;
2397: }
2398:
2399: foreach ($restoreThisScope->nativeExpressionTypes as $exprString => $expressionTypeHolder) {
2400: if (!str_starts_with($exprString, '$this')) {
2401: continue;
2402: }
2403:
2404: $nativeExpressionTypes[$exprString] = $expressionTypeHolder;
2405: }
2406: } else {
2407: unset($expressionTypes['$this']);
2408: unset($nativeExpressionTypes['$this']);
2409: }
2410:
2411: return $this->scopeFactory->create(
2412: $this->context,
2413: $this->isDeclareStrictTypes(),
2414: $this->getFunction(),
2415: $this->getNamespace(),
2416: $expressionTypes,
2417: $nativeExpressionTypes,
2418: $this->conditionalExpressions,
2419: $restoreThisScope->inClosureBindScopeClasses,
2420: $this->anonymousFunctionReflection,
2421: $this->inFirstLevelStatement,
2422: [],
2423: [],
2424: $this->inFunctionCallsStack,
2425: $this->afterExtractCall,
2426: $this->parentScope,
2427: $this->nativeTypesPromoted,
2428: $this->templateArgumentFrame,
2429: $this->templateArgumentConstraints,
2430: );
2431: }
2432:
2433: public function enterClosureCall(Type $thisType, Type $nativeThisType): self
2434: {
2435: $expressionTypes = $this->expressionTypes;
2436: $expressionTypes['$this'] = ExpressionTypeHolder::createYes(new Variable('this'), $thisType);
2437:
2438: $nativeExpressionTypes = $this->nativeExpressionTypes;
2439: $nativeExpressionTypes['$this'] = ExpressionTypeHolder::createYes(new Variable('this'), $nativeThisType);
2440:
2441: return $this->scopeFactory->create(
2442: $this->context,
2443: $this->isDeclareStrictTypes(),
2444: $this->getFunction(),
2445: $this->getNamespace(),
2446: $expressionTypes,
2447: $nativeExpressionTypes,
2448: $this->conditionalExpressions,
2449: $thisType->getObjectClassNames(),
2450: $this->anonymousFunctionReflection,
2451: templateArgumentFrame: $this->templateArgumentFrame,
2452: templateArgumentConstraints: $this->templateArgumentConstraints,
2453: );
2454: }
2455:
2456: /** @api */
2457: public function isInClosureBind(): bool
2458: {
2459: return $this->inClosureBindScopeClasses !== [];
2460: }
2461:
2462: /**
2463: * @param list<non-empty-string> $scopeClasses
2464: */
2465: public function withClosureBindScopeClasses(array $scopeClasses): self
2466: {
2467: return $this->scopeFactory->create(
2468: $this->context,
2469: $this->isDeclareStrictTypes(),
2470: $this->getFunction(),
2471: $this->getNamespace(),
2472: $this->expressionTypes,
2473: $this->nativeExpressionTypes,
2474: $this->conditionalExpressions,
2475: $scopeClasses,
2476: $this->anonymousFunctionReflection,
2477: $this->isInFirstLevelStatement(),
2478: $this->currentlyAssignedExpressions,
2479: $this->currentlyAllowedUndefinedExpressions,
2480: $this->inFunctionCallsStack,
2481: $this->afterExtractCall,
2482: $this->parentScope,
2483: $this->nativeTypesPromoted,
2484: $this->templateArgumentFrame,
2485: $this->templateArgumentConstraints,
2486: );
2487: }
2488:
2489: /**
2490: * @api
2491: * @param ParameterReflection[]|null $callableParameters
2492: * @param ParameterReflection[]|null $nativeCallableParameters
2493: */
2494: public function enterAnonymousFunction(
2495: Expr\Closure $closure,
2496: ?array $callableParameters,
2497: ?array $nativeCallableParameters = null,
2498: ): self
2499: {
2500: $anonymousFunctionReflection = $this->services->container->getByType(ClosureTypeResolver::class)->getClosureType($this, $closure, true, $this->getCurrentExpressionResultStorage());
2501:
2502: $scope = $this->enterAnonymousFunctionWithoutReflection($closure, $callableParameters, $nativeCallableParameters);
2503:
2504: return $this->scopeFactory->create(
2505: $scope->context,
2506: $scope->isDeclareStrictTypes(),
2507: $scope->getFunction(),
2508: $scope->getNamespace(),
2509: $scope->expressionTypes,
2510: $scope->nativeExpressionTypes,
2511: $scope->conditionalExpressions,
2512: $scope->inClosureBindScopeClasses,
2513: $anonymousFunctionReflection,
2514: true,
2515: [],
2516: [],
2517: $this->inFunctionCallsStack,
2518: false,
2519: $this,
2520: $this->nativeTypesPromoted,
2521: $this->templateArgumentFrame,
2522: $this->templateArgumentConstraints,
2523: );
2524: }
2525:
2526: /**
2527: * @param ParameterReflection[]|null $callableParameters
2528: * @param ParameterReflection[]|null $nativeCallableParameters
2529: */
2530: public function enterAnonymousFunctionWithoutReflection(
2531: Expr\Closure $closure,
2532: ?array $callableParameters,
2533: ?array $nativeCallableParameters,
2534: ): self
2535: {
2536: $expressionTypes = [];
2537: $nativeTypes = [];
2538: foreach ($closure->params as $i => $parameter) {
2539: if (!$parameter->var instanceof Variable || !is_string($parameter->var->name)) {
2540: throw new ShouldNotHappenException();
2541: }
2542: $paramExprString = sprintf('$%s', $parameter->var->name);
2543: $isNullable = $this->isParameterValueNullable($parameter);
2544: $nativeParameterType = $parameterType = $this->getFunctionType($parameter->type, $isNullable, $parameter->variadic);
2545: if ($callableParameters !== null) {
2546: $parameterType = self::intersectButNotNever($parameterType, $this->getCallableParameterType($parameter, $callableParameters, $i));
2547: }
2548: if ($nativeCallableParameters !== null) {
2549: $nativeParameterType = self::intersectButNotNever($nativeParameterType, $this->getCallableParameterType($parameter, $nativeCallableParameters, $i));
2550: }
2551: $expressionTypes[$paramExprString] = ExpressionTypeHolder::createYes($parameter->var, $parameterType);
2552: $nativeTypes[$paramExprString] = ExpressionTypeHolder::createYes($parameter->var, $nativeParameterType);
2553: }
2554:
2555: $nonRefVariableNames = [];
2556: $useVariableNames = [];
2557: foreach ($closure->uses as $use) {
2558: if (!is_string($use->var->name)) {
2559: throw new ShouldNotHappenException();
2560: }
2561: $variableName = $use->var->name;
2562: $paramExprString = '$' . $use->var->name;
2563: $useVariableNames[$paramExprString] = true;
2564: if ($use->byRef) {
2565: $holder = ExpressionTypeHolder::createYes($use->var, new MixedType());
2566: $expressionTypes[$paramExprString] = $holder;
2567: $nativeTypes[$paramExprString] = $holder;
2568: continue;
2569: }
2570: $nonRefVariableNames[$variableName] = true;
2571: if ($this->hasVariableType($variableName)->no()) {
2572: $variableType = new ErrorType();
2573: $variableNativeType = new ErrorType();
2574: } else {
2575: $variableType = $this->getVariableType($variableName);
2576: // a plain variable read is scope state - never priced via the
2577: // node, which may not have been processed yet
2578: $nativeScope = $this->doNotTreatPhpDocTypesAsCertain();
2579: $variableNativeType = $nativeScope->hasVariableType($variableName)->no() ? new ErrorType() : $nativeScope->getVariableType($variableName);
2580: }
2581: $expressionTypes[$paramExprString] = ExpressionTypeHolder::createYes($use->var, $variableType);
2582: $nativeTypes[$paramExprString] = ExpressionTypeHolder::createYes($use->var, $variableNativeType);
2583: }
2584:
2585: $nonStaticExpressions = $this->invalidateStaticExpressions($this->expressionTypes);
2586: foreach ($nonStaticExpressions as $exprString => $typeHolder) {
2587: $expr = $typeHolder->getExpr();
2588:
2589: if ($expr instanceof Variable) {
2590: continue;
2591: }
2592:
2593: $variables = (new NodeFinder())->findInstanceOf([$expr], Variable::class);
2594: if ($variables === [] && !$this->expressionTypeIsUnchangeable($typeHolder)) {
2595: continue;
2596: }
2597:
2598: foreach ($variables as $variable) {
2599: if (!is_string($variable->name)) {
2600: continue 2;
2601: }
2602: if (!array_key_exists($variable->name, $nonRefVariableNames)) {
2603: continue 2;
2604: }
2605: }
2606:
2607: $expressionTypes[$exprString] = $typeHolder;
2608: }
2609:
2610: if ($this->hasVariableType('this')->yes() && !$closure->static) {
2611: $node = new Variable('this');
2612: $expressionTypes['$this'] = ExpressionTypeHolder::createYes($node, $this->getType($node));
2613: $nativeTypes['$this'] = ExpressionTypeHolder::createYes($node, $this->getNativeType($node));
2614:
2615: foreach ($nonStaticExpressions as $exprString => $typeHolder) {
2616: $expr = $typeHolder->getExpr();
2617:
2618: if (!$expr instanceof PropertyFetch) {
2619: continue;
2620: }
2621:
2622: if (!$this->isReadonlyPropertyFetch($expr, true)) {
2623: continue;
2624: }
2625:
2626: $expressionTypes[$exprString] = $typeHolder;
2627: }
2628: }
2629:
2630: $filteredConditionalExpressions = [];
2631: foreach ($this->conditionalExpressions as $conditionalExprString => $holders) {
2632: if (!array_key_exists($conditionalExprString, $useVariableNames)) {
2633: continue;
2634: }
2635: $filteredHolders = [];
2636: foreach ($holders as $key => $holder) {
2637: foreach (array_keys($holder->getConditionExpressionTypeHolders()) as $holderExprString) {
2638: if (!array_key_exists($holderExprString, $useVariableNames)) {
2639: continue 2;
2640: }
2641: }
2642: $filteredHolders[$key] = $holder;
2643: }
2644: if ($filteredHolders === []) {
2645: continue;
2646: }
2647:
2648: $filteredConditionalExpressions[$conditionalExprString] = $filteredHolders;
2649: }
2650:
2651: return $this->scopeFactory->create(
2652: $this->context,
2653: $this->isDeclareStrictTypes(),
2654: $this->getFunction(),
2655: $this->getNamespace(),
2656: array_merge($this->getConstantTypes(), $expressionTypes),
2657: array_merge($this->getNativeConstantTypes(), $nativeTypes),
2658: $filteredConditionalExpressions,
2659: $this->inClosureBindScopeClasses,
2660: new ClosureType(),
2661: true,
2662: [],
2663: [],
2664: [],
2665: false,
2666: $this,
2667: $this->nativeTypesPromoted,
2668: $this->templateArgumentFrame,
2669: $this->templateArgumentConstraints,
2670: );
2671: }
2672:
2673: private function expressionTypeIsUnchangeable(ExpressionTypeHolder $typeHolder): bool
2674: {
2675: $expr = $typeHolder->getExpr();
2676: $type = $typeHolder->getType();
2677:
2678: return $expr instanceof FuncCall
2679: && !$expr->isPartialFunctionApplication()
2680: && $expr->name instanceof FullyQualified
2681: && in_array(
2682: $expr->name->toLowerString(),
2683: [
2684: 'class_exists',
2685: 'interface_exists',
2686: 'trait_exists',
2687: 'enum_exists',
2688: 'function_exists',
2689: ],
2690: true,
2691: )
2692: && isset($expr->getArgs()[0])
2693: && count($this->getScopeStateType($expr->getArgs()[0]->value)->getConstantStrings()) === 1
2694: && $type->isTrue()->yes();
2695: }
2696:
2697: /**
2698: * @param array<string, ExpressionTypeHolder> $expressionTypes
2699: * @return array<string, ExpressionTypeHolder>
2700: */
2701: private function invalidateStaticExpressions(array $expressionTypes): array
2702: {
2703: $filteredExpressionTypes = [];
2704: $nodeFinder = new NodeFinder();
2705: foreach ($expressionTypes as $exprString => $expressionType) {
2706: $staticExpression = $nodeFinder->findFirst(
2707: [$expressionType->getExpr()],
2708: static fn ($node) => $node instanceof Expr\StaticCall || $node instanceof Expr\StaticPropertyFetch,
2709: );
2710: if ($staticExpression !== null) {
2711: continue;
2712: }
2713: $filteredExpressionTypes[$exprString] = $expressionType;
2714: }
2715: return $filteredExpressionTypes;
2716: }
2717:
2718: /**
2719: * @api
2720: * @param ParameterReflection[]|null $callableParameters
2721: * @param ParameterReflection[]|null $nativeCallableParameters
2722: */
2723: public function enterArrowFunction(Expr\ArrowFunction $arrowFunction, ?array $callableParameters, ?array $nativeCallableParameters = null): self
2724: {
2725: $anonymousFunctionReflection = $this->services->container->getByType(ClosureTypeResolver::class)->getClosureType($this, $arrowFunction, true, $this->getCurrentExpressionResultStorage());
2726:
2727: $scope = $this->enterArrowFunctionWithoutReflection($arrowFunction, $callableParameters, $nativeCallableParameters);
2728:
2729: return $this->scopeFactory->create(
2730: $scope->context,
2731: $scope->isDeclareStrictTypes(),
2732: $scope->getFunction(),
2733: $scope->getNamespace(),
2734: $scope->expressionTypes,
2735: $scope->nativeExpressionTypes,
2736: $scope->conditionalExpressions,
2737: $scope->inClosureBindScopeClasses,
2738: $anonymousFunctionReflection,
2739: true,
2740: [],
2741: [],
2742: $this->inFunctionCallsStack,
2743: $scope->afterExtractCall,
2744: $scope->parentScope,
2745: $this->nativeTypesPromoted,
2746: $this->templateArgumentFrame,
2747: $this->templateArgumentConstraints,
2748: );
2749: }
2750:
2751: /**
2752: * @param ParameterReflection[]|null $callableParameters
2753: * @param ParameterReflection[]|null $nativeCallableParameters
2754: */
2755: public function enterArrowFunctionWithoutReflection(Expr\ArrowFunction $arrowFunction, ?array $callableParameters, ?array $nativeCallableParameters): self
2756: {
2757: $arrowFunctionScope = $this;
2758: foreach ($arrowFunction->params as $i => $parameter) {
2759: $isNullable = $this->isParameterValueNullable($parameter);
2760: $nativeParameterType = $parameterType = $this->getFunctionType($parameter->type, $isNullable, $parameter->variadic);
2761: if ($callableParameters !== null) {
2762: $parameterType = self::intersectButNotNever($parameterType, $this->getCallableParameterType($parameter, $callableParameters, $i));
2763: }
2764: if ($nativeCallableParameters !== null) {
2765: $nativeParameterType = self::intersectButNotNever($nativeParameterType, $this->getCallableParameterType($parameter, $nativeCallableParameters, $i));
2766: }
2767:
2768: if (!$parameter->var instanceof Variable || !is_string($parameter->var->name)) {
2769: throw new ShouldNotHappenException();
2770: }
2771: $arrowFunctionScope = $arrowFunctionScope->assignVariable($parameter->var->name, $parameterType, $nativeParameterType, TrinaryLogic::createYes());
2772: }
2773:
2774: if ($arrowFunction->static) {
2775: $arrowFunctionScope = $arrowFunctionScope->invalidateExpression(new Variable('this'));
2776: }
2777:
2778: return $this->scopeFactory->create(
2779: $arrowFunctionScope->context,
2780: $this->isDeclareStrictTypes(),
2781: $arrowFunctionScope->getFunction(),
2782: $arrowFunctionScope->getNamespace(),
2783: $this->invalidateStaticExpressions($arrowFunctionScope->expressionTypes),
2784: $arrowFunctionScope->nativeExpressionTypes,
2785: $arrowFunctionScope->conditionalExpressions,
2786: $arrowFunctionScope->inClosureBindScopeClasses,
2787: new ClosureType(),
2788: true,
2789: [],
2790: [],
2791: [],
2792: $arrowFunctionScope->afterExtractCall,
2793: $arrowFunctionScope->parentScope,
2794: $this->nativeTypesPromoted,
2795: $this->templateArgumentFrame,
2796: $this->templateArgumentConstraints,
2797: );
2798: }
2799:
2800: public function isParameterValueNullable(Node\Param $parameter): bool
2801: {
2802: if ($parameter->default instanceof ConstFetch) {
2803: return strtolower((string) $parameter->default->name) === 'null';
2804: }
2805:
2806: return false;
2807: }
2808:
2809: /**
2810: * @api
2811: * @param Node\Name|Node\Identifier|Node\ComplexType|null $type
2812: */
2813: public function getFunctionType($type, bool $isNullable, bool $isVariadic): Type
2814: {
2815: if ($isVariadic) {
2816: if (!$this->getPhpVersion()->supportsNamedArguments()->no()) {
2817: return new ArrayType(new UnionType([IntegerRangeType::createAllGreaterThanOrEqualTo(0), new StringType()]), $this->getFunctionType(
2818: $type,
2819: $isNullable,
2820: false,
2821: ));
2822: }
2823:
2824: return new IntersectionType([new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), $this->getFunctionType(
2825: $type,
2826: $isNullable,
2827: false,
2828: )), new AccessoryArrayListType()]);
2829: }
2830: if (
2831: $type instanceof Name
2832: && $this->inClosureBindScopeClasses !== []
2833: && $this->inClosureBindScopeClasses !== ['static']
2834: && in_array($type->toLowerString(), ['static', 'self', 'parent'], true)
2835: && $this->services->reflectionProvider->hasClass($this->inClosureBindScopeClasses[0])
2836: ) {
2837: return $this->services->initializerExprTypeResolver->getFunctionType(
2838: $type,
2839: $isNullable,
2840: false,
2841: InitializerExprContext::fromClassReflection(
2842: $this->services->reflectionProvider->getClass($this->inClosureBindScopeClasses[0]),
2843: ),
2844: );
2845: }
2846:
2847: return $this->services->initializerExprTypeResolver->getFunctionType($type, $isNullable, false, InitializerExprContext::fromScope($this));
2848: }
2849:
2850: /**
2851: * @param ParameterReflection[] $callableParameters
2852: */
2853: private function getCallableParameterType(Node\Param $parameter, array $callableParameters, int $index): Type
2854: {
2855: if ($parameter->variadic) {
2856: return $this->buildVariadicArrayTypeFromCallableParameters($callableParameters, $index);
2857: }
2858:
2859: if (isset($callableParameters[$index])) {
2860: return $callableParameters[$index]->getType();
2861: }
2862:
2863: if (count($callableParameters) === 0) {
2864: return new MixedType();
2865: }
2866:
2867: $lastParameter = array_last($callableParameters);
2868: if ($lastParameter->isVariadic()) {
2869: return $lastParameter->getType();
2870: }
2871:
2872: return new MixedType();
2873: }
2874:
2875: /**
2876: * @param array<ParameterReflection> $callableParameters
2877: */
2878: private function buildVariadicArrayTypeFromCallableParameters(array $callableParameters, int $startIndex): Type
2879: {
2880: $elementTypes = [];
2881: $callableParametersCount = count($callableParameters);
2882: for ($j = $startIndex; $j < $callableParametersCount; $j++) {
2883: $elementTypes[] = $callableParameters[$j]->getType();
2884: if ($callableParameters[$j]->isVariadic()) {
2885: break;
2886: }
2887: }
2888:
2889: if ($elementTypes === [] && $callableParametersCount > 0) {
2890: $lastParameter = array_last($callableParameters);
2891: if ($lastParameter->isVariadic()) {
2892: $elementTypes[] = $lastParameter->getType();
2893: }
2894: }
2895:
2896: if ($elementTypes === []) {
2897: return new MixedType();
2898: }
2899:
2900: $elementType = TypeCombinator::union(...$elementTypes);
2901:
2902: if (!$this->getPhpVersion()->supportsNamedArguments()->no()) {
2903: return new ArrayType(new UnionType([IntegerRangeType::createAllGreaterThanOrEqualTo(0), new StringType()]), $elementType);
2904: }
2905:
2906: return new IntersectionType([new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), $elementType), new AccessoryArrayListType()]);
2907: }
2908:
2909: public static function intersectButNotNever(Type $nativeType, Type $inferredType): Type
2910: {
2911: if ($nativeType->isSuperTypeOf($inferredType)->no()) {
2912: return $nativeType;
2913: }
2914:
2915: $result = TypeCombinator::intersect($nativeType, $inferredType);
2916: if ($result instanceof NeverType) {
2917: // the inferred type says no value is ever produced - the native
2918: // type's nullability must not resurrect one
2919: return $result;
2920: }
2921:
2922: if (TypeCombinator::containsNull($nativeType)) {
2923: return TypeCombinator::addNull($result);
2924: }
2925:
2926: return $result;
2927: }
2928:
2929: public function enterMatch(Expr\Match_ $expr, Type $condType, Type $condNativeType): self
2930: {
2931: if ($expr->cond instanceof Variable) {
2932: return $this;
2933: }
2934: if ($expr->cond instanceof AlwaysRememberedExpr) {
2935: $cond = $expr->cond->expr;
2936: } else {
2937: $cond = $expr->cond;
2938: }
2939: if ($cond instanceof Scalar) {
2940: return $this;
2941: }
2942:
2943: $type = $condType;
2944: $nativeType = $condNativeType;
2945: $condExpr = new AlwaysRememberedExpr($cond, $type, $nativeType);
2946: $expr->cond = $condExpr;
2947:
2948: return $this->assignExpression($condExpr, $type, $nativeType);
2949: }
2950:
2951: public function enterForeach(self $originalScope, Expr $iteratee, Type $iterateeType, Type $nativeIterateeType, string $valueName, ?string $keyName, bool $valueByRef): self
2952: {
2953: $valueType = $originalScope->getIterableValueType($iterateeType);
2954: $nativeValueType = $originalScope->getIterableValueType($nativeIterateeType);
2955: $scope = $this->assignVariable(
2956: $valueName,
2957: $valueType,
2958: $nativeValueType,
2959: TrinaryLogic::createYes(),
2960: );
2961: // Track the original foreach value so narrowings applied to the value
2962: // variable (e.g. is_string($type)) can later be projected back onto the
2963: // corresponding array dim fetch without being confused by a reassignment
2964: // ($type = 'foo' invalidates this expression, same as OriginalForeachKeyExpr).
2965: $scope = $scope->assignExpression(new OriginalForeachValueExpr($valueName), $valueType, $nativeValueType);
2966: if ($valueByRef && $iterateeType->isArray()->yes() && $iterateeType->isConstantArray()->no()) {
2967: // the write-through rebuilds the iteratee AT FOREACH ENTRY with the
2968: // value variable's latest type - captured here, not read live: a
2969: // live read would union the transient mid-iteration value states
2970: // into the array (the loop convergence owns cross-iteration merging)
2971: $scope = $scope->assignExpression(
2972: new IntertwinedVariableByReferenceWithExpr($valueName, $iteratee, new SetExistingOffsetValueTypeExpr(
2973: new NativeTypeExpr($iterateeType, $nativeIterateeType),
2974: new NativeTypeExpr(
2975: $originalScope->getIterableKeyType($iterateeType),
2976: $originalScope->getIterableKeyType($nativeIterateeType),
2977: ),
2978: new Variable($valueName),
2979: )),
2980: $valueType,
2981: $nativeValueType,
2982: );
2983: }
2984: if ($keyName !== null) {
2985: $scope = $scope->enterForeachKey($originalScope, $iteratee, $iterateeType, $nativeIterateeType, $keyName);
2986:
2987: if ($valueByRef && $iterateeType->isArray()->yes() && $iterateeType->isConstantArray()->no()) {
2988: $scope = $scope->assignExpression(
2989: new IntertwinedVariableByReferenceWithExpr($valueName, new Expr\ArrayDimFetch($iteratee, new Variable($keyName)), new Variable($valueName)),
2990: $valueType,
2991: $nativeValueType,
2992: );
2993: }
2994: }
2995:
2996: return $scope;
2997: }
2998:
2999: public function enterForeachKey(self $originalScope, Expr $iteratee, Type $iterateeType, Type $nativeIterateeType, string $keyName): self
3000: {
3001: $keyType = $originalScope->getIterableKeyType($iterateeType);
3002: $nativeKeyType = $originalScope->getIterableKeyType($nativeIterateeType);
3003:
3004: $scope = $this->assignVariable(
3005: $keyName,
3006: $keyType,
3007: $nativeKeyType,
3008: TrinaryLogic::createYes(),
3009: );
3010:
3011: $originalForeachKeyExpr = new OriginalForeachKeyExpr($keyName);
3012: $scope = $scope->assignExpression($originalForeachKeyExpr, $keyType, $nativeKeyType);
3013: if ($iterateeType->isArray()->yes()) {
3014: $scope = $scope->assignExpression(
3015: new Expr\ArrayDimFetch($iteratee, new Variable($keyName)),
3016: $originalScope->getIterableValueType($iterateeType),
3017: $originalScope->getIterableValueType($nativeIterateeType),
3018: );
3019: }
3020:
3021: return $scope;
3022: }
3023:
3024: public function enterCatchType(Type $catchType, ?string $variableName): self
3025: {
3026: if ($variableName === null) {
3027: return $this;
3028: }
3029:
3030: return $this->assignVariable(
3031: $variableName,
3032: TypeCombinator::intersect($catchType, new ObjectType(Throwable::class)),
3033: TypeCombinator::intersect($catchType, new ObjectType(Throwable::class)),
3034: TrinaryLogic::createYes(),
3035: );
3036: }
3037:
3038: public function enterExpressionAssign(Expr $expr, bool $isPlainWrite = true): self
3039: {
3040: $exprString = $this->getNodeKey($expr);
3041: $currentlyAssignedExpressions = $this->currentlyAssignedExpressions;
3042: $currentlyAssignedExpressions[$exprString] = $isPlainWrite;
3043:
3044: $scope = $this->scopeFactory->create(
3045: $this->context,
3046: $this->isDeclareStrictTypes(),
3047: $this->getFunction(),
3048: $this->getNamespace(),
3049: $this->expressionTypes,
3050: $this->nativeExpressionTypes,
3051: $this->conditionalExpressions,
3052: $this->inClosureBindScopeClasses,
3053: $this->anonymousFunctionReflection,
3054: $this->isInFirstLevelStatement(),
3055: $currentlyAssignedExpressions,
3056: $this->currentlyAllowedUndefinedExpressions,
3057: [],
3058: $this->afterExtractCall,
3059: $this->parentScope,
3060: $this->nativeTypesPromoted,
3061: $this->templateArgumentFrame,
3062: $this->templateArgumentConstraints,
3063: );
3064: $scope->resolvedTypes = $this->resolvedTypes;
3065:
3066: return $scope;
3067: }
3068:
3069: public function exitExpressionAssign(Expr $expr): self
3070: {
3071: $exprString = $this->getNodeKey($expr);
3072: $currentlyAssignedExpressions = $this->currentlyAssignedExpressions;
3073: unset($currentlyAssignedExpressions[$exprString]);
3074:
3075: $scope = $this->scopeFactory->create(
3076: $this->context,
3077: $this->isDeclareStrictTypes(),
3078: $this->getFunction(),
3079: $this->getNamespace(),
3080: $this->expressionTypes,
3081: $this->nativeExpressionTypes,
3082: $this->conditionalExpressions,
3083: $this->inClosureBindScopeClasses,
3084: $this->anonymousFunctionReflection,
3085: $this->isInFirstLevelStatement(),
3086: $currentlyAssignedExpressions,
3087: $this->currentlyAllowedUndefinedExpressions,
3088: [],
3089: $this->afterExtractCall,
3090: $this->parentScope,
3091: $this->nativeTypesPromoted,
3092: $this->templateArgumentFrame,
3093: $this->templateArgumentConstraints,
3094: );
3095: $scope->resolvedTypes = $this->resolvedTypes;
3096:
3097: return $scope;
3098: }
3099:
3100: /** @api */
3101: public function isInExpressionAssign(Expr $expr): bool
3102: {
3103: if (count($this->currentlyAssignedExpressions) === 0) {
3104: return false;
3105: }
3106:
3107: $exprString = $this->getNodeKey($expr);
3108: return array_key_exists($exprString, $this->currentlyAssignedExpressions);
3109: }
3110:
3111: /**
3112: * Whether the expression is a plain write target of an assignment, as opposed to being
3113: * read-modified in place (e.g. the base of `$prop[] = ...`). Used to decide whether a
3114: * property fetch resolves to its writable or readable type.
3115: */
3116: public function isInWriteExpressionAssign(Expr $expr): bool
3117: {
3118: if (count($this->currentlyAssignedExpressions) === 0) {
3119: return false;
3120: }
3121:
3122: $exprString = $this->getNodeKey($expr);
3123: return ($this->currentlyAssignedExpressions[$exprString] ?? false) === true;
3124: }
3125:
3126: public function setAllowedUndefinedExpression(Expr $expr): self
3127: {
3128: if ($expr instanceof Expr\StaticPropertyFetch) {
3129: return $this;
3130: }
3131:
3132: $exprString = $this->getNodeKey($expr);
3133: $currentlyAllowedUndefinedExpressions = $this->currentlyAllowedUndefinedExpressions;
3134: $currentlyAllowedUndefinedExpressions[$exprString] = true;
3135:
3136: $scope = $this->scopeFactory->create(
3137: $this->context,
3138: $this->isDeclareStrictTypes(),
3139: $this->getFunction(),
3140: $this->getNamespace(),
3141: $this->expressionTypes,
3142: $this->nativeExpressionTypes,
3143: $this->conditionalExpressions,
3144: $this->inClosureBindScopeClasses,
3145: $this->anonymousFunctionReflection,
3146: $this->isInFirstLevelStatement(),
3147: $this->currentlyAssignedExpressions,
3148: $currentlyAllowedUndefinedExpressions,
3149: [],
3150: $this->afterExtractCall,
3151: $this->parentScope,
3152: $this->nativeTypesPromoted,
3153: $this->templateArgumentFrame,
3154: $this->templateArgumentConstraints,
3155: );
3156: $scope->resolvedTypes = $this->resolvedTypes;
3157:
3158: return $scope;
3159: }
3160:
3161: public function unsetAllowedUndefinedExpression(Expr $expr): self
3162: {
3163: $exprString = $this->getNodeKey($expr);
3164: $currentlyAllowedUndefinedExpressions = $this->currentlyAllowedUndefinedExpressions;
3165: unset($currentlyAllowedUndefinedExpressions[$exprString]);
3166:
3167: $scope = $this->scopeFactory->create(
3168: $this->context,
3169: $this->isDeclareStrictTypes(),
3170: $this->getFunction(),
3171: $this->getNamespace(),
3172: $this->expressionTypes,
3173: $this->nativeExpressionTypes,
3174: $this->conditionalExpressions,
3175: $this->inClosureBindScopeClasses,
3176: $this->anonymousFunctionReflection,
3177: $this->isInFirstLevelStatement(),
3178: $this->currentlyAssignedExpressions,
3179: $currentlyAllowedUndefinedExpressions,
3180: [],
3181: $this->afterExtractCall,
3182: $this->parentScope,
3183: $this->nativeTypesPromoted,
3184: $this->templateArgumentFrame,
3185: $this->templateArgumentConstraints,
3186: );
3187: $scope->resolvedTypes = $this->resolvedTypes;
3188:
3189: return $scope;
3190: }
3191:
3192: /** @api */
3193: public function isUndefinedExpressionAllowed(Expr $expr): bool
3194: {
3195: if (count($this->currentlyAllowedUndefinedExpressions) === 0) {
3196: return false;
3197: }
3198: $exprString = $this->getNodeKey($expr);
3199: return array_key_exists($exprString, $this->currentlyAllowedUndefinedExpressions);
3200: }
3201:
3202: /**
3203: * @param list<string> $intertwinedPropagatedFrom
3204: */
3205: public function assignVariable(string $variableName, Type $type, Type $nativeType, TrinaryLogic $certainty, array $intertwinedPropagatedFrom = []): self
3206: {
3207: $node = new Variable($variableName);
3208: $scope = $this->assignExpression($node, $type, $nativeType);
3209: if ($certainty->no()) {
3210: throw new ShouldNotHappenException();
3211: } elseif (!$certainty->yes()) {
3212: $exprString = '$' . $variableName;
3213: $scope->expressionTypes[$exprString] = new ExpressionTypeHolder($node, $type, $certainty);
3214: $scope->nativeExpressionTypes[$exprString] = new ExpressionTypeHolder($node, $nativeType, $certainty);
3215: }
3216:
3217: foreach ($scope->expressionTypes as $exprString => $expressionType) {
3218: if (!$expressionType->getExpr() instanceof IntertwinedVariableByReferenceWithExpr) {
3219: continue;
3220: }
3221: if (!$expressionType->getCertainty()->yes()) {
3222: continue;
3223: }
3224: if ($expressionType->getExpr()->getVariableName() !== $variableName) {
3225: continue;
3226: }
3227:
3228: $assignedExpr = $expressionType->getExpr()->getAssignedExpr();
3229: if (
3230: $assignedExpr instanceof Expr\ArrayDimFetch
3231: && !$this->isDimFetchPathReachable($scope, $assignedExpr)
3232: ) {
3233: unset($scope->expressionTypes[$exprString]);
3234: unset($scope->nativeExpressionTypes[$exprString]);
3235: continue;
3236: }
3237:
3238: // When the byref's dim is non-constant AND not enumerable as a
3239: // finite set of scalars (e.g. general `int` or `mixed`), the just-
3240: // performed write to $array might or might not have hit the byref's
3241: // slot. Union the new $array[dim] read with the byref's previous
3242: // type and the pre-write $array[dim] so values that could still be
3243: // at the slot (unmodified or shadowed by an explicit-key overwrite)
3244: // survive. For finitely-enumerable dims (e.g. `bool`, `int<0, 5>`)
3245: // the array literal builder enumerates all possibilities, so the
3246: // new $array[dim] read already covers every reachable slot.
3247: $unionWithOld = false;
3248: if ($assignedExpr instanceof Expr\ArrayDimFetch && $assignedExpr->dim !== null) {
3249: $dimType = $scope->getType($assignedExpr->dim);
3250: if (count($dimType->getConstantScalarValues()) !== 1 && count($dimType->getFiniteTypes()) === 0) {
3251: $unionWithOld = true;
3252: }
3253: }
3254:
3255: // Resolve the byref slot's new value directly from the just-assigned
3256: // root variable's type, instead of re-evaluating the (stale) $assignedExpr
3257: // node via Scope::getType(): the stored ArrayDimFetch result captured the
3258: // array variable before it existed, so re-reading it would only resolve
3259: // through the asking scope. We already hold the authoritative value here.
3260: $assignedType = $this->resolveIntertwinedAssignedType($scope, $type, $assignedExpr, $variableName, false);
3261: $assignedNativeType = $this->resolveIntertwinedAssignedType($scope, $nativeType, $assignedExpr, $variableName, true);
3262:
3263: $has = $scope->hasExpressionType($expressionType->getExpr()->getExpr());
3264: if (
3265: $expressionType->getExpr()->getExpr() instanceof Variable
3266: && is_string($expressionType->getExpr()->getExpr()->name)
3267: && !$has->no()
3268: ) {
3269: $targetVarName = $expressionType->getExpr()->getExpr()->name;
3270: if (in_array($targetVarName, $intertwinedPropagatedFrom, true)) {
3271: continue;
3272: }
3273: if ($unionWithOld) {
3274: $targetVarNode = new Variable($targetVarName);
3275: $rootVarNode = new Variable($variableName);
3276: $assignedType = TypeCombinator::union(
3277: $assignedType,
3278: $this->resolveIntertwinedAssignedType($this, $this->getType($rootVarNode), $assignedExpr, $variableName, false),
3279: $scope->getType($targetVarNode),
3280: );
3281: $assignedNativeType = TypeCombinator::union(
3282: $assignedNativeType,
3283: $this->resolveIntertwinedAssignedType($this, $this->getNativeType($rootVarNode), $assignedExpr, $variableName, true),
3284: $scope->getNativeType($targetVarNode),
3285: );
3286: }
3287: $scope = $scope->assignVariable(
3288: $targetVarName,
3289: $assignedType,
3290: $assignedNativeType,
3291: $has,
3292: array_merge($intertwinedPropagatedFrom, [$variableName]),
3293: );
3294: } else {
3295: $targetRootVar = ScopeOps::getIntertwinedRefRootVariableName($expressionType->getExpr()->getExpr());
3296: if ($targetRootVar !== null && in_array($targetRootVar, $intertwinedPropagatedFrom, true)) {
3297: continue;
3298: }
3299: $scope = $scope->overwriteExpression(
3300: $expressionType->getExpr()->getExpr(),
3301: $assignedType,
3302: $assignedNativeType,
3303: );
3304: }
3305: }
3306:
3307: return $scope;
3308: }
3309:
3310: /**
3311: * assignExpression() for a value that overwrites what an already existing
3312: * offset holds - a byref alias write or a setAlwaysOverwriteTypes()
3313: * specification.
3314: *
3315: * For an `ArrayDimFetch` the new value has to be *written* into the containing
3316: * array. assignExpression() would instead narrow it: specifyExpressionType()
3317: * intersects the parent with HasOffsetValueType(dim, newValue), which
3318: * contradicts - and collapses to `never` - a parent still holding the offset's
3319: * previous (constant) value.
3320: */
3321: private function overwriteExpression(Expr $expr, Type $type, Type $nativeType): self
3322: {
3323: if (!$expr instanceof Expr\ArrayDimFetch || $expr->dim === null) {
3324: return $this->assignExpression($expr, $type, $nativeType);
3325: }
3326:
3327: $dimType = $this->getType($expr->dim);
3328: $scope = $this->overwriteExpression(
3329: $expr->var,
3330: $this->getType($expr->var)->setExistingOffsetValueType($dimType, $type),
3331: $this->getNativeType($expr->var)->setExistingOffsetValueType($dimType, $nativeType),
3332: );
3333:
3334: return $scope->specifyExpressionType($expr, $type, $nativeType, TrinaryLogic::createYes());
3335: }
3336:
3337: /**
3338: * Resolves the type of a byref slot expression (rooted at $rootVariableName)
3339: * from $rootType - the type just assigned to that root variable - by walking
3340: * the offsets, without re-evaluating the stored $assignedExpr node via
3341: * Scope::getType().
3342: */
3343: private function resolveIntertwinedAssignedType(self $scope, Type $rootType, Expr $assignedExpr, string $rootVariableName, bool $native): Type
3344: {
3345: if ($assignedExpr instanceof Variable && is_string($assignedExpr->name) && $assignedExpr->name === $rootVariableName) {
3346: return $rootType;
3347: }
3348:
3349: if ($assignedExpr instanceof Expr\ArrayDimFetch && $assignedExpr->dim !== null) {
3350: return $this->resolveIntertwinedAssignedType($scope, $rootType, $assignedExpr->var, $rootVariableName, $native)
3351: ->getOffsetValueType($native ? $scope->getNativeType($assignedExpr->dim) : $scope->getType($assignedExpr->dim));
3352: }
3353:
3354: if ($assignedExpr instanceof SetExistingOffsetValueTypeExpr) {
3355: // foreach-byref slot: the iteratee with its key offset set to the value
3356: // variable's new type ($rootType is exactly that value - the expr's
3357: // getValue()).
3358: $iterateeType = $native
3359: ? $scope->getNativeType($assignedExpr->getVar())
3360: : $scope->getType($assignedExpr->getVar());
3361:
3362: $dimType = $native
3363: ? $scope->getNativeType($assignedExpr->getDim())
3364: : $scope->getType($assignedExpr->getDim());
3365:
3366: return $iterateeType->setExistingOffsetValueType($dimType, $rootType);
3367: }
3368:
3369: throw new ShouldNotHappenException();
3370: }
3371:
3372: private function isDimFetchPathReachable(self $scope, Expr\ArrayDimFetch $dimFetch): bool
3373: {
3374: if ($dimFetch->dim === null) {
3375: return false;
3376: }
3377:
3378: if (!$dimFetch->var instanceof Expr\ArrayDimFetch) {
3379: return true;
3380: }
3381:
3382: $varType = $scope->getType($dimFetch->var);
3383: $dimType = $scope->getType($dimFetch->dim);
3384:
3385: if (!$varType->hasOffsetValueType($dimType)->yes()) {
3386: return false;
3387: }
3388:
3389: return $this->isDimFetchPathReachable($scope, $dimFetch->var);
3390: }
3391:
3392: private function unsetExpression(Expr $expr): self
3393: {
3394: $scope = $this;
3395: if ($expr instanceof Expr\ArrayDimFetch && $expr->dim !== null) {
3396: $exprVarType = $scope->getScopeStateType($expr->var);
3397: $dimType = $scope->getType($expr->dim);
3398: $unsetType = $exprVarType->unsetOffset($dimType);
3399: $exprVarNativeType = $scope->getScopeStateNativeType($expr->var);
3400: $dimNativeType = $scope->getNativeType($expr->dim);
3401: $unsetNativeType = $exprVarNativeType->unsetOffset($dimNativeType);
3402: $scope = $scope->assignExpression($expr->var, $unsetType, $unsetNativeType)->invalidateExpression(
3403: new FuncCall(new FullyQualified('count'), [new Arg($expr->var)]),
3404: )->invalidateExpression(
3405: new FuncCall(new FullyQualified('sizeof'), [new Arg($expr->var)]),
3406: )->invalidateExpression(
3407: new FuncCall(new Name('count'), [new Arg($expr->var)]),
3408: )->invalidateExpression(
3409: new FuncCall(new Name('sizeof'), [new Arg($expr->var)]),
3410: );
3411:
3412: if ($expr->var instanceof Expr\ArrayDimFetch && $expr->var->dim !== null) {
3413: $scope = $scope->assignExpression(
3414: $expr->var->var,
3415: $this->getType($expr->var->var)->setOffsetValueType(
3416: $scope->getType($expr->var->dim),
3417: $scope->getScopeStateType($expr->var),
3418: ),
3419: $this->getNativeType($expr->var->var)->setOffsetValueType(
3420: $scope->getNativeType($expr->var->dim),
3421: $scope->getScopeStateNativeType($expr->var),
3422: ),
3423: );
3424: }
3425: }
3426:
3427: return $scope->invalidateExpression($expr);
3428: }
3429:
3430: /**
3431: * A narrowable expression's current type as this scope sees it, derived
3432: * from tracked state (recursing into operands via reflection/offset reads)
3433: * - never by processing the node. The flavour follows the scope: a
3434: * native-promoted scope answers native types. Non-narrowable expressions
3435: * (calls, constants) fall back to getType().
3436: */
3437: public function getStateType(Expr $expr): Type
3438: {
3439: return $this->resolveScopeStateType($expr, $this->nativeTypesPromoted);
3440: }
3441:
3442: private function getScopeStateType(Expr $expr): Type
3443: {
3444: return $this->resolveScopeStateType($expr, false);
3445: }
3446:
3447: private function getScopeStateNativeType(Expr $expr): Type
3448: {
3449: return $this->resolveScopeStateType($expr, true);
3450: }
3451:
3452: /**
3453: * Reads a narrowable expression's current type from the scope's tracked
3454: * state (recursing into its operands), instead of routing through the stored
3455: * ExpressionResult callbacks - so it reflects narrowings and assignments
3456: * applied to this scope rather than the expression's original evaluation
3457: * point (where Variable callbacks would read their captured beforeScope).
3458: */
3459: private function resolveScopeStateType(Expr $expr, bool $native): Type
3460: {
3461: if (!$expr instanceof Variable && $this->hasExpressionType($expr)->yes()) {
3462: // mirror resolveType()'s tracked-holder lookup without pricing the
3463: // node - the tracked type IS scope state (the extension hook is
3464: // deliberately skipped, like the getVariableType() read below)
3465: $askScope = $native ? $this->doNotTreatPhpDocTypesAsCertain() : $this;
3466: $trackedType = ScopeOps::expressionTypeByKey($askScope, $expr, $askScope->getNodeKey($expr));
3467: if ($trackedType !== null) {
3468: return TypeUtils::resolveLateResolvableTypes($trackedType);
3469: }
3470:
3471: return $native ? $this->getNativeType($expr) : $this->getType($expr);
3472: }
3473:
3474: if ($expr instanceof Variable && is_string($expr->name)) {
3475: $scope = $native ? $this->doNotTreatPhpDocTypesAsCertain() : $this;
3476:
3477: return $scope->hasVariableType($expr->name)->no() ? new ErrorType() : $scope->getVariableType($expr->name);
3478: }
3479:
3480: if ($expr instanceof Expr\ArrayDimFetch && $expr->dim !== null) {
3481: $varStateType = $this->resolveScopeStateType($expr->var, $native);
3482: if ($varStateType instanceof NeverType) {
3483: // real pricing of an offset read on never yields ErrorType (a
3484: // benevolent mixed), never NeverType - mirror it, or a narrowing
3485: // applied in a dead branch intersects its type against never and
3486: // loses it (e.g. is_object($x[0]) no longer tracks $x[0] as object,
3487: // silencing rules that read the narrowed type)
3488: return new ErrorType();
3489: }
3490:
3491: return $varStateType->getOffsetValueType($this->resolveScopeStateType($expr->dim, $native));
3492: }
3493:
3494: if ($expr instanceof PropertyFetch && $expr->name instanceof Identifier) {
3495: $propertyReflection = $this->getInstancePropertyReflection(
3496: $this->resolveScopeStateType($expr->var, $native),
3497: $expr->name->toString(),
3498: );
3499: if ($propertyReflection === null) {
3500: return new ErrorType();
3501: }
3502:
3503: if ($native) {
3504: return $propertyReflection->hasNativeType() ? $propertyReflection->getNativeType() : new MixedType();
3505: }
3506:
3507: return $propertyReflection->getReadableType();
3508: }
3509:
3510: if ($expr instanceof Expr\StaticPropertyFetch && $expr->name instanceof Node\VarLikeIdentifier) {
3511: $fetchedOnType = $expr->class instanceof Name
3512: ? $this->resolveTypeByName($expr->class)
3513: : TypeCombinator::removeNull($this->resolveScopeStateType($expr->class, $native))->getObjectTypeOrClassStringObjectType();
3514: $propertyReflection = $this->getStaticPropertyReflection($fetchedOnType, $expr->name->toString());
3515: if ($propertyReflection === null) {
3516: return new ErrorType();
3517: }
3518:
3519: if ($native) {
3520: return $propertyReflection->hasNativeType() ? $propertyReflection->getNativeType() : new MixedType();
3521: }
3522:
3523: return $propertyReflection->getReadableType();
3524: }
3525:
3526: // a nullsafe link of a chain being ensured non-null ahead of its walk
3527: // (isset()/empty()/?? over `$a?->b()?->c`): its state is the plain
3528: // link's state on the receiver's state, plus the short-circuit null -
3529: // the same reflection-derived read as the plain fetch/call arms below,
3530: // never a walk of the still-unprocessed node
3531: if ($expr instanceof Expr\NullsafePropertyFetch && $expr->name instanceof Identifier) {
3532: return TypeCombinator::addNull($this->resolveScopeStateType(new PropertyFetch($expr->var, $expr->name), $native));
3533: }
3534: if (
3535: $expr instanceof Expr\NullsafeMethodCall
3536: && $expr->name instanceof Identifier
3537: && !$expr->isPartialFunctionApplication()
3538: && $expr->getArgs() === []
3539: ) {
3540: $attributes = $expr->getAttributes();
3541: unset($attributes[ExprPrinter::ATTRIBUTE_CACHE_KEY]);
3542: return TypeCombinator::addNull($this->resolveScopeStateType(new Expr\MethodCall($expr->var, $expr->name, attributes: $attributes), $native));
3543: }
3544:
3545: // an argument-less instance call - the shape @phpstan-assert subjects
3546: // take (synthetic nodes built fresh from the assert tag, never stored):
3547: // its declared return type on the receiver's state is the narrowing
3548: // base, derived from reflection instead of walking the synthetic node.
3549: // A call the walk did store answers from that result: the declared
3550: // return type lacks what the walk resolved against the arguments (a
3551: // conditional return type, a template, a dynamic return type extension)
3552: if (
3553: $expr instanceof Expr\MethodCall
3554: && $expr->name instanceof Identifier
3555: && !$expr->isPartialFunctionApplication()
3556: && $expr->getArgs() === []
3557: ) {
3558: $storage = $this->services->expressionResultStorageStack->getCurrent();
3559: if ($storage !== null && $storage->findExpressionResult($expr) !== null) {
3560: return $native ? $this->getNativeType($expr) : $this->getType($expr);
3561: }
3562:
3563: $methodReflection = $this->getMethodReflection(
3564: $this->resolveScopeStateType($expr->var, $native),
3565: $expr->name->toString(),
3566: );
3567: if ($methodReflection === null) {
3568: return new ErrorType();
3569: }
3570:
3571: // resolved against the (empty) argument list so a template inferred
3572: // from an omitted parameter's default resolves the way a walk
3573: // resolves it (Collection::first()'s TFirstDefault -> null)
3574: $variant = ParametersAcceptorSelector::selectFromArgs($this, [], $methodReflection->getVariants(), $methodReflection->getNamedArgumentsVariants());
3575:
3576: return $native && $variant instanceof ExtendedParametersAcceptor ? $variant->getNativeReturnType() : TemplateArgumentFrame::returnTypeOfCall($variant, $this, $expr, true);
3577: }
3578:
3579: // position-independent constant expressions (isset()/?? dimensions and
3580: // narrowing subjects like self::KEY) are priced without walking the node
3581: if (
3582: $expr instanceof Node\Scalar\String_
3583: || $expr instanceof Node\Scalar\Int_
3584: || $expr instanceof Node\Scalar\Float_
3585: || ($expr instanceof Expr\ClassConstFetch && $expr->class instanceof Name && $expr->name instanceof Identifier)
3586: || $expr instanceof ConstFetch
3587: ) {
3588: return $this->services->initializerExprTypeResolver->getType($expr, InitializerExprContext::fromScope($this));
3589: }
3590:
3591: // genuinely non-narrowed expressions (calls, ...) have no
3592: // variable-callback hazard, so read them normally.
3593: return $native ? $this->getNativeType($expr) : $this->getType($expr);
3594: }
3595:
3596: public function specifyExpressionType(Expr $expr, Type $type, Type $nativeType, TrinaryLogic $certainty): self
3597: {
3598: if ($expr instanceof Scalar || $this->isSpecifyExpressionTypeNoop($expr, $type)) {
3599: return $this;
3600: }
3601:
3602: $scope = $this->openSpecificationScope();
3603: $scope->specifyExpressionTypeInPlace($expr, $type, $nativeType, $certainty);
3604:
3605: return $scope;
3606: }
3607:
3608: /** An unpublished copy of this scope that in-place specification may mutate. */
3609: private function openSpecificationScope(): self
3610: {
3611: return $this->scopeFactory->create(
3612: $this->context,
3613: $this->isDeclareStrictTypes(),
3614: $this->getFunction(),
3615: $this->getNamespace(),
3616: $this->expressionTypes,
3617: $this->nativeExpressionTypes,
3618: $this->conditionalExpressions,
3619: $this->inClosureBindScopeClasses,
3620: $this->anonymousFunctionReflection,
3621: $this->inFirstLevelStatement,
3622: $this->currentlyAssignedExpressions,
3623: $this->currentlyAllowedUndefinedExpressions,
3624: $this->inFunctionCallsStack,
3625: $this->afterExtractCall,
3626: $this->parentScope,
3627: $this->nativeTypesPromoted,
3628: $this->templateArgumentFrame,
3629: $this->templateArgumentConstraints,
3630: );
3631: }
3632:
3633: private function isSpecifyExpressionTypeNoop(Expr $expr, Type $type): bool
3634: {
3635: if ($expr instanceof Scalar) {
3636: return true;
3637: }
3638:
3639: if ($expr instanceof ConstFetch) {
3640: $loweredConstName = strtolower($expr->name->toString());
3641: if (in_array($loweredConstName, ['true', 'false', 'null'], true)) {
3642: return true;
3643: }
3644: }
3645:
3646: if ($expr instanceof FuncCall && $expr->name instanceof Name && $type->isFalse()->yes()) {
3647: $functionName = $this->services->reflectionProvider->resolveFunctionName($expr->name, $this);
3648: if ($functionName !== null && in_array(strtolower($functionName), [
3649: 'is_dir',
3650: 'is_file',
3651: 'file_exists',
3652: ], true)) {
3653: return true;
3654: }
3655: }
3656:
3657: return false;
3658: }
3659:
3660: /**
3661: * The body of specifyExpressionType() writing straight into this scope's
3662: * holder maps - only to be called on an unpublished scope (see
3663: * openSpecificationScope()). Batching callers avoid one whole-map copy and
3664: * scope construction per specification (and per array-dim level).
3665: */
3666: private function specifyExpressionTypeInPlace(Expr $expr, Type $type, Type $nativeType, TrinaryLogic $certainty): void
3667: {
3668: if ($this->isSpecifyExpressionTypeNoop($expr, $type)) {
3669: return;
3670: }
3671:
3672: if (
3673: $expr instanceof Expr\ArrayDimFetch
3674: && $expr->dim !== null
3675: && !$expr->dim instanceof Expr\PreInc
3676: && !$expr->dim instanceof Expr\PreDec
3677: && !$expr->dim instanceof Expr\PostDec
3678: && !$expr->dim instanceof Expr\PostInc
3679: ) {
3680: $dimType = $this->getScopeStateType($expr->dim)->toArrayKey();
3681: if ($dimType->isInteger()->yes() || $dimType->isString()->yes()) {
3682: $exprVarType = $this->getScopeStateType($expr->var);
3683: $isArray = $exprVarType->isArray();
3684: if (!$exprVarType instanceof MixedType && !$isArray->no()) {
3685: $varType = $exprVarType;
3686: if (!$isArray->yes()) {
3687: if ($dimType->isInteger()->yes()) {
3688: $varType = TypeCombinator::intersect($exprVarType, StaticTypeFactory::intOffsetAccessibleType());
3689: } else {
3690: $varType = TypeCombinator::intersect($exprVarType, StaticTypeFactory::generalOffsetAccessibleType());
3691: }
3692: }
3693:
3694: if ($dimType instanceof ConstantIntegerType || $dimType instanceof ConstantStringType) {
3695: if (!$this->isComplexUnionType($varType)) {
3696: $varType = TypeCombinator::intersect(
3697: $varType,
3698: new HasOffsetValueType($dimType, $type),
3699: );
3700: }
3701: }
3702:
3703: $this->specifyExpressionTypeInPlace(
3704: $expr->var,
3705: $varType,
3706: $this->getScopeStateNativeType($expr->var),
3707: $certainty,
3708: );
3709: }
3710: }
3711: }
3712:
3713: if ($certainty->no()) {
3714: throw new ShouldNotHappenException();
3715: }
3716:
3717: $exprString = $this->getNodeKey($expr);
3718: $this->expressionTypes[$exprString] = new ExpressionTypeHolder($expr, $type, $certainty);
3719: $this->nativeExpressionTypes[$exprString] = new ExpressionTypeHolder($expr, $nativeType, $certainty);
3720:
3721: if (!($expr instanceof AlwaysRememberedExpr)) {
3722: return;
3723: }
3724:
3725: $this->specifyExpressionTypeInPlace($expr->expr, $type, $nativeType, $certainty);
3726: }
3727:
3728: public function assignExpression(Expr $expr, Type $type, Type $nativeType): self
3729: {
3730: $scope = $this;
3731: if ($expr instanceof PropertyFetch) {
3732: $scope = $this->invalidateExpression($expr)
3733: ->invalidateMethodsOnExpression($expr->var);
3734: } elseif ($expr instanceof Expr\StaticPropertyFetch) {
3735: $scope = $this->invalidateExpression($expr);
3736: } elseif ($expr instanceof Variable) {
3737: $scope = $this->invalidateExpression($expr);
3738: }
3739:
3740: return $scope->specifyExpressionType($expr, $type, $nativeType, TrinaryLogic::createYes());
3741: }
3742:
3743: public function assignInitializedProperty(Type $fetchedOnType, string $propertyName): self
3744: {
3745: if (!$this->isInClass()) {
3746: return $this;
3747: }
3748:
3749: if (TypeUtils::findThisType($fetchedOnType) === null) {
3750: return $this;
3751: }
3752:
3753: $propertyReflection = $this->getInstancePropertyReflection($fetchedOnType, $propertyName);
3754: if ($propertyReflection === null) {
3755: return $this;
3756: }
3757: $declaringClass = $propertyReflection->getDeclaringClass();
3758: if ($this->getClassReflection()->getName() !== $declaringClass->getName()) {
3759: return $this;
3760: }
3761: if (!$declaringClass->hasNativeProperty($propertyName)) {
3762: return $this;
3763: }
3764:
3765: $scope = $this->assignExpression(new PropertyInitializationExpr($propertyName), new MixedType(), new MixedType());
3766:
3767: $function = $scope->getFunction();
3768: if (
3769: $function instanceof MethodReflection
3770: && strtolower($function->getName()) === '__clone'
3771: && $scope->getPhpVersion()->supportsReadonlyPropertyReinitializationOnClone()->yes()
3772: ) {
3773: $scope = $scope->assignExpression(new CloneReinitializationExpr($propertyName), new MixedType(), new MixedType());
3774: }
3775:
3776: return $scope;
3777: }
3778:
3779: /**
3780: * @param bool $keepPropertyFetches Keeps property fetches on the invalidated expression
3781: * (like '$this->foo') - for callees that never receive
3782: * the object, like static methods and static closures.
3783: */
3784: public function invalidateExpression(Expr $expressionToInvalidate, bool $requireMoreCharacters = false, ?ClassReflection $invalidatingClass = null, bool $keepPropertyFetches = false): self
3785: {
3786: $exprStringToInvalidate = $this->getNodeKey($expressionToInvalidate);
3787:
3788: $result = ScopeOps::invalidateExpressionEntries(
3789: $this,
3790: $this->services->exprPrinter,
3791: $exprStringToInvalidate,
3792: $expressionToInvalidate,
3793: $requireMoreCharacters,
3794: $invalidatingClass,
3795: $this->expressionTypes,
3796: $this->nativeExpressionTypes,
3797: $this->conditionalExpressions,
3798: $keepPropertyFetches,
3799: );
3800: if ($result === null) {
3801: return $this;
3802: }
3803:
3804: /** @var static */
3805: return ScopeOps::scopeWith(
3806: $this,
3807: $result[0],
3808: $result[1],
3809: $result[2],
3810: $this->currentlyAssignedExpressions,
3811: $this->currentlyAllowedUndefinedExpressions,
3812: [],
3813: $this->inFirstLevelStatement,
3814: $this->afterExtractCall,
3815: );
3816: }
3817:
3818: /** @internal called by ScopeOps */
3819: public function isPrivatePropertyOfDifferentClass(Expr $expr, ClassReflection $invalidatingClass): bool
3820: {
3821: if ($expr instanceof Expr\StaticPropertyFetch || $expr instanceof PropertyFetch) {
3822: $propertyReflection = $this->services->propertyReflectionFinder->findPropertyReflectionFromNode($expr, $this);
3823: if ($propertyReflection === null) {
3824: return false;
3825: }
3826: if (!$propertyReflection->isPrivate()) {
3827: return false;
3828: }
3829: return $propertyReflection->getDeclaringClass()->getName() !== $invalidatingClass->getName();
3830: }
3831:
3832: return false;
3833: }
3834:
3835: private function invalidateMethodsOnExpression(Expr $expressionToInvalidate): self
3836: {
3837: $result = ScopeOps::invalidateMethodsOnExpression(
3838: $this->services->exprPrinter,
3839: $this->getNodeKey($expressionToInvalidate),
3840: $this->expressionTypes,
3841: $this->nativeExpressionTypes,
3842: );
3843: if ($result === null) {
3844: return $this;
3845: }
3846:
3847: /** @var static */
3848: return ScopeOps::scopeWith(
3849: $this,
3850: $result[0],
3851: $result[1],
3852: $this->conditionalExpressions,
3853: $this->currentlyAssignedExpressions,
3854: $this->currentlyAllowedUndefinedExpressions,
3855: [],
3856: $this->inFirstLevelStatement,
3857: $this->afterExtractCall,
3858: );
3859: }
3860:
3861: /**
3862: * Certainty change for applySpecifiedTypes():
3863: * it keeps the type already held for the expression instead of re-reading it
3864: * via getType(). getType() only reports the type of Yes-certainty holders, so
3865: * for a maybe-defined variable it broadens to the original type - which would
3866: * overwrite a co-applied narrowing (e.g. isset's $a -> null in the else branch).
3867: */
3868: private function setExpressionCertaintyKeepingType(Expr $expr, TrinaryLogic $certainty): self
3869: {
3870: $exprString = $this->getNodeKey($expr);
3871: if (!array_key_exists($exprString, $this->expressionTypes)) {
3872: throw new ShouldNotHappenException();
3873: }
3874:
3875: $exprType = $this->expressionTypes[$exprString]->getType();
3876: $nativeType = array_key_exists($exprString, $this->nativeExpressionTypes)
3877: ? $this->nativeExpressionTypes[$exprString]->getType()
3878: : $exprType;
3879:
3880: return $this->specifyExpressionType(
3881: $expr,
3882: $exprType,
3883: $nativeType,
3884: $certainty,
3885: );
3886: }
3887:
3888: /**
3889: * Returns true when the type is a large union with intersection
3890: * members that carry HasOffsetValueType — a sign of combinatorial
3891: * growth from successive array|object offset access patterns.
3892: * Operating on such types is expensive and should be skipped.
3893: */
3894: private function isComplexUnionType(Type $type): bool
3895: {
3896: if (!$type instanceof UnionType) {
3897: return false;
3898: }
3899: $types = $type->getTypes();
3900: if (count($types) <= self::COMPLEX_UNION_TYPE_MEMBER_LIMIT) {
3901: return false;
3902: }
3903: foreach ($types as $member) {
3904: if (!$member instanceof IntersectionType) {
3905: continue;
3906: }
3907: foreach ($member->getTypes() as $innerType) {
3908: if ($innerType instanceof HasOffsetValueType) {
3909: return true;
3910: }
3911: }
3912: }
3913: return false;
3914: }
3915:
3916: public function addTypeToExpression(Expr $expr, Type $type): self
3917: {
3918: $originalExprType = $this->getScopeStateType($expr);
3919: if ($this->isComplexUnionType($originalExprType)) {
3920: return $this;
3921: }
3922:
3923: $nativeType = $this->getScopeStateNativeType($expr);
3924:
3925: if ($originalExprType->equals($nativeType)) {
3926: $newType = TypeCombinator::intersect($type, $originalExprType);
3927: return $this->specifyExpressionType($expr, $newType, $newType, TrinaryLogic::createYes());
3928: }
3929:
3930: return $this->specifyExpressionType(
3931: $expr,
3932: TypeCombinator::intersect($type, $originalExprType),
3933: TypeCombinator::intersect($type, $nativeType),
3934: TrinaryLogic::createYes(),
3935: );
3936: }
3937:
3938: public function removeTypeFromExpression(Expr $expr, Type $typeToRemove): self
3939: {
3940: if ($typeToRemove instanceof NeverType) {
3941: return $this;
3942: }
3943:
3944: $exprType = $this->getScopeStateType($expr);
3945: if ($exprType instanceof NeverType) {
3946: return $this;
3947: }
3948:
3949: if ($this->isComplexUnionType($exprType)) {
3950: return $this;
3951: }
3952:
3953: return $this->specifyExpressionType(
3954: $expr,
3955: TypeCombinator::remove($exprType, $typeToRemove),
3956: TypeCombinator::remove($this->getScopeStateNativeType($expr), $typeToRemove),
3957: TrinaryLogic::createYes(),
3958: );
3959: }
3960:
3961: /**
3962: * @api
3963: */
3964: public function filterByTruthyValue(Expr $expr): self
3965: {
3966: $specifiedTypes = $this->services->typeSpecifier->specifyTypesInCondition($this, $expr, TypeSpecifierContext::createTruthy());
3967: if ($specifiedTypes->isEquality() && $this->getType($expr)->isBoolean()->yes()) {
3968: $specifiedTypes = $specifiedTypes->unionWith(
3969: $this->services->typeSpecifier->create($expr, new ConstantBooleanType(true), TypeSpecifierContext::createTrue(), $this),
3970: );
3971: }
3972:
3973: return $this->applySpecifiedTypes($specifiedTypes);
3974: }
3975:
3976: /**
3977: * @api
3978: */
3979: public function filterByFalseyValue(Expr $expr): self
3980: {
3981: $specifiedTypes = $this->services->typeSpecifier->specifyTypesInCondition($this, $expr, TypeSpecifierContext::createFalsey());
3982: if ($specifiedTypes->isEquality() && $this->getType($expr)->isBoolean()->yes()) {
3983: $specifiedTypes = $specifiedTypes->unionWith(
3984: $this->services->typeSpecifier->create($expr, new ConstantBooleanType(false), TypeSpecifierContext::createTrue(), $this),
3985: );
3986: }
3987:
3988: return $this->applySpecifiedTypes($specifiedTypes);
3989: }
3990:
3991: /**
3992: * Applies computed narrowing to this scope.
3993: *
3994: * The types inside SpecifiedTypes were already computed from ExpressionResults
3995: * by the specifyTypesCallback of an ExprHandler. This method must never call
3996: * Scope::getType() - it only combines the given types with already-tracked
3997: * expression type holders.
3998: *
3999: * @return static
4000: */
4001: public function applySpecifiedTypes(SpecifiedTypes $specifiedTypes): self
4002: {
4003: // deferred augments see this scope's pre-application state - the
4004: // application point of the narrowing; their entries join this batch
4005: $pendingAugments = $specifiedTypes->getDeferredAugments();
4006: while ($pendingAugments !== []) {
4007: $augment = array_shift($pendingAugments);
4008: $augmentTypes = $augment->evaluate($this);
4009: if ($augmentTypes === null) {
4010: continue;
4011: }
4012:
4013: foreach ($augmentTypes->getDeferredAugments() as $nestedAugment) {
4014: $pendingAugments[] = $nestedAugment;
4015: }
4016: $specifiedTypes = $specifiedTypes->unionWith($augmentTypes);
4017: }
4018:
4019: $typeSpecifications = [];
4020: foreach ($specifiedTypes->getSureTypes() as $exprString => [$expr, $type]) {
4021: if ($expr instanceof Node\Scalar || $expr instanceof Array_ || $expr instanceof Expr\UnaryMinus && $expr->expr instanceof Node\Scalar) {
4022: continue;
4023: }
4024: $typeSpecifications[] = [
4025: 'sure' => true,
4026: 'exprString' => (string) $exprString,
4027: 'expr' => $expr,
4028: 'type' => $type,
4029: ];
4030: }
4031: foreach ($specifiedTypes->getSureNotTypes() as $exprString => [$expr, $type]) {
4032: if ($expr instanceof Node\Scalar || $expr instanceof Array_ || $expr instanceof Expr\UnaryMinus && $expr->expr instanceof Node\Scalar) {
4033: continue;
4034: }
4035: $typeSpecifications[] = [
4036: 'sure' => false,
4037: 'exprString' => (string) $exprString,
4038: 'expr' => $expr,
4039: 'type' => $type,
4040: ];
4041: }
4042: foreach ($specifiedTypes->getAlternativeTypes() as $exprString => [$expr, $terms]) {
4043: if ($expr instanceof Node\Scalar || $expr instanceof Array_ || $expr instanceof Expr\UnaryMinus && $expr->expr instanceof Node\Scalar) {
4044: continue;
4045: }
4046: $typeSpecifications[] = [
4047: 'sure' => true,
4048: 'exprString' => (string) $exprString,
4049: 'expr' => $expr,
4050: 'terms' => $terms,
4051: ];
4052: }
4053:
4054: usort($typeSpecifications, static function (array $a, array $b): int {
4055: $length = strlen($a['exprString']) - strlen($b['exprString']);
4056: if ($length !== 0) {
4057: return $length;
4058: }
4059:
4060: return $b['sure'] - $a['sure']; // @phpstan-ignore minus.leftNonNumeric, minus.rightNonNumeric
4061: });
4062:
4063: $scope = $this;
4064: // one unpublished working copy takes all in-place specifications of the
4065: // batch; operations that go through other scope derivations publish it
4066: // and a fresh copy opens on the next specification
4067: $scopeIsWorkingCopy = false;
4068: $specifiedExpressions = [];
4069: foreach ($typeSpecifications as $typeSpecification) {
4070: $expr = $typeSpecification['expr'];
4071: $exprString = $typeSpecification['exprString'];
4072:
4073: if ($expr instanceof IssetExpr) {
4074: $issetExpr = $expr;
4075: $expr = $issetExpr->getExpr();
4076:
4077: if ($typeSpecification['sure']) {
4078: $scope = $scope->setExpressionCertaintyKeepingType(
4079: $expr,
4080: TrinaryLogic::createMaybe(),
4081: );
4082: } else {
4083: $scope = $scope->unsetExpression($expr);
4084: }
4085: $scopeIsWorkingCopy = false;
4086:
4087: continue;
4088: }
4089:
4090: if (
4091: !$typeSpecification['sure']
4092: && $expr instanceof Variable && is_string($expr->name)
4093: && $scope->hasVariableType($expr->name)->no()
4094: ) {
4095: // removing type from a certainly-undefined variable cannot make
4096: // it defined; a sure specification (e.g. is_string($a)) still can -
4097: // the condition can only hold for a defined variable
4098: continue;
4099: }
4100:
4101: // only Yes-certainty holders hold the current type of the expression -
4102: // a Maybe-certainty holder holds the when-defined type (e.g. after
4103: // merging a branch where the expression was never assigned), which
4104: // the certainty-aware Scope::getType() of the old world never returned
4105: $trackedType = null;
4106: $trackedNativeType = null;
4107: if (
4108: array_key_exists($exprString, $scope->expressionTypes)
4109: && $scope->expressionTypes[$exprString]->getCertainty()->yes()
4110: ) {
4111: $trackedType = $scope->expressionTypes[$exprString]->getType();
4112: }
4113: if (
4114: array_key_exists($exprString, $scope->nativeExpressionTypes)
4115: && $scope->nativeExpressionTypes[$exprString]->getCertainty()->yes()
4116: ) {
4117: $trackedNativeType = $scope->nativeExpressionTypes[$exprString]->getType();
4118: }
4119: if ($trackedType === null) {
4120: $currentTypes = $scope->getCurrentTypesOfSpecifiedExpr($expr);
4121: if ($currentTypes !== null) {
4122: if ($scope->isComplexUnionType($currentTypes[0])) {
4123: continue;
4124: }
4125:
4126: $trackedType = $currentTypes[0];
4127: $trackedNativeType ??= $currentTypes[1];
4128: }
4129: } elseif (!$specifiedTypes->shouldOverwrite() && $scope->isComplexUnionType($trackedType)) {
4130: // mirrors addTypeToExpression()/removeTypeFromExpression(): narrowing
4131: // a combinatorially-grown offset union doubles it with every isset()-
4132: // style check and gets skipped (overwrites assign, they never narrow)
4133: continue;
4134: }
4135:
4136: if (isset($typeSpecification['terms'])) {
4137: // an alternative-form entry: the union over its terms of
4138: // `(sure ?? current) minus subtract`, evaluated here at the
4139: // application point - the deferred descendant of the old
4140: // SpecifiedTypes::normalize()
4141: $evaluate = static function (?Type $current) use ($typeSpecification): ?Type {
4142: $parts = [];
4143: foreach ($typeSpecification['terms'] as [$sure, $subtract]) {
4144: $base = $sure ?? $current;
4145: if ($base === null) {
4146: return null;
4147: }
4148: $parts[] = $subtract !== null ? TypeCombinator::remove($base, $subtract) : $base;
4149: }
4150:
4151: return TypeCombinator::union(...$parts);
4152: };
4153: $evaluated = $evaluate($trackedType);
4154: if ($evaluated === null) {
4155: // a current-type-dependent term with no known current type -
4156: // nothing sound to specify (mirrors the sure-not behaviour)
4157: continue;
4158: }
4159: $evaluatedNative = $evaluate($trackedNativeType ?? $trackedType) ?? $evaluated;
4160:
4161: $newType = $trackedType !== null ? TypeCombinator::intersect($evaluated, $trackedType) : $evaluated;
4162: $newNativeType = $trackedNativeType !== null ? TypeCombinator::intersect($evaluatedNative, $trackedNativeType) : $evaluatedNative;
4163: if (!$this->isSpecifyExpressionTypeNoop($expr, $newType)) {
4164: if (!$scopeIsWorkingCopy) {
4165: $scope = $scope->openSpecificationScope();
4166: $scopeIsWorkingCopy = true;
4167: }
4168: $scope->specifyExpressionTypeInPlace($expr, $newType, $newNativeType, TrinaryLogic::createYes());
4169: }
4170:
4171: $holderType = array_key_exists($exprString, $scope->expressionTypes)
4172: ? $scope->expressionTypes[$exprString]->getType()
4173: : $newType;
4174: $specifiedExpressions[$exprString] = ExpressionTypeHolder::createYes($expr, $holderType);
4175: continue;
4176: }
4177:
4178: $type = $typeSpecification['type'];
4179: if ($typeSpecification['sure']) {
4180: if ($specifiedTypes->shouldOverwrite()) {
4181: $scope = $scope->overwriteExpression($expr, $type, $type);
4182: $scopeIsWorkingCopy = false;
4183: } else {
4184: $newType = $trackedType !== null ? TypeCombinator::intersect($type, $trackedType) : $type;
4185: $newNativeType = $trackedNativeType !== null ? TypeCombinator::intersect($type, $trackedNativeType) : $type;
4186: if (!$this->isSpecifyExpressionTypeNoop($expr, $newType)) {
4187: if (!$scopeIsWorkingCopy) {
4188: $scope = $scope->openSpecificationScope();
4189: $scopeIsWorkingCopy = true;
4190: }
4191: $scope->specifyExpressionTypeInPlace($expr, $newType, $newNativeType, TrinaryLogic::createYes());
4192: }
4193: }
4194: } else {
4195: if ($type instanceof NeverType || $trackedType instanceof NeverType) {
4196: continue;
4197: }
4198: $newType = $trackedType !== null ? TypeCombinator::remove($trackedType, $type) : null;
4199: if ($newType === null) {
4200: // the expression is not tracked - there is nothing to subtract from
4201: continue;
4202: }
4203: $newNativeType = $trackedNativeType !== null ? TypeCombinator::remove($trackedNativeType, $type) : $newType;
4204: if (!$this->isSpecifyExpressionTypeNoop($expr, $newType)) {
4205: if (!$scopeIsWorkingCopy) {
4206: $scope = $scope->openSpecificationScope();
4207: $scopeIsWorkingCopy = true;
4208: }
4209: $scope->specifyExpressionTypeInPlace($expr, $newType, $newNativeType, TrinaryLogic::createYes());
4210: }
4211: }
4212:
4213: $holderType = array_key_exists($exprString, $scope->expressionTypes)
4214: ? $scope->expressionTypes[$exprString]->getType()
4215: : $type;
4216: $specifiedExpressions[$exprString] = ExpressionTypeHolder::createYes($expr, $holderType);
4217: }
4218:
4219: $scope = $scope->processConditionalExpressionsAfterSpecifying($specifiedExpressions);
4220:
4221: $newConditionalExpressionHolders = $specifiedTypes->getNewConditionalExpressionHolders();
4222: foreach ($specifiedTypes->getConditionalExpressionHolderRecipes() as $recipe) {
4223: // the recipes' state-dependent math runs here, against this scope's
4224: // pre-application state - the application point of the narrowing
4225: foreach ($recipe->evaluate($this) as $exprString => $recipeHolders) {
4226: foreach ($recipeHolders as $key => $holder) {
4227: $newConditionalExpressionHolders[$exprString][$key] = $holder;
4228: }
4229: }
4230: }
4231:
4232: /** @var static */
4233: return $scope->scopeFactory->create(
4234: $scope->context,
4235: $scope->isDeclareStrictTypes(),
4236: $scope->getFunction(),
4237: $scope->getNamespace(),
4238: $scope->expressionTypes,
4239: $scope->nativeExpressionTypes,
4240: $this->mergeConditionalExpressions($newConditionalExpressionHolders, $scope->conditionalExpressions),
4241: $scope->inClosureBindScopeClasses,
4242: $scope->anonymousFunctionReflection,
4243: $scope->inFirstLevelStatement,
4244: $scope->currentlyAssignedExpressions,
4245: $scope->currentlyAllowedUndefinedExpressions,
4246: $scope->inFunctionCallsStack,
4247: $scope->afterExtractCall,
4248: $scope->parentScope,
4249: $scope->nativeTypesPromoted,
4250: $scope->templateArgumentFrame,
4251: $scope->templateArgumentConstraints,
4252: );
4253: }
4254:
4255: /**
4256: * Matches already-registered conditional expressions against the just-specified
4257: * expression type holders and applies the matching consequences.
4258: *
4259: * Mutates and returns $this - only to be called on an intermediate scope
4260: * that is about to be rebuilt through the scope factory.
4261: *
4262: * @param array<string, ExpressionTypeHolder> $specifiedExpressions
4263: */
4264: private function processConditionalExpressionsAfterSpecifying(array $specifiedExpressions): self
4265: {
4266: $scope = $this;
4267: [$conditions] = ScopeOps::matchConditionalExpressions($scope->conditionalExpressions, $specifiedExpressions);
4268:
4269: foreach ($conditions as $conditionalExprString => $expressions) {
4270: $certainty = TrinaryLogic::lazyExtremeIdentity($expressions, static fn (ConditionalExpressionHolder $holder) => $holder->getTypeHolder()->getCertainty());
4271: if ($certainty->no()) {
4272: unset($scope->expressionTypes[$conditionalExprString]);
4273: } else {
4274: if (array_key_exists($conditionalExprString, $scope->expressionTypes)) {
4275: $type = $expressions[0]->getTypeHolder()->getType();
4276: for ($i = 1, $count = count($expressions); $i < $count; $i++) {
4277: $type = TypeCombinator::intersect($type, $expressions[$i]->getTypeHolder()->getType());
4278: }
4279:
4280: $scope->expressionTypes[$conditionalExprString] = new ExpressionTypeHolder(
4281: $scope->expressionTypes[$conditionalExprString]->getExpr(),
4282: TypeCombinator::intersect($scope->expressionTypes[$conditionalExprString]->getType(), $type),
4283: TrinaryLogic::maxMin($scope->expressionTypes[$conditionalExprString]->getCertainty(), $certainty),
4284: );
4285: } else {
4286: $scope->expressionTypes[$conditionalExprString] = $expressions[0]->getTypeHolder();
4287: }
4288: }
4289: }
4290:
4291: return $scope;
4292: }
4293:
4294: /**
4295: * @return array<string, ConditionalExpressionHolder[]>
4296: */
4297: public function getConditionalExpressions(): array
4298: {
4299: return $this->conditionalExpressions;
4300: }
4301:
4302: /**
4303: * @param ConditionalExpressionHolder[] $conditionalExpressionHolders
4304: */
4305: public function addConditionalExpressions(string $exprString, array $conditionalExpressionHolders): self
4306: {
4307: $conditionalExpressions = $this->conditionalExpressions;
4308: // Merge rather than overwrite: multiple independent holders can target the same
4309: // expression (e.g. `$xIsA = $x instanceof A && $y instanceof A` stores a holder
4310: // for `$x` keyed on `$xIsA`; later `$yIsA = $y instanceof A && $x instanceof A`
4311: // stores another holder for the same target `$x` keyed on `$yIsA`). Replacing
4312: // the existing entry here would throw away the earlier binding, breaking
4313: // narrowing inside later `if ($xIsA) { … }` inside `if ($xIsA || $yIsA)`.
4314: // Holder keys (`getKey()`) disambiguate identical entries so we still dedupe.
4315: $existing = $conditionalExpressions[$exprString] ?? [];
4316: foreach ($conditionalExpressionHolders as $holder) {
4317: $existing[$holder->getKey()] = $holder;
4318: }
4319: $conditionalExpressions[$exprString] = $existing;
4320:
4321: /** @var static */
4322: return ScopeOps::scopeWith(
4323: $this,
4324: $this->expressionTypes,
4325: $this->nativeExpressionTypes,
4326: $conditionalExpressions,
4327: $this->currentlyAssignedExpressions,
4328: $this->currentlyAllowedUndefinedExpressions,
4329: $this->inFunctionCallsStack,
4330: $this->inFirstLevelStatement,
4331: $this->afterExtractCall,
4332: );
4333: }
4334:
4335: public function exitFirstLevelStatements(): self
4336: {
4337: if (!$this->inFirstLevelStatement) {
4338: return $this;
4339: }
4340:
4341: if ($this->scopeOutOfFirstLevelStatement !== null) {
4342: return $this->scopeOutOfFirstLevelStatement;
4343: }
4344:
4345: /** @var static $scope */
4346: $scope = ScopeOps::scopeWith(
4347: $this,
4348: $this->expressionTypes,
4349: $this->nativeExpressionTypes,
4350: $this->conditionalExpressions,
4351: $this->currentlyAssignedExpressions,
4352: $this->currentlyAllowedUndefinedExpressions,
4353: $this->inFunctionCallsStack,
4354: false,
4355: $this->afterExtractCall,
4356: );
4357: $scope->resolvedTypes = $this->resolvedTypes;
4358: $this->scopeOutOfFirstLevelStatement = $scope;
4359:
4360: return $scope;
4361: }
4362:
4363: /** @api */
4364: public function isInFirstLevelStatement(): bool
4365: {
4366: return $this->inFirstLevelStatement;
4367: }
4368:
4369: public function mergeWith(?self $otherScope, bool $preserveVacuousConditionals = false): self
4370: {
4371: if ($otherScope === null || $otherScope === $this) {
4372: return $this;
4373: }
4374:
4375: $merged = $this->mergeWithVariableState($otherScope, $preserveVacuousConditionals)->addTemplateArgumentConstraints($otherScope->getTemplateArgumentConstraints());
4376: if (
4377: $merged->templateArgumentConstraints === null
4378: || $merged->templateArgumentFrame === null
4379: || !$merged->templateArgumentFrame->isObservingClosures()
4380: ) {
4381: return $merged;
4382: }
4383:
4384: return $merged->addTemplateArgumentConstraints($merged->collectAbsorbedClosures($this, $otherScope));
4385: }
4386:
4387: /**
4388: * The closures a variable held on one side of a merge and the merged
4389: * variable lost - see ClosureSignatureInference::collectAbsorbed().
4390: */
4391: private function collectAbsorbedClosures(self $ours, self $theirs): ?TemplateArgumentConstraints
4392: {
4393: $constraints = null;
4394: foreach ($this->expressionTypes as $key => $holder) {
4395: foreach ([$ours->expressionTypes[$key] ?? null, $theirs->expressionTypes[$key] ?? null] as $sideHolder) {
4396: if ($sideHolder === null || $sideHolder === $holder || $sideHolder->getType() === $holder->getType()) {
4397: continue;
4398: }
4399: $absorbed = ClosureSignatureInference::collectAbsorbed($sideHolder->getType(), $holder->getType());
4400: if ($absorbed->isEmpty()) {
4401: continue;
4402: }
4403: $constraints = $constraints === null ? $absorbed : $constraints->merge($absorbed);
4404: }
4405: }
4406:
4407: return $constraints;
4408: }
4409:
4410: private function mergeWithVariableState(?self $otherScope, bool $preserveVacuousConditionals = false): self
4411: {
4412: if ($otherScope === null || $this === $otherScope) {
4413: return $this;
4414: }
4415: $ourExpressionTypes = $this->expressionTypes;
4416: $theirExpressionTypes = $otherScope->expressionTypes;
4417:
4418: $differingExpressionKeys = [];
4419: $mergedExpressionTypes = ScopeOps::mergeVariableHolders($ourExpressionTypes, $theirExpressionTypes, $differingExpressionKeys);
4420: $differingExpressionKeys = $this->withoutPreciseClassConstantFetches($differingExpressionKeys, $ourExpressionTypes, $theirExpressionTypes);
4421: $conditionalExpressions = ScopeOps::intersectConditionalExpressions($this->conditionalExpressions, $otherScope->conditionalExpressions);
4422: if ($preserveVacuousConditionals) {
4423: $conditionalExpressions = $this->preserveVacuousConditionalExpressions(
4424: $conditionalExpressions,
4425: $this->conditionalExpressions,
4426: $theirExpressionTypes,
4427: );
4428: $conditionalExpressions = $this->preserveVacuousConditionalExpressions(
4429: $conditionalExpressions,
4430: $otherScope->conditionalExpressions,
4431: $ourExpressionTypes,
4432: );
4433: }
4434: $conditionalExpressions = $this->mergeSameGuardConditionalExpressions(
4435: $conditionalExpressions,
4436: $this->conditionalExpressions,
4437: $otherScope->conditionalExpressions,
4438: );
4439: $conditionalExpressions = ScopeOps::createConditionalExpressions(
4440: $conditionalExpressions,
4441: $ourExpressionTypes,
4442: $theirExpressionTypes,
4443: $mergedExpressionTypes,
4444: $differingExpressionKeys,
4445: );
4446: $conditionalExpressions = ScopeOps::createConditionalExpressions(
4447: $conditionalExpressions,
4448: $theirExpressionTypes,
4449: $ourExpressionTypes,
4450: $mergedExpressionTypes,
4451: $differingExpressionKeys,
4452: );
4453:
4454: [$mergedExpressionTypes, $mergedNativeTypes] = ScopeOps::finishMerge(
4455: $mergedExpressionTypes,
4456: $ourExpressionTypes,
4457: $theirExpressionTypes,
4458: $this->nativeExpressionTypes,
4459: $otherScope->nativeExpressionTypes,
4460: );
4461:
4462: $afterExtractCall = $this->afterExtractCall && $otherScope->afterExtractCall;
4463:
4464: // Remembered calls whose type differs between the branches may merge into
4465: // exactly what the call resolves to on its own - e.g. count($a) of
4466: // int<3, max> and int<0, 2> merges into int<0, max>. Such an entry adds
4467: // nothing and would shadow what later narrowing of $a implies for the call,
4468: // so it is not written into the merged scope at all.
4469: $callCandidates = self::findMergedCallCandidates($differingExpressionKeys, $mergedExpressionTypes);
4470: $scope = ScopeOps::scopeWith(
4471: $this,
4472: $callCandidates === [] ? $mergedExpressionTypes : array_diff_key($mergedExpressionTypes, $callCandidates),
4473: $callCandidates === [] ? $mergedNativeTypes : array_diff_key($mergedNativeTypes, $callCandidates),
4474: $conditionalExpressions,
4475: [],
4476: [],
4477: [],
4478: $this->inFirstLevelStatement,
4479: $afterExtractCall,
4480: );
4481: if ($callCandidates === []) {
4482: /** @var static */
4483: return $scope;
4484: }
4485:
4486: $uninformativeKeys = $scope->findUninformativeMergedCalls($callCandidates, $mergedNativeTypes);
4487: if (count($uninformativeKeys) === count($callCandidates)) {
4488: /** @var static */
4489: return $scope;
4490: }
4491:
4492: /** @var static */
4493: return ScopeOps::scopeWith(
4494: $this,
4495: array_diff_key($mergedExpressionTypes, $uninformativeKeys),
4496: array_diff_key($mergedNativeTypes, $uninformativeKeys),
4497: $conditionalExpressions,
4498: [],
4499: [],
4500: [],
4501: $this->inFirstLevelStatement,
4502: $afterExtractCall,
4503: );
4504: }
4505:
4506: /**
4507: * Certain merged call expressions whose type differs between the merged branches.
4508: *
4509: * @param array<string, true> $differingExpressionKeys
4510: * @param array<string, ExpressionTypeHolder> $mergedExpressionTypes
4511: * @return array<string, ExpressionTypeHolder>
4512: */
4513: private static function findMergedCallCandidates(array $differingExpressionKeys, array $mergedExpressionTypes): array
4514: {
4515: $candidates = [];
4516: foreach (array_keys($differingExpressionKeys) as $exprString) {
4517: $holder = $mergedExpressionTypes[$exprString] ?? null;
4518: if ($holder === null || !$holder->getCertainty()->yes()) {
4519: continue;
4520: }
4521: $expr = $holder->getExpr();
4522: if (!$expr instanceof FuncCall && !$expr instanceof MethodCall && !$expr instanceof Expr\StaticCall) {
4523: continue;
4524: }
4525: if (!self::hasNarrowableArgument($expr)) {
4526: continue;
4527: }
4528: $candidates[$exprString] = $holder;
4529: }
4530:
4531: return $candidates;
4532: }
4533:
4534: /**
4535: * Whether the call has an argument that later narrowing can change - only then
4536: * can its remembered entry go stale. Any other call keeps its entry even when
4537: * it is uninformative: merging with a branch that lacks the entry would leave a
4538: * Maybe holder instead, which derives no conditional guards and is intersected
4539: * as if it held the call's type when a conditional expression narrows the call.
4540: */
4541: private static function hasNarrowableArgument(FuncCall|MethodCall|Expr\StaticCall $call): bool
4542: {
4543: foreach ($call->args as $arg) {
4544: if (!$arg instanceof Arg) {
4545: continue;
4546: }
4547: $value = $arg->value;
4548: if ($value instanceof Scalar && !$value instanceof Scalar\InterpolatedString) {
4549: continue;
4550: }
4551: if ($value instanceof ConstFetch) {
4552: continue;
4553: }
4554: if ($value instanceof ClassConstFetch && $value->class instanceof Name && $value->name instanceof Identifier) {
4555: continue;
4556: }
4557:
4558: return true;
4559: }
4560:
4561: return false;
4562: }
4563:
4564: /**
4565: * Called on the merged scope without the candidates: keys of candidates whose
4566: * merged type (and native type) is exactly what the call resolves to here.
4567: *
4568: * @param array<string, ExpressionTypeHolder> $candidates
4569: * @param array<string, ExpressionTypeHolder> $mergedNativeTypes
4570: * @return array<string, true>
4571: */
4572: private function findUninformativeMergedCalls(array $candidates, array $mergedNativeTypes): array
4573: {
4574: $uninformativeKeys = [];
4575: foreach ($candidates as $exprString => $holder) {
4576: if (isset(self::$resolvingMergedCalls[$exprString])) {
4577: continue;
4578: }
4579: $expr = $holder->getExpr();
4580: $nativeHolder = $mergedNativeTypes[$exprString] ?? null;
4581: self::$resolvingMergedCalls[$exprString] = true;
4582: try {
4583: $isUninformative = $holder->getType()->equals($this->getType($expr))
4584: && ($nativeHolder === null || $nativeHolder->getType()->equals($this->getNativeType($expr)));
4585: } finally {
4586: unset(self::$resolvingMergedCalls[$exprString]);
4587: }
4588: if (!$isUninformative) {
4589: continue;
4590: }
4591: $uninformativeKeys[$exprString] = true;
4592: }
4593:
4594: return $uninformativeKeys;
4595: }
4596:
4597: /**
4598: * Drops the keys of class-constant fetches that resolve to their declared value.
4599: *
4600: * A conditional expression records "when the guard holds, this expression had
4601: * that type in the branch the guard selects". Such a record can only ever pay
4602: * off when the expression resolves to something less precise on its own - and
4603: * a class-constant fetch with a statically known class resolves to the exact
4604: * declared value, unless the constant is configured as dynamic. So the record
4605: * is bookkeeping that can never narrow anything, and an expensive one: creating
4606: * it compares the guard against every member of the (potentially very wide)
4607: * merged guard type.
4608: *
4609: * @param array<string, true> $differingExpressionKeys
4610: * @param array<string, ExpressionTypeHolder> $ourExpressionTypes
4611: * @param array<string, ExpressionTypeHolder> $theirExpressionTypes
4612: * @return array<string, true>
4613: */
4614: private function withoutPreciseClassConstantFetches(
4615: array $differingExpressionKeys,
4616: array $ourExpressionTypes,
4617: array $theirExpressionTypes,
4618: ): array
4619: {
4620: foreach (array_keys($differingExpressionKeys) as $exprString) {
4621: $holder = $ourExpressionTypes[$exprString] ?? $theirExpressionTypes[$exprString] ?? null;
4622: if ($holder === null) {
4623: continue;
4624: }
4625:
4626: $expr = $holder->getExpr();
4627: if (
4628: !$expr instanceof ClassConstFetch
4629: || !$expr->class instanceof Name
4630: || !$expr->name instanceof Identifier
4631: ) {
4632: continue;
4633: }
4634:
4635: // static::CONST is late-bound, so which class - and therefore which
4636: // declared value - it resolves to is not known here.
4637: if ($expr->class->toLowerString() === 'static') {
4638: continue;
4639: }
4640:
4641: if ($this->services->constantResolver->isDynamicClassConstant($this->resolveName($expr->class), $expr->name->toString())) {
4642: continue;
4643: }
4644:
4645: unset($differingExpressionKeys[$exprString]);
4646: }
4647:
4648: return $differingExpressionKeys;
4649: }
4650:
4651: /**
4652: * Rescues one-sided conditional holders across an if-merge.
4653: *
4654: * A holder missing from the intersection survives when either some guard's
4655: * recorded type is impossible in the other branch (the holder is vacuously
4656: * true there), or the other branch's flat state for the holder's target
4657: * already satisfies the holder's consequent (subtype with at-least-as-strong
4658: * certainty) - the consequent then holds on both paths under the guard.
4659: *
4660: * @param array<string, ConditionalExpressionHolder[]> $currentConditionalExpressions
4661: * @param array<string, ConditionalExpressionHolder[]> $sourceConditionalExpressions
4662: * @param array<string, ExpressionTypeHolder> $otherExpressionTypes
4663: * @return array<string, ConditionalExpressionHolder[]>
4664: */
4665: private function preserveVacuousConditionalExpressions(
4666: array $currentConditionalExpressions,
4667: array $sourceConditionalExpressions,
4668: array $otherExpressionTypes,
4669: ): array
4670: {
4671: foreach ($sourceConditionalExpressions as $exprString => $holders) {
4672: foreach ($holders as $key => $holder) {
4673: if (isset($currentConditionalExpressions[$exprString][$key])) {
4674: continue;
4675: }
4676:
4677: $typeHolder = $holder->getTypeHolder();
4678: if ($typeHolder->getCertainty()->no() && !$typeHolder->getExpr() instanceof Variable) {
4679: continue;
4680: }
4681:
4682: foreach ($holder->getConditionExpressionTypeHolders() as $guardExprString => $guardTypeHolder) {
4683: if (!array_key_exists($guardExprString, $otherExpressionTypes)) {
4684: continue;
4685: }
4686:
4687: $otherType = $otherExpressionTypes[$guardExprString]->getType();
4688: $guardType = $guardTypeHolder->getType();
4689:
4690: if ($otherType->isSuperTypeOf($guardType)->no()) {
4691: $currentConditionalExpressions[$exprString][$key] = $holder;
4692: continue 2;
4693: }
4694: }
4695:
4696: if ($typeHolder->getCertainty()->no() || !array_key_exists($exprString, $otherExpressionTypes)) {
4697: continue;
4698: }
4699:
4700: $otherTargetHolder = $otherExpressionTypes[$exprString];
4701: $otherTargetCertainty = $otherTargetHolder->getCertainty();
4702: if (!$otherTargetCertainty->yes() && !$otherTargetCertainty->equals($typeHolder->getCertainty())) {
4703: continue;
4704: }
4705:
4706: // An unresolved expression (e.g. an access to an undefined property) is held
4707: // as ErrorType. ErrorType is a subtype of everything, so a consequent or an
4708: // other-branch state of ErrorType would look "already satisfied" and preserve
4709: // a holder that tracks the expression and hides the underlying error. Such a
4710: // holder carries no real type relationship, so skip it.
4711: if ($typeHolder->getType() instanceof ErrorType || $otherTargetHolder->getType() instanceof ErrorType) {
4712: continue;
4713: }
4714:
4715: if (!$typeHolder->getType()->isSuperTypeOf($otherTargetHolder->getType())->yes()) {
4716: continue;
4717: }
4718:
4719: // Array shapes are unsealed in isSuperTypeOf(): array{a?: int} is a supertype
4720: // of array{a?: int, b: int}, yet applying the holder would drop the 'b' key
4721: // the other branch tracks. The consequent only holds on both paths when the
4722: // other branch's state adds nothing to it.
4723: if (!TypeCombinator::union($typeHolder->getType(), $otherTargetHolder->getType())->equals($typeHolder->getType())) {
4724: continue;
4725: }
4726:
4727: $currentConditionalExpressions[$exprString][$key] = $holder;
4728: }
4729: }
4730:
4731: return $currentConditionalExpressions;
4732: }
4733:
4734: /**
4735: * Merges one-sided holders that share a target and an identical guard set:
4736: * whichever branch a merged path came from, the guard matching later implies
4737: * one of the recorded consequents, so the union of the consequent types
4738: * (under their shared certainty) holds on every merged path.
4739: *
4740: * @param array<string, ConditionalExpressionHolder[]> $currentConditionalExpressions
4741: * @param array<string, ConditionalExpressionHolder[]> $ourConditionalExpressions
4742: * @param array<string, ConditionalExpressionHolder[]> $theirConditionalExpressions
4743: * @return array<string, ConditionalExpressionHolder[]>
4744: */
4745: private function mergeSameGuardConditionalExpressions(
4746: array $currentConditionalExpressions,
4747: array $ourConditionalExpressions,
4748: array $theirConditionalExpressions,
4749: ): array
4750: {
4751: foreach ($ourConditionalExpressions as $exprString => $ourHolders) {
4752: if (!array_key_exists($exprString, $theirConditionalExpressions)) {
4753: continue;
4754: }
4755:
4756: $theirHolders = $theirConditionalExpressions[$exprString];
4757: foreach ($ourHolders as $ourKey => $ourHolder) {
4758: if (isset($currentConditionalExpressions[$exprString][$ourKey])) {
4759: continue;
4760: }
4761:
4762: $ourTypeHolder = $ourHolder->getTypeHolder();
4763: if ($ourTypeHolder->getCertainty()->no()) {
4764: continue;
4765: }
4766:
4767: foreach ($theirHolders as $theirKey => $theirHolder) {
4768: if (isset($currentConditionalExpressions[$exprString][$theirKey])) {
4769: continue;
4770: }
4771:
4772: $theirTypeHolder = $theirHolder->getTypeHolder();
4773: if (!$theirTypeHolder->getCertainty()->equals($ourTypeHolder->getCertainty())) {
4774: continue;
4775: }
4776:
4777: $ourGuards = $ourHolder->getConditionExpressionTypeHolders();
4778: $theirGuards = $theirHolder->getConditionExpressionTypeHolders();
4779: if (count($ourGuards) !== count($theirGuards)) {
4780: continue;
4781: }
4782:
4783: foreach ($ourGuards as $guardExprString => $ourGuardHolder) {
4784: if (
4785: !array_key_exists($guardExprString, $theirGuards)
4786: || !$ourGuardHolder->equals($theirGuards[$guardExprString])
4787: ) {
4788: continue 2;
4789: }
4790: }
4791:
4792: $unionHolder = new ConditionalExpressionHolder(
4793: $ourGuards,
4794: new ExpressionTypeHolder(
4795: $ourTypeHolder->getExpr(),
4796: TypeCombinator::union($ourTypeHolder->getType(), $theirTypeHolder->getType()),
4797: $ourTypeHolder->getCertainty(),
4798: ),
4799: );
4800: $currentConditionalExpressions[$exprString][$unionHolder->getKey()] = $unionHolder;
4801: }
4802: }
4803: }
4804:
4805: return $currentConditionalExpressions;
4806: }
4807:
4808: /**
4809: * @param array<string, ConditionalExpressionHolder[]> $newConditionalExpressions
4810: * @param array<string, ConditionalExpressionHolder[]> $existingConditionalExpressions
4811: * @return array<string, ConditionalExpressionHolder[]>
4812: */
4813: private function mergeConditionalExpressions(array $newConditionalExpressions, array $existingConditionalExpressions): array
4814: {
4815: $result = $existingConditionalExpressions;
4816: foreach ($newConditionalExpressions as $exprString => $holders) {
4817: if (!array_key_exists($exprString, $result)) {
4818: $result[$exprString] = $holders;
4819: } else {
4820: $result[$exprString] = array_merge($result[$exprString], $holders);
4821: }
4822: }
4823:
4824: return $result;
4825: }
4826:
4827: public function mergeInitializedProperties(self $calledMethodScope): self
4828: {
4829: $scope = $this;
4830: foreach ($calledMethodScope->expressionTypes as $exprString => $typeHolder) {
4831: $exprString = (string) $exprString;
4832: if (!str_starts_with($exprString, '__phpstanPropertyInitialization(')) {
4833: continue;
4834: }
4835: $propertyName = substr($exprString, strlen('__phpstanPropertyInitialization('), -1);
4836: $propertyExpr = new PropertyInitializationExpr($propertyName);
4837: if (!array_key_exists($exprString, $scope->expressionTypes)) {
4838: $scope = $scope->assignExpression($propertyExpr, new MixedType(), new MixedType());
4839: $scope->expressionTypes[$exprString] = $typeHolder;
4840: continue;
4841: }
4842:
4843: $certainty = $scope->expressionTypes[$exprString]->getCertainty();
4844: $scope = $scope->assignExpression($propertyExpr, new MixedType(), new MixedType());
4845: $scope->expressionTypes[$exprString] = new ExpressionTypeHolder(
4846: $typeHolder->getExpr(),
4847: $typeHolder->getType(),
4848: $typeHolder->getCertainty()->or($certainty),
4849: );
4850: }
4851:
4852: return $scope;
4853: }
4854:
4855: public function processFinallyScope(self $finallyScope, self $originalFinallyScope): self
4856: {
4857: return $this->scopeFactory->create(
4858: $this->context,
4859: $this->isDeclareStrictTypes(),
4860: $this->getFunction(),
4861: $this->getNamespace(),
4862: $this->processFinallyScopeVariableTypeHolders(
4863: $this->expressionTypes,
4864: $finallyScope->expressionTypes,
4865: $originalFinallyScope->expressionTypes,
4866: ),
4867: $this->processFinallyScopeVariableTypeHolders(
4868: $this->nativeExpressionTypes,
4869: $finallyScope->nativeExpressionTypes,
4870: $originalFinallyScope->nativeExpressionTypes,
4871: ),
4872: ScopeOps::intersectConditionalExpressions($this->conditionalExpressions, $finallyScope->conditionalExpressions),
4873: $this->inClosureBindScopeClasses,
4874: $this->anonymousFunctionReflection,
4875: $this->inFirstLevelStatement,
4876: [],
4877: [],
4878: [],
4879: $this->afterExtractCall,
4880: $this->parentScope,
4881: $this->nativeTypesPromoted,
4882: $this->templateArgumentFrame,
4883: $this->templateArgumentConstraints,
4884: );
4885: }
4886:
4887: /**
4888: * @param array<string, ExpressionTypeHolder> $ourVariableTypeHolders
4889: * @param array<string, ExpressionTypeHolder> $finallyVariableTypeHolders
4890: * @param array<string, ExpressionTypeHolder> $originalVariableTypeHolders
4891: * @return array<string, ExpressionTypeHolder>
4892: */
4893: private function processFinallyScopeVariableTypeHolders(
4894: array $ourVariableTypeHolders,
4895: array $finallyVariableTypeHolders,
4896: array $originalVariableTypeHolders,
4897: ): array
4898: {
4899: foreach ($finallyVariableTypeHolders as $exprString => $variableTypeHolder) {
4900: if (
4901: isset($originalVariableTypeHolders[$exprString])
4902: && !$originalVariableTypeHolders[$exprString]->equalTypes($variableTypeHolder)
4903: ) {
4904: $ourVariableTypeHolders[$exprString] = $variableTypeHolder;
4905: continue;
4906: }
4907:
4908: if (isset($originalVariableTypeHolders[$exprString])) {
4909: continue;
4910: }
4911:
4912: $ourVariableTypeHolders[$exprString] = $variableTypeHolder;
4913: }
4914:
4915: return $ourVariableTypeHolders;
4916: }
4917:
4918: /**
4919: * @param Node\ClosureUse[] $byRefUses
4920: */
4921: public function processClosureScope(
4922: self $closureScope,
4923: ?self $prevScope,
4924: array $byRefUses,
4925: ): self
4926: {
4927: $nativeExpressionTypes = $this->nativeExpressionTypes;
4928: $expressionTypes = $this->expressionTypes;
4929: if (count($byRefUses) === 0) {
4930: return $this;
4931: }
4932:
4933: foreach ($byRefUses as $use) {
4934: if (!is_string($use->var->name)) {
4935: throw new ShouldNotHappenException();
4936: }
4937:
4938: $variableName = $use->var->name;
4939: $variableExprString = '$' . $variableName;
4940:
4941: if (!$closureScope->hasVariableType($variableName)->yes()) {
4942: $holder = ExpressionTypeHolder::createYes($use->var, new NullType());
4943: $expressionTypes[$variableExprString] = $holder;
4944: $nativeExpressionTypes[$variableExprString] = $holder;
4945: continue;
4946: }
4947:
4948: $variableType = $closureScope->getVariableType($variableName);
4949:
4950: if ($prevScope !== null) {
4951: $prevVariableType = $prevScope->getVariableType($variableName);
4952: if (!$variableType->equals($prevVariableType)) {
4953: $variableType = TypeCombinator::union($variableType, $prevVariableType);
4954: $variableType = $this->generalizeType($variableType, $prevVariableType, 0);
4955: }
4956: }
4957:
4958: $holder = ExpressionTypeHolder::createYes($use->var, $variableType);
4959: $expressionTypes[$variableExprString] = $holder;
4960: $nativeExpressionTypes[$variableExprString] = $holder;
4961: }
4962:
4963: return $this->scopeFactory->create(
4964: $this->context,
4965: $this->isDeclareStrictTypes(),
4966: $this->getFunction(),
4967: $this->getNamespace(),
4968: $expressionTypes,
4969: $nativeExpressionTypes,
4970: $this->conditionalExpressions,
4971: $this->inClosureBindScopeClasses,
4972: $this->anonymousFunctionReflection,
4973: $this->inFirstLevelStatement,
4974: [],
4975: [],
4976: $this->inFunctionCallsStack,
4977: $this->afterExtractCall,
4978: $this->parentScope,
4979: $this->nativeTypesPromoted,
4980: $this->templateArgumentFrame,
4981: $this->templateArgumentConstraints,
4982: );
4983: }
4984:
4985: public function processAlwaysIterableForeachScopeWithoutPollute(self $finalScope): self
4986: {
4987: $expressionTypes = $this->expressionTypes;
4988: foreach ($finalScope->expressionTypes as $variableExprString => $variableTypeHolder) {
4989: if (!isset($expressionTypes[$variableExprString])) {
4990: $expressionTypes[$variableExprString] = ExpressionTypeHolder::createMaybe($variableTypeHolder->getExpr(), $variableTypeHolder->getType());
4991: continue;
4992: }
4993:
4994: $expressionTypes[$variableExprString] = new ExpressionTypeHolder(
4995: $variableTypeHolder->getExpr(),
4996: $variableTypeHolder->getType(),
4997: $variableTypeHolder->getCertainty()->and($expressionTypes[$variableExprString]->getCertainty()),
4998: );
4999: }
5000: $nativeTypes = $this->nativeExpressionTypes;
5001: foreach ($finalScope->nativeExpressionTypes as $variableExprString => $variableTypeHolder) {
5002: if (!isset($nativeTypes[$variableExprString])) {
5003: $nativeTypes[$variableExprString] = ExpressionTypeHolder::createMaybe($variableTypeHolder->getExpr(), $variableTypeHolder->getType());
5004: continue;
5005: }
5006:
5007: $nativeTypes[$variableExprString] = new ExpressionTypeHolder(
5008: $variableTypeHolder->getExpr(),
5009: $variableTypeHolder->getType(),
5010: $variableTypeHolder->getCertainty()->and($nativeTypes[$variableExprString]->getCertainty()),
5011: );
5012: }
5013:
5014: return $this->scopeFactory->create(
5015: $this->context,
5016: $this->isDeclareStrictTypes(),
5017: $this->getFunction(),
5018: $this->getNamespace(),
5019: $expressionTypes,
5020: $nativeTypes,
5021: ScopeOps::intersectConditionalExpressions($this->conditionalExpressions, $finalScope->conditionalExpressions),
5022: $this->inClosureBindScopeClasses,
5023: $this->anonymousFunctionReflection,
5024: $this->inFirstLevelStatement,
5025: [],
5026: [],
5027: [],
5028: $this->afterExtractCall,
5029: $this->parentScope,
5030: $this->nativeTypesPromoted,
5031: $this->templateArgumentFrame,
5032: $this->templateArgumentConstraints,
5033: );
5034: }
5035:
5036: /**
5037: * @param array<string, true>|null $writableVariableNames variables the loop can write, null when unknown
5038: */
5039: public function generalizeWith(self $otherScope, ?array $writableVariableNames = null): self
5040: {
5041: return $this->generalizeWithVariableState($otherScope, $writableVariableNames)->addTemplateArgumentConstraints($otherScope->getTemplateArgumentConstraints());
5042: }
5043:
5044: /**
5045: * @param array<string, true>|null $writableVariableNames
5046: */
5047: private function generalizeWithVariableState(self $otherScope, ?array $writableVariableNames): self
5048: {
5049: if ($writableVariableNames !== null) {
5050: // a reference created before the loop lets the loop write a variable it does not name
5051: foreach ([$this->expressionTypes, $otherScope->expressionTypes] as $expressionTypes) {
5052: foreach ($expressionTypes as $expressionTypeHolder) {
5053: $intertwinedExpr = $expressionTypeHolder->getExpr();
5054: if (!$intertwinedExpr instanceof IntertwinedVariableByReferenceWithExpr) {
5055: continue;
5056: }
5057: $writableVariableNames[$intertwinedExpr->getVariableName()] = true;
5058: foreach ([$intertwinedExpr->getExpr(), $intertwinedExpr->getAssignedExpr()] as $aliasedExpr) {
5059: $aliasedVariableName = ScopeOps::getIntertwinedRefRootVariableName($aliasedExpr);
5060: if ($aliasedVariableName === null) {
5061: continue;
5062: }
5063: $writableVariableNames[$aliasedVariableName] = true;
5064: }
5065: }
5066: }
5067: }
5068: $variableTypeHolders = $this->generalizeVariableTypeHolders(
5069: $this->expressionTypes,
5070: $otherScope->expressionTypes,
5071: $writableVariableNames,
5072: );
5073: $nativeTypes = $this->generalizeVariableTypeHolders(
5074: $this->nativeExpressionTypes,
5075: $otherScope->nativeExpressionTypes,
5076: $writableVariableNames,
5077: );
5078:
5079: return $this->scopeFactory->create(
5080: $this->context,
5081: $this->isDeclareStrictTypes(),
5082: $this->getFunction(),
5083: $this->getNamespace(),
5084: $variableTypeHolders,
5085: $nativeTypes,
5086: $this->conditionalExpressions,
5087: $this->inClosureBindScopeClasses,
5088: $this->anonymousFunctionReflection,
5089: $this->inFirstLevelStatement,
5090: [],
5091: [],
5092: [],
5093: $this->afterExtractCall,
5094: $this->parentScope,
5095: $this->nativeTypesPromoted,
5096: $this->templateArgumentFrame,
5097: $this->templateArgumentConstraints,
5098: );
5099: }
5100:
5101: /**
5102: * @param array<string, ExpressionTypeHolder> $variableTypeHolders
5103: * @param array<string, ExpressionTypeHolder> $otherVariableTypeHolders
5104: * @param array<string, true>|null $writableVariableNames
5105: * @return array<string, ExpressionTypeHolder>
5106: */
5107: private function generalizeVariableTypeHolders(
5108: array $variableTypeHolders,
5109: array $otherVariableTypeHolders,
5110: ?array $writableVariableNames,
5111: ): array
5112: {
5113: uksort($variableTypeHolders, static fn (string $exprA, string $exprB): int => strlen($exprA) <=> strlen($exprB));
5114:
5115: $generalizedExpressions = [];
5116: $newVariableTypeHolders = [];
5117: foreach ($variableTypeHolders as $variableExprString => $variableTypeHolder) {
5118: foreach ($generalizedExpressions as $generalizedExprString => $generalizedExpr) {
5119: if (!ScopeOps::shouldInvalidateExpression($this, $this->services->exprPrinter, $generalizedExprString, $generalizedExpr, $variableTypeHolder->getExpr(), $variableExprString)) {
5120: continue;
5121: }
5122:
5123: continue 2;
5124: }
5125: if (!isset($otherVariableTypeHolders[$variableExprString])) {
5126: $newVariableTypeHolders[$variableExprString] = $variableTypeHolder;
5127: continue;
5128: }
5129:
5130: $variableExpr = $variableTypeHolder->getExpr();
5131: if (
5132: $writableVariableNames !== null
5133: && $variableExpr instanceof Variable
5134: && is_string($variableExpr->name)
5135: && !isset($writableVariableNames[$variableExpr->name])
5136: ) {
5137: // the loop does not write this variable, its types differ between passes only by narrowing
5138: $generalizedType = TypeCombinator::union($variableTypeHolder->getType(), $otherVariableTypeHolders[$variableExprString]->getType());
5139: } else {
5140: $generalizedType = $this->generalizeType($variableTypeHolder->getType(), $otherVariableTypeHolders[$variableExprString]->getType(), 0);
5141: }
5142: if (
5143: !$generalizedType->equals($variableTypeHolder->getType())
5144: ) {
5145: $generalizedExpressions[$variableExprString] = $variableTypeHolder->getExpr();
5146: }
5147: $newVariableTypeHolders[$variableExprString] = new ExpressionTypeHolder(
5148: $variableTypeHolder->getExpr(),
5149: $generalizedType,
5150: $variableTypeHolder->getCertainty(),
5151: );
5152: }
5153:
5154: return $newVariableTypeHolders;
5155: }
5156:
5157: /**
5158: * TypeUtils::flattenTypes() expands a shape with optional keys into every
5159: * concrete variant (2^N of them, four lossy representatives above ten),
5160: * only for the union below to merge them back into the very same shape -
5161: * quadratic in the number of variants. The per-key widening reads the
5162: * shape's keys, values and optionality directly, so only unions are split.
5163: *
5164: * @return list<Type>
5165: */
5166: private function flattenUnionForGeneralization(Type $type): array
5167: {
5168: if (!$type instanceof UnionType) {
5169: return [$type];
5170: }
5171:
5172: $types = [];
5173: foreach ($type->getTypes() as $innerType) {
5174: foreach ($this->flattenUnionForGeneralization($innerType) as $flattenedType) {
5175: $types[] = $flattenedType;
5176: }
5177: }
5178:
5179: return $types;
5180: }
5181:
5182: private function generalizeType(Type $a, Type $b, int $depth): Type
5183: {
5184: if ($a->equals($b)) {
5185: return $a;
5186: }
5187:
5188: // Track whether either input carries a BenevolentUnion so the result
5189: // can be re-wrapped at the end. `flattenTypes` below drops the
5190: // BenevolentUnion wrapper, which would silently downgrade e.g.
5191: // `(float|int)` (numeric-accepting) to a strict `float|int`. Inside a
5192: // loop's fixed-point this propagates into the iterable value type of
5193: // an array and turns `return [..., $int]` checks into false positives
5194: // when the iteration body's `+ 1` arithmetic was originally produced
5195: // by an `ErrorType`-derived `int|float` benevolent union (the typical
5196: // case for reads of literally-missing keys inside the body).
5197: $wrapBenevolent = $a instanceof BenevolentUnionType || $b instanceof BenevolentUnionType;
5198:
5199: $constantIntegers = ['a' => [], 'b' => []];
5200: $constantFloats = ['a' => [], 'b' => []];
5201: $constantBooleans = ['a' => [], 'b' => []];
5202: $constantStrings = ['a' => [], 'b' => []];
5203: $constantArrays = ['a' => [], 'b' => []];
5204: $generalArrays = ['a' => [], 'b' => []];
5205: $integerRanges = ['a' => [], 'b' => []];
5206: $otherTypes = [];
5207:
5208: foreach ([
5209: 'a' => $this->flattenUnionForGeneralization($a),
5210: 'b' => $this->flattenUnionForGeneralization($b),
5211: ] as $key => $types) {
5212: foreach ($types as $type) {
5213: if ($type instanceof ConstantIntegerType) {
5214: $constantIntegers[$key][] = $type;
5215: continue;
5216: }
5217: if ($type instanceof ConstantFloatType) {
5218: $constantFloats[$key][] = $type;
5219: continue;
5220: }
5221: if ($type instanceof ConstantBooleanType) {
5222: $constantBooleans[$key][] = $type;
5223: continue;
5224: }
5225: if ($type instanceof ConstantStringType) {
5226: $constantStrings[$key][] = $type;
5227: continue;
5228: }
5229: if ($type->isConstantArray()->yes()) {
5230: $constantArrays[$key][] = $type;
5231: continue;
5232: }
5233: if ($type->isArray()->yes()) {
5234: $generalArrays[$key][] = $type;
5235: continue;
5236: }
5237: if ($type instanceof IntegerRangeType) {
5238: $integerRanges[$key][] = $type;
5239: continue;
5240: }
5241:
5242: $otherTypes[] = $type;
5243: }
5244: }
5245:
5246: $resultTypes = [];
5247: foreach ([
5248: $constantFloats,
5249: $constantBooleans,
5250: $constantStrings,
5251: ] as $constantTypes) {
5252: if (count($constantTypes['a']) === 0) {
5253: if (count($constantTypes['b']) > 0) {
5254: $resultTypes[] = TypeCombinator::union(...$constantTypes['b']);
5255: }
5256: continue;
5257: } elseif (count($constantTypes['b']) === 0) {
5258: $resultTypes[] = TypeCombinator::union(...$constantTypes['a']);
5259: continue;
5260: }
5261:
5262: $aTypes = TypeCombinator::union(...$constantTypes['a']);
5263: $bTypes = TypeCombinator::union(...$constantTypes['b']);
5264: if ($aTypes->equals($bTypes)) {
5265: $resultTypes[] = $aTypes;
5266: continue;
5267: }
5268:
5269: $resultTypes[] = TypeCombinator::union(...$constantTypes['a'], ...$constantTypes['b'])->generalize(GeneralizePrecision::moreSpecific());
5270: }
5271:
5272: if (count($constantArrays['a']) > 0) {
5273: if (count($constantArrays['b']) === 0) {
5274: $resultTypes[] = TypeCombinator::union(...$constantArrays['a']);
5275: } else {
5276: $constantArraysA = TypeCombinator::union(...$constantArrays['a']);
5277: $constantArraysB = TypeCombinator::union(...$constantArrays['b']);
5278: if (
5279: $constantArraysA->getIterableKeyType()->equals($constantArraysB->getIterableKeyType())
5280: && $constantArraysA->getArraySize()->getGreaterOrEqualType($this->services->phpVersion)->isSuperTypeOf($constantArraysB->getArraySize())->yes()
5281: ) {
5282: $resultArrayBuilder = ConstantArrayTypeBuilder::createEmpty();
5283: foreach (TypeUtils::flattenTypes($constantArraysA->getIterableKeyType()) as $keyType) {
5284: $resultArrayBuilder->setOffsetValueType(
5285: $keyType,
5286: $this->generalizeType(
5287: $constantArraysA->getOffsetValueType($keyType),
5288: $constantArraysB->getOffsetValueType($keyType),
5289: $depth + 1,
5290: ),
5291: !$constantArraysA->hasOffsetValueType($keyType)->and($constantArraysB->hasOffsetValueType($keyType))->negate()->no(),
5292: );
5293: }
5294:
5295: $resultTypes[] = $resultArrayBuilder->getArray();
5296: } else {
5297: // Neither input has unsealed extra keys, so their key sets
5298: // are finite — the constant keys of the shapes. That holds
5299: // for sealed shapes as well as for shapes of unknown
5300: // sealedness (the only kind without bleeding edge). The
5301: // latter report `isUnsealed()` as maybe and are deliberately
5302: // let through: they carry no extra key type, so only
5303: // `isUnsealed()->yes()` (an explicit `...<K, V>`) bails. On the
5304: // fall-through ArrayType path, recursing into
5305: // `generalizeType` would widen e.g. `0|1` to `int<0, max>`
5306: // — for both the keys and the values — losing the loop's
5307: // per-iteration precision. Keep the literal union instead
5308: // so the loop's bounds stay visible.
5309: $noneUnsealed = true;
5310: foreach ([...$constantArrays['a'], ...$constantArrays['b']] as $constantArrayCheck) {
5311: foreach ($constantArrayCheck->getConstantArrays() as $constantArrayInstance) {
5312: if ($constantArrayInstance->isUnsealed()->yes()) {
5313: $noneUnsealed = false;
5314: break 2;
5315: }
5316: }
5317: }
5318: if ($noneUnsealed) {
5319: $resultKeyType = TypeCombinator::union($constantArraysA->getIterableKeyType(), $constantArraysB->getIterableKeyType());
5320: $resultValueType = TypeCombinator::union($constantArraysA->getIterableValueType(), $constantArraysB->getIterableValueType());
5321: if ($resultValueType->isOversizedArray()->yes()) {
5322: // The literal value union outgrew the shape limit (a
5323: // deeply/widely nested value): fall back to generalizing
5324: // it into a bounded range-keyed array rather than
5325: // keeping an oversized literal shape.
5326: $resultValueType = TypeCombinator::union($this->generalizeType($constantArraysA->getIterableValueType(), $constantArraysB->getIterableValueType(), $depth + 1));
5327: }
5328: } else {
5329: $resultKeyType = TypeCombinator::union($this->generalizeType($constantArraysA->getIterableKeyType(), $constantArraysB->getIterableKeyType(), $depth + 1));
5330: $resultValueType = TypeCombinator::union($this->generalizeType($constantArraysA->getIterableValueType(), $constantArraysB->getIterableValueType(), $depth + 1));
5331: }
5332: $resultType = new ArrayType(
5333: $resultKeyType,
5334: $resultValueType,
5335: );
5336: $accessories = [];
5337: if (
5338: $constantArraysA->isIterableAtLeastOnce()->yes()
5339: && $constantArraysB->isIterableAtLeastOnce()->yes()
5340: && $constantArraysA->getArraySize()->getGreaterOrEqualType($this->services->phpVersion)->isSuperTypeOf($constantArraysB->getArraySize())->yes()
5341: ) {
5342: $accessories[] = new NonEmptyArrayType();
5343: }
5344: if ($constantArraysA->isList()->yes() && $constantArraysB->isList()->yes()) {
5345: $accessories[] = new AccessoryArrayListType();
5346: }
5347:
5348: if (count($accessories) === 0) {
5349: $resultTypes[] = $resultType;
5350: } else {
5351: $resultTypes[] = TypeCombinator::intersect($resultType, ...$accessories);
5352: }
5353: }
5354: }
5355: } elseif (count($constantArrays['b']) > 0) {
5356: $resultTypes[] = TypeCombinator::union(...$constantArrays['b']);
5357: }
5358:
5359: if (count($generalArrays['a']) > 0) {
5360: if (count($generalArrays['b']) === 0) {
5361: $resultTypes[] = TypeCombinator::union(...$generalArrays['a']);
5362: } else {
5363: $generalArraysA = TypeCombinator::union(...$generalArrays['a']);
5364: $generalArraysB = TypeCombinator::union(...$generalArrays['b']);
5365:
5366: $aValueType = $generalArraysA->getIterableValueType();
5367: $bValueType = $generalArraysB->getIterableValueType();
5368: if (
5369: $aValueType->isArray()->yes()
5370: && $aValueType->isConstantArray()->no()
5371: && $bValueType->isArray()->yes()
5372: && $bValueType->isConstantArray()->no()
5373: ) {
5374: $aDepth = self::getArrayDepth($aValueType) + $depth;
5375: $bDepth = self::getArrayDepth($bValueType) + $depth;
5376: if (
5377: ($aDepth > 2 || $bDepth > 2)
5378: && abs($aDepth - $bDepth) > 0
5379: ) {
5380: $aValueType = new MixedType();
5381: $bValueType = new MixedType();
5382: }
5383: }
5384:
5385: $resultType = new ArrayType(
5386: TypeCombinator::union($this->generalizeType($generalArraysA->getIterableKeyType(), $generalArraysB->getIterableKeyType(), $depth + 1)),
5387: TypeCombinator::union($this->generalizeType($aValueType, $bValueType, $depth + 1)),
5388: );
5389:
5390: $accessories = [];
5391: if ($generalArraysA->isIterableAtLeastOnce()->yes() && $generalArraysB->isIterableAtLeastOnce()->yes()) {
5392: $accessories[] = new NonEmptyArrayType();
5393: }
5394: if ($generalArraysA->isList()->yes() && $generalArraysB->isList()->yes()) {
5395: $accessories[] = new AccessoryArrayListType();
5396: }
5397: if ($generalArraysA->isOversizedArray()->yes() && $generalArraysB->isOversizedArray()->yes()) {
5398: $accessories[] = new OversizedArrayType();
5399: }
5400:
5401: if (count($accessories) === 0) {
5402: $resultTypes[] = $resultType;
5403: } else {
5404: $resultTypes[] = TypeCombinator::intersect($resultType, ...$accessories);
5405: }
5406: }
5407: } elseif (count($generalArrays['b']) > 0) {
5408: $resultTypes[] = TypeCombinator::union(...$generalArrays['b']);
5409: }
5410:
5411: if (count($constantIntegers['a']) > 0) {
5412: if (count($constantIntegers['b']) === 0) {
5413: $resultTypes[] = TypeCombinator::union(...$constantIntegers['a']);
5414: } else {
5415: $constantIntegersA = TypeCombinator::union(...$constantIntegers['a']);
5416: $constantIntegersB = TypeCombinator::union(...$constantIntegers['b']);
5417:
5418: if ($constantIntegersA->equals($constantIntegersB)) {
5419: $resultTypes[] = $constantIntegersA;
5420: } else {
5421: $min = null;
5422: $max = null;
5423: foreach ($constantIntegers['a'] as $int) {
5424: if ($min === null || $int->getValue() < $min) {
5425: $min = $int->getValue();
5426: }
5427: if ($max !== null && $int->getValue() <= $max) {
5428: continue;
5429: }
5430:
5431: $max = $int->getValue();
5432: }
5433:
5434: $newMin = $min;
5435: $newMax = $max;
5436: foreach ($constantIntegers['b'] as $int) {
5437: if ($int->getValue() > $newMax) {
5438: $newMax = $int->getValue();
5439: }
5440: if ($int->getValue() >= $newMin) {
5441: continue;
5442: }
5443:
5444: $newMin = $int->getValue();
5445: }
5446:
5447: if ($newMax > $max && $newMin < $min) {
5448: $resultTypes[] = IntegerRangeType::fromInterval($newMin, $newMax);
5449: } elseif ($newMax > $max) {
5450: $resultTypes[] = IntegerRangeType::fromInterval($min, null);
5451: } elseif ($newMin < $min) {
5452: $resultTypes[] = IntegerRangeType::fromInterval(null, $max);
5453: } else {
5454: $resultTypes[] = TypeCombinator::union($constantIntegersA, $constantIntegersB);
5455: }
5456: }
5457: }
5458: } elseif (count($constantIntegers['b']) > 0) {
5459: $resultTypes[] = TypeCombinator::union(...$constantIntegers['b']);
5460: }
5461:
5462: if (count($integerRanges['a']) > 0) {
5463: if (count($integerRanges['b']) === 0) {
5464: $resultTypes[] = TypeCombinator::union(...$integerRanges['a']);
5465: } else {
5466: $integerRangesA = TypeCombinator::union(...$integerRanges['a']);
5467: $integerRangesB = TypeCombinator::union(...$integerRanges['b']);
5468:
5469: if ($integerRangesA->equals($integerRangesB)) {
5470: $resultTypes[] = $integerRangesA;
5471: } else {
5472: $min = null;
5473: $max = null;
5474: foreach ($integerRanges['a'] as $range) {
5475: if ($range->getMin() === null) {
5476: $rangeMin = PHP_INT_MIN;
5477: } else {
5478: $rangeMin = $range->getMin();
5479: }
5480: if ($range->getMax() === null) {
5481: $rangeMax = PHP_INT_MAX;
5482: } else {
5483: $rangeMax = $range->getMax();
5484: }
5485:
5486: if ($min === null || $rangeMin < $min) {
5487: $min = $rangeMin;
5488: }
5489: if ($max !== null && $rangeMax <= $max) {
5490: continue;
5491: }
5492:
5493: $max = $rangeMax;
5494: }
5495:
5496: $newMin = $min;
5497: $newMax = $max;
5498: foreach ($integerRanges['b'] as $range) {
5499: if ($range->getMin() === null) {
5500: $rangeMin = PHP_INT_MIN;
5501: } else {
5502: $rangeMin = $range->getMin();
5503: }
5504: if ($range->getMax() === null) {
5505: $rangeMax = PHP_INT_MAX;
5506: } else {
5507: $rangeMax = $range->getMax();
5508: }
5509:
5510: if ($rangeMax > $newMax) {
5511: $newMax = $rangeMax;
5512: }
5513: if ($rangeMin >= $newMin) {
5514: continue;
5515: }
5516:
5517: $newMin = $rangeMin;
5518: }
5519:
5520: $gotGreater = $newMax > $max;
5521: $gotSmaller = $newMin < $min;
5522:
5523: if ($min === PHP_INT_MIN) {
5524: $min = null;
5525: }
5526: if ($max === PHP_INT_MAX) {
5527: $max = null;
5528: }
5529: if ($newMin === PHP_INT_MIN) {
5530: $newMin = null;
5531: }
5532: if ($newMax === PHP_INT_MAX) {
5533: $newMax = null;
5534: }
5535:
5536: if ($gotGreater && $gotSmaller) {
5537: $resultTypes[] = IntegerRangeType::fromInterval($newMin, $newMax);
5538: } elseif ($gotGreater) {
5539: $resultTypes[] = IntegerRangeType::fromInterval($min, null);
5540: } elseif ($gotSmaller) {
5541: $resultTypes[] = IntegerRangeType::fromInterval(null, $max);
5542: } else {
5543: $resultTypes[] = TypeCombinator::union($integerRangesA, $integerRangesB);
5544: }
5545: }
5546: }
5547: } elseif (count($integerRanges['b']) > 0) {
5548: $resultTypes[] = TypeCombinator::union(...$integerRanges['b']);
5549: }
5550:
5551: $accessoryTypes = array_map(
5552: static fn (Type $type): Type => $type->generalize(GeneralizePrecision::moreSpecific()),
5553: TypeUtils::getAccessoryTypes($a),
5554: );
5555:
5556: $combined = TypeCombinator::union(...$resultTypes, ...$otherTypes);
5557: if ($wrapBenevolent) {
5558: $combined = TypeUtils::toBenevolentUnion($combined);
5559: }
5560:
5561: return TypeCombinator::union(TypeCombinator::intersect(
5562: $combined,
5563: ...$accessoryTypes,
5564: ), ...$otherTypes);
5565: }
5566:
5567: private static function getArrayDepth(Type $type): int
5568: {
5569: $depth = 0;
5570: $arrays = TypeUtils::toBenevolentUnion($type)->getArrays();
5571: while (count($arrays) > 0) {
5572: $temp = $type->getIterableValueType();
5573: $type = $temp;
5574: $arrays = TypeUtils::toBenevolentUnion($type)->getArrays();
5575: $depth++;
5576: }
5577:
5578: return $depth;
5579: }
5580:
5581: public function equals(self $otherScope): bool
5582: {
5583: if (!$this->context->equals($otherScope->context)) {
5584: return false;
5585: }
5586:
5587: if (!$this->compareVariableTypeHolders($this->expressionTypes, $otherScope->expressionTypes)) {
5588: return false;
5589: }
5590: if (!$this->compareVariableTypeHolders($this->nativeExpressionTypes, $otherScope->nativeExpressionTypes)) {
5591: return false;
5592: }
5593:
5594: return $this->compareConditionalExpressions($this->conditionalExpressions, $otherScope->conditionalExpressions);
5595: }
5596:
5597: /**
5598: * @param array<string, ConditionalExpressionHolder[]> $conditionalExpressions
5599: * @param array<string, ConditionalExpressionHolder[]> $otherConditionalExpressions
5600: */
5601: private function compareConditionalExpressions(array $conditionalExpressions, array $otherConditionalExpressions): bool
5602: {
5603: if (count($conditionalExpressions) !== count($otherConditionalExpressions)) {
5604: return false;
5605: }
5606: foreach ($conditionalExpressions as $exprString => $holders) {
5607: if (!isset($otherConditionalExpressions[$exprString])) {
5608: return false;
5609: }
5610: $otherHolders = $otherConditionalExpressions[$exprString];
5611: if (count($holders) !== count($otherHolders)) {
5612: return false;
5613: }
5614: foreach ($holders as $key => $holder) {
5615: if (!isset($otherHolders[$key])) {
5616: return false;
5617: }
5618: $otherHolder = $otherHolders[$key];
5619: if (!$holder->getTypeHolder()->equals($otherHolder->getTypeHolder())) {
5620: return false;
5621: }
5622: $conditions = $holder->getConditionExpressionTypeHolders();
5623: $otherConditions = $otherHolder->getConditionExpressionTypeHolders();
5624: if (count($conditions) !== count($otherConditions)) {
5625: return false;
5626: }
5627: foreach ($conditions as $conditionExprString => $conditionHolder) {
5628: if (!isset($otherConditions[$conditionExprString])) {
5629: return false;
5630: }
5631: if (!$conditionHolder->equals($otherConditions[$conditionExprString])) {
5632: return false;
5633: }
5634: }
5635: }
5636: }
5637:
5638: return true;
5639: }
5640:
5641: /**
5642: * @param array<string, ExpressionTypeHolder> $variableTypeHolders
5643: * @param array<string, ExpressionTypeHolder> $otherVariableTypeHolders
5644: */
5645: private function compareVariableTypeHolders(array $variableTypeHolders, array $otherVariableTypeHolders): bool
5646: {
5647: if (count($variableTypeHolders) !== count($otherVariableTypeHolders)) {
5648: return false;
5649: }
5650: foreach ($variableTypeHolders as $variableExprString => $variableTypeHolder) {
5651: if (!isset($otherVariableTypeHolders[$variableExprString])) {
5652: return false;
5653: }
5654:
5655: if (!$variableTypeHolder->getCertainty()->equals($otherVariableTypeHolders[$variableExprString]->getCertainty())) {
5656: return false;
5657: }
5658:
5659: if (!$variableTypeHolder->equalTypes($otherVariableTypeHolders[$variableExprString])) {
5660: return false;
5661: }
5662: }
5663:
5664: return true;
5665: }
5666:
5667: /**
5668: * @api
5669: * @deprecated Use canReadProperty() or canWriteProperty()
5670: */
5671: public function canAccessProperty(PropertyReflection $propertyReflection): bool
5672: {
5673: return $this->canAccessClassMember($propertyReflection);
5674: }
5675:
5676: /** @api */
5677: public function canReadProperty(ExtendedPropertyReflection $propertyReflection): bool
5678: {
5679: return $this->canAccessClassMember($propertyReflection);
5680: }
5681:
5682: /** @api */
5683: public function canWriteProperty(ExtendedPropertyReflection $propertyReflection): bool
5684: {
5685: if (!$propertyReflection->isPrivateSet() && !$propertyReflection->isProtectedSet()) {
5686: return $this->canAccessClassMember($propertyReflection);
5687: }
5688:
5689: $supportsAsymmetricVisibility = $this->getPhpVersion()->supportsAsymmetricVisibility();
5690: if ($this->services->checkWholePhpVersionRange ? $supportsAsymmetricVisibility->no() : !$supportsAsymmetricVisibility->yes()) {
5691: return $this->canAccessClassMember($propertyReflection);
5692: }
5693:
5694: $propertyDeclaringClass = $propertyReflection->getDeclaringClass();
5695: $canAccessClassMember = static function (ClassReflection $classReflection) use ($propertyReflection, $propertyDeclaringClass) {
5696: if ($propertyReflection->isPrivateSet()) {
5697: return $classReflection->getName() === $propertyDeclaringClass->getName();
5698: }
5699:
5700: // protected set
5701:
5702: if (
5703: $classReflection->getName() === $propertyDeclaringClass->getName()
5704: || $classReflection->isSubclassOfClass($propertyDeclaringClass->removeFinalKeywordOverride())
5705: ) {
5706: return true;
5707: }
5708:
5709: return $propertyReflection->getDeclaringClass()->isSubclassOfClass($classReflection);
5710: };
5711:
5712: foreach ($this->inClosureBindScopeClasses as $inClosureBindScopeClass) {
5713: if (!$this->services->reflectionProvider->hasClass($inClosureBindScopeClass)) {
5714: continue;
5715: }
5716:
5717: if ($canAccessClassMember($this->services->reflectionProvider->getClass($inClosureBindScopeClass))) {
5718: return true;
5719: }
5720: }
5721:
5722: if ($this->isInClass()) {
5723: return $canAccessClassMember($this->getClassReflection());
5724: }
5725:
5726: return false;
5727: }
5728:
5729: /** @api */
5730: public function canCallMethod(MethodReflection $methodReflection): bool
5731: {
5732: if ($this->canAccessClassMember($methodReflection)) {
5733: return true;
5734: }
5735:
5736: return $this->canAccessClassMember($methodReflection->getPrototype());
5737: }
5738:
5739: /** @api */
5740: public function canAccessConstant(ClassConstantReflection $constantReflection): bool
5741: {
5742: return $this->canAccessClassMember($constantReflection);
5743: }
5744:
5745: private function canAccessClassMember(ClassMemberReflection $classMemberReflection): bool
5746: {
5747: if ($classMemberReflection->isPublic()) {
5748: return true;
5749: }
5750:
5751: $classMemberDeclaringClass = $classMemberReflection->getDeclaringClass();
5752: $canAccessClassMember = static function (ClassReflection $classReflection) use ($classMemberReflection, $classMemberDeclaringClass) {
5753: if ($classMemberReflection->isPrivate()) {
5754: return $classReflection->getName() === $classMemberDeclaringClass->getName();
5755: }
5756:
5757: // protected
5758:
5759: if (
5760: $classReflection->getName() === $classMemberDeclaringClass->getName()
5761: || $classReflection->isSubclassOfClass($classMemberDeclaringClass->removeFinalKeywordOverride())
5762: ) {
5763: return true;
5764: }
5765:
5766: return $classMemberReflection->getDeclaringClass()->isSubclassOfClass($classReflection);
5767: };
5768:
5769: foreach ($this->inClosureBindScopeClasses as $inClosureBindScopeClass) {
5770: if (!$this->services->reflectionProvider->hasClass($inClosureBindScopeClass)) {
5771: continue;
5772: }
5773:
5774: if ($canAccessClassMember($this->services->reflectionProvider->getClass($inClosureBindScopeClass))) {
5775: return true;
5776: }
5777: }
5778:
5779: if ($this->isInClass()) {
5780: return $canAccessClassMember($this->getClassReflection());
5781: }
5782:
5783: return false;
5784: }
5785:
5786: /**
5787: * @return string[]
5788: */
5789: public function debug(): array
5790: {
5791: $descriptions = [];
5792: foreach ($this->expressionTypes as $name => $variableTypeHolder) {
5793: $key = sprintf('%s (%s)', $name, $variableTypeHolder->getCertainty()->describe());
5794: $descriptions[$key] = $variableTypeHolder->getType()->describe(VerbosityLevel::precise());
5795: }
5796: foreach ($this->nativeExpressionTypes as $exprString => $nativeTypeHolder) {
5797: $key = sprintf('native %s (%s)', $exprString, $nativeTypeHolder->getCertainty()->describe());
5798: $descriptions[$key] = $nativeTypeHolder->getType()->describe(VerbosityLevel::precise());
5799: }
5800:
5801: foreach (array_keys($this->currentlyAssignedExpressions) as $exprString) {
5802: $descriptions[sprintf('currently assigned %s', $exprString)] = 'true';
5803: }
5804:
5805: foreach (array_keys($this->currentlyAllowedUndefinedExpressions) as $exprString) {
5806: $descriptions[sprintf('currently allowed undefined %s', $exprString)] = 'true';
5807: }
5808:
5809: foreach ($this->conditionalExpressions as $exprString => $holders) {
5810: foreach (array_values($holders) as $i => $holder) {
5811: $key = sprintf('condition about %s #%d', $exprString, $i + 1);
5812: $parts = [];
5813: foreach ($holder->getConditionExpressionTypeHolders() as $conditionalExprString => $expressionTypeHolder) {
5814: $parts[] = $conditionalExprString . '=' . $expressionTypeHolder->getType()->describe(VerbosityLevel::precise());
5815: }
5816: $condition = implode(' && ', $parts);
5817: $descriptions[$key] = sprintf(
5818: 'if %s then %s is %s (%s)',
5819: $condition,
5820: $exprString,
5821: $holder->getTypeHolder()->getType()->describe(VerbosityLevel::precise()),
5822: $holder->getTypeHolder()->getCertainty()->describe(),
5823: );
5824: }
5825: }
5826:
5827: return $descriptions;
5828: }
5829:
5830: public function filterTypeWithMethod(Type $typeWithMethod, string $methodName): ?Type
5831: {
5832: if ($typeWithMethod instanceof UnionType) {
5833: $typeWithMethod = $typeWithMethod->filterTypes(static fn (Type $innerType) => $innerType->hasMethod($methodName)->yes());
5834: if ($typeWithMethod instanceof NeverType) {
5835: return null;
5836: }
5837: } elseif (!$typeWithMethod->hasMethod($methodName)->yes()) {
5838: return null;
5839: }
5840:
5841: return $typeWithMethod;
5842: }
5843:
5844: /** @api */
5845: public function getMethodReflection(Type $typeWithMethod, string $methodName): ?ExtendedMethodReflection
5846: {
5847: $type = $this->filterTypeWithMethod($typeWithMethod, $methodName);
5848: if ($type === null) {
5849: return null;
5850: }
5851:
5852: return $type->getMethod($methodName, $this);
5853: }
5854:
5855: public function getNakedMethod(Type $typeWithMethod, string $methodName): ?ExtendedMethodReflection
5856: {
5857: $type = $this->filterTypeWithMethod($typeWithMethod, $methodName);
5858: if ($type === null) {
5859: return null;
5860: }
5861:
5862: return $type->getUnresolvedMethodPrototype($methodName, $this)->getNakedMethod();
5863: }
5864:
5865: /**
5866: * @api
5867: * @deprecated Use getInstancePropertyReflection or getStaticPropertyReflection instead
5868: */
5869: public function getPropertyReflection(Type $typeWithProperty, string $propertyName): ?ExtendedPropertyReflection
5870: {
5871: if ($typeWithProperty instanceof UnionType) {
5872: $typeWithProperty = $typeWithProperty->filterTypes(static fn (Type $innerType) => $innerType->hasProperty($propertyName)->yes());
5873: if ($typeWithProperty instanceof NeverType) {
5874: return null;
5875: }
5876: } elseif (!$typeWithProperty->hasProperty($propertyName)->yes()) {
5877: return null;
5878: }
5879:
5880: return $typeWithProperty->getProperty($propertyName, $this);
5881: }
5882:
5883: /** @api */
5884: public function getInstancePropertyReflection(Type $typeWithProperty, string $propertyName): ?ExtendedPropertyReflection
5885: {
5886: if ($typeWithProperty instanceof UnionType) {
5887: $typeWithProperty = $typeWithProperty->filterTypes(static fn (Type $innerType) => $innerType->hasInstanceProperty($propertyName)->yes());
5888: if ($typeWithProperty instanceof NeverType) {
5889: return null;
5890: }
5891: }
5892: if (!$typeWithProperty->hasInstanceProperty($propertyName)->yes()) {
5893: return null;
5894: }
5895:
5896: return $typeWithProperty->getInstanceProperty($propertyName, $this);
5897: }
5898:
5899: /** @api */
5900: public function getStaticPropertyReflection(Type $typeWithProperty, string $propertyName): ?ExtendedPropertyReflection
5901: {
5902: if ($typeWithProperty instanceof UnionType) {
5903: $typeWithProperty = $typeWithProperty->filterTypes(static fn (Type $innerType) => $innerType->hasStaticProperty($propertyName)->yes());
5904: if ($typeWithProperty instanceof NeverType) {
5905: return null;
5906: }
5907: }
5908: if (!$typeWithProperty->hasStaticProperty($propertyName)->yes()) {
5909: return null;
5910: }
5911:
5912: return $typeWithProperty->getStaticProperty($propertyName, $this);
5913: }
5914:
5915: public function getConstantReflection(Type $typeWithConstant, string $constantName): ?ClassConstantReflection
5916: {
5917: if ($typeWithConstant instanceof UnionType) {
5918: $typeWithConstant = $typeWithConstant->filterTypes(static fn (Type $innerType) => $innerType->hasConstant($constantName)->yes());
5919:
5920: if ($typeWithConstant instanceof NeverType) {
5921: return null;
5922: }
5923: } elseif (!$typeWithConstant->hasConstant($constantName)->yes()) {
5924: return null;
5925: }
5926:
5927: return $typeWithConstant->getConstant($constantName);
5928: }
5929:
5930: public function getConstantExplicitTypeFromConfig(string $constantName, Type $constantType): Type
5931: {
5932: return $this->services->constantResolver->resolveConstantType($constantName, $constantType);
5933: }
5934:
5935: /**
5936: * @return array<string, ExpressionTypeHolder>
5937: */
5938: private function getConstantTypes(): array
5939: {
5940: $constantTypes = [];
5941: foreach ($this->expressionTypes as $exprString => $typeHolder) {
5942: $expr = $typeHolder->getExpr();
5943: if (!$expr instanceof ConstFetch) {
5944: continue;
5945: }
5946: $constantTypes[$exprString] = $typeHolder;
5947: }
5948: return $constantTypes;
5949: }
5950:
5951: private function getGlobalConstantType(Name $name): ?Type
5952: {
5953: // the namespace only takes part for a name that is not already fully qualified
5954: $namespace = $name->isFullyQualified() ? null : $this->getNamespace();
5955: $nameString = $name->toString();
5956: $cacheKey = get_class($name) . "\0" . $nameString . "\0" . ($namespace ?? "\0");
5957:
5958: $exprStrings = self::$globalConstantFetchKeys[$cacheKey] ?? null;
5959: if ($exprStrings === null) {
5960: $exprStrings = [];
5961: foreach (self::createGlobalConstantFetches($name, $nameString, $namespace) as $constFetch) {
5962: $exprStrings[] = $this->getNodeKey($constFetch);
5963: }
5964:
5965: if (count(self::$globalConstantFetchKeys) < self::GLOBAL_CONSTANT_FETCH_KEYS_LIMIT) {
5966: self::$globalConstantFetchKeys[$cacheKey] = $exprStrings;
5967: }
5968: }
5969:
5970: foreach ($exprStrings as $i => $exprString) {
5971: // what hasExpressionType() does for a node that is not a Variable: the
5972: // key is all it looks at, and the key is exactly what is memoized above
5973: $typeHolder = $this->expressionTypes[$exprString] ?? null;
5974: if ($typeHolder === null || !$typeHolder->getCertainty()->yes()) {
5975: continue;
5976: }
5977:
5978: return $this->getType(self::createGlobalConstantFetches($name, $nameString, $namespace)[$i]);
5979: }
5980:
5981: return null;
5982: }
5983:
5984: /**
5985: * The nodes a global constant name is looked up as, in priority order: the
5986: * current namespace's constant, the global one, then the name as written.
5987: *
5988: * Fresh nodes on every call by design - everything that keys on node identity
5989: * (ExpressionResultStorage, NodeScopeResolver's processed-node guards) must
5990: * keep seeing a node of its own; only the keys they print as are memoized.
5991: *
5992: * @param non-empty-string $nameString
5993: * @return list<ConstFetch>
5994: */
5995: private static function createGlobalConstantFetches(Name $name, string $nameString, ?string $namespace): array
5996: {
5997: $fetches = [];
5998: if ($namespace !== null) {
5999: $fetches[] = new ConstFetch(new FullyQualified([$namespace, $nameString]));
6000: }
6001:
6002: $fetches[] = new ConstFetch(new FullyQualified($nameString));
6003: $fetches[] = new ConstFetch($name);
6004:
6005: return $fetches;
6006: }
6007:
6008: /**
6009: * @return array<string, ExpressionTypeHolder>
6010: */
6011: private function getNativeConstantTypes(): array
6012: {
6013: $constantTypes = [];
6014: foreach ($this->nativeExpressionTypes as $exprString => $typeHolder) {
6015: $expr = $typeHolder->getExpr();
6016: if (!$expr instanceof ConstFetch) {
6017: continue;
6018: }
6019: $constantTypes[$exprString] = $typeHolder;
6020: }
6021: return $constantTypes;
6022: }
6023:
6024: public function getIterableKeyType(Type $iteratee): Type
6025: {
6026: if ($iteratee instanceof UnionType) {
6027: $filtered = $iteratee->filterTypes(static fn (Type $innerType) => $innerType->isIterable()->yes());
6028: if (!$filtered instanceof NeverType) {
6029: $iteratee = $filtered;
6030: }
6031: }
6032:
6033: return $iteratee->getIterableKeyType();
6034: }
6035:
6036: public function getIterableValueType(Type $iteratee): Type
6037: {
6038: if ($iteratee instanceof UnionType) {
6039: $filtered = $iteratee->filterTypes(static fn (Type $innerType) => $innerType->isIterable()->yes());
6040: if (!$filtered instanceof NeverType) {
6041: $iteratee = $filtered;
6042: }
6043: }
6044:
6045: return $iteratee->getIterableValueType();
6046: }
6047:
6048: public function getPhpVersion(): PhpVersions
6049: {
6050: // The same scope is asked over and over - on every property fetch, among others - and the
6051: // answer depends only on its expression types. While they are untouched, both properties
6052: // hold the same array and the comparison is a pointer check; a write in place separates
6053: // them and the answer is computed again.
6054: if ($this->phpVersion !== null && $this->phpVersionExpressionTypes === $this->expressionTypes) {
6055: return $this->phpVersion;
6056: }
6057:
6058: $this->phpVersionExpressionTypes = $this->expressionTypes;
6059:
6060: return $this->phpVersion = $this->resolvePhpVersion();
6061: }
6062:
6063: private function resolvePhpVersion(): PhpVersions
6064: {
6065: $constType = $this->getGlobalConstantType(new Name('PHP_VERSION_ID'));
6066: if ($constType !== null && !$this->isOverallPhpVersionRange($constType)) {
6067: if (
6068: $constType instanceof IntegerRangeType
6069: && $constType->getMin() === ConstantResolver::PHP_MIN_ANALYZABLE_VERSION_ID
6070: && $constType->getMax() !== null
6071: && $this->getConfiguredPhpVersionRange() === null
6072: ) {
6073: // A guard like `PHP_VERSION_ID < 80400` only gives an upper bound. Without
6074: // a configured version range, the lower bound is merely the lowest version
6075: // PHPStan knows, while outside the guard the single analysed PHP version
6076: // applies. Keep the lower bound at that version, or as close to it as
6077: // the guard allows.
6078: $maxVersionId = $constType->getMax();
6079: return new PhpVersions(IntegerRangeType::fromInterval(
6080: min($this->services->phpVersion->getVersionId(), $maxVersionId),
6081: $maxVersionId,
6082: ));
6083: }
6084:
6085: return new PhpVersions($constType);
6086: }
6087:
6088: $configuredRange = $this->getConfiguredPhpVersionRange();
6089: if ($configuredRange !== null) {
6090: return new PhpVersions($configuredRange);
6091: }
6092:
6093: return new PhpVersions(new ConstantIntegerType($this->services->phpVersion->getVersionId()));
6094: }
6095:
6096: /**
6097: * The analysed PHP version range comes either from the NEON phpVersion min/max
6098: * config or from the composer.json "require.php" constraint - the very same
6099: * source ConstantResolver narrows PHP_VERSION_ID with, so that
6100: * Scope::getPhpVersion() never contradicts the PHP_VERSION_ID constant.
6101: * Null when neither is set and a single PHP version is analysed.
6102: */
6103: private function getConfiguredPhpVersionRange(): ?Type
6104: {
6105: [$minPhpVersion, $maxPhpVersion] = $this->services->configuredPhpVersionRangeHelper->getVersionRange();
6106: if (
6107: $minPhpVersion === null
6108: && ($maxPhpVersion === null || $maxPhpVersion->getVersionId() === PhpVersionFactory::MAX_PHP_VERSION)
6109: ) {
6110: return null;
6111: }
6112:
6113: return IntegerRangeType::fromInterval(
6114: $minPhpVersion !== null ? $minPhpVersion->getVersionId() : ConstantResolver::PHP_MIN_ANALYZABLE_VERSION_ID,
6115: $maxPhpVersion?->getVersionId(),
6116: );
6117: }
6118:
6119: /**
6120: * Whether the type carries no information about the analysed PHP version,
6121: * i.e. it spans everything PHPStan is able to analyse.
6122: */
6123: private function isOverallPhpVersionRange(Type $type): bool
6124: {
6125: return $type instanceof IntegerRangeType
6126: && $type->getMin() === ConstantResolver::PHP_MIN_ANALYZABLE_VERSION_ID
6127: && ($type->getMax() === null || $type->getMax() === PhpVersionFactory::MAX_PHP_VERSION);
6128: }
6129:
6130: public function invokeNodeCallback(Node $node): void
6131: {
6132: $nodeCallback = $this->services->nodeCallback;
6133: if ($nodeCallback === null) {
6134: throw new ShouldNotHappenException('Node callback is not present in this scope');
6135: }
6136:
6137: $nodeCallback($node, $this);
6138: }
6139:
6140: /**
6141: * @template TNodeType of Node
6142: * @template TValue
6143: * @param class-string<Collector<TNodeType, TValue>> $collectorType
6144: * @param TValue $data
6145: */
6146: public function emitCollectedData(string $collectorType, mixed $data): void
6147: {
6148: $nodeCallback = $this->services->nodeCallback;
6149: if ($nodeCallback === null) {
6150: throw new ShouldNotHappenException('Node callback is not present in this scope');
6151: }
6152:
6153: $nodeCallback(new EmitCollectedDataNode($collectorType, $data), $this);
6154: }
6155:
6156: public function trackValueDependency(string $extensionClass, string $key): void
6157: {
6158: // a scope without a node callback is outside the walk of the analysed file - see ValueDependencyCollector
6159: $this->services->container->getByType(ValueDependencyCollector::class)->record($extensionClass, $key, $this, $this->services->nodeCallback !== null);
6160: }
6161:
6162: public function trackFileDependency(string $file): void
6163: {
6164: $this->services->container->getByType(ValueDependencyCollector::class)->recordFile($file, $this, $this->services->nodeCallback !== null);
6165: }
6166:
6167: public function trackDirectoryDependency(string $directory, string $pattern = '*'): void
6168: {
6169: $this->services->container->getByType(ValueDependencyCollector::class)->recordDirectory($directory, $pattern, $this, $this->services->nodeCallback !== null);
6170: }
6171:
6172: public function trackClassDependency(string $className): void
6173: {
6174: $this->services->container->getByType(ValueDependencyCollector::class)->recordClass($className, $this, $this->services->nodeCallback !== null);
6175: }
6176:
6177: }
6178: