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