1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type;
4:
5: use PHPStan\Php\PhpVersion;
6: use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
7: use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
8: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
9: use PHPStan\ShouldNotHappenException;
10: use PHPStan\TrinaryLogic;
11: use PHPStan\Turbo\ReferencedByTurboExtension;
12: use PHPStan\Type\Generic\TemplateTypeMap;
13: use PHPStan\Type\Generic\TemplateTypeVariance;
14: use PHPStan\Type\Traits\DelegatingTypeTrait;
15: use function array_key_exists;
16: use function array_pop;
17: use function count;
18: use function in_array;
19: use function spl_object_id;
20: use function sprintf;
21: use const PHP_INT_MAX;
22:
23: /**
24: * A type that contains itself, like `@phpstan-type Selection = array<string, true|Selection>`
25: * or `__recursive<array<string, true|__recursion>>` in a stub.
26: *
27: * The body holds a RecursiveTypeReference wherever the type contains itself. The methods
28: * that answer questions about the values of the type ask the body with those references
29: * replaced by this type, which is one level deeper and contains this type, never more.
30: * describe(), equals(), traverse() and the other methods that walk the structure of a
31: * type stay on the body, so they end at the references.
32: *
33: * Comparing two recursive types with each other comes back to the same two types once
34: * their bodies are compared one level deeper. The comparison then assumes it holds,
35: * because nothing it has compared so far says otherwise.
36: *
37: * The id tells apart the references to nested recursive types. An alias uses its name
38: * in the declaring class, a `__recursive<…>` the depth of its nesting.
39: */
40: #[ReferencedByTurboExtension(key: 'recursiveType')]
41: final class RecursiveType implements CompoundType
42: {
43:
44: use DelegatingTypeTrait;
45:
46: /**
47: * The comparisons being computed, by the operation and this type: the other types.
48: * They are matched by equals(), because code between two levels of the same
49: * comparison often builds the other type anew, like a union of what is left.
50: *
51: * @var array<string, list<array{Type, int}>>
52: */
53: private static array $assumptions = [];
54:
55: private static int $depth = 0;
56:
57: /** The depth of the outermost assumption the current comparison relied on. */
58: private static int $shallowestAssumptionUsed = PHP_INT_MAX;
59:
60: /**
61: * The comparisons finished during the outermost one, so that the paths through
62: * a type that meet the same pair again do not compute it again, which would take
63: * time exponential in how often the types nest each other.
64: *
65: * @var array<string, mixed>
66: */
67: private static array $finished = [];
68:
69: /**
70: * The recursive types whose bodies describe() or toPhpDocNode() is in, innermost last,
71: * so that a reference in them tells which one it refers to, like `__recursion<2>`.
72: *
73: * @var list<self>
74: */
75: private static array $describing = [];
76:
77: /** How many create() calls the current one is in, for the ids of their references. */
78: private static int $creating = 0;
79:
80: private ?Type $unfolded = null;
81:
82: private bool $unfolding = false;
83:
84: public function __construct(
85: private Type $body,
86: private string $id,
87: private ?string $name,
88: )
89: {
90: // the bound references answer like this type while the body is rebuilt with them
91: $this->body = self::bindReferences($body, $id, $this);
92: $this->unfolded = null;
93: }
94:
95: /**
96: * A body contains its references only below an array, an iterable, a generic object,
97: * a shape or a callable, because a union or an intersection of the type with something
98: * else, like `A = A|int`, would not be anything.
99: */
100: public static function isGuarded(Type $body, string $id): bool
101: {
102: $guarded = true;
103: TypeTraverser::map($body, static function (Type $type, callable $traverse) use ($id, &$guarded): Type {
104: if (!$guarded) {
105: return $type;
106: }
107:
108: if ($type instanceof RecursiveTypeReference) {
109: if ($type->getId() === $id) {
110: $guarded = false;
111: }
112:
113: return $type;
114: }
115:
116: if ($type instanceof UnionType || $type instanceof IntersectionType || $type instanceof LateResolvableType) {
117: return $traverse($type);
118: }
119:
120: return $type;
121: });
122:
123: return $guarded;
124: }
125:
126: /**
127: * Whether the type contains a reference no recursive type in it binds, like the
128: * body of an alias that is being resolved.
129: *
130: * @param string|null $id only the references with this id
131: */
132: public static function hasFreeReferences(Type $type, ?string $id = null): bool
133: {
134: $bound = [];
135: $found = false;
136: // a type outside every recursive type that has no free references has none anywhere,
137: // so a type repeated in many places, like an alias in many offsets of a shape, is walked once;
138: // the types are kept so that their ids are not reused during the walk
139: $clean = [];
140: TypeTraverser::map($type, static function (Type $type, callable $traverse) use ($id, &$bound, &$found, &$clean): Type {
141: $objectId = spl_object_id($type);
142: if (isset($clean[$objectId])) {
143: return $type;
144: }
145:
146: if ($type instanceof RecursiveTypeReference) {
147: $referenceId = $type->getId();
148: if (($id === null || $referenceId === $id) && !array_key_exists($referenceId, $bound)) {
149: $found = true;
150: }
151:
152: return $type;
153: }
154:
155: if ($type instanceof self) {
156: $typeId = $type->id;
157: if (array_key_exists($typeId, $bound)) {
158: // a nested recursive type with the same id binds its own references
159: return $type;
160: }
161:
162: $bound[$typeId] = true;
163: $traverse($type);
164: unset($bound[$typeId]);
165: } else {
166: $traverse($type);
167: }
168:
169: if (!$found && $bound === []) {
170: $clean[$objectId] = $type;
171: }
172:
173: return $type;
174: });
175:
176: return $found;
177: }
178:
179: /**
180: * The type of a value a loop nests in itself on every pass, like `$node = ['next' => $node]`:
181: * where $next holds $previous, it holds itself instead, if that is below an array or another
182: * type that is not a union, and the type that contains itself holds both of them.
183: */
184: public static function fromRepetition(Type $previous, Type $next): ?self
185: {
186: // an empty array or a scalar below the next value, like the `[]` of `$runs[] = [0, 0, []]`
187: // after `$runs = []`, is a value of its own, not the previous one nested in it
188: if (!$previous->isIterableAtLeastOnce()->yes()) {
189: return null;
190: }
191:
192: $id = self::freeId($next);
193: $reference = new RecursiveTypeReference($id, null);
194: $found = false;
195: $body = self::mapNested($next, static function (Type $type) use ($previous, $reference, &$found): ?Type {
196: if (!$type->equals($previous)) {
197: return null;
198: }
199:
200: $found = true;
201: return $reference;
202: });
203:
204: return $found ? self::holdingBoth($body, $id, $previous, $next) : null;
205: }
206:
207: /**
208: * The type of a value nested loops nest in itself, each loop in its own shape, like
209: * `$x = [$x]` in three loops: a shape below another one, with the keys of a shape
210: * the value is at the top, is the whole value there. Unlike fromRepetition(), this
211: * holds the value of every pass of every loop, so the loops meet at a fixpoint.
212: */
213: public static function fromNestedShapes(Type $previous, Type $next): ?self
214: {
215: // the loops nest the value of the pass before, not only shapes with the same keys
216: // like the pairs a list collects
217: $previousMembers = $previous instanceof UnionType ? $previous->getTypes() : [$previous];
218: $nestsPrevious = false;
219: self::mapNested($next, static function (Type $type) use ($previousMembers, &$nestsPrevious): ?Type {
220: if (!$type instanceof self && !$type->isConstantArray()->yes()) {
221: return null;
222: }
223: foreach ($previousMembers as $previousMember) {
224: // an empty array is where every nesting ends, not a sign of one
225: if (!$previousMember->isIterableAtLeastOnce()->yes() || !$type->isSuperTypeOf($previousMember)->yes()) {
226: continue;
227: }
228:
229: $nestsPrevious = true;
230: }
231:
232: return null;
233: });
234: if (!$nestsPrevious) {
235: return null;
236: }
237:
238: $id = self::freeId($next);
239: $union = TypeCombinator::union($previous, $next);
240: $members = [];
241: foreach ($union instanceof UnionType ? $union->getTypes() : [$union] as $member) {
242: // what an earlier pass folded is its shapes at the top, which hold it again below
243: if ($member instanceof self) {
244: $unfolded = $member->unfold();
245: foreach ($unfolded instanceof UnionType ? $unfolded->getTypes() : [$unfolded] as $unfoldedMember) {
246: $members[] = $unfoldedMember;
247: }
248: continue;
249: }
250: $members[] = $member;
251: }
252: $keySets = [];
253: foreach ($members as $member) {
254: $keySet = NestedShapeFolder::getKeySet($member);
255: if ($keySet === null) {
256: // a general array is what the shapes were widened to, which they would not hold
257: if ($member->isArray()->yes()) {
258: return null;
259: }
260: continue;
261: }
262: $keySets[$keySet] = true;
263: }
264: if ($keySets === []) {
265: return null;
266: }
267:
268: $folder = new NestedShapeFolder($keySets);
269: foreach ($members as $member) {
270: $folder->collectNestingKeys($member);
271: }
272:
273: // the shapes below are in the body too, because the reference stands for them
274: foreach ($members as $member) {
275: foreach ($folder->getNestedShapes($member) as $shape) {
276: if (in_array($shape, $members, true)) {
277: continue;
278: }
279: $members[] = $shape;
280: }
281: }
282:
283: $reference = new RecursiveTypeReference($id, null);
284: $found = false;
285: $body = self::mapNested(count($members) === 1 ? $members[0] : new UnionType($members), static function (Type $type) use ($folder, $reference, &$found): ?Type {
286: if (!$folder->folds($type)) {
287: return null;
288: }
289:
290: $found = true;
291: // the values where the shapes end, like 0 in `array{array{0}}`, are still there
292: return TypeCombinator::union($reference, ...$folder->getEnds($type));
293: });
294:
295: return $found ? self::holdingBoth($body, $id, $previous, $next) : null;
296: }
297:
298: /** An id no recursive type in the type has, which would bind the new references. */
299: private static function freeId(Type $type): string
300: {
301: $ids = [];
302: TypeTraverser::map($type, static function (Type $type, callable $traverse) use (&$ids): Type {
303: if ($type instanceof self) {
304: $ids[$type->id] = true;
305: }
306:
307: return $traverse($type);
308: });
309: $i = 1;
310: while (array_key_exists('~' . $i, $ids)) {
311: $i++;
312: }
313:
314: return '~' . $i;
315: }
316:
317: /**
318: * The type with the parts below an array or another type that is not a union replaced
319: * where $replace returns a type; the members of a union at the top stay.
320: *
321: * @param callable(Type): ?Type $replace
322: */
323: private static function mapNested(Type $type, callable $replace, bool $nested = false): Type
324: {
325: return TypeTraverser::map($type, static function (Type $type, callable $traverse) use ($replace, $nested): Type {
326: if ($type instanceof UnionType || $type instanceof IntersectionType) {
327: return $traverse($type);
328: }
329:
330: if (!$nested) {
331: return $type->traverse(static fn (Type $inner): Type => self::mapNested($inner, $replace, true));
332: }
333:
334: return $replace($type) ?? $traverse($type);
335: });
336: }
337:
338: private static function holdingBoth(Type $body, string $id, Type $previous, Type $next): ?self
339: {
340: if (!self::isGuarded($body, $id)) {
341: return null;
342: }
343:
344: $recursiveType = new self($body, $id, null);
345: if (!$recursiveType->isSuperTypeOf($previous)->yes() || !$recursiveType->isSuperTypeOf($next)->yes()) {
346: return null;
347: }
348:
349: return $recursiveType;
350: }
351:
352: private static function bindReferences(Type $body, string $id, self $binder): Type
353: {
354: return TypeTraverser::map($body, static function (Type $type, callable $traverse) use ($id, $binder): Type {
355: if ($type instanceof RecursiveTypeReference) {
356: if ($type->getId() !== $id) {
357: return $type;
358: }
359:
360: return $type->bindTo($binder);
361: }
362:
363: if ($type instanceof self && $type->id === $id) {
364: return $type;
365: }
366:
367: return $traverse($type);
368: });
369: }
370:
371: public function getBody(): Type
372: {
373: return $this->body;
374: }
375:
376: /**
377: * One level deeper: the body with this type in place of its references, so that
378: * what a question takes out of the body, like the value of an offset, is this type
379: * and not a reference. While that is being built, the body answers instead, because
380: * its references are bound to this type and answer like it.
381: */
382: public function unfold(): Type
383: {
384: if ($this->unfolded !== null) {
385: return $this->unfolded;
386: }
387: if ($this->unfolding) {
388: return $this->body;
389: }
390:
391: $this->unfolding = true;
392: try {
393: return $this->unfolded = TypeTraverser::map($this->body, function (Type $type, callable $traverse): Type {
394: if ($type instanceof RecursiveTypeReference) {
395: return $type->getBinder() === $this ? $this : $type;
396: }
397:
398: return $traverse($type);
399: });
400: } finally {
401: $this->unfolding = false;
402: }
403: }
404:
405: protected function getDelegate(): Type
406: {
407: return $this->unfold();
408: }
409:
410: /**
411: * @template T
412: * @param callable(): T $compute
413: * @param T $assumed
414: * @return T
415: */
416: private function assuming(string $operation, Type $other, callable $compute, $assumed)
417: {
418: $key = sprintf('%s:%d:%d', $operation, spl_object_id($this), spl_object_id($other));
419: if (array_key_exists($key, self::$finished)) {
420: return self::$finished[$key];
421: }
422:
423: $assumptionsKey = sprintf('%s:%d', $operation, spl_object_id($this));
424: foreach (self::$assumptions[$assumptionsKey] ?? [] as [$assumedOther, $assumedDepth]) {
425: if ($assumedOther !== $other && !$assumedOther->equals($other)) {
426: continue;
427: }
428:
429: if ($assumedDepth < self::$shallowestAssumptionUsed) {
430: self::$shallowestAssumptionUsed = $assumedDepth;
431: }
432: return $assumed;
433: }
434:
435: $outermost = self::$assumptions === [];
436: $depth = ++self::$depth;
437: $shallowestAssumptionUsedOutside = self::$shallowestAssumptionUsed;
438: self::$shallowestAssumptionUsed = PHP_INT_MAX;
439: self::$assumptions[$assumptionsKey][] = [$other, $depth];
440: try {
441: $result = $compute();
442: // a result that relied on an assumption made further out holds only
443: // if that assumption does, which is not known until it finishes
444: if (self::$shallowestAssumptionUsed >= $depth) {
445: self::$finished[$key] = $result;
446: }
447:
448: return $result;
449: } finally {
450: self::$depth--;
451: if (self::$shallowestAssumptionUsed >= $depth) {
452: self::$shallowestAssumptionUsed = $shallowestAssumptionUsedOutside;
453: } elseif ($shallowestAssumptionUsedOutside < self::$shallowestAssumptionUsed) {
454: self::$shallowestAssumptionUsed = $shallowestAssumptionUsedOutside;
455: }
456: array_pop(self::$assumptions[$assumptionsKey]);
457: if (self::$assumptions[$assumptionsKey] === []) {
458: unset(self::$assumptions[$assumptionsKey]);
459: }
460: // object ids are reused once the objects are freed, so the results
461: // are only remembered while the outermost comparison runs
462: if ($outermost) {
463: self::$finished = [];
464: }
465: }
466: }
467:
468: private static function unfoldOther(Type $type): Type
469: {
470: if ($type instanceof RecursiveTypeReference) {
471: $type = $type->getBinder() ?? $type;
472: }
473:
474: if ($type instanceof self) {
475: return $type->unfold();
476: }
477:
478: return $type;
479: }
480:
481: public function isSuperTypeOf(Type $type): IsSuperTypeOfResult
482: {
483: return $this->assuming(
484: 'isSuperTypeOf',
485: $type,
486: fn (): IsSuperTypeOfResult => $this->unfold()->isSuperTypeOf(self::unfoldOther($type)),
487: IsSuperTypeOfResult::createYes(),
488: );
489: }
490:
491: public function isSubTypeOf(Type $otherType): IsSuperTypeOfResult
492: {
493: return $this->assuming(
494: 'isSubTypeOf',
495: $otherType,
496: fn (): IsSuperTypeOfResult => $otherType->isSuperTypeOf($this->unfold()),
497: IsSuperTypeOfResult::createYes(),
498: );
499: }
500:
501: public function accepts(Type $type, bool $strictTypes): AcceptsResult
502: {
503: return $this->assuming(
504: $strictTypes ? 'accepts:strict' : 'accepts',
505: $type,
506: fn (): AcceptsResult => $this->unfold()->accepts(self::unfoldOther($type), $strictTypes),
507: AcceptsResult::createYes(),
508: );
509: }
510:
511: public function isAcceptedBy(Type $acceptingType, bool $strictTypes): AcceptsResult
512: {
513: return $this->assuming(
514: $strictTypes ? 'isAcceptedBy:strict' : 'isAcceptedBy',
515: $acceptingType,
516: fn (): AcceptsResult => $acceptingType->accepts($this->unfold(), $strictTypes),
517: AcceptsResult::createYes(),
518: );
519: }
520:
521: public function isGreaterThan(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
522: {
523: return $this->assuming(
524: 'isGreaterThan',
525: $otherType,
526: fn (): TrinaryLogic => $otherType->isSmallerThan($this->unfold(), $phpVersion),
527: TrinaryLogic::createMaybe(),
528: );
529: }
530:
531: public function isGreaterThanOrEqual(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
532: {
533: return $this->assuming(
534: 'isGreaterThanOrEqual',
535: $otherType,
536: fn (): TrinaryLogic => $otherType->isSmallerThanOrEqual($this->unfold(), $phpVersion),
537: TrinaryLogic::createMaybe(),
538: );
539: }
540:
541: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
542: {
543: return $this->assuming(
544: 'inferTemplateTypes',
545: $receivedType,
546: fn (): TemplateTypeMap => $this->unfold()->inferTemplateTypes(self::unfoldOther($receivedType)),
547: TemplateTypeMap::createEmpty(),
548: );
549: }
550:
551: public function equals(Type $type): bool
552: {
553: if ($type === $this) {
554: return true;
555: }
556:
557: if (!$type instanceof self || $type->id !== $this->id) {
558: return false;
559: }
560:
561: return $this->assuming(
562: 'equals',
563: $type,
564: fn (): bool => $this->body->equals($type->body),
565: true,
566: );
567: }
568:
569: public function describe(VerbosityLevel $level): string
570: {
571: if ($this->name !== null) {
572: return $this->body->describe($level);
573: }
574:
575: // error messages show only where the type repeats, like var_dump() and print_r() do,
576: // a precise description and the cache keys which part repeats
577: return $level->handle(
578: fn (): string => $this->body->describe($level),
579: fn (): string => $this->body->describe($level),
580: fn (): string => sprintf('__recursive<%s>', $this->inBody(fn (): string => $this->body->describe($level))),
581: fn (): string => sprintf('__recursive<%s>', $this->inBody(fn (): string => $this->body->describe($level))),
582: );
583: }
584:
585: /**
586: * @template T
587: * @param callable(): T $callback
588: * @return T
589: */
590: private function inBody(callable $callback)
591: {
592: self::$describing[] = $this;
593: try {
594: return $callback();
595: } finally {
596: array_pop(self::$describing);
597: }
598: }
599:
600: /**
601: * Which recursive type around the body being described the reference refers to:
602: * 1 for the innermost one, written `__recursion`, 2 for the one around that one,
603: * written `__recursion<2>`, or null when it is described outside of the type.
604: */
605: public static function getReferenceLevel(self $binder): ?int
606: {
607: $level = 0;
608: for ($i = count(self::$describing) - 1; $i >= 0; $i--) {
609: $level++;
610: if (self::$describing[$i] === $binder) {
611: return $level;
612: }
613: }
614:
615: return null;
616: }
617:
618: /**
619: * Builds a type that contains itself: $build gets the type and returns its body, which
620: * has to contain the type below an array, an iterable, a generic object, a shape or a callable.
621: *
622: * RecursiveType::create(static fn (Type $self): Type => new ArrayType(new StringType(), TypeCombinator::union(new StringType(), $self)))
623: * is `array<string, string|array<string, string|…>>`, written `__recursive<array<string, string|__recursion>>` in stubs.
624: *
625: * @api
626: * @param callable(Type): Type $build
627: */
628: public static function create(callable $build): Type
629: {
630: self::$creating++;
631: // the same for every type built at this depth, so that they are equal when their bodies are
632: $id = '^' . self::$creating;
633: try {
634: $body = $build(new RecursiveTypeReference($id, null));
635: } finally {
636: self::$creating--;
637: }
638:
639: if (!self::hasFreeReferences($body, $id)) {
640: return $body;
641: }
642:
643: if (!self::isGuarded($body, $id)) {
644: throw new ShouldNotHappenException('The body of a recursive type contains it only next to something else, like `A = A|int`, so it is not anything.');
645: }
646:
647: return new self($body, $id, null);
648: }
649:
650: public function getReferencedClasses(): array
651: {
652: return $this->body->getReferencedClasses();
653: }
654:
655: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
656: {
657: return $this->body->getReferencedTemplateTypes($positionVariance);
658: }
659:
660: public function hasTemplateOrLateResolvableType(): bool
661: {
662: return $this->body->hasTemplateOrLateResolvableType();
663: }
664:
665: public function hasUnresolvedTemplateArgumentType(): bool
666: {
667: return $this->body->hasUnresolvedTemplateArgumentType();
668: }
669:
670: /** A type that contains itself has infinitely many values. */
671: public function getFiniteTypes(): array
672: {
673: return [];
674: }
675:
676: public function generalize(GeneralizePrecision $precision): Type
677: {
678: return $this->withBody($this->body->generalize($precision));
679: }
680:
681: /**
682: * @param callable(Type): Type $cb
683: */
684: public function traverse(callable $cb): Type
685: {
686: return $this->withBody($cb($this->body));
687: }
688:
689: public function traverseSimultaneously(Type $right, callable $cb): Type
690: {
691: if (!$right instanceof self) {
692: return $this;
693: }
694:
695: return $this->withBody($cb($this->body, $right->body));
696: }
697:
698: private function withBody(Type $body): Type
699: {
700: if ($body === $this->body) {
701: return $this;
702: }
703:
704: if (!self::hasFreeReferences($body, $this->id)) {
705: return $body;
706: }
707:
708: return new self($body, $this->id, $this->name);
709: }
710:
711: public function toPhpDocNode(): TypeNode
712: {
713: return new GenericTypeNode(new IdentifierTypeNode('__recursive'), [$this->inBody(fn (): TypeNode => $this->body->toPhpDocNode())]);
714: }
715:
716: }
717: