1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Analyser;
4:
5: use Closure;
6: use PhpParser\Node\Expr;
7: use PHPStan\Turbo\ShadowedByTurboExtension;
8: use PHPStan\Type\Accessory\AccessoryType;
9: use PHPStan\Type\NeverType;
10: use PHPStan\Type\Type;
11: use PHPStan\Type\TypeCombinator;
12: use function array_key_exists;
13: use function array_merge;
14: use function count;
15:
16: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/SpecifiedTypes.cpp')]
17: final class SpecifiedTypes
18: {
19:
20: /** @var (Closure(TypeSpecifierContext, bool): self)|null */
21: private static ?Closure $emptySpecifyCallback = null;
22:
23: /**
24: * Cross-producing alternative forms doubles the term count per conjunction;
25: * past this many terms the entry is widened to a single covering term.
26: */
27: private const ALTERNATIVE_TERMS_LIMIT = 32;
28:
29: private bool $overwrite = false;
30:
31: private bool $equality = false;
32:
33: /** @var array<string, ConditionalExpressionHolder[]> */
34: private array $newConditionalExpressionHolders = [];
35:
36: /**
37: * Deferred boolean-decomposition holders, evaluated against the applying
38: * scope by MutatingScope::applySpecifiedTypes().
39: *
40: * @var list<ConditionalExpressionHolderRecipe>
41: */
42: private array $conditionalExpressionHolderRecipes = [];
43:
44: /**
45: * State-dependent augmentations evaluated against the applying scope by
46: * MutatingScope::applySpecifiedTypes(); their entries join the applied
47: * batch.
48: *
49: * @var list<DeferredSpecifiedTypesAugment>
50: */
51: private array $deferredAugments = [];
52:
53: private ?Expr $rootExpr = null;
54:
55: /**
56: * Alternative-form entries produced by intersectWith() when the two sides
57: * constrain the same expression with different kinds (a sure type in one
58: * branch, a sure-not in the other). Each term (sure, subtract) reads as
59: * `(sure ?? current type) minus subtract`; the entry's value is the union
60: * of its terms, evaluated by MutatingScope::applySpecifiedTypes() against
61: * the subject's type at the application point - the deferred form of what
62: * the old SpecifiedTypes::normalize() computed eagerly with a scope.
63: *
64: * @var array<string, array{Expr, list<array{?Type, ?Type}>}>
65: */
66: private array $alternativeTypes = [];
67:
68: /**
69: * @api
70: * @param array<string, array{Expr, Type}> $sureTypes
71: * @param array<string, array{Expr, Type}> $sureNotTypes
72: */
73: public function __construct(
74: private array $sureTypes = [],
75: private array $sureNotTypes = [],
76: )
77: {
78: }
79:
80: /**
81: * A shared no-narrowing specify callback for results whose expression never
82: * narrows anything (literals, virtual write nodes) - one process-wide
83: * closure instead of one allocation per created ExpressionResult.
84: *
85: * @return Closure(TypeSpecifierContext, bool): self
86: */
87: public static function emptySpecifyCallback(): Closure
88: {
89: return self::$emptySpecifyCallback ??= static fn (): self => new self();
90: }
91:
92: /**
93: * Normally, $sureTypes in truthy context are used to intersect with the pre-existing type.
94: * And $sureNotTypes are used to remove type from the pre-existing type.
95: *
96: * Example: By default, non-empty-string intersected with '' (ConstantStringType) will lead to NeverType.
97: * Because it's not possible to narrow non-empty-string to an empty string.
98: *
99: * In rare cases, a type-specifying extension might want to overwrite the pre-existing types
100: * without taking the pre-existing types into consideration.
101: *
102: * In that case it should also call setAlwaysOverwriteTypes() on
103: * the returned object.
104: *
105: * ! Only do this if you're certain. Otherwise, this is a source of common bugs. !
106: *
107: * @api
108: */
109: public function setAlwaysOverwriteTypes(): self
110: {
111: $self = clone $this;
112: $self->overwrite = true;
113:
114: return $self;
115: }
116:
117: /**
118: * Marks these types as coming from an equality check, the same concept as
119: * the "=Type" equality assertions documented at
120: * https://phpstan.org/writing-php-code/narrowing-types#equality-assertions
121: *
122: * The narrowed types are only applied; they do not determine the check
123: * outcome, so ImpossibleCheckTypeHelper will not use them to report
124: * always-true/false for the check expression.
125: *
126: * @api
127: */
128: public function setEquality(): self
129: {
130: $self = clone $this;
131: $self->equality = true;
132:
133: return $self;
134: }
135:
136: public function isEquality(): bool
137: {
138: return $this->equality;
139: }
140:
141: /**
142: * @api
143: */
144: public function setRootExpr(?Expr $rootExpr): self
145: {
146: $self = clone $this;
147: $self->rootExpr = $rootExpr;
148:
149: return $self;
150: }
151:
152: /**
153: * @param array<string, ConditionalExpressionHolder[]> $newConditionalExpressionHolders
154: */
155: public function setNewConditionalExpressionHolders(array $newConditionalExpressionHolders): self
156: {
157: $self = clone $this;
158: $self->newConditionalExpressionHolders = $newConditionalExpressionHolders;
159:
160: return $self;
161: }
162:
163: /**
164: * @param list<ConditionalExpressionHolderRecipe> $recipes
165: */
166: public function setConditionalExpressionHolderRecipes(array $recipes): self
167: {
168: $self = clone $this;
169: $self->conditionalExpressionHolderRecipes = $recipes;
170:
171: return $self;
172: }
173:
174: /**
175: * @return list<ConditionalExpressionHolderRecipe>
176: */
177: public function getConditionalExpressionHolderRecipes(): array
178: {
179: return $this->conditionalExpressionHolderRecipes;
180: }
181:
182: public function withDeferredAugment(DeferredSpecifiedTypesAugment $augment): self
183: {
184: $self = clone $this;
185: $self->deferredAugments = [...$this->deferredAugments, $augment];
186:
187: return $self;
188: }
189:
190: /**
191: * @return list<DeferredSpecifiedTypesAugment>
192: */
193: public function getDeferredAugments(): array
194: {
195: return $this->deferredAugments;
196: }
197:
198: /**
199: * @api
200: * @return array<string, array{Expr, Type}>
201: */
202: public function getSureTypes(): array
203: {
204: return $this->sureTypes;
205: }
206:
207: /**
208: * @api
209: * @return array<string, array{Expr, Type}>
210: */
211: public function getSureNotTypes(): array
212: {
213: return $this->sureNotTypes;
214: }
215:
216: /**
217: * @return array<string, array{Expr, list<array{?Type, ?Type}>}>
218: */
219: public function getAlternativeTypes(): array
220: {
221: return $this->alternativeTypes;
222: }
223:
224: /**
225: * A copy without conditional-expression holders and holder recipes - for
226: * the boolean-decomposition tails that replace them with freshly built
227: * recipes while keeping everything else (entries, alternatives, augments)
228: * intact.
229: */
230: public function withoutConditionalExpressionHolders(): self
231: {
232: $self = clone $this;
233: $self->newConditionalExpressionHolders = [];
234: $self->conditionalExpressionHolderRecipes = [];
235:
236: return $self;
237: }
238:
239: public function shouldOverwrite(): bool
240: {
241: return $this->overwrite;
242: }
243:
244: /**
245: * @return array<string, ConditionalExpressionHolder[]>
246: */
247: public function getNewConditionalExpressionHolders(): array
248: {
249: return $this->newConditionalExpressionHolders;
250: }
251:
252: public function getRootExpr(): ?Expr
253: {
254: return $this->rootExpr;
255: }
256:
257: public function removeExpr(string $exprString): self
258: {
259: $self = clone $this;
260: unset($self->sureTypes[$exprString]);
261: unset($self->sureNotTypes[$exprString]);
262: unset($self->alternativeTypes[$exprString]);
263:
264: return $self;
265: }
266:
267: /**
268: * The either-branch merge: the result holds when at least one side holds
269: * (the falsey narrowing of `&&`, the truthy narrowing of `||`). Same-kind
270: * constraints merge exactly (sure: union of values, sure-not: intersection
271: * of removed types); an expression constrained with different kinds on the
272: * two sides becomes an alternative-form entry - `(sure ?? current) minus
273: * subtract` per side, united at the application point. An expression
274: * constrained on only one side is unconstrained in the merge.
275: *
276: * @api
277: */
278: public function intersectWith(SpecifiedTypes $other): self
279: {
280: $sureTypeUnion = [];
281: $sureNotTypeUnion = [];
282: $alternativeUnion = [];
283: $rootExpr = $this->mergeRootExpr($this->rootExpr, $other->rootExpr);
284:
285: $keys = [];
286: foreach ([$this->sureTypes, $this->sureNotTypes, $this->alternativeTypes, $other->sureTypes, $other->sureNotTypes, $other->alternativeTypes] as $map) {
287: foreach ($map as $exprString => $entry) {
288: $keys[$exprString] = $entry[0];
289: }
290: }
291:
292: foreach ($keys as $exprString => $exprNode) {
293: $thisTerms = $this->collectTerms($exprString);
294: $otherTerms = $other->collectTerms($exprString);
295: if ($thisTerms === null || $otherTerms === null) {
296: // unconstrained on one side - unconstrained in the merge
297: continue;
298: }
299:
300: $terms = array_merge($thisTerms, $otherTerms);
301: $sures = [];
302: $subtracts = [];
303: $pureSure = true;
304: $pureSureNot = true;
305: foreach ($terms as [$sure, $subtract]) {
306: if ($sure === null) {
307: $pureSure = false;
308: } else {
309: $sures[] = $sure;
310: if ($sure instanceof AccessoryType) {
311: // an accessory type alone, as non-empty-array, means
312: // something only intersected with the current type -
313: // united with another sure type first, it does not
314: $pureSure = false;
315: }
316: }
317: if ($subtract === null) {
318: $pureSureNot = false;
319: } else {
320: $subtracts[] = $subtract;
321: }
322: if ($sure === null || $subtract === null) {
323: continue;
324: }
325:
326: $pureSure = false;
327: $pureSureNot = false;
328: }
329:
330: if ($pureSure) {
331: $sureTypeUnion[$exprString] = [$exprNode, TypeCombinator::union(...$sures)];
332: } elseif ($pureSureNot) {
333: $merged = TypeCombinator::intersect(...$subtracts);
334: if ($merged instanceof NeverType) {
335: // removing never removes nothing - a vacuous constraint
336: continue;
337: }
338: $sureNotTypeUnion[$exprString] = [$exprNode, $merged];
339: } else {
340: $alternativeUnion[$exprString] = [$exprNode, $terms];
341: }
342: }
343:
344: $result = new self($sureTypeUnion, $sureNotTypeUnion);
345: $result->alternativeTypes = $alternativeUnion;
346: if ($this->overwrite && $other->overwrite) {
347: $result = $result->setAlwaysOverwriteTypes();
348: }
349: if ($this->equality || $other->equality) {
350: $result->equality = true;
351: }
352:
353: return $result->setRootExpr($rootExpr);
354: }
355:
356: /**
357: * This side's constraint on the expression as alternative-form terms, or
358: * null when unconstrained. A sure and a sure-not on the same key are one
359: * term (the sure with the sure-not removed) - both constraints hold here.
360: *
361: * @return list<array{?Type, ?Type}>|null
362: */
363: private function collectTerms(string|int $exprString): ?array
364: {
365: if (isset($this->alternativeTypes[$exprString])) {
366: $terms = $this->alternativeTypes[$exprString][1];
367: // sure/sureNot on the same key as an alternative entry: fold them
368: // into every term (they hold in addition to the alternatives)
369: if (isset($this->sureTypes[$exprString]) || isset($this->sureNotTypes[$exprString])) {
370: $extraSure = $this->sureTypes[$exprString][1] ?? null;
371: $extraSubtract = $this->sureNotTypes[$exprString][1] ?? null;
372: $folded = [];
373: foreach ($terms as [$sure, $subtract]) {
374: if ($extraSure !== null) {
375: $sure = $sure === null ? $extraSure : TypeCombinator::intersect($sure, $extraSure);
376: }
377: if ($extraSubtract !== null) {
378: $subtract = $subtract === null ? $extraSubtract : TypeCombinator::union($subtract, $extraSubtract);
379: }
380: $folded[] = [$sure, $subtract];
381: }
382:
383: return $folded;
384: }
385:
386: return $terms;
387: }
388:
389: $sure = $this->sureTypes[$exprString][1] ?? null;
390: $subtract = $this->sureNotTypes[$exprString][1] ?? null;
391: if ($sure === null && $subtract === null) {
392: return null;
393: }
394:
395: return [[$sure, $subtract]];
396: }
397:
398: /**
399: * The both-sides-hold merge of two alternative forms. An entry's value is
400: * the union of its terms, so conjoining two entries distributes over both
401: * lists: every pair of terms contributes `(sureA and sureB) minus (subtractA
402: * or subtractB)`, the same folding collectTerms() does for a sure/sure-not
403: * pair. Pairs whose sure types cannot hold together drop out.
404: *
405: * @param list<array{?Type, ?Type}> $terms
406: * @param list<array{?Type, ?Type}> $otherTerms
407: * @return list<array{?Type, ?Type}>
408: */
409: private static function conjoinTerms(array $terms, array $otherTerms): array
410: {
411: $conjoined = [];
412: foreach ($terms as [$sure, $subtract]) {
413: foreach ($otherTerms as [$otherSure, $otherSubtract]) {
414: if ($sure === null) {
415: $mergedSure = $otherSure;
416: } elseif ($otherSure === null) {
417: $mergedSure = $sure;
418: } else {
419: $mergedSure = TypeCombinator::intersect($sure, $otherSure);
420: }
421:
422: if ($subtract === null) {
423: $mergedSubtract = $otherSubtract;
424: } elseif ($otherSubtract === null) {
425: $mergedSubtract = $subtract;
426: } else {
427: $mergedSubtract = TypeCombinator::union($subtract, $otherSubtract);
428: }
429:
430: if ($mergedSure !== null) {
431: if ($mergedSubtract !== null) {
432: // a fixed base with a subtraction is just the narrower base -
433: // folding it keeps the term list free of redundant pairs
434: $mergedSure = TypeCombinator::remove($mergedSure, $mergedSubtract);
435: $mergedSubtract = null;
436: }
437: if ($mergedSure instanceof NeverType) {
438: continue;
439: }
440: }
441:
442: $conjoined[] = [$mergedSure, $mergedSubtract];
443: }
444: }
445:
446: if ($conjoined === []) {
447: // every pair was impossible - so is the conjunction
448: return [[new NeverType(), null]];
449: }
450:
451: $conjoined = self::dedupeTerms($conjoined);
452: if (count($conjoined) > self::ALTERNATIVE_TERMS_LIMIT) {
453: return [self::widenTerms($conjoined)];
454: }
455:
456: return $conjoined;
457: }
458:
459: /**
460: * @param list<array{?Type, ?Type}> $terms
461: * @return list<array{?Type, ?Type}>
462: */
463: private static function dedupeTerms(array $terms): array
464: {
465: $deduped = [];
466: foreach ($terms as [$sure, $subtract]) {
467: foreach ($deduped as [$seenSure, $seenSubtract]) {
468: if (($sure === null) !== ($seenSure === null)) {
469: continue;
470: }
471: if (($subtract === null) !== ($seenSubtract === null)) {
472: continue;
473: }
474: if ($sure !== null && $seenSure !== null && !$sure->equals($seenSure)) {
475: continue;
476: }
477: if ($subtract !== null && $seenSubtract !== null && !$subtract->equals($seenSubtract)) {
478: continue;
479: }
480:
481: continue 2;
482: }
483:
484: $deduped[] = [$sure, $subtract];
485: }
486:
487: return $deduped;
488: }
489:
490: /**
491: * A single term covering the union of all of them - the safety net that
492: * stops a chain of conjoined alternative forms from growing its
493: * cross-product without bound. Widening a narrowing only loses precision.
494: *
495: * @param non-empty-list<array{?Type, ?Type}> $terms
496: * @return array{?Type, ?Type}
497: */
498: private static function widenTerms(array $terms): array
499: {
500: $sures = [];
501: $subtracts = [];
502: foreach ($terms as [$sure, $subtract]) {
503: if ($sure === null) {
504: // null reads as the subject's type at the application point,
505: // which every term is narrowed to anyway
506: $sures = null;
507: } elseif ($sures !== null) {
508: $sures[] = $sure;
509: }
510:
511: if ($subtract === null) {
512: $subtracts = null;
513: } elseif ($subtracts !== null) {
514: $subtracts[] = $subtract;
515: }
516: }
517:
518: return [
519: $sures === null ? null : TypeCombinator::union(...$sures),
520: $subtracts === null ? null : TypeCombinator::intersect(...$subtracts),
521: ];
522: }
523:
524: /** @api */
525: public function unionWith(SpecifiedTypes $other): self
526: {
527: $sureTypeUnion = $this->sureTypes + $other->sureTypes;
528: $sureNotTypeUnion = $this->sureNotTypes + $other->sureNotTypes;
529: $rootExpr = $this->mergeRootExpr($this->rootExpr, $other->rootExpr);
530:
531: foreach ($this->sureTypes as $exprString => [$exprNode, $type]) {
532: if (!isset($other->sureTypes[$exprString])) {
533: continue;
534: }
535:
536: $sureTypeUnion[$exprString] = [
537: $exprNode,
538: TypeCombinator::intersect($type, $other->sureTypes[$exprString][1]),
539: ];
540: }
541:
542: foreach ($this->sureNotTypes as $exprString => [$exprNode, $type]) {
543: if (!isset($other->sureNotTypes[$exprString])) {
544: continue;
545: }
546:
547: $sureNotTypeUnion[$exprString] = [
548: $exprNode,
549: TypeCombinator::union($type, $other->sureNotTypes[$exprString][1]),
550: ];
551: }
552:
553: $result = new self($sureTypeUnion, $sureNotTypeUnion);
554: $alternativeUnion = $this->alternativeTypes;
555: foreach ($other->alternativeTypes as $exprString => [$exprNode, $otherTerms]) {
556: if (!isset($alternativeUnion[$exprString])) {
557: $alternativeUnion[$exprString] = [$exprNode, $otherTerms];
558: continue;
559: }
560:
561: $alternativeUnion[$exprString] = [
562: $alternativeUnion[$exprString][0],
563: self::conjoinTerms($alternativeUnion[$exprString][1], $otherTerms),
564: ];
565: }
566:
567: $result->alternativeTypes = $alternativeUnion;
568: if ($this->overwrite || $other->overwrite) {
569: $result = $result->setAlwaysOverwriteTypes();
570: }
571: if ($this->equality || $other->equality) {
572: $result->equality = true;
573: }
574:
575: $conditionalExpressionHolders = $this->newConditionalExpressionHolders;
576: foreach ($other->newConditionalExpressionHolders as $exprString => $holders) {
577: if (!array_key_exists($exprString, $conditionalExpressionHolders)) {
578: $conditionalExpressionHolders[$exprString] = $holders;
579: } else {
580: $conditionalExpressionHolders[$exprString] = array_merge($conditionalExpressionHolders[$exprString], $holders);
581: }
582: }
583: $result->newConditionalExpressionHolders = $conditionalExpressionHolders;
584: $result->conditionalExpressionHolderRecipes = array_merge($this->conditionalExpressionHolderRecipes, $other->conditionalExpressionHolderRecipes);
585: $result->deferredAugments = array_merge($this->deferredAugments, $other->deferredAugments);
586:
587: return $result->setRootExpr($rootExpr);
588: }
589:
590: private function mergeRootExpr(?Expr $rootExprA, ?Expr $rootExprB): ?Expr
591: {
592: if ($rootExprA === $rootExprB) {
593: return $rootExprA;
594: }
595:
596: if ($rootExprA === null || $rootExprB === null) {
597: return $rootExprA ?? $rootExprB;
598: }
599:
600: return null;
601: }
602:
603: }
604: