1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type;
4:
5: use DateTime;
6: use DateTimeImmutable;
7: use DateTimeInterface;
8: use Error;
9: use Exception;
10: use PHPStan\DependencyInjection\ReportUnsafeArrayStringKeyCastingToggle;
11: use PHPStan\Php\PhpVersion;
12: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
13: use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
14: use PHPStan\Reflection\ClassConstantReflection;
15: use PHPStan\Reflection\ClassMemberAccessAnswerer;
16: use PHPStan\Reflection\ExtendedMethodReflection;
17: use PHPStan\Reflection\ExtendedPropertyReflection;
18: use PHPStan\Reflection\InitializerExprTypeResolver;
19: use PHPStan\Reflection\MissingMethodFromReflectionException;
20: use PHPStan\Reflection\MissingPropertyFromReflectionException;
21: use PHPStan\Reflection\ReflectionProvider;
22: use PHPStan\Reflection\Type\UnionTypeUnresolvedMethodPrototypeReflection;
23: use PHPStan\Reflection\Type\UnionTypeUnresolvedPropertyPrototypeReflection;
24: use PHPStan\Reflection\Type\UnresolvedMethodPrototypeReflection;
25: use PHPStan\Reflection\Type\UnresolvedPropertyPrototypeReflection;
26: use PHPStan\ShouldNotHappenException;
27: use PHPStan\TrinaryLogic;
28: use PHPStan\Turbo\ShadowedByTurboExtension;
29: use PHPStan\Type\Enum\EnumCaseObjectType;
30: use PHPStan\Type\Generic\AbsorbedTemplateArgumentType;
31: use PHPStan\Type\Generic\GenericClassStringType;
32: use PHPStan\Type\Generic\TemplateIntegerRangeType;
33: use PHPStan\Type\Generic\TemplateIterableType;
34: use PHPStan\Type\Generic\TemplateMixedType;
35: use PHPStan\Type\Generic\TemplateType;
36: use PHPStan\Type\Generic\TemplateTypeHelper;
37: use PHPStan\Type\Generic\TemplateTypeMap;
38: use PHPStan\Type\Generic\TemplateTypeVariance;
39: use PHPStan\Type\Generic\TemplateUnionType;
40: use PHPStan\Type\Generic\UnresolvedTemplateArgumentType;
41: use PHPStan\Type\Traits\NonGeneralizableTypeTrait;
42: use PHPStan\Type\Traits\OperatorTypeTrait;
43: use Throwable;
44: use function array_diff_assoc;
45: use function array_fill_keys;
46: use function array_intersect;
47: use function array_key_exists;
48: use function array_keys;
49: use function array_map;
50: use function array_merge;
51: use function array_slice;
52: use function array_unique;
53: use function array_values;
54: use function count;
55: use function implode;
56: use function spl_object_id;
57: use function sprintf;
58: use function str_contains;
59:
60: /** @api */
61: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/UnionType.cpp')]
62: class UnionType implements CompoundType
63: {
64:
65: use NonGeneralizableTypeTrait;
66: use OperatorTypeTrait;
67:
68: public const EQUAL_UNION_CLASSES = [
69: DateTimeInterface::class => [DateTimeImmutable::class, DateTime::class],
70: Throwable::class => [Error::class, Exception::class], // phpcs:ignore SlevomatCodingStandard.Exceptions.ReferenceThrowableOnly.ReferencedGeneralException
71: ];
72:
73: /**
74: * Sorting must not reorder $types: describe() sorts for readability, but $types is the
75: * type's value — getTypes() exposes it and callers merge array shapes in that order. It
76: * used to be sorted in place, so describing a union permanently changed what getTypes()
77: * returned, making an immutable value object's observable state depend on what had been
78: * called on it before.
79: *
80: * @var list<Type>|null
81: */
82: private ?array $sortedTypesCache = null;
83:
84: /** @var array<int, string> */
85: private array $cachedDescriptions = [];
86:
87: /**
88: * Identity-keyed view of $types, built on first use. False once it is known that the
89: * members cannot be keyed at all, so a union of objects pays for the attempt only once.
90: */
91: private FiniteTypeSet|false|null $finiteTypeSet = null;
92:
93: /** @var list<Type>|null */
94: private ?array $finiteTypes = null;
95:
96: private ?TrinaryLogic $isNull = null;
97:
98: private ?TrinaryLogic $isCallable = null;
99:
100: private ?bool $hasTemplateOrLateResolvableType = null;
101:
102: /** @var array<int, Type> */
103: private array $possiblyLooselyEqualTypes = [];
104:
105: /** @var array<int, Type> */
106: private array $alwaysLooselyEqualTypes = [];
107:
108: /**
109: * @api
110: * @param list<Type> $types
111: */
112: public function __construct(private array $types, private bool $normalized = false)
113: {
114: $throwException = static function () use ($types): void {
115: throw new ShouldNotHappenException(sprintf(
116: 'Cannot create %s with: %s',
117: self::class,
118: implode(', ', array_map(static fn (Type $type): string => $type->describe(VerbosityLevel::value()), $types)),
119: ));
120: };
121: if (count($types) < 2) {
122: $throwException();
123: }
124: foreach ($types as $type) {
125: if (!($type instanceof UnionType)) {
126: continue;
127: }
128: if ($type instanceof TemplateType) {
129: continue;
130: }
131:
132: $throwException();
133: }
134: }
135:
136: /** @var array<int, Type> */
137: private array $generalizedTypes = [];
138:
139: /** @var array<string, Type> */
140: private array $cachedGetOffsetValueType = [];
141:
142: public function generalize(GeneralizePrecision $precision): Type
143: {
144: // Immutable, so it generalizes the same way every time - remembered
145: // because a member shared by several nested types is otherwise
146: // generalized once per path leading to it (see ConstantArrayType::generalize()).
147: return $this->generalizedTypes[spl_object_id($precision)] ??= $this->traverse(static fn (Type $type) => $type->generalize($precision));
148: }
149:
150: /**
151: * @return list<Type>
152: */
153: public function getTypes(): array
154: {
155: return $this->types;
156: }
157:
158: /**
159: * @param callable(Type $type): bool $filterCb
160: */
161: public function filterTypes(callable $filterCb): Type
162: {
163: $newTypes = [];
164: $changed = false;
165: foreach ($this->getTypes() as $innerType) {
166: if (!$filterCb($innerType)) {
167: $changed = true;
168: continue;
169: }
170:
171: $newTypes[] = $innerType;
172: }
173:
174: if (!$changed) {
175: return $this;
176: }
177:
178: return TypeCombinator::union(...$newTypes);
179: }
180:
181: public function isNormalized(): bool
182: {
183: return $this->normalized;
184: }
185:
186: public function getFiniteTypeSet(): ?FiniteTypeSet
187: {
188: $finiteTypeSet = $this->finiteTypeSet ??= FiniteTypeSet::create($this->types) ?? false;
189: if ($finiteTypeSet === false) {
190: return null;
191: }
192:
193: return $finiteTypeSet;
194: }
195:
196: /**
197: * @return list<Type>
198: */
199: protected function getSortedTypes(): array
200: {
201: return $this->sortedTypesCache ??= UnionTypeHelper::sortTypes($this->types);
202: }
203:
204: public function getReferencedClasses(): array
205: {
206: $classes = [];
207: foreach ($this->types as $type) {
208: foreach ($type->getReferencedClasses() as $className) {
209: $classes[] = $className;
210: }
211: }
212:
213: return $classes;
214: }
215:
216: public function getObjectClassNames(): array
217: {
218: return array_values(array_unique($this->pickFromTypes(
219: static fn (Type $type) => $type->getObjectClassNames(),
220: static fn (Type $type) => $type->isObject()->yes(),
221: )));
222: }
223:
224: public function getObjectClassReflections(): array
225: {
226: return $this->pickFromTypes(
227: static fn (Type $type) => $type->getObjectClassReflections(),
228: static fn (Type $type) => $type->isObject()->yes(),
229: );
230: }
231:
232: public function getArrays(): array
233: {
234: return $this->pickFromTypes(
235: static fn (Type $type) => $type->getArrays(),
236: static fn (Type $type) => $type->isArray()->yes(),
237: );
238: }
239:
240: public function getConstantArrays(): array
241: {
242: return $this->pickFromTypes(
243: static fn (Type $type) => $type->getConstantArrays(),
244: static fn (Type $type) => $type->isArray()->yes(),
245: );
246: }
247:
248: public function getConstantStrings(): array
249: {
250: return $this->pickFromTypes(
251: static fn (Type $type) => $type->getConstantStrings(),
252: static fn (Type $type) => $type->isString()->yes(),
253: );
254: }
255:
256: public function accepts(Type $type, bool $strictTypes): AcceptsResult
257: {
258: $finiteTypeSet = $this->getFiniteTypeSet();
259: if ($finiteTypeSet !== null) {
260: $key = FiniteTypeSet::key($type);
261: if ($key !== null && $finiteTypeSet->has($key)) {
262: return AcceptsResult::createYes();
263: }
264:
265: if ($finiteTypeSet->isComplete()) {
266: if ($key !== null) {
267: // A value the union does not hold can still be accepted through scalar
268: // coercion, so unlike isSuperTypeOf() the answer is not simply no - but it
269: // is the same for every member of a kind, so one member of each is enough.
270: // None of the branches below apply to a value: it is not iterable, not
271: // compound, and an enum case already is the union of its own cases.
272: $result = AcceptsResult::createNo();
273: foreach ($finiteTypeSet->getRepresentativesOfOtherKinds($type) as $representative) {
274: $result = $result->or($representative->accepts($type, $strictTypes));
275: }
276:
277: return $result;
278: }
279:
280: if ($type instanceof self && !$type instanceof TemplateType) {
281: $otherFiniteTypeSet = $type->getFiniteTypeSet();
282: if ($otherFiniteTypeSet !== null && $otherFiniteTypeSet->isComplete()) {
283: // A member standing for a single value never accepts more than one of
284: // the other union's values, and the other union has at least two of
285: // them - so the member-by-member or() below cannot come out yes, and
286: // its result is discarded in favour of the compound answer anyway.
287: return $type->isAcceptedBy($this, $strictTypes);
288: }
289: }
290: }
291: }
292:
293: if ($type instanceof IterableType) {
294: return $this->accepts($type->toArrayOrTraversable(), $strictTypes);
295: }
296:
297: foreach (self::EQUAL_UNION_CLASSES as $baseClass => $classes) {
298: if (!$type->equals(new ObjectType($baseClass))) {
299: continue;
300: }
301:
302: $union = TypeCombinator::union(
303: ...array_map(static fn (string $objectClass): Type => new ObjectType($objectClass), $classes),
304: );
305: if ($this->accepts($union, $strictTypes)->yes()) {
306: return AcceptsResult::createYes();
307: }
308: break;
309: }
310:
311: if ($type instanceof self && !$type instanceof TemplateType) {
312: // A member accepts the other union only when it accepts each of its members, which
313: // this union then accepts too - the member-by-member or() below cannot come out
314: // yes unless the compound answer does, and that answer replaces any other. Asking
315: // both would walk the members' nested types twice at every level.
316: return $type->isAcceptedBy($this, $strictTypes);
317: }
318:
319: $innerAccepts = [];
320: $result = AcceptsResult::createNo();
321: foreach ($this->getSortedTypes() as $i => $innerType) {
322: $innerResult = $innerType->accepts($type, $strictTypes);
323: $innerAccepts[$i] = $innerResult;
324: $result = $result->or($innerResult->decorateReasons(static fn (string $reason) => sprintf('Type #%d from the union: %s', $i + 1, $reason)));
325: }
326: if ($result->yes()) {
327: // the reasons are those of the members that do not accept the type,
328: // which do not matter once one does
329: return AcceptsResult::createYes();
330: }
331:
332: // A shape that union() merged from shapes differing at one key is accepted when
333: // each of the shapes it holds is, even when no single member accepts all of them.
334: $constantArrays = $type->getConstantArrays();
335: if (count($constantArrays) === 1 && !$type instanceof TemplateType && $type->isConstantArray()->yes()) {
336: $shapes = ArrayAlgebra::splitConstantArrayAtFiniteValue($constantArrays[0]);
337: if ($shapes !== null) {
338: $acceptsShapes = true;
339: foreach ($shapes as $shape) {
340: if (!$this->accepts($shape, $strictTypes)->yes()) {
341: $acceptsShapes = false;
342: break;
343: }
344: }
345: if ($acceptsShapes) {
346: return AcceptsResult::createYes();
347: }
348: }
349: }
350:
351: $commonReasons = null;
352: foreach ($innerAccepts as $innerResult) {
353: if ($commonReasons === null) {
354: $commonReasons = $innerResult->reasons;
355: continue;
356: }
357: $commonReasons = array_values(array_intersect($commonReasons, $innerResult->reasons));
358: }
359: if ($commonReasons !== null && count($commonReasons) > 0) {
360: $decorated = [];
361: foreach (array_keys($innerAccepts) as $i) {
362: foreach ($commonReasons as $reason) {
363: $decorated[] = sprintf('Type #%d from the union: %s', $i + 1, $reason);
364: }
365: }
366: $result = new AcceptsResult($result->result, $decorated);
367: }
368:
369: if ($type instanceof CompoundType && !$type instanceof CallableType && !$type instanceof TemplateType && !$type instanceof IntersectionType) {
370: return $type->isAcceptedBy($this, $strictTypes);
371: }
372:
373: if ($type instanceof TemplateUnionType) {
374: return $result->or($type->isAcceptedBy($this, $strictTypes));
375: }
376:
377: if ($type->isEnum()->yes() && !$this->isEnum()->no()) {
378: $enumCasesUnion = TypeCombinator::union(...$type->getEnumCases());
379: if (!$type->equals($enumCasesUnion)) {
380: return $this->accepts($enumCasesUnion, $strictTypes);
381: }
382: }
383:
384: return $result;
385: }
386:
387: public function isSuperTypeOf(Type $otherType): IsSuperTypeOfResult
388: {
389: if (
390: ($otherType instanceof self && !$otherType instanceof TemplateUnionType)
391: || ($otherType instanceof IterableType && !$otherType instanceof TemplateIterableType)
392: || $otherType instanceof NeverType
393: || ($otherType instanceof IntegerRangeType && !$otherType instanceof TemplateIntegerRangeType)
394: // stands for its delegate, which can itself be a union
395: || $otherType instanceof UnresolvedTemplateArgumentType
396: // unfolds to its members, each of which another member here can hold
397: || $otherType instanceof RecursiveType
398: ) {
399: return $otherType->isSubTypeOf($this);
400: }
401:
402: $types = $this->types;
403: $finiteTypeSet = $this->getFiniteTypeSet();
404: if ($finiteTypeSet !== null) {
405: $key = FiniteTypeSet::key($otherType);
406: if ($key !== null) {
407: if ($finiteTypeSet->has($key)) {
408: return IsSuperTypeOfResult::createYes();
409: }
410:
411: // Every keyed member stands for a different value than $otherType, so all of
412: // them answer no - only the members that could not be keyed are left to ask.
413: if ($finiteTypeSet->isComplete()) {
414: return IsSuperTypeOfResult::createNo();
415: }
416:
417: $types = $finiteTypeSet->getOthers();
418: }
419: }
420:
421: $results = [];
422: foreach ($types as $innerType) {
423: $result = $innerType->isSuperTypeOf($otherType);
424: if ($result->yes()) {
425: return $result;
426: }
427: $results[] = $result;
428: }
429: $result = IsSuperTypeOfResult::createNo()->or(...$results);
430:
431: if (
432: $otherType instanceof TemplateUnionType
433: || ($otherType instanceof LateResolvableType && $otherType instanceof CompoundType && !$otherType instanceof TemplateType)
434: ) {
435: return $result->or($otherType->isSubTypeOf($this));
436: }
437:
438: return $result;
439: }
440:
441: public function isSubTypeOf(Type $otherType): IsSuperTypeOfResult
442: {
443: $containment = $this->finiteTypeSetContainedIn($otherType, false);
444: if ($containment !== null) {
445: if ($containment->maybe()) {
446: return IsSuperTypeOfResult::createMaybe();
447: }
448:
449: return IsSuperTypeOfResult::createFromBoolean($containment->yes());
450: }
451:
452: $results = array_map(static fn (Type $innerType) => $otherType->isSuperTypeOf($innerType), $this->types);
453: if ($this->hasClosureMember()) {
454: $results = ClosureOrigin::combineOverloadIsSuperTypeOfResults($this->types, $results);
455: }
456:
457: return IsSuperTypeOfResult::extremeIdentity(...$results);
458: }
459:
460: public function isAcceptedBy(Type $acceptingType, bool $strictTypes): AcceptsResult
461: {
462: // Unlike isSubTypeOf() only the positive answer holds: a member $acceptingType does
463: // not hold can still be accepted through scalar coercion.
464: $containment = $this->finiteTypeSetContainedIn($acceptingType, true);
465: if ($containment !== null && $containment->yes()) {
466: return AcceptsResult::createYes();
467: }
468:
469: $results = array_map(static fn (Type $innerType) => $acceptingType->accepts($innerType, $strictTypes), $this->types);
470: if ($this->hasClosureMember()) {
471: $results = ClosureOrigin::combineOverloadAcceptsResults($this->types, $results);
472: }
473:
474: return AcceptsResult::extremeIdentity(...$results);
475: }
476:
477: /** Closure members of one overloaded callee answer together, see ClosureOrigin::combineOverloadAcceptsResults(). */
478: private function hasClosureMember(): bool
479: {
480: foreach ($this->types as $type) {
481: if ($type instanceof ClosureType) {
482: return true;
483: }
484: }
485:
486: return false;
487: }
488:
489: /**
490: * Whether $otherType holds every member of this one, or null when the question cannot
491: * be settled from the identity maps alone.
492: *
493: * $otherType is compared as a set of values: a union through its own map, a single
494: * finite value as the one-member set holding it.
495: *
496: * $yesOnly skips the completeness requirement on the other union: a member missing from
497: * its map only rules out the yes answer, which is all the caller is after.
498: */
499: private function finiteTypeSetContainedIn(Type $otherType, bool $yesOnly): ?TrinaryLogic
500: {
501: if (!$otherType instanceof self || $otherType instanceof TemplateType) {
502: // A single value covers a member iff they are the same value, and no member
503: // stands for a value it is not keyed by - so one lookup answers for every member
504: // at once. This is the shape TypeCombinator::remove() takes to ask whether
505: // removing a value empties a union of values, and the only way a non-union other
506: // type reaches this helper at all. Its key comes first: without one, such as for
507: // string accepting a union of strings, this union's set is not built.
508: $key = FiniteTypeSet::key($otherType);
509: if ($key === null) {
510: return null;
511: }
512:
513: $finiteTypeSet = $this->getFiniteTypeSet();
514: if ($finiteTypeSet === null || !$finiteTypeSet->isComplete()) {
515: return null;
516: }
517:
518: $containment = $finiteTypeSet->containedInKey($key);
519:
520: // No constant value accepts another one - not even a numeric string an int, in
521: // either direction - so today accepts() agrees with isSuperTypeOf() here and this
522: // guard never changes an answer. It is kept because that is a fact about the
523: // current value types rather than something the identity map guarantees: a value
524: // the map does not hold being accepted anyway is exactly what accepts() is
525: // allowed to do, and all isAcceptedBy() wants from the map is the yes.
526: if (!$containment->yes() && $yesOnly) {
527: return null;
528: }
529:
530: return $containment;
531: }
532:
533: $finiteTypeSet = $this->getFiniteTypeSet();
534: if ($finiteTypeSet === null || !$finiteTypeSet->isComplete()) {
535: return null;
536: }
537:
538: $otherFiniteTypeSet = $otherType->getFiniteTypeSet();
539: if ($otherFiniteTypeSet === null) {
540: return null;
541: }
542:
543: $containment = $finiteTypeSet->containedIn($otherFiniteTypeSet);
544: if (!$containment->yes() && ($yesOnly || !$otherFiniteTypeSet->isComplete())) {
545: return null;
546: }
547:
548: return $containment;
549: }
550:
551: public function equals(Type $type): bool
552: {
553: if (!$type instanceof static) {
554: return false;
555: }
556:
557: if (count($this->types) !== count($type->types)) {
558: return false;
559: }
560:
561: $finiteTypeSet = $this->getFiniteTypeSet();
562: if ($finiteTypeSet !== null && $finiteTypeSet->isComplete()) {
563: $otherFiniteTypeSet = $type->getFiniteTypeSet();
564: if ($otherFiniteTypeSet !== null && $otherFiniteTypeSet->isComplete()) {
565: return $finiteTypeSet->containedIn($otherFiniteTypeSet)->yes();
566: }
567: }
568:
569: $otherTypes = $type->types;
570: foreach ($this->types as $innerType) {
571: $match = false;
572: foreach ($otherTypes as $i => $otherType) {
573: if (!$innerType->equals($otherType)) {
574: continue;
575: }
576:
577: $match = true;
578: unset($otherTypes[$i]);
579: break;
580: }
581:
582: if (!$match) {
583: return false;
584: }
585: }
586:
587: return count($otherTypes) === 0;
588: }
589:
590: public function describe(VerbosityLevel $level): string
591: {
592: if (isset($this->cachedDescriptions[$level->getLevelValue()])) {
593: return $this->cachedDescriptions[$level->getLevelValue()];
594: }
595: $benevolent = $this instanceof BenevolentUnionType;
596: $joinTypes = static function (array $types) use ($level, $benevolent): string {
597: $typeNames = [];
598: foreach ($types as $i => $type) {
599: if ($type instanceof ClosureType || $type instanceof CallableType || $type instanceof TemplateUnionType) {
600: $typeNames[] = sprintf('(%s)', $type->describe($level));
601: } elseif ($type instanceof TemplateType) {
602: $isLast = $i >= count($types) - 1;
603: $bound = $type->getBound();
604: if (
605: !$isLast
606: && ($level->isTypeOnly() || $level->isValue())
607: && !($bound instanceof MixedType && $bound->getSubtractedType() === null && !$bound instanceof TemplateMixedType)
608: ) {
609: $typeNames[] = sprintf('(%s)', $type->describe($level));
610: } else {
611: $typeNames[] = $type->describe($level);
612: }
613: } elseif ($type instanceof IntersectionType) {
614: $intersectionDescription = $type->describe($level);
615: if (str_contains($intersectionDescription, '&')) {
616: $typeNames[] = sprintf('(%s)', $intersectionDescription);
617: } else {
618: $typeNames[] = $intersectionDescription;
619: }
620: } else {
621: $typeNames[] = $type->describe($level);
622: }
623: }
624:
625: if ($level->isPrecise() || $level->isCache()) {
626: $duplicates = array_diff_assoc($typeNames, array_unique($typeNames));
627: if (count($duplicates) > 0) {
628: $indexByDuplicate = array_fill_keys($duplicates, 0);
629: foreach ($typeNames as $key => $typeName) {
630: if (!isset($indexByDuplicate[$typeName])) {
631: continue;
632: }
633:
634: $typeNames[$key] = $typeName . '#' . ++$indexByDuplicate[$typeName];
635: }
636: }
637: } else {
638: $typeNames = array_unique($typeNames);
639: }
640:
641: if (count($typeNames) > 1024) {
642: $description = implode('|', array_slice($typeNames, 0, 1024)) . "|\u{2026}";
643: } else {
644: $description = implode('|', $typeNames);
645: }
646:
647: // the members of a benevolent union can describe the same, like decimal-int-string and non-empty-string as string
648: if ($benevolent && count($typeNames) > 1) {
649: return '(' . $description . ')';
650: }
651:
652: return $description;
653: };
654:
655: return $this->cachedDescriptions[$level->getLevelValue()] = $level->handle(
656: function () use ($joinTypes): string {
657: $types = TypeCombinator::union(...array_map(static function (Type $type): Type {
658: if (
659: $type->isConstantValue()->yes()
660: && $type->isTrue()->or($type->isFalse())->no()
661: ) {
662: return $type->generalize(GeneralizePrecision::lessSpecific());
663: }
664:
665: return $type;
666: }, $this->getSortedTypes()));
667:
668: if ($types instanceof UnionType) {
669: return $joinTypes($types->getSortedTypes());
670: }
671:
672: return $joinTypes([$types]);
673: },
674: fn (): string => $joinTypes($this->getSortedTypes()),
675: );
676: }
677:
678: /**
679: * @param callable(Type $type): TrinaryLogic $canCallback
680: * @param callable(Type $type): TrinaryLogic $hasCallback
681: */
682: private function hasInternal(
683: callable $canCallback,
684: callable $hasCallback,
685: ): TrinaryLogic
686: {
687: return TrinaryLogic::lazyExtremeIdentity($this->types, static function (Type $type) use ($canCallback, $hasCallback): TrinaryLogic {
688: if ($canCallback($type)->no()) {
689: return TrinaryLogic::createNo();
690: }
691:
692: return $hasCallback($type);
693: });
694: }
695:
696: /**
697: * @template TObject of object
698: * @param callable(Type $type): TrinaryLogic $hasCallback
699: * @param callable(Type $type): TObject $getCallback
700: * @return TObject
701: */
702: private function getInternal(
703: callable $hasCallback,
704: callable $getCallback,
705: ): object
706: {
707: /** @var TrinaryLogic|null $result */
708: $result = null;
709:
710: /** @var TObject|null $object */
711: $object = null;
712: foreach ($this->types as $type) {
713: $has = $hasCallback($type);
714: if (!$has->yes()) {
715: continue;
716: }
717: if ($result !== null && $result->compareTo($has) !== $has) {
718: continue;
719: }
720:
721: $get = $getCallback($type);
722: $result = $has;
723: $object = $get;
724: }
725:
726: if ($object === null) {
727: throw new ShouldNotHappenException();
728: }
729:
730: return $object;
731: }
732:
733: public function getTemplateType(string $ancestorClassName, string $templateTypeName): Type
734: {
735: return $this->unionTypes(static fn (Type $type): Type => $type->getTemplateType($ancestorClassName, $templateTypeName));
736: }
737:
738: public function isObject(): TrinaryLogic
739: {
740: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->isObject());
741: }
742:
743: public function getClassStringType(): Type
744: {
745: return $this->unionTypes(static fn (Type $type): Type => $type->getClassStringType());
746: }
747:
748: public function isEnum(): TrinaryLogic
749: {
750: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->isEnum());
751: }
752:
753: public function canAccessProperties(): TrinaryLogic
754: {
755: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->canAccessProperties());
756: }
757:
758: public function hasProperty(string $propertyName): TrinaryLogic
759: {
760: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->hasProperty($propertyName));
761: }
762:
763: public function getProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
764: {
765: return $this->getUnresolvedPropertyPrototype($propertyName, $scope)->getTransformedProperty();
766: }
767:
768: public function getUnresolvedPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
769: {
770: $propertyPrototypes = [];
771: foreach ($this->types as $type) {
772: if (!$type->hasProperty($propertyName)->yes()) {
773: continue;
774: }
775:
776: $propertyPrototypes[] = $type->getUnresolvedPropertyPrototype($propertyName, $scope)->withFechedOnType($this);
777: }
778:
779: $propertiesCount = count($propertyPrototypes);
780: if ($propertiesCount === 0) {
781: throw new MissingPropertyFromReflectionException($this->describe(VerbosityLevel::typeOnly()), $propertyName);
782: }
783:
784: if ($propertiesCount === 1) {
785: return $propertyPrototypes[0];
786: }
787:
788: return new UnionTypeUnresolvedPropertyPrototypeReflection($propertyPrototypes);
789: }
790:
791: public function hasInstanceProperty(string $propertyName): TrinaryLogic
792: {
793: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->hasInstanceProperty($propertyName));
794: }
795:
796: public function getInstanceProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
797: {
798: return $this->getUnresolvedInstancePropertyPrototype($propertyName, $scope)->getTransformedProperty();
799: }
800:
801: public function getUnresolvedInstancePropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
802: {
803: $propertyPrototypes = [];
804: foreach ($this->types as $type) {
805: if (!$type->hasInstanceProperty($propertyName)->yes()) {
806: continue;
807: }
808:
809: $propertyPrototypes[] = $type->getUnresolvedInstancePropertyPrototype($propertyName, $scope)->withFechedOnType($this);
810: }
811:
812: $propertiesCount = count($propertyPrototypes);
813: if ($propertiesCount === 0) {
814: throw new MissingPropertyFromReflectionException($this->describe(VerbosityLevel::typeOnly()), $propertyName);
815: }
816:
817: if ($propertiesCount === 1) {
818: return $propertyPrototypes[0];
819: }
820:
821: return new UnionTypeUnresolvedPropertyPrototypeReflection($propertyPrototypes);
822: }
823:
824: public function hasStaticProperty(string $propertyName): TrinaryLogic
825: {
826: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->hasStaticProperty($propertyName));
827: }
828:
829: public function getStaticProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
830: {
831: return $this->getUnresolvedStaticPropertyPrototype($propertyName, $scope)->getTransformedProperty();
832: }
833:
834: public function getUnresolvedStaticPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
835: {
836: $propertyPrototypes = [];
837: foreach ($this->types as $type) {
838: if (!$type->hasStaticProperty($propertyName)->yes()) {
839: continue;
840: }
841:
842: $propertyPrototypes[] = $type->getUnresolvedStaticPropertyPrototype($propertyName, $scope)->withFechedOnType($this);
843: }
844:
845: $propertiesCount = count($propertyPrototypes);
846: if ($propertiesCount === 0) {
847: throw new MissingPropertyFromReflectionException($this->describe(VerbosityLevel::typeOnly()), $propertyName);
848: }
849:
850: if ($propertiesCount === 1) {
851: return $propertyPrototypes[0];
852: }
853:
854: return new UnionTypeUnresolvedPropertyPrototypeReflection($propertyPrototypes);
855: }
856:
857: public function canCallMethods(): TrinaryLogic
858: {
859: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->canCallMethods());
860: }
861:
862: public function hasMethod(string $methodName): TrinaryLogic
863: {
864: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->hasMethod($methodName));
865: }
866:
867: public function getMethod(string $methodName, ClassMemberAccessAnswerer $scope): ExtendedMethodReflection
868: {
869: return $this->getUnresolvedMethodPrototype($methodName, $scope)->getTransformedMethod();
870: }
871:
872: public function getUnresolvedMethodPrototype(string $methodName, ClassMemberAccessAnswerer $scope): UnresolvedMethodPrototypeReflection
873: {
874: $methodPrototypes = [];
875: foreach ($this->types as $type) {
876: if (!$type->hasMethod($methodName)->yes()) {
877: continue;
878: }
879:
880: $prototype = $type->getUnresolvedMethodPrototype($methodName, $scope);
881: if ($this instanceof TemplateType) {
882: $prototype = $prototype->withCalledOnType($this);
883: }
884: $methodPrototypes[] = $prototype;
885: }
886:
887: $methodsCount = count($methodPrototypes);
888: if ($methodsCount === 0) {
889: throw new MissingMethodFromReflectionException($this->describe(VerbosityLevel::typeOnly()), $methodName);
890: }
891:
892: if ($methodsCount === 1) {
893: return $methodPrototypes[0];
894: }
895:
896: return new UnionTypeUnresolvedMethodPrototypeReflection($methodName, $methodPrototypes);
897: }
898:
899: public function canAccessConstants(): TrinaryLogic
900: {
901: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->canAccessConstants());
902: }
903:
904: public function hasConstant(string $constantName): TrinaryLogic
905: {
906: return $this->hasInternal(
907: static fn (Type $type): TrinaryLogic => $type->canAccessConstants(),
908: static fn (Type $type): TrinaryLogic => $type->hasConstant($constantName),
909: );
910: }
911:
912: public function getConstant(string $constantName): ClassConstantReflection
913: {
914: return $this->getInternal(
915: static fn (Type $type): TrinaryLogic => $type->hasConstant($constantName),
916: static fn (Type $type): ClassConstantReflection => $type->getConstant($constantName),
917: );
918: }
919:
920: public function isIterable(): TrinaryLogic
921: {
922: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->isIterable());
923: }
924:
925: public function isIterableAtLeastOnce(): TrinaryLogic
926: {
927: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->isIterableAtLeastOnce());
928: }
929:
930: public function getArraySize(): Type
931: {
932: return $this->unionTypes(static fn (Type $type): Type => $type->getArraySize());
933: }
934:
935: public function getIterableKeyType(): Type
936: {
937: return $this->unionTypes(static fn (Type $type): Type => $type->getIterableKeyType());
938: }
939:
940: public function getFirstIterableKeyType(): Type
941: {
942: return $this->unionTypes(static fn (Type $type): Type => $type->getFirstIterableKeyType());
943: }
944:
945: public function getLastIterableKeyType(): Type
946: {
947: return $this->unionTypes(static fn (Type $type): Type => $type->getLastIterableKeyType());
948: }
949:
950: public function getIterableValueType(): Type
951: {
952: return $this->unionTypes(static fn (Type $type): Type => $type->getIterableValueType());
953: }
954:
955: public function getFirstIterableValueType(): Type
956: {
957: return $this->unionTypes(static fn (Type $type): Type => $type->getFirstIterableValueType());
958: }
959:
960: public function getLastIterableValueType(): Type
961: {
962: return $this->unionTypes(static fn (Type $type): Type => $type->getLastIterableValueType());
963: }
964:
965: public function isArray(): TrinaryLogic
966: {
967: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isArray());
968: }
969:
970: public function isConstantArray(): TrinaryLogic
971: {
972: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isConstantArray());
973: }
974:
975: public function isOversizedArray(): TrinaryLogic
976: {
977: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isOversizedArray());
978: }
979:
980: public function isList(): TrinaryLogic
981: {
982: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isList());
983: }
984:
985: public function isString(): TrinaryLogic
986: {
987: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isString());
988: }
989:
990: public function isNumericString(): TrinaryLogic
991: {
992: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isNumericString());
993: }
994:
995: public function isDecimalIntegerString(): TrinaryLogic
996: {
997: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isDecimalIntegerString());
998: }
999:
1000: public function isNonEmptyString(): TrinaryLogic
1001: {
1002: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isNonEmptyString());
1003: }
1004:
1005: public function isNonFalsyString(): TrinaryLogic
1006: {
1007: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isNonFalsyString());
1008: }
1009:
1010: public function isLiteralString(): TrinaryLogic
1011: {
1012: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isLiteralString());
1013: }
1014:
1015: public function getStringRefinement(): ?int
1016: {
1017: return null;
1018: }
1019:
1020: public function isLowercaseString(): TrinaryLogic
1021: {
1022: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isLowercaseString());
1023: }
1024:
1025: public function isUppercaseString(): TrinaryLogic
1026: {
1027: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isUppercaseString());
1028: }
1029:
1030: public function isClassString(): TrinaryLogic
1031: {
1032: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isClassString());
1033: }
1034:
1035: public function getClassStringObjectType(): Type
1036: {
1037: return $this->unionTypes(static fn (Type $type): Type => $type->getClassStringObjectType());
1038: }
1039:
1040: public function getObjectTypeOrClassStringObjectType(): Type
1041: {
1042: return $this->unionTypes(static fn (Type $type): Type => $type->getObjectTypeOrClassStringObjectType());
1043: }
1044:
1045: public function isVoid(): TrinaryLogic
1046: {
1047: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->isVoid());
1048: }
1049:
1050: public function isScalar(): TrinaryLogic
1051: {
1052: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->isScalar());
1053: }
1054:
1055: public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
1056: {
1057: return $this->notBenevolentUnionResults(
1058: static fn (Type $innerType): TrinaryLogic => $innerType->looseCompare($type, $phpVersion)->toTrinaryLogic(),
1059: )->toBooleanType();
1060: }
1061:
1062: public function isOffsetAccessible(): TrinaryLogic
1063: {
1064: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->isOffsetAccessible());
1065: }
1066:
1067: public function isOffsetAccessLegal(): TrinaryLogic
1068: {
1069: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->isOffsetAccessLegal());
1070: }
1071:
1072: public function hasOffsetValueType(Type $offsetType): TrinaryLogic
1073: {
1074: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->hasOffsetValueType($offsetType));
1075: }
1076:
1077: public function getOffsetValueType(Type $offsetType): Type
1078: {
1079: // Immutable, so it answers the same way every time - remembered
1080: // because comparing nested shapes looks the same offset up on the
1081: // same union once per path leading to it, and a new union each time
1082: // would also defeat the memos of the types inside the result.
1083: return $this->cachedGetOffsetValueType[$offsetType->describe(VerbosityLevel::cache())] ??= $this->doGetOffsetValueType($offsetType);
1084: }
1085:
1086: private function doGetOffsetValueType(Type $offsetType): Type
1087: {
1088: $types = [];
1089: foreach ($this->types as $innerType) {
1090: $valueType = $innerType->getOffsetValueType($offsetType);
1091: if ($valueType instanceof ErrorType) {
1092: continue;
1093: }
1094:
1095: $types[] = $valueType;
1096: }
1097:
1098: if (count($types) === 0) {
1099: return new ErrorType();
1100: }
1101:
1102: return TypeCombinator::union(...$types);
1103: }
1104:
1105: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
1106: {
1107: return $this->unionTypes(static fn (Type $type): Type => $type->setOffsetValueType($offsetType, $valueType));
1108: }
1109:
1110: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
1111: {
1112: return $this->unionTypes(static fn (Type $type): Type => $type->setExistingOffsetValueType($offsetType, $valueType));
1113: }
1114:
1115: public function unsetOffset(Type $offsetType): Type
1116: {
1117: return $this->unionTypes(static fn (Type $type): Type => $type->unsetOffset($offsetType));
1118: }
1119:
1120: public function getKeysArrayFiltered(Type $filterValueType, TrinaryLogic $strict): Type
1121: {
1122: return $this->unionTypes(static fn (Type $type): Type => $type->getKeysArrayFiltered($filterValueType, $strict));
1123: }
1124:
1125: public function getKeysArray(): Type
1126: {
1127: return $this->unionTypes(static fn (Type $type): Type => $type->getKeysArray());
1128: }
1129:
1130: public function getValuesArray(): Type
1131: {
1132: return $this->unionTypes(static fn (Type $type): Type => $type->getValuesArray());
1133: }
1134:
1135: public function chunkArray(Type $lengthType, TrinaryLogic $preserveKeys): Type
1136: {
1137: return $this->unionTypes(static fn (Type $type): Type => $type->chunkArray($lengthType, $preserveKeys));
1138: }
1139:
1140: public function fillKeysArray(Type $valueType): Type
1141: {
1142: return $this->unionTypes(static fn (Type $type): Type => $type->fillKeysArray($valueType));
1143: }
1144:
1145: public function flipArray(): Type
1146: {
1147: return $this->unionTypes(static fn (Type $type): Type => $type->flipArray());
1148: }
1149:
1150: public function intersectKeyArray(Type $otherArraysType): Type
1151: {
1152: return $this->unionTypes(static fn (Type $type): Type => $type->intersectKeyArray($otherArraysType));
1153: }
1154:
1155: public function popArray(): Type
1156: {
1157: return $this->unionTypes(static fn (Type $type): Type => $type->popArray());
1158: }
1159:
1160: public function reverseArray(TrinaryLogic $preserveKeys): Type
1161: {
1162: return $this->unionTypes(static fn (Type $type): Type => $type->reverseArray($preserveKeys));
1163: }
1164:
1165: public function searchArray(Type $needleType, ?TrinaryLogic $strict = null): Type
1166: {
1167: return $this->unionTypes(static fn (Type $type): Type => $type->searchArray($needleType, $strict));
1168: }
1169:
1170: public function shiftArray(): Type
1171: {
1172: return $this->unionTypes(static fn (Type $type): Type => $type->shiftArray());
1173: }
1174:
1175: public function shuffleArray(): Type
1176: {
1177: return $this->unionTypes(static fn (Type $type): Type => $type->shuffleArray());
1178: }
1179:
1180: public function sliceArray(Type $offsetType, Type $lengthType, TrinaryLogic $preserveKeys): Type
1181: {
1182: return $this->unionTypes(static fn (Type $type): Type => $type->sliceArray($offsetType, $lengthType, $preserveKeys));
1183: }
1184:
1185: public function spliceArray(Type $offsetType, Type $lengthType, Type $replacementType): Type
1186: {
1187: return $this->unionTypes(static fn (Type $type): Type => $type->spliceArray($offsetType, $lengthType, $replacementType));
1188: }
1189:
1190: public function truncateListToSize(Type $sizeType): Type
1191: {
1192: return $this->unionTypes(static fn (Type $type): Type => $type->truncateListToSize($sizeType));
1193: }
1194:
1195: public function makeListMaybe(): Type
1196: {
1197: return $this->unionTypes(static fn (Type $type): Type => $type->makeListMaybe());
1198: }
1199:
1200: public function mapValueType(callable $cb): Type
1201: {
1202: return $this->unionTypes(static fn (Type $type): Type => $type->mapValueType($cb));
1203: }
1204:
1205: public function mapKeyType(callable $cb): Type
1206: {
1207: return $this->unionTypes(static fn (Type $type): Type => $type->mapKeyType($cb));
1208: }
1209:
1210: public function makeAllArrayKeysOptional(): Type
1211: {
1212: return $this->unionTypes(static fn (Type $type): Type => $type->makeAllArrayKeysOptional());
1213: }
1214:
1215: public function changeKeyCaseArray(?int $case): Type
1216: {
1217: return $this->unionTypes(static fn (Type $type): Type => $type->changeKeyCaseArray($case));
1218: }
1219:
1220: public function filterArrayRemovingFalsey(): Type
1221: {
1222: return $this->unionTypes(static fn (Type $type): Type => $type->filterArrayRemovingFalsey());
1223: }
1224:
1225: public function getEnumCases(): array
1226: {
1227: return $this->pickFromTypes(
1228: static fn (Type $type) => $type->getEnumCases(),
1229: static fn (Type $type) => $type->isObject()->yes(),
1230: );
1231: }
1232:
1233: public function getEnumCaseObject(): ?EnumCaseObjectType
1234: {
1235: $cases = $this->getEnumCases();
1236:
1237: if (count($cases) === 1) {
1238: return $cases[0];
1239: }
1240:
1241: return null;
1242: }
1243:
1244: public function isCallable(): TrinaryLogic
1245: {
1246: return $this->isCallable ??= $this->unionResults(static fn (Type $type): TrinaryLogic => $type->isCallable());
1247: }
1248:
1249: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
1250: {
1251: $acceptors = [];
1252:
1253: foreach ($this->types as $type) {
1254: if ($type->isCallable()->no()) {
1255: continue;
1256: }
1257:
1258: $acceptors = array_merge($acceptors, $type->getCallableParametersAcceptors($scope));
1259: }
1260:
1261: if (count($acceptors) === 0) {
1262: throw new ShouldNotHappenException();
1263: }
1264:
1265: return $acceptors;
1266: }
1267:
1268: public function isCloneable(): TrinaryLogic
1269: {
1270: return $this->unionResults(static fn (Type $type): TrinaryLogic => $type->isCloneable());
1271: }
1272:
1273: public function isSmallerThan(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
1274: {
1275: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isSmallerThan($otherType, $phpVersion));
1276: }
1277:
1278: public function isSmallerThanOrEqual(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
1279: {
1280: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isSmallerThanOrEqual($otherType, $phpVersion));
1281: }
1282:
1283: public function getKindMask(): int
1284: {
1285: $mask = 0;
1286: foreach ($this->types as $type) {
1287: $mask |= $type->getKindMask();
1288: }
1289:
1290: return $mask;
1291: }
1292:
1293: public function isNull(): TrinaryLogic
1294: {
1295: return $this->isNull ??= $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isNull());
1296: }
1297:
1298: public function isConstantValue(): TrinaryLogic
1299: {
1300: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isConstantValue());
1301: }
1302:
1303: public function isConstantScalarValue(): TrinaryLogic
1304: {
1305: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isConstantScalarValue());
1306: }
1307:
1308: public function getConstantScalarTypes(): array
1309: {
1310: return $this->notBenevolentPickFromTypes(static fn (Type $type) => $type->getConstantScalarTypes());
1311: }
1312:
1313: public function getConstantScalarValues(): array
1314: {
1315: return $this->notBenevolentPickFromTypes(static fn (Type $type) => $type->getConstantScalarValues());
1316: }
1317:
1318: public function isTrue(): TrinaryLogic
1319: {
1320: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isTrue());
1321: }
1322:
1323: public function isFalse(): TrinaryLogic
1324: {
1325: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isFalse());
1326: }
1327:
1328: public function isBoolean(): TrinaryLogic
1329: {
1330: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isBoolean());
1331: }
1332:
1333: public function isFloat(): TrinaryLogic
1334: {
1335: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isFloat());
1336: }
1337:
1338: public function isInteger(): TrinaryLogic
1339: {
1340: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $type->isInteger());
1341: }
1342:
1343: public function getSmallerType(PhpVersion $phpVersion): Type
1344: {
1345: return $this->unionTypes(static fn (Type $type): Type => $type->getSmallerType($phpVersion));
1346: }
1347:
1348: public function getSmallerOrEqualType(PhpVersion $phpVersion): Type
1349: {
1350: return $this->unionTypes(static fn (Type $type): Type => $type->getSmallerOrEqualType($phpVersion));
1351: }
1352:
1353: public function getGreaterType(PhpVersion $phpVersion): Type
1354: {
1355: return $this->unionTypes(static fn (Type $type): Type => $type->getGreaterType($phpVersion));
1356: }
1357:
1358: public function getGreaterOrEqualType(PhpVersion $phpVersion): Type
1359: {
1360: return $this->unionTypes(static fn (Type $type): Type => $type->getGreaterOrEqualType($phpVersion));
1361: }
1362:
1363: public function isGreaterThan(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
1364: {
1365: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $otherType->isSmallerThan($type, $phpVersion));
1366: }
1367:
1368: public function isGreaterThanOrEqual(Type $otherType, PhpVersion $phpVersion): TrinaryLogic
1369: {
1370: return $this->notBenevolentUnionResults(static fn (Type $type): TrinaryLogic => $otherType->isSmallerThanOrEqual($type, $phpVersion));
1371: }
1372:
1373: public function toBoolean(): BooleanType
1374: {
1375: /** @var BooleanType $type */
1376: $type = $this->unionTypes(static fn (Type $type): BooleanType => $type->toBoolean());
1377:
1378: return $type;
1379: }
1380:
1381: public function toNumber(): Type
1382: {
1383: $type = $this->unionTypes(static fn (Type $type): Type => $type->toNumber());
1384:
1385: return $type;
1386: }
1387:
1388: public function toNumberSet(): ?NumberSet
1389: {
1390: $integerIntervals = [];
1391: $floatIntervals = [];
1392: $nan = false;
1393: foreach ($this->types as $type) {
1394: $numberSet = $type->toNumberSet();
1395: if ($numberSet === null) {
1396: return null;
1397: }
1398:
1399: $integerIntervals = array_merge($integerIntervals, $numberSet->getIntegerIntervals());
1400: $floatIntervals = array_merge($floatIntervals, $numberSet->getFloatIntervals());
1401: $nan = $nan || $numberSet->hasNan();
1402: }
1403:
1404: return new NumberSet($integerIntervals, $floatIntervals, $nan);
1405: }
1406:
1407: public function toBitwiseNotType(): Type
1408: {
1409: return $this->unionTypes(static fn (Type $type): Type => $type->toBitwiseNotType());
1410: }
1411:
1412: public function toGetClassResultType(): Type
1413: {
1414: return $this->unionTypes(static fn (Type $type): Type => $type->toGetClassResultType());
1415: }
1416:
1417: public function toClassConstantType(ReflectionProvider $reflectionProvider): Type
1418: {
1419: return $this->unionTypes(static fn (Type $type): Type => $type->toClassConstantType($reflectionProvider));
1420: }
1421:
1422: public function toObjectTypeForInstanceofCheck(): ClassNameToObjectTypeResult
1423: {
1424: $types = [];
1425: $uncertainty = false;
1426: foreach ($this->getTypes() as $innerType) {
1427: $result = $innerType->toObjectTypeForInstanceofCheck();
1428: $types[] = $result->type;
1429: if (!$result->uncertainty) {
1430: continue;
1431: }
1432:
1433: $uncertainty = true;
1434: }
1435:
1436: return new ClassNameToObjectTypeResult(TypeCombinator::union(...$types), $uncertainty);
1437: }
1438:
1439: public function toObjectTypeForIsACheck(Type $objectOrClassType, bool $allowString, bool $allowSameClass): ClassNameToObjectTypeResult
1440: {
1441: $types = [];
1442: $uncertainty = false;
1443: foreach ($this->getTypes() as $innerType) {
1444: $result = $innerType->toObjectTypeForIsACheck($objectOrClassType, $allowString, $allowSameClass);
1445: $types[] = $result->type;
1446: if (!$result->uncertainty) {
1447: continue;
1448: }
1449:
1450: $uncertainty = true;
1451: }
1452:
1453: return new ClassNameToObjectTypeResult(TypeCombinator::union(...$types), $uncertainty);
1454: }
1455:
1456: public function toAbsoluteNumber(): Type
1457: {
1458: $type = $this->unionTypes(static fn (Type $type): Type => $type->toAbsoluteNumber());
1459:
1460: return $type;
1461: }
1462:
1463: public function toString(): Type
1464: {
1465: $type = $this->unionTypes(static fn (Type $type): Type => $type->toString());
1466:
1467: return $type;
1468: }
1469:
1470: public function toInteger(): Type
1471: {
1472: $type = $this->unionTypes(static fn (Type $type): Type => $type->toInteger());
1473:
1474: return $type;
1475: }
1476:
1477: public function toFloat(): Type
1478: {
1479: $type = $this->unionTypes(static fn (Type $type): Type => $type->toFloat());
1480:
1481: return $type;
1482: }
1483:
1484: public function toArray(): Type
1485: {
1486: $type = $this->unionTypes(static fn (Type $type): Type => $type->toArray());
1487:
1488: return $type;
1489: }
1490:
1491: public function toArrayKey(): Type
1492: {
1493: $level = ReportUnsafeArrayStringKeyCastingToggle::getLevel();
1494: if ($level !== ReportUnsafeArrayStringKeyCastingToggle::PREVENT || $this->isInteger()->no()) {
1495: return $this->unionTypes(static fn (Type $type): Type => $type->toArrayKey());
1496: }
1497:
1498: return $this->unionTypes(static function (Type $type): Type {
1499: if ($type instanceof StringType) { // @phpstan-ignore phpstanApi.instanceofType
1500: return $type;
1501: }
1502:
1503: return $type->toArrayKey();
1504: });
1505: }
1506:
1507: public function toCoercedArgumentType(bool $strictTypes): Type
1508: {
1509: return $this->unionTypes(static fn (Type $type): Type => $type->toCoercedArgumentType($strictTypes));
1510: }
1511:
1512: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
1513: {
1514: if ($receivedType instanceof IterableType) {
1515: $receivedType = $receivedType->toArrayOrTraversable();
1516: }
1517:
1518: // A received type that one of the members definitely accepts is
1519: // absorbed by that member: it tells nothing about the other members,
1520: // so T|null receiving null must not bind T. Only what no member
1521: // absorbs is inferred against the remaining members below.
1522: // never is the exception: every member is its supertype, so which
1523: // member absorbs it is meaningless - it always has to be inferred.
1524: $types = TemplateTypeMap::createEmpty();
1525: $receivedTypes = $receivedType instanceof UnionType ? $receivedType->getTypes() : [$receivedType];
1526: $remainingReceivedTypes = [];
1527: foreach ($receivedTypes as $receivedInnerType) {
1528: if ($receivedInnerType instanceof NeverType) {
1529: $remainingReceivedTypes[] = $receivedInnerType;
1530: continue;
1531: }
1532: foreach ($this->types as $type) {
1533: if ($type->isSuperTypeOf($receivedInnerType)->yes()) {
1534: $types = $types->union($type->inferTemplateTypes($receivedInnerType));
1535: continue 2;
1536: }
1537: }
1538: $remainingReceivedTypes[] = $receivedInnerType;
1539: }
1540: if (count($remainingReceivedTypes) === 0) {
1541: return $types->union($this->getAbsorbedTemplateTypes($types));
1542: }
1543: if (count($remainingReceivedTypes) !== count($receivedTypes)) {
1544: $receivedType = TypeCombinator::union(...$remainingReceivedTypes);
1545: }
1546:
1547: foreach ($this->types as $type) {
1548: if (self::getNakedTemplateType($type) !== null) {
1549: continue;
1550: }
1551: $types = $types->union($type->inferTemplateTypes($receivedType));
1552: }
1553:
1554: // the parts of the argument the other members infer nothing from, like 1 of
1555: // 1|array{2} for T|array<T>, are values of the naked templates
1556: $receivedForNaked = [];
1557: foreach ($receivedType instanceof UnionType ? $receivedType->getTypes() : [$receivedType] as $receivedInnerType) {
1558: foreach ($this->types as $type) {
1559: if (self::getNakedTemplateType($type) !== null) {
1560: continue;
1561: }
1562: // a recursive member infers nothing from what it is already inferring from
1563: // further out, like the nested arrays of __recursive<array<T|__recursion>>
1564: if (
1565: !$type->inferTemplateTypes($receivedInnerType)->isEmpty()
1566: || ($type instanceof RecursiveType && !$receivedInnerType instanceof NeverType && TemplateTypeHelper::resolveToBounds($type)->isSuperTypeOf($receivedInnerType)->yes())
1567: ) {
1568: continue 2;
1569: }
1570: }
1571: $receivedForNaked[] = $receivedInnerType;
1572: }
1573: if (count($receivedForNaked) === 0) {
1574: return $types;
1575: }
1576:
1577: $receivedForNakedType = TypeCombinator::union(...$receivedForNaked);
1578: foreach ($this->types as $type) {
1579: if (self::getNakedTemplateType($type) === null) {
1580: continue;
1581: }
1582: $types = $types->union($type->inferTemplateTypes($receivedForNakedType));
1583: }
1584:
1585: return $types;
1586: }
1587:
1588: private static function getNakedTemplateType(Type $type): ?TemplateType
1589: {
1590: if ($type instanceof TemplateType) {
1591: return $type;
1592: }
1593:
1594: if ($type instanceof GenericClassStringType) {
1595: $genericType = $type->getGenericType();
1596: if ($genericType instanceof TemplateType) {
1597: return $genericType;
1598: }
1599: }
1600:
1601: return null;
1602: }
1603:
1604: /**
1605: * Naked template members that the absorption above left without a type were not
1606: * forgotten - the parameter type declares them next to a member that took the
1607: * whole argument, so there was nothing for them to infer from.
1608: */
1609: private function getAbsorbedTemplateTypes(TemplateTypeMap $inferred): TemplateTypeMap
1610: {
1611: $absorbed = [];
1612: foreach ($this->types as $type) {
1613: $templateType = self::getNakedTemplateType($type);
1614: if ($templateType === null) {
1615: continue;
1616: }
1617: if ($inferred->hasType($templateType->getName())) {
1618: continue;
1619: }
1620:
1621: $absorbed[$templateType->getName()] = new AbsorbedTemplateArgumentType();
1622: }
1623:
1624: if (count($absorbed) === 0) {
1625: return TemplateTypeMap::createEmpty();
1626: }
1627:
1628: return new TemplateTypeMap($absorbed);
1629: }
1630:
1631: public function inferTemplateTypesOn(Type $templateType): TemplateTypeMap
1632: {
1633: $types = TemplateTypeMap::createEmpty();
1634:
1635: foreach ($this->types as $type) {
1636: $types = $types->union($templateType->inferTemplateTypes($type));
1637: }
1638:
1639: return $types;
1640: }
1641:
1642: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
1643: {
1644: $references = [];
1645:
1646: foreach ($this->types as $type) {
1647: foreach ($type->getReferencedTemplateTypes($positionVariance) as $reference) {
1648: $references[] = $reference;
1649: }
1650: }
1651:
1652: return $references;
1653: }
1654:
1655: public function traverse(callable $cb): Type
1656: {
1657: $types = [];
1658: $changed = false;
1659:
1660: foreach ($this->types as $type) {
1661: $newType = $cb($type);
1662: if ($type !== $newType) {
1663: $changed = true;
1664: }
1665: $types[] = $newType;
1666: }
1667:
1668: if ($changed) {
1669: return TypeCombinator::union(...$types);
1670: }
1671:
1672: return $this;
1673: }
1674:
1675: public function traverseSimultaneously(Type $right, callable $cb): Type
1676: {
1677: $rightTypes = TypeUtils::flattenTypes($right);
1678: $newTypes = [];
1679: $changed = false;
1680: foreach ($this->types as $innerType) {
1681: $candidates = [];
1682: foreach ($rightTypes as $i => $rightType) {
1683: if (!$innerType->isSuperTypeOf($rightType)->yes()) {
1684: continue;
1685: }
1686:
1687: $candidates[] = $rightType;
1688: unset($rightTypes[$i]);
1689: }
1690:
1691: if (count($candidates) === 0) {
1692: $newTypes[] = $innerType;
1693: continue;
1694: }
1695:
1696: $newType = $cb($innerType, TypeCombinator::union(...$candidates));
1697: if ($innerType !== $newType) {
1698: $changed = true;
1699: }
1700:
1701: $newTypes[] = $newType;
1702: }
1703:
1704: if ($changed) {
1705: return TypeCombinator::union(...$newTypes);
1706: }
1707:
1708: return $this;
1709: }
1710:
1711: public function tryRemove(Type $typeToRemove): ?Type
1712: {
1713: $finiteTypeSet = $this->getFiniteTypeSet();
1714: if ($finiteTypeSet !== null && $finiteTypeSet->isComplete()) {
1715: $key = FiniteTypeSet::key($typeToRemove);
1716: if ($key !== null) {
1717: if (!$finiteTypeSet->has($key)) {
1718: return null;
1719: }
1720:
1721: $remainingTypes = [];
1722: foreach ($finiteTypeSet->getMembers() as $memberKey => $member) {
1723: if ($memberKey === $key) {
1724: continue;
1725: }
1726:
1727: $remainingTypes[] = $member;
1728: }
1729:
1730: if (count($remainingTypes) === 1) {
1731: return $remainingTypes[0];
1732: }
1733:
1734: return new UnionType($remainingTypes);
1735: }
1736:
1737: // Every member of this union is a distinct value, and so is every member
1738: // of the removed one: the result is their set difference, which no order
1739: // of removals can sharpen. Taking it in one pass keeps removing a union
1740: // of values linear instead of re-deriving this union once per value.
1741: if ($typeToRemove instanceof self) {
1742: $keysToRemove = [];
1743: foreach ($typeToRemove->getTypes() as $innerTypeToRemove) {
1744: $innerKey = FiniteTypeSet::key($innerTypeToRemove);
1745: if ($innerKey === null) {
1746: $keysToRemove = null;
1747: break;
1748: }
1749:
1750: $keysToRemove[$innerKey] = true;
1751: }
1752:
1753: if ($keysToRemove !== null) {
1754: $remainingTypes = [];
1755: $removedAny = false;
1756: foreach ($finiteTypeSet->getMembers() as $memberKey => $member) {
1757: if (array_key_exists($memberKey, $keysToRemove)) {
1758: $removedAny = true;
1759: continue;
1760: }
1761:
1762: $remainingTypes[] = $member;
1763: }
1764:
1765: if (!$removedAny) {
1766: return null;
1767: }
1768:
1769: if (count($remainingTypes) === 0) {
1770: return new NeverType();
1771: }
1772:
1773: if (count($remainingTypes) === 1) {
1774: return $remainingTypes[0];
1775: }
1776:
1777: return new UnionType($remainingTypes);
1778: }
1779: }
1780: }
1781:
1782: $innerTypes = [];
1783: $changed = false;
1784: foreach ($this->types as $innerType) {
1785: $removed = TypeCombinator::remove($innerType, $typeToRemove);
1786: if (!$removed->equals($innerType)) {
1787: $changed = true;
1788: }
1789: if ($removed instanceof NeverType) {
1790: continue;
1791: }
1792: if ($removed instanceof self && !$removed instanceof TemplateType) {
1793: foreach ($removed->getTypes() as $removedInnerType) {
1794: $innerTypes[] = $removedInnerType;
1795: }
1796: } else {
1797: $innerTypes[] = $removed;
1798: }
1799: }
1800:
1801: if (!$changed) {
1802: return null;
1803: }
1804:
1805: if (count($innerTypes) === 0) {
1806: return new NeverType();
1807: }
1808:
1809: if (count($innerTypes) === 1) {
1810: return $innerTypes[0];
1811: }
1812:
1813: return new UnionType($innerTypes);
1814: }
1815:
1816: public function arithmeticPower(Type $exponent, PhpVersion $phpVersion): Type
1817: {
1818: return $this->unionTypes(static fn (Type $type): Type => $type->arithmeticPower($exponent, $phpVersion));
1819: }
1820:
1821: public function getFiniteTypes(): array
1822: {
1823: if ($this->finiteTypes !== null) {
1824: return $this->finiteTypes;
1825: }
1826:
1827: $types = $this->notBenevolentPickFromTypes(static fn (Type $type) => $type->getFiniteTypes());
1828: $uniquedTypes = [];
1829: foreach ($types as $type) {
1830: // These are finite types, so FiniteTypeSet keys them by the value they
1831: // stand for - which is what the uniquing wants and what describe() was
1832: // standing in for. Floats have no such key (equals() does not agree with
1833: // value identity for them) and keep describing themselves.
1834: $uniquedTypes[FiniteTypeSet::key($type) ?? $type->describe(VerbosityLevel::cache())] = $type;
1835: }
1836:
1837: if (count($uniquedTypes) > InitializerExprTypeResolver::CALCULATE_SCALARS_LIMIT) {
1838: return $this->finiteTypes = [];
1839: }
1840:
1841: return $this->finiteTypes = array_values($uniquedTypes);
1842: }
1843:
1844: /**
1845: * @param callable(Type $type): TrinaryLogic $getResult
1846: */
1847: protected function unionResults(callable $getResult): TrinaryLogic
1848: {
1849: return TrinaryLogic::lazyExtremeIdentity($this->types, $getResult);
1850: }
1851:
1852: /**
1853: * @param callable(Type $type): TrinaryLogic $getResult
1854: */
1855: private function notBenevolentUnionResults(callable $getResult): TrinaryLogic
1856: {
1857: return TrinaryLogic::lazyExtremeIdentity($this->types, $getResult);
1858: }
1859:
1860: /**
1861: * @param callable(Type $type): Type $getType
1862: */
1863: protected function unionTypes(callable $getType): Type
1864: {
1865: $newTypes = [];
1866: $changed = false;
1867: foreach ($this->types as $type) {
1868: $newType = $getType($type);
1869: if ($newType !== $type) {
1870: $changed = true;
1871: }
1872: $newTypes[] = $newType;
1873: }
1874:
1875: if (!$changed) {
1876: return $this;
1877: }
1878:
1879: // a join of what the members answer, such as the values of all their arrays
1880: return TypeCombinator::widen(TypeCombinator::union(...$newTypes));
1881: }
1882:
1883: /**
1884: * @template T
1885: * @param callable(Type $type): list<T> $getValues
1886: * @param callable(Type $type): bool $criteria
1887: * @return list<T>
1888: */
1889: protected function pickFromTypes(
1890: callable $getValues,
1891: callable $criteria,
1892: ): array
1893: {
1894: $values = [];
1895: foreach ($this->types as $type) {
1896: $innerValues = $getValues($type);
1897: if ($innerValues === []) {
1898: return [];
1899: }
1900:
1901: foreach ($innerValues as $innerType) {
1902: $values[] = $innerType;
1903: }
1904: }
1905:
1906: return $values;
1907: }
1908:
1909: public function toPhpDocNode(): TypeNode
1910: {
1911: return new UnionTypeNode(array_map(static fn (Type $type) => $type->toPhpDocNode(), $this->getSortedTypes()));
1912: }
1913:
1914: public function toNativePhpTypeNode(NativeTypePosition $position)
1915: {
1916: return NativePhpTypeNodeHelper::union($this, $position);
1917: }
1918:
1919: /**
1920: * @template T
1921: * @param callable(Type $type): list<T> $getValues
1922: * @return list<T>
1923: */
1924: private function notBenevolentPickFromTypes(callable $getValues): array
1925: {
1926: $values = [];
1927: foreach ($this->types as $type) {
1928: $innerValues = $getValues($type);
1929: if ($innerValues === []) {
1930: return [];
1931: }
1932:
1933: foreach ($innerValues as $innerType) {
1934: $values[] = $innerType;
1935: }
1936: }
1937:
1938: return $values;
1939: }
1940:
1941: public function hasTemplateOrLateResolvableType(): bool
1942: {
1943: if ($this->hasTemplateOrLateResolvableType !== null) {
1944: return $this->hasTemplateOrLateResolvableType;
1945: }
1946:
1947: foreach ($this->types as $type) {
1948: if (!$type->hasTemplateOrLateResolvableType()) {
1949: continue;
1950: }
1951:
1952: return $this->hasTemplateOrLateResolvableType = true;
1953: }
1954:
1955: return $this->hasTemplateOrLateResolvableType = false;
1956: }
1957:
1958: public function hasUnresolvedTemplateArgumentType(): bool
1959: {
1960: foreach ($this->types as $type) {
1961: if ($type->hasUnresolvedTemplateArgumentType()) {
1962: return true;
1963: }
1964: }
1965:
1966: return false;
1967: }
1968:
1969: public function getPossiblyLooselyEqualType(PhpVersion $phpVersion): Type
1970: {
1971: return $this->possiblyLooselyEqualTypes[$phpVersion->getVersionId()] ??= $this->toValueSet()->getPossiblyLooselyEqualType($phpVersion);
1972: }
1973:
1974: public function getAlwaysLooselyEqualType(PhpVersion $phpVersion): Type
1975: {
1976: return $this->alwaysLooselyEqualTypes[$phpVersion->getVersionId()] ??= $this->toValueSet()->getAlwaysLooselyEqualType($phpVersion);
1977: }
1978:
1979: public function toValueSet(): ValueSet
1980: {
1981: $valueSet = ValueSet::createEmpty();
1982: foreach ($this->types as $type) {
1983: $valueSet = $valueSet->union($type->toValueSet());
1984: }
1985:
1986: return $valueSet;
1987: }
1988:
1989: public function tryUnion(Type $otherType): ?Type
1990: {
1991: return null;
1992: }
1993:
1994: public function tryIntersect(Type $otherType): ?Type
1995: {
1996: return null;
1997: }
1998:
1999: }
2000: