1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type;
4:
5: use PHPStan\DependencyInjection\BleedingEdgeToggle;
6: use PHPStan\Turbo\ReferencedByTurboExtension;
7: use PHPStan\Turbo\TurboExtensionEnabler;
8: use PHPStan\Type\Accessory\AccessoryType;
9: use PHPStan\Type\Combinator\AbsorbedArrayUnionRule;
10: use PHPStan\Type\Combinator\ArrayWidening;
11: use PHPStan\Type\Combinator\AtOnceUnionRemoveRule;
12: use PHPStan\Type\Combinator\BooleanUnionRule;
13: use PHPStan\Type\Combinator\DisjointFiniteUnionRemoveRule;
14: use PHPStan\Type\Combinator\DuplicateIntersectRule;
15: use PHPStan\Type\Combinator\ExactIntersectRule;
16: use PHPStan\Type\Combinator\FiniteTypesRemoveRule;
17: use PHPStan\Type\Combinator\FoldedShapeUnionRule;
18: use PHPStan\Type\Combinator\GeneralArrayUnionRule;
19: use PHPStan\Type\Combinator\IntegerUnionRemoveRule;
20: use PHPStan\Type\Combinator\IntersectRule;
21: use PHPStan\Type\Combinator\IterableUnionRule;
22: use PHPStan\Type\Combinator\MergedGeneralArrayUnionRule;
23: use PHPStan\Type\Combinator\MixedUnionRemoveRule;
24: use PHPStan\Type\Combinator\NumberUnionRule;
25: use PHPStan\Type\Combinator\OffsetValueLimitIntersectRule;
26: use PHPStan\Type\Combinator\OverlappingArrayUnionRule;
27: use PHPStan\Type\Combinator\PeelUnionRemoveRule;
28: use PHPStan\Type\Combinator\RemoveRule;
29: use PHPStan\Type\Combinator\ShapeRemoveRule;
30: use PHPStan\Type\Combinator\ShapeUnionRule;
31: use PHPStan\Type\Combinator\SingleValueUnionRule;
32: use PHPStan\Type\Combinator\StringUnionRule;
33: use PHPStan\Type\Combinator\SubsumptionIntersectRule;
34: use PHPStan\Type\Combinator\SubsumptionRemoveRule;
35: use PHPStan\Type\Combinator\SubsumptionUnionRule;
36: use PHPStan\Type\Combinator\SubtractedMixedRemoveRule;
37: use PHPStan\Type\Combinator\TypeRemoveRule;
38: use PHPStan\Type\Combinator\UnionRemoveRule;
39: use PHPStan\Type\Combinator\UnionRule;
40: use PHPStan\Type\Constant\ConstantArrayType;
41: use PHPStan\Type\Generic\TemplateBenevolentUnionType;
42: use PHPStan\Type\Generic\TemplateMixedType;
43: use PHPStan\Type\Generic\TemplateType;
44: use PHPStan\Type\Generic\TemplateTypeFactory;
45: use PHPStan\Type\Generic\TemplateUnionType;
46: use PHPStan\Type\Generic\UnresolvedTemplateArgumentType;
47: use function array_key_exists;
48: use function array_push;
49: use function array_slice;
50: use function array_values;
51: use function count;
52: use function get_class;
53: use function is_float;
54: use function spl_object_id;
55: use function usort;
56:
57: /**
58: * @api
59: */
60: #[ReferencedByTurboExtension(key: 'typeCombinator')]
61: final class TypeCombinator
62: {
63:
64: /** @var array<int, list<UnionRule>> by whether bleeding edge is on */
65: private static array $unionRules = [];
66:
67: /** @var array<int, list<UnionRule>> by whether bleeding edge is on */
68: private static array $widenRules = [];
69:
70: /** @var list<IntersectRule>|null */
71: private static ?array $intersectRules = null;
72:
73: /** @var list<UnionRemoveRule>|null */
74: private static ?array $unionRemoveRules = null;
75:
76: /** @var list<RemoveRule>|null */
77: private static ?array $removeRules = null;
78:
79: /**
80: * Turned on by TurboExtensionEnabler when the native extension is active, so that
81: * union(), intersect() and remove() route through the memoizing TypeCombinatorCache.
82: * Without the extension the operations run exactly as they always have — the flag
83: * costs a property read, and nothing else changes.
84: */
85: private static ?bool $cacheEnabled = null;
86:
87: /**
88: * Memoization hands back shared Type instances, and a Type lazily resolves a
89: * ClassReflection belonging to the container that created it — so the cache must
90: * not outlive its container.
91: */
92: public static function clearCache(): void
93: {
94: if ((self::$cacheEnabled ??= TurboExtensionEnabler::isTypeCombinatorCacheEnabled()) === false) {
95: return;
96: }
97:
98: TypeCombinatorCache::clearCache();
99: }
100:
101: public static function addNull(Type $type): Type
102: {
103: // asking the type itself is both cheaper than NullType::isSuperTypeOf()
104: // (UnionType memoizes isNull(), isSubTypeOf() recomputes) and right for
105: // `never`, of which null is a supertype without never containing it.
106: if ($type->isNull()->no()) {
107: return self::union($type, new NullType());
108: }
109:
110: return $type;
111: }
112:
113: /**
114: * The rules remove() asks in order when it removes a union, the first
115: * answer winning: all members at once where the order of removals cannot
116: * matter, then one at a time.
117: *
118: * @return list<UnionRemoveRule>
119: */
120: private static function createUnionRemoveRules(): array
121: {
122: return [
123: new IntegerUnionRemoveRule(),
124: new AtOnceUnionRemoveRule(),
125: new MixedUnionRemoveRule(),
126: new DisjointFiniteUnionRemoveRule(),
127: new PeelUnionRemoveRule(),
128: ];
129: }
130:
131: /**
132: * The rules remove() asks in order when it removes any other type, the
133: * first answer winning.
134: *
135: * @return list<RemoveRule>
136: */
137: private static function createRemoveRules(): array
138: {
139: return [
140: new SubsumptionRemoveRule(),
141: new SubtractedMixedRemoveRule(),
142: new ShapeRemoveRule(),
143: new TypeRemoveRule(),
144: new FiniteTypesRemoveRule(),
145: ];
146: }
147:
148: public static function remove(Type $fromType, Type $typeToRemove): Type
149: {
150: if (self::$cacheEnabled ??= TurboExtensionEnabler::isTypeCombinatorCacheEnabled()) {
151: return TypeCombinatorCache::remove($fromType, $typeToRemove);
152: }
153:
154: return self::doRemove($fromType, $typeToRemove);
155: }
156:
157: /** @internal Delegated to from TypeCombinatorCache, which the native extension shadows to memoize it. */
158: public static function doRemove(Type $fromType, Type $typeToRemove): Type
159: {
160: if ($typeToRemove instanceof UnionType) {
161: foreach (self::$unionRemoveRules ??= self::createUnionRemoveRules() as $rule) {
162: $removed = $rule->tryRemove($fromType, $typeToRemove);
163: if ($removed !== null) {
164: return $removed;
165: }
166: }
167:
168: return $fromType;
169: }
170:
171: foreach (self::$removeRules ??= self::createRemoveRules() as $rule) {
172: $removed = $rule->tryRemove($fromType, $typeToRemove);
173: if ($removed !== null) {
174: return $removed;
175: }
176: }
177:
178: return $fromType;
179: }
180:
181: public static function removeNull(Type $type): Type
182: {
183: if (self::containsNull($type)) {
184: return self::remove($type, new NullType());
185: }
186:
187: return $type;
188: }
189:
190: public static function containsNull(Type $type): bool
191: {
192: if ($type instanceof UnionType) {
193: foreach ($type->getTypes() as $innerType) {
194: if ($innerType->isNull()->yes()) {
195: return true;
196: }
197: }
198:
199: return false;
200: }
201:
202: return $type instanceof NullType;
203: }
204:
205: /**
206: * The type, generalized where it holds more constant array values than
207: * ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT or more shapes than
208: * ArrayWidening::UNION_SHAPES_LIMIT: shapes with the same keys
209: * merged, shapes sharing a required key folded into one, and what is still
210: * too big degraded to an oversized array.
211: *
212: * union() is exact and never does this. Call it where the analysis joins
213: * values that can grow without bound, such as the types of a variable after
214: * branches, so a join stays small enough to compute with.
215: */
216: public static function widen(Type $type): Type
217: {
218: // no member is an array
219: if (($type->getKindMask() & TypeKind::ARRAY) === 0) {
220: return $type;
221: }
222:
223: $types = $type instanceof UnionType && !$type instanceof TemplateType ? $type->getTypes() : [$type];
224: $arrayTypes = [];
225: $otherTypes = [];
226: foreach ($types as $member) {
227: if ($member->isArray()->yes() && !$member instanceof LateResolvableType && !$member instanceof RecursiveType && !$member instanceof RecursiveTypeReference) {
228: $arrayTypes[] = $member;
229: continue;
230: }
231: $otherTypes[] = $member;
232: }
233: if ($arrayTypes === []) {
234: return $type;
235: }
236:
237: $bleedingEdge = BleedingEdgeToggle::isBleedingEdge();
238: if (
239: ArrayWidening::isWithinLimit($arrayTypes)
240: && (!$bleedingEdge || count(GeneralArrayUnionRule::getGeneralArrays($arrayTypes)) <= GeneralArrayUnionRule::GENERAL_ARRAYS_LIMIT)
241: ) {
242: return $type;
243: }
244:
245: $types = [...$otherTypes, ...$arrayTypes];
246: foreach (self::$widenRules[(int) $bleedingEdge] ??= self::createWidenRules($bleedingEdge) as $rule) {
247: $types = $rule->apply($types, []);
248: }
249:
250: $widened = self::union(...$types);
251: if ($type instanceof BenevolentUnionType) {
252: return TypeUtils::toBenevolentUnion($widened);
253: }
254:
255: return $widened;
256: }
257:
258: /**
259: * The rules union() runs, in this order: the scalars merge kind by kind,
260: * the arrays merge with each other, and then any member holding another
261: * takes its place. Without bleeding edge, every general array merges with
262: * the other arrays before the shapes merge among themselves.
263: *
264: * @return list<UnionRule>
265: */
266: private static function createUnionRules(bool $bleedingEdge): array
267: {
268: $arrayRules = $bleedingEdge
269: ? [new ShapeUnionRule(), new OverlappingArrayUnionRule()]
270: : [new MergedGeneralArrayUnionRule(), new ShapeUnionRule()];
271:
272: return [
273: new SingleValueUnionRule(),
274: new NumberUnionRule(),
275: new StringUnionRule(),
276: new BooleanUnionRule(),
277: new IterableUnionRule(),
278: new AbsorbedArrayUnionRule(),
279: ...$arrayRules,
280: new SubsumptionUnionRule(),
281: ];
282: }
283:
284: /**
285: * The rules widen() runs on the members before union() runs its own: they
286: * give up precision to keep big joins of arrays small. Without bleeding
287: * edge, every general array merges with the other arrays first.
288: *
289: * @return list<UnionRule>
290: */
291: private static function createWidenRules(bool $bleedingEdge): array
292: {
293: if (!$bleedingEdge) {
294: return [
295: new MergedGeneralArrayUnionRule(),
296: new FoldedShapeUnionRule(),
297: ];
298: }
299:
300: return [
301: new FoldedShapeUnionRule(),
302: new GeneralArrayUnionRule(),
303: ];
304: }
305:
306: public static function union(Type ...$types): Type
307: {
308: if (self::$cacheEnabled ??= TurboExtensionEnabler::isTypeCombinatorCacheEnabled()) {
309: return TypeCombinatorCache::union(...$types);
310: }
311:
312: return self::doUnion(...$types);
313: }
314:
315: /**
316: * The union of the values that different paths produce, as of the branches
317: * of a ternary or the scopes merged after an if. Unlike union(), a mixed
318: * result keeps the members it absorbed as its witness type: a path is known
319: * to produce them. Narrowing must not call this, as its unions are not paths.
320: */
321: public static function joinValues(Type ...$types): Type
322: {
323: $union = self::union(...$types);
324: if (!$union instanceof MixedType || !self::holdsWitnessType($union) || count($types) < 2) {
325: return $union;
326: }
327:
328: return self::witnessAbsorbedTypes($union, ...$types);
329: }
330:
331: /**
332: * joinValues() of values that a narrowing may have refined from another
333: * value, given at the same key in $narrowedFromTypes. A value narrowed from
334: * mixed is not one a path produces: it brings to the witness type only the
335: * part of that mixed's own witness it still allows.
336: *
337: * @param list<Type> $types
338: * @param list<Type|null> $narrowedFromTypes
339: */
340: public static function joinNarrowedValues(array $types, array $narrowedFromTypes): Type
341: {
342: $union = self::union(...$types);
343: if (!$union instanceof MixedType || !self::holdsWitnessType($union) || count($types) < 2) {
344: return $union;
345: }
346:
347: $witnessSources = [];
348: foreach ($types as $i => $type) {
349: $narrowedFrom = $narrowedFromTypes[$i] ?? null;
350: if ($narrowedFrom instanceof MixedType && self::holdsWitnessType($narrowedFrom)) {
351: $witnessType = $narrowedFrom->getWitnessType();
352: $type = new MixedType(witnessType: $witnessType !== null ? self::intersect($witnessType, $type) : null);
353: }
354: $witnessSources[] = $type;
355: }
356:
357: return self::witnessAbsorbedTypes($union, ...$witnessSources);
358: }
359:
360: /** A plain mixed or error keeps a witness type; a template or another mixed of its own kind does not. */
361: private static function holdsWitnessType(Type $type): bool
362: {
363: return get_class($type) === MixedType::class || get_class($type) === ErrorType::class;
364: }
365:
366: /**
367: * A mixed that absorbed other members keeps them as its witness type, so a
368: * path known to produce a value of the wrong type is still reported where
369: * mixed itself is accepted. A plain mixed member contributes its own witness.
370: *
371: * @internal The second half of joinValues(), also called by the native extension.
372: */
373: public static function witnessAbsorbedTypes(MixedType $union, Type ...$types): MixedType
374: {
375: if (!BleedingEdgeToggle::isBleedingEdge()) {
376: return $union;
377: }
378:
379: $witnessTypes = [];
380: foreach ($types as $type) {
381: $members = $type instanceof UnionType && !$type instanceof TemplateType && !$type instanceof BenevolentUnionType ? $type->getTypes() : [$type];
382: foreach ($members as $member) {
383: if ($member instanceof MixedType && self::holdsWitnessType($member)) {
384: $witnessType = $member->getWitnessType();
385: if ($witnessType !== null) {
386: $witnessTypes[] = $witnessType;
387: }
388: continue;
389: }
390:
391: if ($member instanceof MixedType || $member instanceof NeverType || $member instanceof UnresolvedTemplateArgumentType || $member instanceof AccessoryType) {
392: continue;
393: }
394:
395: $witnessTypes[] = $member;
396: }
397: }
398:
399: // a witness of a witness would grow with every loop iteration that wraps the value
400: $witnessType = $witnessTypes === [] ? null : TypeTraverser::map(
401: self::union(...$witnessTypes),
402: static function (Type $type, callable $traverse): Type {
403: if ($type instanceof MixedType && self::holdsWitnessType($type) && $type->getWitnessType() !== null) {
404: return $type->changeWitnessType(null);
405: }
406:
407: return $traverse($type);
408: },
409: );
410: if ($witnessType === $union->getWitnessType() || ($witnessType !== null && $union->getWitnessType() !== null && $witnessType->equals($union->getWitnessType()))) {
411: return $union;
412: }
413:
414: return $union->changeWitnessType($witnessType);
415: }
416:
417: /** @internal Delegated to from TypeCombinatorCache, which the native extension shadows to memoize it. */
418: public static function doUnion(Type ...$types): Type
419: {
420: $typesCount = count($types);
421: if ($typesCount === 0) {
422: return new NeverType();
423: }
424:
425: // Fast path for single non-union type
426: if ($typesCount === 1) {
427: $singleType = $types[0];
428: // a union is normalized already
429: if ($singleType instanceof UnionType || !$singleType->isArray()->yes()) {
430: return $singleType;
431: }
432: }
433:
434: // Fast path for common 2-type cases
435: if ($typesCount === 2) {
436: $a = $types[0];
437: $b = $types[1];
438:
439: // union(never, X) = X and union(X, never) = X
440: if ($a instanceof NeverType && !$a->isExplicit()) {
441: return $b;
442: }
443: if ($b instanceof NeverType && !$b->isExplicit()) {
444: return $a;
445: }
446:
447: // union(mixed, X) = mixed (non-explicit, non-template, no subtracted)
448: if ($a instanceof MixedType && !$a->isExplicitMixed() && !$a instanceof TemplateMixedType && $a->getSubtractedType() === null) {
449: return $a;
450: }
451: if ($b instanceof MixedType && !$b->isExplicitMixed() && !$b instanceof TemplateMixedType && $b->getSubtractedType() === null) {
452: return $b;
453: }
454:
455: // union(X, X) = X — for equal array operands, not just identical
456: // ones. For arrays the general path below is not a no-op on a pair
457: // that already denotes a single type: it rebuilds them from
458: // ArrayType::getIterableKeyType(), which coerces a subtracted key
459: // type down to the plain array-key union, so `array<mixed~'User',
460: // mixed>` unioned with an equal instance came back as plain
461: // `array`. Whether the two operands happen to be the same object
462: // must not decide the result.
463: //
464: // Equal non-array operands are not decided by equals(): it is weaker
465: // than interchangeability for some types - a benevolent
466: // `(int|string)` equals a plain `int|string` and `Foo=final` equals
467: // `Foo` - so they are left to findAbsorbingOperand() and the rules,
468: // which keep the wider operand rather than whichever one was passed first.
469: if ($a === $b || ($a->equals($b) && $a->isArray()->yes())) {
470: return $a;
471: }
472:
473: // union(A, B) = A when A holds B, as `float|int` holds `0`
474: $absorbing = self::findAbsorbingOperand($a, $b);
475: if ($absorbing !== null) {
476: return $absorbing;
477: }
478: }
479:
480: // A member passed more than once contributes nothing; dropping the
481: // repeats up front keeps the pairwise comparison below from paying for
482: // them (array_values() of a shape unions the same value type per slot).
483: if ($typesCount > 2) {
484: $seenTypes = [];
485: $uniqueTypes = [];
486: foreach ($types as $type) {
487: $typeId = spl_object_id($type);
488: if (isset($seenTypes[$typeId])) {
489: continue;
490: }
491: $seenTypes[$typeId] = true;
492: $uniqueTypes[] = $type;
493: }
494: if (count($uniqueTypes) === 1) {
495: return $uniqueTypes[0];
496: }
497: if (count($uniqueTypes) === 2) {
498: return self::union($uniqueTypes[0], $uniqueTypes[1]);
499: }
500: $types = $uniqueTypes;
501: }
502:
503: $alreadyNormalized = [];
504: $alreadyNormalizedCounter = 0;
505:
506: $benevolentTypes = [];
507: $neverCount = 0;
508: $markers = [];
509: // transform A | (B | C) to A | B | C - in one pass, a union's members are
510: // never unions, implicit never or implicit mixed themselves
511: $flattenedTypes = [];
512: foreach ($types as $type) {
513: if (
514: $type instanceof MixedType
515: && !$type->isExplicitMixed()
516: && !$type instanceof TemplateMixedType
517: && $type->getSubtractedType() === null
518: ) {
519: return $type;
520: }
521: if ($type instanceof UnresolvedTemplateArgumentType && !$type->isClosureSignature()) {
522: $markers = self::addMarker($markers, $type);
523: continue;
524: }
525: if ($type instanceof NeverType && !$type->isExplicit()) {
526: $neverCount++;
527: $flattenedTypes[] = $type;
528: continue;
529: }
530: if ($type instanceof BenevolentUnionType) {
531: if ($type instanceof TemplateType) {
532: $flattenedTypes[] = $type;
533: continue;
534: }
535: foreach ($type->getTypes() as $benevolentInnerType) {
536: $benevolentTypes[spl_object_id($benevolentInnerType)] = $benevolentInnerType;
537: $flattenedTypes[] = $benevolentInnerType;
538: }
539: continue;
540: }
541: if (!($type instanceof UnionType) || $type instanceof TemplateType) {
542: $flattenedTypes[] = $type;
543: continue;
544: }
545:
546: $typesInner = $type->getTypes();
547: $alreadyNormalized[$alreadyNormalizedCounter] = $typesInner;
548: $alreadyNormalizedCounter++;
549: foreach ($typesInner as $innerType) {
550: if ($innerType instanceof UnresolvedTemplateArgumentType && !$innerType->isClosureSignature()) {
551: $markers = self::addMarker($markers, $innerType);
552: continue;
553: }
554: $flattenedTypes[] = $innerType;
555: }
556: }
557: if ($markers !== []) {
558: return self::unionWithMarkers(self::union(...$flattenedTypes), $markers);
559: }
560: $types = $flattenedTypes;
561: $typesCount = count($types);
562:
563: // Bulk-remove implicit NeverTypes (skipped during the loop above)
564: if ($neverCount > 0) {
565: if ($neverCount === $typesCount) {
566: return new NeverType();
567: }
568:
569: $filtered = [];
570: for ($i = 0; $i < $typesCount; $i++) {
571: if ($types[$i] instanceof NeverType && !$types[$i]->isExplicit()) {
572: continue;
573: }
574: $filtered[] = $types[$i];
575: }
576: $types = $filtered;
577: $typesCount = count($types);
578:
579: if ($typesCount === 0) {
580: return new NeverType();
581: }
582: if ($typesCount === 1 && !$types[0]->isArray()->yes()) {
583: return $types[0];
584: }
585: if ($typesCount === 2) {
586: return self::union($types[0], $types[1]);
587: }
588: }
589:
590: if ($typesCount === 0) {
591: return new NeverType();
592: }
593:
594: if ($typesCount === 1 && !$types[0]->isArray()->yes()) {
595: return $types[0];
596: }
597:
598: // the kinds of the members, never - of no values - overlapping every kind,
599: // and of those that are not one constant scalar value
600: $kindMask = 0;
601: $nonConstantKindMask = 0;
602: foreach ($types as $type) {
603: $memberKindMask = $type->getKindMask();
604: if ($memberKindMask === 0) {
605: $memberKindMask = TypeKind::ALL;
606: }
607: $kindMask |= $memberKindMask;
608: if (count($type->getConstantScalarValues()) === 1) {
609: continue;
610: }
611: $nonConstantKindMask |= $memberKindMask;
612: }
613: $bleedingEdge = BleedingEdgeToggle::isBleedingEdge();
614: foreach (self::$unionRules[(int) $bleedingEdge] ??= self::createUnionRules($bleedingEdge) as $rule) {
615: if (($rule->getKindMask() & ($rule->mergesConstantScalarValues() ? $kindMask : $nonConstantKindMask)) === 0) {
616: continue;
617: }
618: $types = $rule->apply($types, $alreadyNormalized);
619: }
620: if (count($types) === 1) {
621: return $types[0];
622: }
623:
624: if ($benevolentTypes !== []) {
625: $allBenevolent = true;
626: foreach ($types as $type) {
627: // the input types keep the benevolent members alive, so their ids stay unique
628: if (isset($benevolentTypes[spl_object_id($type)])) {
629: continue;
630: }
631:
632: // a member that absorbed a benevolent member stays benevolent,
633: // like int absorbing int<1, max> from (int<1, max>|string) and 0
634: foreach ($benevolentTypes as $benevolentType) {
635: if ($type->isSuperTypeOf($benevolentType)->yes()) {
636: continue 2;
637: }
638: }
639:
640: $allBenevolent = false;
641: break;
642: }
643:
644: if ($allBenevolent) {
645: return new BenevolentUnionType($types, true);
646: }
647: }
648:
649: return new UnionType($types, true);
650: }
651:
652: /**
653: * The union of two operands when it is known without the rules: of two that
654: * never merge into one member - of different kinds, or two different constant
655: * scalars - the union of both, of a normalized union and another operand what
656: * unionWithNormalizedUnion() answers, and when one holds the other the one that
657: * holds the other and is not held by it, and of two holding each other the
658: * later one, as SingleValueUnionRule and SubsumptionUnionRule keep it, unless
659: * tryUnion() merges them into another type or they are two values, as -0.0
660: * and 0.0. Null when neither holds the
661: * other, when one is of no kinds (never) or an unresolved template argument,
662: * which only addMarker() merges, and when either may be an array: the array
663: * rules rebuild arrays even from a supertype and its subtype, as the shapes
664: * of `array{a: int}|array{a: int, b?: int}` merge.
665: */
666: private static function findAbsorbingOperand(Type $a, Type $b): ?Type
667: {
668: $aKinds = $a->getKindMask();
669: $bKinds = $b->getKindMask();
670: if (
671: ($aKinds & $bKinds) === 0
672: && $aKinds !== 0
673: && $bKinds !== 0
674: && (($aKinds | $bKinds) & TypeKind::ARRAY) === 0
675: // true and false merge into bool
676: && (($aKinds & TypeKind::BOOL) === 0 || ($bKinds & TypeKind::BOOL) === 0)
677: && !$a instanceof UnionType
678: && !$b instanceof UnionType
679: && !$a instanceof UnresolvedTemplateArgumentType
680: && !$b instanceof UnresolvedTemplateArgumentType
681: ) {
682: // values of different kinds never merge into one member
683: return new UnionType([$a, $b], true);
684: }
685: if (
686: ($aKinds & $bKinds) === 0
687: || (($aKinds | $bKinds) & TypeKind::ARRAY) !== 0
688: || $a instanceof UnresolvedTemplateArgumentType
689: || $b instanceof UnresolvedTemplateArgumentType
690: ) {
691: return null;
692: }
693:
694: if ($a instanceof UnionType || $b instanceof UnionType) {
695: return self::unionWithNormalizedUnion($a, $b, false) ?? self::unionWithNormalizedUnion($b, $a, true);
696: }
697: if (
698: self::isValueApartFromSingleValues($a)
699: && self::isValueApartFromSingleValues($b)
700: && SingleValueUnionRule::getValueKey($a) !== SingleValueUnionRule::getValueKey($b)
701: ) {
702: return new UnionType([$a, $b], true);
703: }
704:
705: $aHoldsB = $a->isSuperTypeOf($b)->yes();
706: $bHoldsA = $b->isSuperTypeOf($a)->yes();
707: if ($aHoldsB !== $bHoldsA) {
708: return $aHoldsB ? $a : $b;
709: }
710: if (
711: !$aHoldsB
712: || $a->tryUnion($b) !== null
713: || $b->tryUnion($a) !== null
714: ) {
715: return null;
716: }
717:
718: // two values SingleValueUnionRule keeps apart, as -0.0 and 0.0
719: $aKey = SingleValueUnionRule::getValueKey($a);
720: $bKey = SingleValueUnionRule::getValueKey($b);
721: if ($aKey !== null && $bKey !== null && $aKey !== $bKey) {
722: return null;
723: }
724:
725: return $b;
726: }
727:
728: /**
729: * The union of a normalized union and another operand that one of its members
730: * holds: the union. Of a constant scalar no member holds, when the members of
731: * its kinds are single values too, which never merge with it: the union with
732: * the value added. Otherwise null, as for a union holding the operand only as
733: * a whole, like `int<0, 5>|int<6, 9>` holds `int<2, 7>`, which is left to the
734: * rules. The members are asked one by one instead of the union, which would
735: * build the set of its values for this one question.
736: */
737: private static function unionWithNormalizedUnion(Type $union, Type $other, bool $otherFirst): ?Type
738: {
739: if (!$union instanceof UnionType || $union instanceof TemplateType || $other instanceof UnionType) {
740: return null;
741: }
742:
743: $otherKinds = $other->getKindMask();
744: $canAdd = self::isValueApartFromSingleValues($other);
745: $otherValues = $canAdd ? $other->getConstantScalarValues() : null;
746: if ($otherValues !== null && is_float($otherValues[0])) {
747: // -0.0 === 0.0 and NAN !== NAN, the value keys tell floats apart
748: $otherValues = null;
749: }
750: $otherKey = SingleValueUnionRule::getValueKey($other);
751: $members = $union->getTypes();
752: foreach ($members as $member) {
753: // a member of other kinds neither holds the value nor merges with it
754: if (($member->getKindMask() & $otherKinds) === 0) {
755: continue;
756: }
757: if ($otherValues !== null && $member->isConstantScalarValue()->yes()) {
758: $memberValues = $member->getConstantScalarValues();
759: // a single value holds only its own value
760: if (count($memberValues) === 1 && $memberValues[0] !== $otherValues[0]) {
761: continue;
762: }
763: }
764: if (
765: $member->isSuperTypeOf($other)->yes()
766: // two values SingleValueUnionRule keeps apart, as -0.0 and 0.0
767: && ($otherKey === null || (SingleValueUnionRule::getValueKey($member) ?? $otherKey) === $otherKey)
768: ) {
769: return $union;
770: }
771: $canAdd = $canAdd && $member->isConstantScalarValue()->yes() && SingleValueUnionRule::isSingleValue($member);
772: }
773: if (!$canAdd) {
774: return null;
775: }
776:
777: // a benevolent union with a value apart from its members is a plain one
778: return new UnionType($otherFirst ? [$other, ...$members] : [...$members, $other], true);
779: }
780:
781: /**
782: * A constant scalar that never merges with another single value, as booleans
783: * merge into bool: a member of its own beside the other values.
784: */
785: private static function isValueApartFromSingleValues(Type $type): bool
786: {
787: return ($type->getKindMask() & TypeKind::BOOL) === 0
788: && $type->isConstantScalarValue()->yes()
789: && SingleValueUnionRule::isSingleValue($type)
790: && !$type->hasTemplateOrLateResolvableType();
791: }
792:
793: /**
794: * An unresolved template argument is a variable of its site, not the type it
795: * currently stands for: unresolved(int) from two different sites are two
796: * variables, and neither int nor the other variable absorbs it. Only the same
797: * variable merges - into the wider of the two inferred types.
798: *
799: * @param array<string, UnresolvedTemplateArgumentType> $markers
800: * @return array<string, UnresolvedTemplateArgumentType>
801: */
802: private static function addMarker(array $markers, UnresolvedTemplateArgumentType $marker): array
803: {
804: $key = spl_object_id($marker->getSite()) . '#' . $marker->getTemplateName();
805: $existing = $markers[$key] ?? null;
806: if ($existing === null || $existing === $marker) {
807: $markers[$key] = $marker;
808: return $markers;
809: }
810:
811: $existingInitial = $existing->getInitialType();
812: $initial = $marker->getInitialType();
813: if ($existingInitial === null || $initial === null) {
814: // nothing inferred stands for the template's default or bound
815: $markers[$key] = $existingInitial === null ? $existing : $marker;
816: return $markers;
817: }
818:
819: $markers[$key] = $existing->withInitialType(self::union($existingInitial, $initial));
820:
821: return $markers;
822: }
823:
824: /**
825: * @param array<string, UnresolvedTemplateArgumentType> $markers
826: */
827: private static function unionWithMarkers(Type $rest, array $markers): Type
828: {
829: if ($rest instanceof MixedType && !$rest instanceof TemplateMixedType && $rest->getSubtractedType() === null) {
830: return $rest;
831: }
832:
833: if ($rest instanceof NeverType) {
834: $members = [];
835: } elseif ($rest instanceof UnionType && !$rest instanceof TemplateType) {
836: $members = $rest->getTypes();
837: } else {
838: $members = [$rest];
839: }
840: foreach ($markers as $marker) {
841: $members[] = $marker;
842: }
843: if (count($members) === 1) {
844: return $members[0];
845: }
846: if ($rest instanceof BenevolentUnionType && !$rest instanceof TemplateType) {
847: return new BenevolentUnionType($members, true);
848: }
849:
850: return new UnionType($members, true);
851: }
852:
853: /**
854: * @param Type[] $types
855: */
856: public static function countConstantArrayValueTypes(array $types): int
857: {
858: $constantArrayValuesCount = 0;
859: // A type shared by several positions (array shape keys written
860: // through a union offset all hold the same value type) is counted
861: // once per position, but traversed only once. The entries keep the
862: // visited types alive so that their object ids are not reused.
863: $countsByType = [];
864: foreach ($types as $type) {
865: // a constant scalar holds no other type
866: if ($type->isConstantScalarValue()->yes()) {
867: continue;
868: }
869: TypeTraverser::map($type, static function (Type $type, callable $traverse) use (&$constantArrayValuesCount, &$countsByType): Type {
870: $id = spl_object_id($type);
871: if (array_key_exists($id, $countsByType)) {
872: $constantArrayValuesCount += $countsByType[$id][1];
873: return $type;
874: }
875:
876: $countBefore = $constantArrayValuesCount;
877: if ($type instanceof ConstantArrayType) {
878: $constantArrayValuesCount += count($type->getValueTypes());
879: }
880:
881: $result = $traverse($type);
882: $countsByType[$id] = [$type, $constantArrayValuesCount - $countBefore];
883:
884: return $result;
885: });
886: }
887: return $constantArrayValuesCount;
888: }
889:
890: /**
891: * Fast path for intersect(): the intersection of two unions whose members are all
892: * finite, mutually-disjoint values (constant scalars and/or enum cases) is their
893: * identity-keyed set intersection. Returns null when either union has a member that is
894: * not such a value, in which case the caller falls back to the general A & (B|C)
895: * distribution.
896: */
897: /** @phpstan-assert-if-true UnionType $type */
898: private static function isPlainOrBenevolentUnion(Type $type): bool
899: {
900: $class = get_class($type);
901:
902: return $class === UnionType::class || $class === BenevolentUnionType::class;
903: }
904:
905: private static function intersectFiniteUnions(UnionType $a, UnionType $b): ?Type
906: {
907: $membersA = self::finiteUnionMembers($a);
908: if ($membersA === null) {
909: return null;
910: }
911:
912: $membersB = self::finiteUnionMembers($b);
913: if ($membersB === null) {
914: return null;
915: }
916:
917: $common = [];
918: foreach ($membersA as $key => $member) {
919: if (!array_key_exists($key, $membersB)) {
920: continue;
921: }
922:
923: $common[] = $member;
924: }
925:
926: if ($common === []) {
927: return new NeverType();
928: }
929:
930: return self::union(...$common);
931: }
932:
933: /**
934: * The union's members keyed by identity, or null when the fast path does not apply.
935: *
936: * FiniteTypeSet does the keying and the union caches it; on top of that, intersect()
937: * hands one of the two members back instead of only comparing them, so a constant string
938: * that is also a class-string is not interchangeable with a same-valued one that is not -
939: * the class-string flag would be lost. Such unions go the slow way.
940: *
941: * @return array<string, Type>|null
942: */
943: private static function finiteUnionMembers(UnionType $union): ?array
944: {
945: $finiteTypeSet = $union->getFiniteTypeSet();
946: if ($finiteTypeSet === null || !$finiteTypeSet->isComplete()) {
947: return null;
948: }
949:
950: return $finiteTypeSet->getMembers();
951: }
952:
953: /**
954: * The rules intersect() runs on the members, in this order: the exact
955: * merges, then any member holding another gives way to it.
956: *
957: * @return list<IntersectRule>
958: */
959: private static function createIntersectRules(): array
960: {
961: $pairRules = [
962: new ExactIntersectRule(),
963: new SubsumptionIntersectRule(),
964: ];
965:
966: return [
967: new DuplicateIntersectRule($pairRules),
968: new OffsetValueLimitIntersectRule(),
969: ...$pairRules,
970: ];
971: }
972:
973: public static function intersect(Type ...$types): Type
974: {
975: if (self::$cacheEnabled ??= TurboExtensionEnabler::isTypeCombinatorCacheEnabled()) {
976: return TypeCombinatorCache::intersect(...$types);
977: }
978:
979: return self::doIntersect(...$types);
980: }
981:
982: /** @internal Delegated to from TypeCombinatorCache, which the native extension shadows to memoize it. */
983: public static function doIntersect(Type ...$types): Type
984: {
985: $typesCount = count($types);
986: if ($typesCount === 0) {
987: return new NeverType();
988: }
989:
990: $types = array_values($types);
991: if ($typesCount === 1) {
992: return $types[0];
993: }
994:
995: // a reference not bound yet is only known to be itself, which would make the intersection never;
996: // it is kept until the reference is bound and answers like the recursive type it refers to
997: foreach ($types as $type) {
998: if ($type instanceof RecursiveTypeReference && $type->getBinder() === null) {
999: return new IntersectionType($types);
1000: }
1001: }
1002:
1003: // The comparator only orders UnionTypes relative to each other, so sorting is
1004: // a no-op unless there are at least two of them. Skip it in the common case.
1005: $unionTypesCount = 0;
1006: foreach ($types as $type) {
1007: if ($type instanceof NeverType && !$type->isExplicit()) {
1008: return $type;
1009: }
1010: if (!$type instanceof UnionType) {
1011: continue;
1012: }
1013: $unionTypesCount++;
1014: }
1015:
1016: // Fast path: the intersection of two unions whose members are all finite,
1017: // mutually-disjoint values (constant scalars and/or enum cases) is their
1018: // identity-keyed set intersection (O(n)), avoiding the O(n*m) `A & (B|C)`
1019: // distribution + union rebuild below. A benevolent union is the one the
1020: // distribution walks first and the benevolence it gives the result is kept;
1021: // the template union types keep their dedicated handling.
1022: if (
1023: $typesCount === 2
1024: && self::isPlainOrBenevolentUnion($types[0])
1025: && self::isPlainOrBenevolentUnion($types[1])
1026: ) {
1027: [$a, $b] = $types;
1028: if ($b instanceof BenevolentUnionType && !$a instanceof BenevolentUnionType) {
1029: [$a, $b] = [$b, $a];
1030: }
1031: $finiteIntersection = self::intersectFiniteUnions($a, $b);
1032: if ($finiteIntersection !== null) {
1033: return $a instanceof BenevolentUnionType ? TypeUtils::toBenevolentUnion($finiteIntersection) : $finiteIntersection;
1034: }
1035: }
1036:
1037: // Integers, ranges and their plain unions intersect by their intervals,
1038: // instead of distributing `A & (B | C)` over each pair of members.
1039: if ($unionTypesCount > 0) {
1040: $operands = [];
1041: foreach ($types as $type) {
1042: if (!$type instanceof UnionType) {
1043: $operands[] = [$type];
1044: continue;
1045: }
1046: if (get_class($type) !== UnionType::class) {
1047: $operands = null;
1048: break;
1049: }
1050: $operands[] = $type->getTypes();
1051: }
1052: $integers = $operands !== null ? ScalarUnion::intersectIntegers($operands) : null;
1053: if ($integers !== null) {
1054: return self::union(...$integers);
1055: }
1056: }
1057:
1058: $sortTypes = static function (Type $a, Type $b): int {
1059: if (!$a instanceof UnionType || !$b instanceof UnionType) {
1060: return 0;
1061: }
1062:
1063: if ($a instanceof TemplateType) {
1064: return -1;
1065: }
1066: if ($b instanceof TemplateType) {
1067: return 1;
1068: }
1069:
1070: if ($a instanceof BenevolentUnionType) {
1071: return -1;
1072: }
1073: if ($b instanceof BenevolentUnionType) {
1074: return 1;
1075: }
1076:
1077: return 0;
1078: };
1079: if ($unionTypesCount >= 2) {
1080: usort($types, $sortTypes);
1081: }
1082: // transform A & (B | C) to (A & B) | (A & C)
1083: foreach ($types as $i => $type) {
1084: if (!$type instanceof UnionType) {
1085: continue;
1086: }
1087:
1088: $topLevelUnionSubTypes = [];
1089: $innerTypes = $type->getTypes();
1090: $innerUnionTypesCount = 0;
1091: foreach ($innerTypes as $innerType) {
1092: if (!$innerType instanceof UnionType) {
1093: continue;
1094: }
1095: $innerUnionTypesCount++;
1096: if ($innerUnionTypesCount >= 2) {
1097: break;
1098: }
1099: }
1100: if ($innerUnionTypesCount >= 2) {
1101: usort($innerTypes, $sortTypes);
1102: }
1103: $slice1 = array_slice($types, 0, $i);
1104: $slice2 = array_slice($types, $i + 1);
1105: foreach ($innerTypes as $innerUnionSubType) {
1106: $topLevelUnionSubTypes[] = self::intersect(
1107: $innerUnionSubType,
1108: ...$slice1,
1109: ...$slice2,
1110: );
1111: }
1112:
1113: $union = self::union(...$topLevelUnionSubTypes);
1114: if ($union instanceof NeverType) {
1115: return $union;
1116: }
1117:
1118: if ($type instanceof BenevolentUnionType) {
1119: $union = TypeUtils::toBenevolentUnion($union);
1120: }
1121:
1122: if ($type instanceof TemplateUnionType || $type instanceof TemplateBenevolentUnionType) {
1123: $union = TemplateTypeFactory::create(
1124: $type->getScope(),
1125: $type->getName(),
1126: $union,
1127: $type->getVariance(),
1128: $type->getStrategy(),
1129: $type->getDefault(),
1130: );
1131: }
1132:
1133: return $union;
1134: }
1135:
1136: // transform A & (B & C) to A & B & C
1137: $members = [];
1138: foreach ($types as $type) {
1139: if ($type instanceof IntersectionType && !$type instanceof TemplateType) {
1140: array_push($members, ...$type->getTypes());
1141: continue;
1142: }
1143: $members[] = $type;
1144: }
1145:
1146: foreach (self::$intersectRules ??= self::createIntersectRules() as $rule) {
1147: $members = $rule->apply($members);
1148: }
1149: $types = $members;
1150: $typesCount = count($types);
1151:
1152: if ($typesCount === 1) {
1153: return $types[0];
1154: }
1155:
1156: $accessoryBaseTypes = [];
1157: foreach ($types as $type) {
1158: if (!$type instanceof AccessoryType) {
1159: $accessoryBaseTypes = null;
1160: break;
1161: }
1162: // Accessory types share their default base type: every string accessory
1163: // returns `string`, hasOffset() and hasOffsetValue() both return
1164: // `array|ArrayAccess`. Adding the same base type again narrows nothing -
1165: // intersection is idempotent - but the intersect() below distributes
1166: // `A & (B | C)` one union at a time, so n copies of `array|ArrayAccess`
1167: // would cost 2^n recursive calls before the duplicates are recognized at
1168: // the leaves. That is why isset() with many offsets used to grow
1169: // exponentially: each offset contributes one hasOffset().
1170: $baseType = $type->getDefaultBaseType();
1171: foreach ($accessoryBaseTypes as $addedBaseType) {
1172: if ($addedBaseType->equals($baseType)) {
1173: continue 2;
1174: }
1175: }
1176: $accessoryBaseTypes[] = $baseType;
1177: }
1178: if ($accessoryBaseTypes !== null) {
1179: // Accessory types never stand alone — supply the base type they refine.
1180: return self::intersect(self::intersect(...$accessoryBaseTypes), ...$types);
1181: }
1182:
1183: return new IntersectionType($types);
1184: }
1185:
1186: public static function removeFalsey(Type $type): Type
1187: {
1188: return self::remove($type, StaticTypeFactory::falsey());
1189: }
1190:
1191: public static function removeTruthy(Type $type): Type
1192: {
1193: return self::remove($type, StaticTypeFactory::truthy());
1194: }
1195:
1196: }
1197: