1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type\Constant;
4:
5: use Nette\Utils\Strings;
6: use PhpParser\Node\Identifier;
7: use PHPStan\Analyser\OutOfClassScope;
8: use PHPStan\DependencyInjection\BleedingEdgeToggle;
9: use PHPStan\Php\PhpVersion;
10: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode;
11: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode;
12: use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode;
13: use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
14: use PHPStan\PhpDocParser\Ast\Type\ArrayShapeUnsealedTypeNode;
15: use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode;
16: use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
17: use PHPStan\PhpDocParser\Ast\Type\TemplateDeclarationTypeNode;
18: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
19: use PHPStan\Reflection\Callables\FunctionCallableVariant;
20: use PHPStan\Reflection\ClassMemberAccessAnswerer;
21: use PHPStan\Reflection\InaccessibleMethod;
22: use PHPStan\Reflection\InitializerExprTypeResolver;
23: use PHPStan\Reflection\PhpVersionStaticAccessor;
24: use PHPStan\Reflection\TrivialParametersAcceptor;
25: use PHPStan\Rules\Arrays\AllowedArrayKeysTypes;
26: use PHPStan\ShouldNotHappenException;
27: use PHPStan\TrinaryLogic;
28: use PHPStan\Turbo\ShadowedByTurboExtension;
29: use PHPStan\Type\AcceptsResult;
30: use PHPStan\Type\Accessory\AccessoryArrayListType;
31: use PHPStan\Type\Accessory\AccessoryLowercaseStringType;
32: use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
33: use PHPStan\Type\Accessory\AccessoryNonFalsyStringType;
34: use PHPStan\Type\Accessory\AccessoryNumericStringType;
35: use PHPStan\Type\Accessory\AccessoryUppercaseStringType;
36: use PHPStan\Type\Accessory\HasOffsetType;
37: use PHPStan\Type\Accessory\HasOffsetValueType;
38: use PHPStan\Type\Accessory\NonEmptyArrayType;
39: use PHPStan\Type\ArrayAlgebra;
40: use PHPStan\Type\ArrayType;
41: use PHPStan\Type\BenevolentUnionType;
42: use PHPStan\Type\BooleanType;
43: use PHPStan\Type\ClassStringType;
44: use PHPStan\Type\CompoundType;
45: use PHPStan\Type\ConstantScalarType;
46: use PHPStan\Type\ErrorType;
47: use PHPStan\Type\GeneralizePrecision;
48: use PHPStan\Type\Generic\ArrayKeyTemplateHelper;
49: use PHPStan\Type\Generic\TemplateMixedType;
50: use PHPStan\Type\Generic\TemplateStrictMixedType;
51: use PHPStan\Type\Generic\TemplateType;
52: use PHPStan\Type\Generic\TemplateTypeMap;
53: use PHPStan\Type\Generic\TemplateTypeReference;
54: use PHPStan\Type\Generic\TemplateTypeVariance;
55: use PHPStan\Type\InstanceofDeprecated;
56: use PHPStan\Type\IntegerRangeType;
57: use PHPStan\Type\IntegerType;
58: use PHPStan\Type\IntersectionType;
59: use PHPStan\Type\IsSuperTypeOfResult;
60: use PHPStan\Type\MixedType;
61: use PHPStan\Type\NativeTypePosition;
62: use PHPStan\Type\NeverType;
63: use PHPStan\Type\NonAcceptingNeverType;
64: use PHPStan\Type\NullType;
65: use PHPStan\Type\ObjectWithoutClassType;
66: use PHPStan\Type\RecursionGuard;
67: use PHPStan\Type\StaticTypeFactory;
68: use PHPStan\Type\StrictMixedType;
69: use PHPStan\Type\StringType;
70: use PHPStan\Type\Traits\ArrayTypeTrait;
71: use PHPStan\Type\Traits\NonObjectTypeTrait;
72: use PHPStan\Type\Traits\UndecidedComparisonTypeTrait;
73: use PHPStan\Type\Traverser\UnsafeArrayStringKeyCastingTraverser;
74: use PHPStan\Type\Type;
75: use PHPStan\Type\TypeCombinator;
76: use PHPStan\Type\UnionType;
77: use PHPStan\Type\VerbosityLevel;
78: use function array_flip;
79: use function array_key_exists;
80: use function array_keys;
81: use function array_map;
82: use function array_merge;
83: use function array_pop;
84: use function array_push;
85: use function array_shift;
86: use function array_slice;
87: use function array_unique;
88: use function array_values;
89: use function assert;
90: use function count;
91: use function implode;
92: use function in_array;
93: use function is_int;
94: use function is_string;
95: use function ksort;
96: use function max;
97: use function min;
98: use function pow;
99: use function range;
100: use function sort;
101: use function spl_object_id;
102: use function sprintf;
103: use function str_contains;
104: use function strtolower;
105: use function strtoupper;
106: use function usort;
107: use const CASE_LOWER;
108: use const CASE_UPPER;
109:
110: /**
111: * @api
112: */
113: #[InstanceofDeprecated(insteadUse: 'Type::getConstantArrays()')]
114: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/ConstantArrayType.cpp')]
115: class ConstantArrayType implements Type
116: {
117:
118: use ArrayTypeTrait {
119: chunkArray as traitChunkArray;
120: }
121: use NonObjectTypeTrait;
122: use UndecidedComparisonTypeTrait;
123:
124: private const DESCRIBE_LIMIT = 8;
125: private const CHUNK_FINITE_TYPES_LIMIT = 5;
126: private const UNSEALED_ARRAY_SHAPES_LINK = 'https://phpstan.org/blog/phpstan-2-2-unsealed-array-shapes-safer-array-keys';
127:
128: private TrinaryLogic $isList;
129:
130: /** @var array{Type, Type}|null */
131: private ?array $unsealed; // phpcs:ignore
132:
133: /** @var self[]|null */
134: private ?array $allArrays = null;
135:
136: private ?Type $iterableKeyType = null;
137:
138: private ?Type $iterableValueType = null;
139:
140: private ?Type $keyTypesUnion = null;
141:
142: /** @var array<int|string, int>|null */
143: private ?array $keyIndexMap = null;
144:
145: /** @var array<int, int>|null */
146: private ?array $optionalKeySet = null;
147:
148: /**
149: * The unsealed key and value types as they are declared when the key declares a template
150: * the value is written with, as ...<K of key-of<Config>, Config[K]>. $unsealed then holds
151: * them with the template standing for its bound, for what does not keep a key with its value.
152: *
153: * @var array{Type, Type}|null
154: */
155: private ?array $unsealedDeclaration = null;
156:
157: private ?bool $hasTemplateOrLateResolvableType = null;
158:
159: /** @var list<non-empty-string>|null */
160: private ?array $referencedClasses = null;
161:
162: /** @var array{TemplateTypeVariance, list<TemplateTypeReference>}|null */
163: private ?array $referencedTemplateTypes = null;
164:
165: /**
166: * @api
167: * @param list<ConstantIntegerType|ConstantStringType> $keyTypes
168: * @param array<int, Type> $valueTypes
169: * @param list<int> $nextAutoIndexes
170: * @param int[] $optionalKeys
171: * @param array{Type, Type}|null $unsealed
172: * @param bool $keyOrderKnown false for a shape that only lists the keys that are present, like one written in PHPDoc
173: */
174: public function __construct(
175: private array $keyTypes,
176: private array $valueTypes,
177: private array $nextAutoIndexes = [0],
178: private array $optionalKeys = [],
179: ?TrinaryLogic $isList = null,
180: ?array $unsealed = null,
181: private bool $keyOrderKnown = true,
182: )
183: {
184: assert(count($keyTypes) === count($valueTypes));
185:
186: // Fill in `$isList` from the shape when the caller didn't pass one.
187: // For empty CATs the answer derives from the unsealed key type
188: // (no explicit keys to inspect); for non-empty ones the default
189: // is `No` and the caller is expected to assert list-ness via
190: // `makeList()` if appropriate.
191: if ($isList === null) {
192: if (count($this->keyTypes) === 0) {
193: if ($unsealed === null) {
194: $isList = TrinaryLogic::createYes();
195: } else {
196: [$unsealedKeyType] = $unsealed;
197: if ($unsealedKeyType instanceof NeverType && $unsealedKeyType->isExplicit()) {
198: $isList = TrinaryLogic::createYes();
199: } elseif ($unsealedKeyType->isInteger()->yes()) {
200: $isList = TrinaryLogic::createMaybe();
201: } else {
202: $isList = TrinaryLogic::createNo();
203: }
204: }
205: } else {
206: $isList = TrinaryLogic::createNo();
207: }
208: }
209: $this->isList = $isList;
210: // a list has its keys in the order it lists them
211: if ($isList->yes()) {
212: $this->keyOrderKnown = true;
213: }
214:
215: if ($unsealed !== null) {
216: // Only a BenevolentUnionType describes with the surrounding parentheses of
217: // '(int|string)' / '(int|non-decimal-int-string)', so skip the describe() call
218: // for every other key type.
219: if ($unsealed[0] instanceof BenevolentUnionType && in_array($unsealed[0]->describe(VerbosityLevel::value()), ['(int|string)', '(int|non-decimal-int-string)'], true)) {
220: $unsealed[0] = new MixedType();
221: }
222: if ($unsealed[0] instanceof StrictMixedType && !$unsealed[0] instanceof TemplateStrictMixedType) {
223: $unsealed[0] = (new UnionType([new StringType(), new IntegerType()]))->toArrayKey();
224: }
225: if ($unsealed[0] instanceof NeverType && $unsealed[0]->isExplicit()) {
226: $unsealed[1] = new NeverType(true);
227: }
228: $template = $unsealed[0]->hasTemplateOrLateResolvableType() ? ArrayKeyTemplateHelper::findTemplate($unsealed[0]) : null;
229: if ($template !== null) {
230: $this->unsealedDeclaration = $unsealed;
231: $unsealed = [
232: ArrayKeyTemplateHelper::resolveKeyType($unsealed[0], $template),
233: ArrayKeyTemplateHelper::getValueType($unsealed[0], $unsealed[1], $template, null),
234: ];
235: }
236: } elseif (BleedingEdgeToggle::isBleedingEdge()) {
237: $never = new NeverType(true);
238: $unsealed = [$never, $never];
239: }
240: $this->unsealed = $unsealed;
241: }
242:
243: /** @var array<int, Type> */
244: private array $normalizedValueTypes = [];
245:
246: /** @var array<int, Type> */
247: private array $generalizedTypes = [];
248:
249: /**
250: * Whether the keys come in the order they are listed. A literal array knows its key order;
251: * an array shape written in PHPDoc only lists the keys that are present. A list and a shape
252: * with fewer than two keys know the order either way.
253: */
254: public function isKeyOrderKnown(): bool
255: {
256: return $this->keyOrderKnown || count($this->keyTypes) < 2 || $this->isList->yes();
257: }
258:
259: /** Whether the shape tells apart the orders of two of its keys, beyond what a list does. */
260: private function hasKeyOrderToKeep(): bool
261: {
262: return $this->keyOrderKnown && count($this->keyTypes) > 1 && !$this->isList->yes();
263: }
264:
265: /**
266: * The same shape without the order of its keys, as a PHPDoc shape that lists them.
267: * A template type's bound keeps it - pass its bound instead.
268: */
269: public function forgetKeyOrder(): self
270: {
271: if (!$this->keyOrderKnown) {
272: return $this;
273: }
274:
275: return new self($this->keyTypes, $this->valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $this->isList, $this->unsealedDeclaration ?? $this->unsealed, false);
276: }
277:
278: private function knowKeyOrder(): self
279: {
280: if ($this->keyOrderKnown) {
281: return $this;
282: }
283:
284: return new self($this->keyTypes, $this->valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $this->isList, $this->unsealedDeclaration ?? $this->unsealed, true);
285: }
286:
287: /**
288: * Whether both shapes know their key order and list the keys they share in the same order.
289: * Two such shapes that list them in different orders never hold the same array.
290: */
291: public function sharesKeyOrderWith(self $other): bool
292: {
293: if (!$this->isKeyOrderKnown() || !$other->isKeyOrderKnown()) {
294: return false;
295: }
296:
297: $otherKeyIndexMap = $other->getKeyIndexMap();
298: $lastIndex = -1;
299: foreach ($this->keyTypes as $keyType) {
300: $otherIndex = $otherKeyIndexMap[$keyType->getValue()] ?? null;
301: if ($otherIndex === null) {
302: continue;
303: }
304: if ($otherIndex < $lastIndex) {
305: return false;
306: }
307: $lastIndex = $otherIndex;
308: }
309:
310: return true;
311: }
312:
313: public function isSealed(): TrinaryLogic
314: {
315: return $this->isUnsealed()->negate();
316: }
317:
318: public function isUnsealed(): TrinaryLogic
319: {
320: $unsealed = $this->unsealed;
321: if ($unsealed === null) {
322: return TrinaryLogic::createMaybe();
323: }
324:
325: [$keyType] = $unsealed;
326:
327: return TrinaryLogic::createFromBoolean(!$keyType instanceof NeverType || !$keyType->isExplicit());
328: }
329:
330: /**
331: * The unsealed key and value types, with the template an unsealed key declares
332: * standing for its bound: ...<string, list<string>> for ...<K of string, list<K>>.
333: *
334: * @phpstan-pure
335: * @return array{Type, Type}|null
336: */
337: public function getUnsealedTypes(): ?array
338: {
339: return $this->unsealed;
340: }
341:
342: /**
343: * The unsealed key and value types as they are declared, as ...<K of string, list<K>>
344: * for an unsealed key that declares a template the value is written with, for what keeps
345: * each extra key with its value.
346: *
347: * @phpstan-pure
348: * @return array{Type, Type}|null
349: */
350: public function getUnsealedDeclaredTypes(): ?array
351: {
352: return $this->unsealedDeclaration ?? $this->unsealed;
353: }
354:
355: /**
356: * The template the unsealed key declares, with the declared unsealed key and value types.
357: *
358: * @return array{TemplateType, Type, Type}|null
359: */
360: private function getUnsealedKeyTemplate(): ?array
361: {
362: if ($this->unsealedDeclaration === null) {
363: return null;
364: }
365:
366: [$keyType, $valueType] = $this->unsealedDeclaration;
367: $template = ArrayKeyTemplateHelper::findTemplate($keyType);
368: if ($template === null) {
369: return null;
370: }
371:
372: return [$template, $keyType, $valueType];
373: }
374:
375: /**
376: * @internal
377: */
378: public function dropUnsealedTypes(): self
379: {
380: return $this->recreate(
381: $this->keyTypes,
382: $this->valueTypes,
383: $this->nextAutoIndexes,
384: $this->optionalKeys,
385: $this->isList,
386: null,
387: );
388: }
389:
390: /**
391: * @param list<ConstantIntegerType|ConstantStringType> $keyTypes
392: * @param array<int, Type> $valueTypes
393: * @param list<int> $nextAutoIndexes
394: * @param int[] $optionalKeys
395: * @param array{Type, Type}|null $unsealed
396: */
397: protected function recreate(
398: array $keyTypes,
399: array $valueTypes,
400: array $nextAutoIndexes,
401: array $optionalKeys,
402: ?TrinaryLogic $isList,
403: ?array $unsealed,
404: ): self
405: {
406: return new self($keyTypes, $valueTypes, $nextAutoIndexes, $optionalKeys, $isList, $this->keepUnsealedDeclaration($unsealed), $this->keyOrderKnown);
407: }
408:
409: /**
410: * The declared unsealed types in place of the bound form of them, when they are what is passed on unchanged.
411: *
412: * @param array{Type, Type}|null $unsealed
413: * @return array{Type, Type}|null
414: */
415: protected function keepUnsealedDeclaration(?array $unsealed): ?array
416: {
417: if ($this->unsealedDeclaration !== null && $unsealed !== null && $this->unsealed !== null && $unsealed[0] === $this->unsealed[0] && $unsealed[1] === $this->unsealed[1]) {
418: return $this->unsealedDeclaration;
419: }
420:
421: return $unsealed;
422: }
423:
424: public function getConstantArrays(): array
425: {
426: return [$this];
427: }
428:
429: public function getReferencedClasses(): array
430: {
431: if ($this->referencedClasses !== null) {
432: return $this->referencedClasses;
433: }
434:
435: $referencedClasses = [];
436: foreach ($this->getKeyTypes() as $keyType) {
437: foreach ($keyType->getReferencedClasses() as $referencedClass) {
438: $referencedClasses[] = $referencedClass;
439: }
440: }
441:
442: foreach ($this->getValueTypes() as $valueType) {
443: foreach ($valueType->getReferencedClasses() as $referencedClass) {
444: $referencedClasses[] = $referencedClass;
445: }
446: }
447:
448: if ($this->unsealed !== null) {
449: [$unsealedKeyType, $unsealedValueType] = $this->unsealed;
450: foreach ($unsealedKeyType->getReferencedClasses() as $referencedClass) {
451: $referencedClasses[] = $referencedClass;
452: }
453: foreach ($unsealedValueType->getReferencedClasses() as $referencedClass) {
454: $referencedClasses[] = $referencedClass;
455: }
456: }
457:
458: return $this->referencedClasses = $referencedClasses;
459: }
460:
461: public function getIterableKeyType(): Type
462: {
463: if ($this->iterableKeyType !== null) {
464: return $this->iterableKeyType;
465: }
466:
467: $keyTypesCount = count($this->keyTypes);
468: if ($keyTypesCount === 0) {
469: $keyType = new NeverType(true);
470: } elseif ($keyTypesCount === 1) {
471: $keyType = $this->keyTypes[0];
472: } else {
473: $keyType = new UnionType($this->keyTypes);
474: }
475:
476: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
477: $unsealedKeyType = $this->unsealed[0];
478: if ($unsealedKeyType instanceof MixedType && !$unsealedKeyType instanceof TemplateMixedType) {
479: $unsealedKeyType = (new BenevolentUnionType([new IntegerType(), new StringType()]))->toArrayKey();
480: } elseif ($unsealedKeyType instanceof StrictMixedType && !$unsealedKeyType instanceof TemplateStrictMixedType) {
481: $unsealedKeyType = (new BenevolentUnionType([new IntegerType(), new StringType()]))->toArrayKey();
482: }
483: $keyType = TypeCombinator::union($keyType, $unsealedKeyType);
484: }
485:
486: return $this->iterableKeyType = UnsafeArrayStringKeyCastingTraverser::castKeyType($keyType);
487: }
488:
489: public function getIterableValueType(): Type
490: {
491: if ($this->iterableValueType !== null) {
492: return $this->iterableValueType;
493: }
494:
495: $valueType = count($this->valueTypes) > 0 ? TypeCombinator::union(...$this->valueTypes) : new NeverType(true);
496: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
497: $valueType = TypeCombinator::union($valueType, $this->unsealed[1]);
498: }
499:
500: // a join of every value, which a big shape makes too big to compute with
501: return $this->iterableValueType = TypeCombinator::widen($valueType);
502: }
503:
504: private function getKeyTypesUnion(): Type
505: {
506: return $this->keyTypesUnion ??= count($this->keyTypes) > 0
507: ? TypeCombinator::union(...$this->keyTypes)
508: : new NeverType();
509: }
510:
511: public function getKeyType(): Type
512: {
513: return $this->getIterableKeyType();
514: }
515:
516: public function getItemType(): Type
517: {
518: return $this->getIterableValueType();
519: }
520:
521: public function isConstantValue(): TrinaryLogic
522: {
523: if ($this->isUnsealed()->yes()) {
524: return TrinaryLogic::createNo();
525: }
526:
527: return TrinaryLogic::createYes();
528: }
529:
530: /**
531: * @return list<int>
532: */
533: public function getNextAutoIndexes(): array
534: {
535: return $this->nextAutoIndexes;
536: }
537:
538: /**
539: * @return int[]
540: */
541: public function getOptionalKeys(): array
542: {
543: return $this->optionalKeys;
544: }
545:
546: /**
547: * @return self[]
548: */
549: public function getAllArrays(): array
550: {
551: if ($this->allArrays !== null) {
552: return $this->allArrays;
553: }
554:
555: if (count($this->optionalKeys) <= 10) {
556: $optionalKeysCombinations = $this->powerSet($this->optionalKeys);
557: } else {
558: $optionalKeysCombinations = [
559: [],
560: array_slice($this->optionalKeys, 0, 1, true),
561: array_slice($this->optionalKeys, -1, 1, true),
562: $this->optionalKeys,
563: ];
564: }
565:
566: $requiredKeys = [];
567: foreach (array_keys($this->keyTypes) as $i) {
568: if (in_array($i, $this->optionalKeys, true)) {
569: continue;
570: }
571: $requiredKeys[] = $i;
572: }
573:
574: $arrays = [];
575: foreach ($optionalKeysCombinations as $combination) {
576: $keys = array_merge($requiredKeys, $combination);
577: sort($keys);
578:
579: if ($this->isList->yes() && array_keys($keys) !== $keys) {
580: continue;
581: }
582:
583: if (count($keys) === 0 && $this->isUnsealed()->yes() && $this->unsealed !== null) {
584: // Variant with no explicit keys but real unsealed extras: the
585: // builder's getArray() would degrade this to a general
586: // ArrayType. Construct the CAT directly so the variant keeps
587: // its extras for downstream consumers (e.g. flattenTypes).
588: $arrays[] = new ConstantArrayType([], [], unsealed: $this->unsealed);
589: continue;
590: }
591:
592: $builder = ConstantArrayTypeBuilder::createEmpty();
593: if ($this->keyOrderKnown) {
594: $builder->makeKeyOrderKnown();
595: }
596: $builder->disableArrayDegradation();
597: foreach ($keys as $i) {
598: $builder->setOffsetValueType($this->keyTypes[$i], $this->valueTypes[$i]);
599: }
600: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
601: $builder->makeUnsealed($this->unsealed[0], $this->unsealed[1]);
602: }
603:
604: $array = $builder->getArray();
605: if (!$array instanceof self) {
606: throw new ShouldNotHappenException();
607: }
608:
609: $arrays[] = $array;
610: }
611:
612: return $this->allArrays = $arrays;
613: }
614:
615: /**
616: * @template T
617: * @param T[] $in
618: * @return T[][]
619: */
620: private function powerSet(array $in): array
621: {
622: $count = count($in);
623: $members = pow(2, $count);
624: $return = [];
625: for ($i = 0; $i < $members; $i++) {
626: $b = sprintf('%0' . $count . 'b', $i);
627: $out = [];
628: for ($j = 0; $j < $count; $j++) {
629: if ($b[$j] !== '1') {
630: continue;
631: }
632:
633: $out[] = $in[$j];
634: }
635: $return[] = $out;
636: }
637:
638: return $return;
639: }
640:
641: /**
642: * @return list<ConstantIntegerType|ConstantStringType>
643: */
644: public function getKeyTypes(): array
645: {
646: return $this->keyTypes;
647: }
648:
649: /**
650: * @return array<int, Type>
651: */
652: public function getValueTypes(): array
653: {
654: return $this->valueTypes;
655: }
656:
657: public function isOptionalKey(int $i): bool
658: {
659: $this->optionalKeySet ??= array_flip($this->optionalKeys);
660:
661: return isset($this->optionalKeySet[$i]);
662: }
663:
664: public function sortKeys(): self
665: {
666: $indices = array_keys($this->keyTypes);
667: usort($indices, fn (int $a, int $b): int => $this->keyTypes[$a]->getValue() <=> $this->keyTypes[$b]->getValue());
668:
669: return $this->reorderKeys($indices);
670: }
671:
672: /**
673: * This shape with its keys in the order of the first of the shapes that knows its key order
674: * and lists every key of this one, or without a known key order when none of them does.
675: * Fits the intersection of the shapes, whose keys come from more than one of them.
676: */
677: public function inKeyOrderOf(self ...$shapes): self
678: {
679: if (!$this->hasKeyOrderToKeep()) {
680: return $this;
681: }
682:
683: foreach ($shapes as $shape) {
684: if (!$shape->isKeyOrderKnown()) {
685: continue;
686: }
687:
688: $shapeKeyIndexMap = $shape->getKeyIndexMap();
689: $indices = [];
690: foreach ($this->keyTypes as $i => $keyType) {
691: $shapeIndex = $shapeKeyIndexMap[$keyType->getValue()] ?? null;
692: if ($shapeIndex === null) {
693: continue 2;
694: }
695: $indices[$shapeIndex] = $i;
696: }
697: ksort($indices);
698:
699: return $this->reorderKeys(array_values($indices));
700: }
701:
702: return $this->forgetKeyOrder();
703: }
704:
705: /** @param list<int> $indices the indices of the keys in their new order */
706: private function reorderKeys(array $indices): self
707: {
708: if ($indices === array_keys($this->keyTypes)) {
709: return $this;
710: }
711:
712: $newKeyTypes = [];
713: $newValueTypes = [];
714: $indexMap = [];
715: foreach ($indices as $newIdx => $oldIdx) {
716: $newKeyTypes[] = $this->keyTypes[$oldIdx];
717: $newValueTypes[] = $this->valueTypes[$oldIdx];
718: $indexMap[$oldIdx] = $newIdx;
719: }
720:
721: $newOptionalKeys = [];
722: foreach ($this->optionalKeys as $oldIdx) {
723: $newOptionalKeys[] = $indexMap[$oldIdx];
724: }
725: sort($newOptionalKeys);
726:
727: return $this->recreate(
728: $newKeyTypes,
729: $newValueTypes,
730: $this->nextAutoIndexes,
731: $newOptionalKeys,
732: $this->isList,
733: $this->unsealed,
734: );
735: }
736:
737: public function accepts(Type $type, bool $strictTypes): AcceptsResult
738: {
739: if ($type instanceof CompoundType && !$type instanceof IntersectionType) {
740: return $type->isAcceptedBy($this, $strictTypes);
741: }
742:
743: $constantArrays = $type->getConstantArrays();
744: if (count($constantArrays) === 1) {
745: // the shape that does not know its key order may hold its keys in another order than this one
746: if ($this->hasKeyOrderToKeep() && !$constantArrays[0]->isKeyOrderKnown()) {
747: return $this->forgetKeyOrder()->accepts($type, $strictTypes)->and(AcceptsResult::createMaybe());
748: }
749: // an array never has its keys in two orders
750: if ($this->isKeyOrderKnown() && $constantArrays[0]->isKeyOrderKnown() && !$this->sharesKeyOrderWith($constantArrays[0])) {
751: return AcceptsResult::createNo();
752: }
753: }
754:
755: $isUnsealed = $this->isUnsealed();
756: if (!$isUnsealed->yes()) {
757: if ($type instanceof self && count($this->keyTypes) === 0) {
758: return AcceptsResult::createFromBoolean(count($type->keyTypes) === 0);
759: }
760: }
761:
762: $result = $this->checkOurKeys($type, $strictTypes)->and(new AcceptsResult($type->isArray(), []));
763: if ($this->unsealed === null) {
764: if ($type->isOversizedArray()->yes()) {
765: if (!$result->no()) {
766: return AcceptsResult::createYes();
767: }
768: }
769:
770: return $result;
771: }
772:
773: if ($result->no()) {
774: return $result;
775: }
776:
777: [$unsealedKeyType, $unsealedValueType] = $this->unsealed;
778:
779: if ($isUnsealed->no()) {
780: if (!$type->isConstantArray()->yes()) {
781: return $result->and(AcceptsResult::createNo([
782: 'Sealed array shape can only accept a constant array. Extra keys are not allowed.',
783: ]));
784: }
785:
786: $constantArrays = $type->getConstantArrays();
787: if (count($constantArrays) !== 1) {
788: throw new ShouldNotHappenException('Type with more than one constant array occurred, should have been eliminated with `instanceof CompoundType` above.');
789: }
790:
791: $keys = [];
792: foreach ($constantArrays[0]->getKeyTypes() as $otherKeyType) {
793: $keys[$otherKeyType->getValue()] = $otherKeyType;
794: }
795:
796: foreach ($this->keyTypes as $keyType) {
797: unset($keys[$keyType->getValue()]);
798: }
799:
800: foreach ($keys as $extraKey) {
801: $result = $result->and(AcceptsResult::createNo([
802: sprintf('Sealed array shape does not accept array with extra key %s.', $extraKey->describe(VerbosityLevel::precise())),
803: ]));
804: }
805:
806: if (!$constantArrays[0]->isUnsealed()->no()) {
807: $result = $result->and(AcceptsResult::createNo([
808: 'Sealed array shape does not accept unsealed array shape.',
809: ]));
810: }
811:
812: return $result;
813: }
814:
815: $keyTemplate = $this->getUnsealedKeyTemplate();
816: if (!$type->isConstantArray()->yes()) {
817: if ($keyTemplate !== null) {
818: return $result->and((new ArrayType($keyTemplate[1], $keyTemplate[2]))->accepts($type, $strictTypes));
819: }
820:
821: return $result->and($unsealedKeyType->accepts($type->getIterableKeyType(), $strictTypes))
822: ->and($unsealedValueType->accepts($type->getIterableValueType(), $strictTypes));
823: }
824:
825: $constantArrays = $type->getConstantArrays();
826: if (count($constantArrays) !== 1) {
827: throw new ShouldNotHappenException('Type with more than one constant array occurred, should have been eliminated with `instanceof CompoundType` above.');
828: }
829:
830: $keys = [];
831: $constantArray = $constantArrays[0];
832: foreach ($constantArray->getKeyTypes() as $i => $otherKeyType) {
833: $keys[$otherKeyType->getValue()] = [$i, $otherKeyType];
834: }
835:
836: foreach ($this->keyTypes as $keyType) {
837: unset($keys[$keyType->getValue()]);
838: }
839:
840: foreach ($keys as [$i, $extraKeyType]) {
841: $acceptsKey = $unsealedKeyType->accepts($extraKeyType, $strictTypes)->decorateReasons(
842: static fn (string $reason) => sprintf(
843: 'Unsealed array key type %s does not accept extra key type %s: %s',
844: $unsealedKeyType->describe(VerbosityLevel::value()),
845: $extraKeyType->describe(VerbosityLevel::value()),
846: $reason,
847: ),
848: );
849: if (!$acceptsKey->yes() && count($acceptsKey->reasons) === 0) {
850: $acceptsKey = new AcceptsResult($acceptsKey->result, [
851: sprintf(
852: 'Unsealed array key type %s does not accept extra key type %s.',
853: $unsealedKeyType->describe(VerbosityLevel::value()),
854: $extraKeyType->describe(VerbosityLevel::value()),
855: ),
856: ]);
857: }
858: $result = $result->and($acceptsKey);
859:
860: $extraValueType = $constantArray->getValueTypes()[$i];
861: $unsealedValueTypeAtKey = $keyTemplate !== null
862: ? ArrayKeyTemplateHelper::getValueType($keyTemplate[1], $keyTemplate[2], $keyTemplate[0], $extraKeyType)
863: : $unsealedValueType;
864: $acceptsValue = ($keyTemplate !== null
865: ? ArrayKeyTemplateHelper::acceptsValue($keyTemplate[1], $keyTemplate[2], $keyTemplate[0], $extraKeyType, $extraValueType, $strictTypes)
866: : $unsealedValueType->accepts($extraValueType, $strictTypes))->decorateReasons(
867: static fn (string $reason) => sprintf(
868: 'Unsealed array value type %s does not accept extra offset %s with value type %s: %s',
869: $unsealedValueTypeAtKey->describe(VerbosityLevel::value()),
870: $extraKeyType->describe(VerbosityLevel::value()),
871: $extraValueType->describe(VerbosityLevel::value()),
872: $reason,
873: ),
874: );
875: if (!$acceptsValue->yes() && count($acceptsValue->reasons) === 0) {
876: $acceptsValue = new AcceptsResult($acceptsValue->result, [
877: sprintf(
878: 'Unsealed array value type %s does not accept extra offset %s with value type %s.',
879: $unsealedValueTypeAtKey->describe(VerbosityLevel::value()),
880: $extraKeyType->describe(VerbosityLevel::value()),
881: $extraValueType->describe(VerbosityLevel::value()),
882: ),
883: ]);
884: }
885: $result = $result->and($acceptsValue);
886: }
887:
888: $otherUnsealed = $constantArray->unsealed;
889: $otherUnsealedEntryTypes = ($constantArray->isUnsealed()->yes() ? $constantArray->getUnsealedDeclaredTypes() : null);
890: if ($keyTemplate !== null && $otherUnsealedEntryTypes !== null) {
891: return $result->and((new ArrayType($keyTemplate[1], $keyTemplate[2]))->accepts(new ArrayType($otherUnsealedEntryTypes[0], $otherUnsealedEntryTypes[1]), $strictTypes));
892: }
893: if ($otherUnsealed !== null && !$constantArray->isUnsealed()->no()) {
894: [$otherUnsealedKeyType, $otherUnsealedValueType] = $otherUnsealed;
895:
896: $acceptsUnsealedKey = $unsealedKeyType->accepts($otherUnsealedKeyType, $strictTypes)->decorateReasons(
897: static fn (string $reason) => sprintf(
898: 'Unsealed array key type %s does not accept unsealed array key type %s: %s',
899: $unsealedKeyType->describe(VerbosityLevel::value()),
900: $otherUnsealedKeyType->describe(VerbosityLevel::value()),
901: $reason,
902: ),
903: );
904: if (!$acceptsUnsealedKey->yes() && count($acceptsUnsealedKey->reasons) === 0) {
905: $acceptsUnsealedKey = new AcceptsResult($acceptsUnsealedKey->result, [
906: sprintf(
907: 'Unsealed array key type %s does not accept unsealed array key type %s.',
908: $unsealedKeyType->describe(VerbosityLevel::value()),
909: $otherUnsealedKeyType->describe(VerbosityLevel::value()),
910: ),
911: ]);
912: }
913: $result = $result->and($acceptsUnsealedKey);
914:
915: $acceptsUnsealedValue = $unsealedValueType->accepts($otherUnsealedValueType, $strictTypes)->decorateReasons(
916: static fn (string $reason) => sprintf(
917: 'Unsealed array value type %s does not accept unsealed array value type %s: %s',
918: $unsealedValueType->describe(VerbosityLevel::value()),
919: $otherUnsealedValueType->describe(VerbosityLevel::value()),
920: $reason,
921: ),
922: );
923: if (!$acceptsUnsealedValue->yes() && count($acceptsUnsealedValue->reasons) === 0) {
924: $acceptsUnsealedValue = new AcceptsResult($acceptsUnsealedValue->result, [
925: sprintf(
926: 'Unsealed array value type %s does not accept unsealed array value type %s.',
927: $unsealedValueType->describe(VerbosityLevel::value()),
928: $otherUnsealedValueType->describe(VerbosityLevel::value()),
929: ),
930: ]);
931: }
932: $result = $result->and($acceptsUnsealedValue);
933: }
934:
935: return $result;
936: }
937:
938: private function checkOurKeys(Type $type, bool $strictTypes): AcceptsResult
939: {
940: $result = AcceptsResult::createYes();
941:
942: // offsets sharing the same value types (e.g. a type alias used for many keys) are compared once
943: /** @var array<string, array{Type, AcceptsResult}> $acceptsValueCache */
944: $acceptsValueCache = [];
945: foreach ($this->keyTypes as $i => $keyType) {
946: $valueType = $this->valueTypes[$i];
947: $hasOffsetValueType = $type->hasOffsetValueType($keyType);
948: $hasOffset = new AcceptsResult(
949: $hasOffsetValueType,
950: $hasOffsetValueType->yes() || !$type->isConstantArray()->yes() ? [] : [sprintf('Array %s have offset %s.', $hasOffsetValueType->no() ? 'does not' : 'might not', $keyType->describe(VerbosityLevel::value()))],
951: );
952: if ($hasOffset->no()) {
953: if ($this->isOptionalKey($i)) {
954: continue;
955: }
956: return $hasOffset;
957: }
958: if ($hasOffset->maybe() && $this->isOptionalKey($i)) {
959: $hasOffset = AcceptsResult::createYes();
960: }
961:
962: $result = $result->and($hasOffset);
963: $otherValueType = $type->getOffsetValueType($keyType);
964: $acceptsValueCacheKey = spl_object_id($valueType) . '-' . spl_object_id($otherValueType);
965: if (isset($acceptsValueCache[$acceptsValueCacheKey])) {
966: $acceptsValue = $acceptsValueCache[$acceptsValueCacheKey][1];
967: } else {
968: $acceptsValue = $valueType->accepts($otherValueType, $strictTypes);
969: // $otherValueType is kept alive so that its id is not reused
970: $acceptsValueCache[$acceptsValueCacheKey] = [$otherValueType, $acceptsValue];
971: }
972: if ($acceptsValue->yes() && count($acceptsValue->reasons) === 0) {
973: continue;
974: }
975:
976: $verbosity = VerbosityLevel::getRecommendedLevelByType($valueType, $otherValueType);
977: $acceptsValue = $acceptsValue->decorateReasons(
978: static fn (string $reason) => sprintf(
979: 'Offset %s (%s) does not accept type %s: %s',
980: $keyType->describe(VerbosityLevel::precise()),
981: $valueType->describe($verbosity),
982: $otherValueType->describe($verbosity),
983: $reason,
984: ),
985: );
986: if (!$acceptsValue->yes() && count($acceptsValue->reasons) === 0 && $type->isConstantArray()->yes()) {
987: $acceptsValue = new AcceptsResult($acceptsValue->result, [
988: sprintf(
989: 'Offset %s (%s) does not accept type %s.',
990: $keyType->describe(VerbosityLevel::precise()),
991: $valueType->describe($verbosity),
992: $otherValueType->describe($verbosity),
993: ),
994: ]);
995: }
996: if ($acceptsValue->no()) {
997: return $acceptsValue;
998: }
999: $result = $result->and($acceptsValue);
1000: }
1001:
1002: return $result;
1003: }
1004:
1005: public function isSuperTypeOf(Type $type): IsSuperTypeOfResult
1006: {
1007: // Shapes nested in each other share their members (`$a['parent'] = $a`),
1008: // so comparing two of them meets the same member on both sides along
1009: // every path leading to it.
1010: if ($type === $this) {
1011: return IsSuperTypeOfResult::createYes();
1012: }
1013:
1014: if ($type instanceof self) {
1015: // an array never has its keys in two orders
1016: if ($this->isKeyOrderKnown() && $type->isKeyOrderKnown() && !$this->sharesKeyOrderWith($type)) {
1017: return IsSuperTypeOfResult::createNo();
1018: }
1019:
1020: $thisUnsealedness = $this->isUnsealed();
1021: $typeUnsealedness = $type->isUnsealed();
1022: $bothDefinite = $this->unsealed !== null && $type->unsealed !== null;
1023:
1024: if (count($this->keyTypes) === 0) {
1025: if (!$bothDefinite) {
1026: return IsSuperTypeOfResult::createFromTrinaryLogic($type->isIterableAtLeastOnce()->negate());
1027: }
1028: if ($thisUnsealedness->no()) {
1029: return IsSuperTypeOfResult::createFromTrinaryLogic($type->isIterableAtLeastOnce()->negate());
1030: }
1031: // $this is unsealed with no known keys — fall through to extras/unsealed-part checks below
1032: }
1033:
1034: // Two sealed shapes where one has a required key the other lacks share
1035: // no value. The loops below would reach the same answer, but only after
1036: // comparing the value of every key that precedes the missing one.
1037: if (
1038: $thisUnsealedness->no()
1039: && $typeUnsealedness->no()
1040: && ($this->hasRequiredKeyMissingIn($type) || $type->hasRequiredKeyMissingIn($this))
1041: ) {
1042: return IsSuperTypeOfResult::createNo(lazyReasons: [fn (): string => $this->sealedArrayShapesCannotBeIntersectedReason($type)]);
1043: }
1044:
1045: $results = [];
1046: $valueResults = [];
1047: $otherKeyIndexMap = $type->getKeyIndexMap();
1048: foreach ($this->keyTypes as $i => $keyType) {
1049: $hasOffset = $type->hasOffsetValueType($keyType);
1050: if ($bothDefinite && $hasOffset->no() && $typeUnsealedness->yes()) {
1051: [$typeUnsealedKey] = $type->unsealed;
1052: if (!$typeUnsealedKey->isSuperTypeOf($keyType)->no()) {
1053: $hasOffset = TrinaryLogic::createMaybe();
1054: }
1055: }
1056: if ($hasOffset->no()) {
1057: if (!$this->isOptionalKey($i)) {
1058: if ($thisUnsealedness->no() && $typeUnsealedness->no()) {
1059: return IsSuperTypeOfResult::createNo(lazyReasons: [fn (): string => $this->sealedArrayShapesCannotBeIntersectedReason($type)]);
1060: }
1061: return IsSuperTypeOfResult::createNo();
1062: }
1063:
1064: $results[] = IsSuperTypeOfResult::createYes();
1065: continue;
1066: } elseif ($hasOffset->maybe() && !$this->isOptionalKey($i)) {
1067: $results[] = IsSuperTypeOfResult::createMaybe();
1068: }
1069:
1070: // The offset value at one of $type's explicit keys depends only on
1071: // the value type stored there, so keys sharing their value types on
1072: // both sides (keys written through a union offset) compare them once.
1073: $otherIndex = $otherKeyIndexMap[$keyType->getValue()] ?? null;
1074: if ($otherIndex !== null) {
1075: $valueId = spl_object_id($this->valueTypes[$i]);
1076: $otherValueId = spl_object_id($type->valueTypes[$otherIndex]);
1077: if (isset($valueResults[$valueId][$otherValueId])) {
1078: $results[] = $valueResults[$valueId][$otherValueId];
1079: continue;
1080: }
1081: }
1082:
1083: $otherValueType = $type->getOffsetValueType($keyType);
1084: if ($otherValueType instanceof ErrorType && $bothDefinite && $typeUnsealedness->yes()) {
1085: [, $typeUnsealedValue] = $type->unsealed;
1086: $otherValueType = $typeUnsealedValue;
1087: }
1088: $isValueSuperType = $this->valueTypes[$i]->isSuperTypeOf($otherValueType);
1089: if ($isValueSuperType->no()) {
1090: return $isValueSuperType->decorateReasons(static fn (string $reason) => sprintf('Offset %s: %s', $keyType->describe(VerbosityLevel::value()), $reason));
1091: }
1092: if ($otherIndex !== null) {
1093: $valueResults[$valueId][$otherValueId] = $isValueSuperType;
1094: }
1095: $results[] = $isValueSuperType;
1096: }
1097:
1098: if ($bothDefinite) {
1099: $thisKeyValues = [];
1100: foreach ($this->keyTypes as $thisKeyType) {
1101: $thisKeyValues[$thisKeyType->getValue()] = true;
1102: }
1103:
1104: foreach ($type->getKeyTypes() as $i => $typeKey) {
1105: if (array_key_exists($typeKey->getValue(), $thisKeyValues)) {
1106: continue;
1107: }
1108:
1109: if ($thisUnsealedness->no()) {
1110: if (!$type->isOptionalKey($i)) {
1111: if ($typeUnsealedness->no()) {
1112: return IsSuperTypeOfResult::createNo(lazyReasons: [fn (): string => $this->sealedArrayShapesCannotBeIntersectedReason($type)]);
1113: }
1114: return IsSuperTypeOfResult::createNo();
1115: }
1116: $results[] = IsSuperTypeOfResult::createMaybe();
1117: continue;
1118: }
1119:
1120: [$thisUnsealedKey, $thisUnsealedValue] = $this->unsealed;
1121: $keyCheck = $thisUnsealedKey->isSuperTypeOf($typeKey);
1122: if ($keyCheck->no()) {
1123: if ($type->isOptionalKey($i)) {
1124: $results[] = IsSuperTypeOfResult::createMaybe();
1125: continue;
1126: }
1127: return IsSuperTypeOfResult::createNo();
1128: }
1129: $thisKeyTemplate = $this->getUnsealedKeyTemplate();
1130: $valueCheck = $thisKeyTemplate !== null
1131: ? ArrayKeyTemplateHelper::isSuperTypeOfValue($thisKeyTemplate[1], $thisKeyTemplate[2], $thisKeyTemplate[0], $typeKey, $type->getValueTypes()[$i])
1132: : $thisUnsealedValue->isSuperTypeOf($type->getValueTypes()[$i]);
1133: if ($valueCheck->no()) {
1134: if ($type->isOptionalKey($i)) {
1135: $results[] = IsSuperTypeOfResult::createMaybe();
1136: continue;
1137: }
1138: return IsSuperTypeOfResult::createNo();
1139: }
1140: $results[] = $keyCheck->and($valueCheck);
1141: }
1142:
1143: if ($typeUnsealedness->yes()) {
1144: if ($thisUnsealedness->no()) {
1145: $results[] = IsSuperTypeOfResult::createMaybe();
1146: } else {
1147: [$thisUnsealedKey, $thisUnsealedValue] = $this->unsealedDeclaration ?? $this->unsealed;
1148: [$typeUnsealedKey, $typeUnsealedValue] = $type->unsealedDeclaration ?? $type->unsealed;
1149: if ($this->unsealedDeclaration !== null || $type->unsealedDeclaration !== null) {
1150: $results[] = (new ArrayType($thisUnsealedKey, $thisUnsealedValue))->isSuperTypeOf(new ArrayType($typeUnsealedKey, $typeUnsealedValue));
1151: } else {
1152: $results[] = $thisUnsealedKey->isSuperTypeOf($typeUnsealedKey);
1153: $results[] = $thisUnsealedValue->isSuperTypeOf($typeUnsealedValue);
1154: }
1155: }
1156: }
1157: }
1158:
1159: // the shape that does not know its key order may hold its keys in another order than this one
1160: if ($this->hasKeyOrderToKeep() && !$type->isKeyOrderKnown()) {
1161: $results[] = IsSuperTypeOfResult::createMaybe();
1162: }
1163:
1164: return IsSuperTypeOfResult::createYes()->and(...$results);
1165: }
1166:
1167: if ($type instanceof ArrayType) {
1168: $result = IsSuperTypeOfResult::createMaybe();
1169: if (count($this->keyTypes) === 0) {
1170: return $result;
1171: }
1172:
1173: $isKeySuperType = $this->getKeyType()->isSuperTypeOf($type->getKeyType());
1174: if ($isKeySuperType->no()) {
1175: return $isKeySuperType;
1176: }
1177:
1178: return $result->and($isKeySuperType, $this->getItemType()->isSuperTypeOf($type->getItemType()));
1179: }
1180:
1181: if ($type instanceof CompoundType) {
1182: return $type->isSubTypeOf($this);
1183: }
1184:
1185: return IsSuperTypeOfResult::createNo();
1186: }
1187:
1188: /**
1189: * Passed as a lazy reason to IsSuperTypeOfResult so the expensive describe() calls only
1190: * run when the reason is actually rendered, never during the hot isSuperTypeOf()
1191: * comparisons whose reasons are discarded.
1192: */
1193: private function sealedArrayShapesCannotBeIntersectedReason(self $type): string
1194: {
1195: return sprintf(
1196: 'Sealed array shapes %s and %s cannot be intersected. Unseal at least one of them with ... syntax. Learn more: %s',
1197: $this->describe(VerbosityLevel::value()),
1198: $type->describe(VerbosityLevel::value()),
1199: self::UNSEALED_ARRAY_SHAPES_LINK,
1200: );
1201: }
1202:
1203: public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
1204: {
1205: if ($type->isInteger()->yes()) {
1206: return new ConstantBooleanType(false);
1207: }
1208:
1209: if ($this->isIterableAtLeastOnce()->no()) {
1210: if ($type->isIterableAtLeastOnce()->yes()) {
1211: return new ConstantBooleanType(false);
1212: }
1213:
1214: $constantScalarValues = $type->getConstantScalarValues();
1215: if (count($constantScalarValues) > 0) {
1216: $results = [];
1217: foreach ($constantScalarValues as $constantScalarValue) {
1218: // @phpstan-ignore equal.invalid, equal.notAllowed
1219: $results[] = TrinaryLogic::createFromBoolean($constantScalarValue == []); // phpcs:ignore
1220: }
1221:
1222: return TrinaryLogic::extremeIdentity(...$results)->toBooleanType();
1223: }
1224: }
1225:
1226: return new BooleanType();
1227: }
1228:
1229: public function equals(Type $type): bool
1230: {
1231: if ($type === $this) {
1232: return true;
1233: }
1234:
1235: if (!$type instanceof self) {
1236: return false;
1237: }
1238:
1239: if (count($this->keyTypes) !== count($type->keyTypes)) {
1240: return false;
1241: }
1242:
1243: $isKeyOrderKnown = $this->isKeyOrderKnown();
1244: if ($isKeyOrderKnown !== $type->isKeyOrderKnown()) {
1245: return false;
1246: }
1247:
1248: if ($isKeyOrderKnown) {
1249: foreach ($this->keyTypes as $i => $keyType) {
1250: $valueType = $this->valueTypes[$i];
1251: if (!$valueType->equals($type->valueTypes[$i])) {
1252: return false;
1253: }
1254: if (!$keyType->equals($type->keyTypes[$i])) {
1255: return false;
1256: }
1257: }
1258:
1259: if ($this->optionalKeys !== $type->optionalKeys) {
1260: return false;
1261: }
1262: } else {
1263: // shapes that do not know their key order are the same type whatever order they list their keys in
1264: $otherKeyIndexMap = $type->getKeyIndexMap();
1265: foreach ($this->keyTypes as $i => $keyType) {
1266: $j = $otherKeyIndexMap[$keyType->getValue()] ?? null;
1267: if ($j === null) {
1268: return false;
1269: }
1270: if (!$this->valueTypes[$i]->equals($type->valueTypes[$j])) {
1271: return false;
1272: }
1273: if ($this->isOptionalKey($i) !== $type->isOptionalKey($j)) {
1274: return false;
1275: }
1276: }
1277: }
1278:
1279: // Both `unsealed === null` (legacy / pre-bleeding-edge, where
1280: // `isUnsealed()` answers `Maybe`) and `unsealed === [explicitNever,
1281: // explicitNever]` (the fresh bleeding-edge sealed marker, where
1282: // `isUnsealed()` answers `No`) mean "no real extras". Treat them as
1283: // equivalent here — use `!isUnsealed()->yes()` rather than
1284: // `isUnsealed()->no()`, otherwise a legacy-null shape and a
1285: // marker-sealed shape compare unequal. Only compare the actual
1286: // extras when both sides genuinely have them.
1287: $thisHasExtras = $this->isUnsealed()->yes();
1288: $otherHasExtras = $type->isUnsealed()->yes();
1289: if ($thisHasExtras !== $otherHasExtras) {
1290: return false;
1291: }
1292:
1293: if (($this->unsealedDeclaration === null) !== ($type->unsealedDeclaration === null)) {
1294: return false;
1295: }
1296:
1297: if ($this->unsealedDeclaration !== null && $type->unsealedDeclaration !== null) {
1298: return $this->unsealedDeclaration[0]->equals($type->unsealedDeclaration[0])
1299: && $this->unsealedDeclaration[1]->equals($type->unsealedDeclaration[1]);
1300: }
1301:
1302: if ($thisHasExtras && $this->unsealed !== null && $type->unsealed !== null) {
1303: if (!$this->unsealed[0]->equals($type->unsealed[0])) {
1304: return false;
1305: }
1306: if (!$this->unsealed[1]->equals($type->unsealed[1])) {
1307: return false;
1308: }
1309: }
1310:
1311: return true;
1312: }
1313:
1314: public function isCallable(): TrinaryLogic
1315: {
1316: // the shapes doFindTypeAndMethodNames() rejects by their keys alone, without
1317: // describing the whole shape for the recursion guard
1318: $keyTypesCount = count($this->keyTypes);
1319: if ($keyTypesCount > 2 || ($keyTypesCount !== 2 && !$this->isUnsealed()->yes())) {
1320: return TrinaryLogic::createNo();
1321: }
1322: foreach ($this->keyTypes as $keyType) {
1323: // a key other than 0 and 1, like a shape of a linked list that contains itself,
1324: // whose description sorts a union that asks whether the shape is callable again
1325: if ($keyType->getValue() !== 0 && $keyType->getValue() !== 1) {
1326: return TrinaryLogic::createNo();
1327: }
1328: }
1329:
1330: $result = RecursionGuard::run($this, function (): TrinaryLogic {
1331: $hasNonExistentMethod = false;
1332: $typeAndMethods = $this->doFindTypeAndMethodNames($hasNonExistentMethod);
1333: if ($typeAndMethods === []) {
1334: return TrinaryLogic::createNo();
1335: }
1336:
1337: $results = array_map(
1338: static fn (ConstantArrayTypeAndMethod $typeAndMethod): TrinaryLogic => $typeAndMethod->getCertainty(),
1339: $typeAndMethods,
1340: );
1341:
1342: $result = TrinaryLogic::createYes()->and(...$results);
1343:
1344: if ($hasNonExistentMethod) {
1345: $result = $result->and(TrinaryLogic::createMaybe());
1346: }
1347:
1348: return $result;
1349: });
1350:
1351: if ($result instanceof ErrorType) {
1352: return TrinaryLogic::createNo();
1353: }
1354:
1355: return $result;
1356: }
1357:
1358: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
1359: {
1360: $typeAndMethodNames = $this->findTypeAndMethodNames();
1361: if ($typeAndMethodNames === []) {
1362: throw new ShouldNotHappenException();
1363: }
1364:
1365: $acceptors = [];
1366: foreach ($typeAndMethodNames as $typeAndMethodName) {
1367: if ($typeAndMethodName->isUnknown() || !$typeAndMethodName->getCertainty()->yes()) {
1368: $acceptors[] = new TrivialParametersAcceptor();
1369: continue;
1370: }
1371:
1372: $method = $typeAndMethodName->getType()
1373: ->getMethod($typeAndMethodName->getMethod(), $scope);
1374:
1375: if (!$scope->canCallMethod($method)) {
1376: $acceptors[] = new InaccessibleMethod($method);
1377: continue;
1378: }
1379:
1380: array_push($acceptors, ...FunctionCallableVariant::createFromVariants($method, $method->getVariants()));
1381: }
1382:
1383: return $acceptors;
1384: }
1385:
1386: /** @return ConstantArrayTypeAndMethod[] */
1387: public function findTypeAndMethodNames(): array
1388: {
1389: return $this->doFindTypeAndMethodNames();
1390: }
1391:
1392: /** @return ConstantArrayTypeAndMethod[] */
1393: private function doFindTypeAndMethodNames(bool &$hasNonExistentMethod = false): array
1394: {
1395: $isUnsealed = $this->isUnsealed()->yes();
1396:
1397: // Sealed: must have exactly the two callable slots, no more, no less.
1398: // Unsealed: explicit keys may cover 0, 1, both, or neither — but any
1399: // explicit key outside {0, 1} immediately disqualifies, because the
1400: // callable shape `[classOrObject, method]` has no room for other
1401: // keys.
1402: if (!$isUnsealed && count($this->keyTypes) !== 2) {
1403: return [];
1404: }
1405: if (count($this->keyTypes) > 2) {
1406: return [];
1407: }
1408:
1409: $classOrObject = null;
1410: $method = null;
1411: foreach ($this->keyTypes as $i => $keyType) {
1412: if ($keyType->isSuperTypeOf(new ConstantIntegerType(0))->yes()) {
1413: $classOrObject = $this->valueTypes[$i];
1414: continue;
1415: }
1416:
1417: if ($keyType->isSuperTypeOf(new ConstantIntegerType(1))->yes()) {
1418: $method = $this->valueTypes[$i];
1419: continue;
1420: }
1421:
1422: // Explicit key is something other than 0 or 1 — not callable.
1423: return [];
1424: }
1425:
1426: // Try to fill missing callable slots from the unsealed extras: an
1427: // unsealed array `array{0: object, ...<int, string>}` *might* turn
1428: // into a callable if the actual value carries a `1 => 'method'`
1429: // extra. Require that the unsealed key range covers the missing
1430: // slot and that the unsealed value type can overlap with the
1431: // type required for that slot (object|class-string for key 0,
1432: // non-falsy-string for key 1) — otherwise no concrete value of
1433: // this CAT can ever be callable.
1434: if ($isUnsealed && $this->unsealed !== null) {
1435: [$unsealedKey, $unsealedValue] = $this->unsealed;
1436:
1437: if ($classOrObject === null) {
1438: if ($unsealedKey->isSuperTypeOf(new ConstantIntegerType(0))->no()) {
1439: return [];
1440: }
1441: $expected = TypeCombinator::union(new ObjectWithoutClassType(), new ClassStringType());
1442: if ($expected->isSuperTypeOf($unsealedValue)->no()) {
1443: return [];
1444: }
1445: $classOrObject = $unsealedValue;
1446: }
1447:
1448: if ($method === null) {
1449: if ($unsealedKey->isSuperTypeOf(new ConstantIntegerType(1))->no()) {
1450: return [];
1451: }
1452: $expected = TypeCombinator::intersect(new StringType(), new AccessoryNonFalsyStringType());
1453: if ($expected->isSuperTypeOf($unsealedValue)->no()) {
1454: return [];
1455: }
1456: $method = $unsealedValue;
1457: }
1458: }
1459:
1460: if ($classOrObject === null || $method === null) {
1461: return [];
1462: }
1463:
1464: // no value of the slots' types names a method
1465: if (
1466: TypeCombinator::union(new ObjectWithoutClassType(), new StringType())->isSuperTypeOf($classOrObject)->no()
1467: || (new StringType())->isSuperTypeOf($method)->no()
1468: ) {
1469: return [];
1470: }
1471:
1472: $callableArray = [$classOrObject, $method];
1473:
1474: [$classOrObject, $methods] = $callableArray;
1475: if (count($methods->getConstantStrings()) === 0) {
1476: return [ConstantArrayTypeAndMethod::createUnknown()];
1477: }
1478:
1479: $type = $classOrObject->getObjectTypeOrClassStringObjectType();
1480: if (!$type->isObject()->yes()) {
1481: return [ConstantArrayTypeAndMethod::createUnknown()];
1482: }
1483:
1484: $typeAndMethods = [];
1485: $phpVersion = PhpVersionStaticAccessor::getInstance();
1486: foreach ($methods->getConstantStrings() as $methodName) {
1487: $has = $type->hasMethod($methodName->getValue());
1488: if ($has->no()) {
1489: $hasNonExistentMethod = true;
1490: continue;
1491: }
1492:
1493: if (
1494: $has->yes()
1495: && !$phpVersion->supportsCallableInstanceMethods()
1496: ) {
1497: $isString = $classOrObject->isString();
1498: if ($isString->yes()) {
1499: $methodReflection = $type->getMethod($methodName->getValue(), new OutOfClassScope());
1500:
1501: if (!$methodReflection->isStatic()) {
1502: continue;
1503: }
1504: } elseif ($isString->maybe()) {
1505: $has = $has->and(TrinaryLogic::createMaybe());
1506: }
1507: }
1508:
1509: if ($this->isOptionalKey(0) || $this->isOptionalKey(1)) {
1510: $has = $has->and(TrinaryLogic::createMaybe());
1511: }
1512:
1513: // Unsealed: the actual value may carry extras beyond keys 0/1,
1514: // which would void the callable shape. The CAT itself describes
1515: // "zero or more extras", so callable-ness is uncertain.
1516: if ($isUnsealed) {
1517: $has = $has->and(TrinaryLogic::createMaybe());
1518: }
1519:
1520: $typeAndMethods[] = ConstantArrayTypeAndMethod::createConcrete($type, $methodName->getValue(), $has);
1521: }
1522:
1523: return $typeAndMethods;
1524: }
1525:
1526: public function hasOffsetValueType(Type $offsetType): TrinaryLogic
1527: {
1528: $offsetArrayKeyType = $offsetType->toArrayKey();
1529: if ($offsetArrayKeyType instanceof ErrorType) {
1530: $allowedArrayKeys = AllowedArrayKeysTypes::getType();
1531: $offsetArrayKeyType = TypeCombinator::intersect($allowedArrayKeys, $offsetType)->toArrayKey();
1532: if ($offsetArrayKeyType instanceof NeverType) {
1533: return TrinaryLogic::createNo();
1534: }
1535: }
1536:
1537: return $this->recursiveHasOffsetValueType($offsetArrayKeyType);
1538: }
1539:
1540: private function recursiveHasOffsetValueType(Type $offsetType): TrinaryLogic
1541: {
1542: if ($offsetType instanceof UnionType) {
1543: $results = [];
1544: foreach ($offsetType->getTypes() as $innerType) {
1545: $results[] = $this->recursiveHasOffsetValueType($innerType);
1546: }
1547:
1548: return TrinaryLogic::extremeIdentity(...$results);
1549: }
1550: if ($offsetType instanceof IntegerRangeType) {
1551: $finiteTypes = $offsetType->getFiniteTypes();
1552: if ($finiteTypes !== []) {
1553: $results = [];
1554: foreach ($finiteTypes as $innerType) {
1555: $results[] = $this->recursiveHasOffsetValueType($innerType);
1556: }
1557:
1558: return TrinaryLogic::extremeIdentity(...$results);
1559: }
1560: }
1561:
1562: // Constant offsets against constant keys resolve by value: a hit at the
1563: // indexed slot is verified before use, an offset no key's value collides
1564: // with skips the scan, any other miss falls through to it (the unsealed
1565: // extras below are checked either way).
1566: $index = $this->findVerifiedKeyIndex($offsetType);
1567: if ($index !== null) {
1568: if ($this->isOptionalKey($index)) {
1569: return TrinaryLogic::createMaybe();
1570: }
1571: return TrinaryLogic::createYes();
1572: }
1573:
1574: $result = TrinaryLogic::createNo();
1575: foreach ($this->isKeyIndexMiss($offsetType) ? [] : $this->keyTypes as $i => $keyType) {
1576: // PHP coerces decimal-integer strings to int when used as array
1577: // keys ("123" → 123), so a non-constant string offset *could* hit
1578: // a constant-integer slot. Skip the upgrade when the offset is
1579: // definitely a non-decimal-integer string — those stay as strings
1580: // and can never collide with an int key.
1581: if (
1582: $keyType instanceof ConstantIntegerType
1583: && !$offsetType->isString()->no()
1584: && $offsetType->isConstantScalarValue()->no()
1585: && !$offsetType->isDecimalIntegerString()->no()
1586: ) {
1587: return TrinaryLogic::createMaybe();
1588: }
1589:
1590: $has = $keyType->isSuperTypeOf($offsetType);
1591: if ($has->yes()) {
1592: if ($this->isOptionalKey($i)) {
1593: return TrinaryLogic::createMaybe();
1594: }
1595: return TrinaryLogic::createYes();
1596: }
1597: if (!$has->maybe()) {
1598: continue;
1599: }
1600:
1601: $result = TrinaryLogic::createMaybe();
1602: }
1603:
1604: // Unsealed extras (zero-or-more additional entries) can never make a
1605: // hit definite — they're uncertain by construction. They only matter
1606: // when no explicit key matched ($result is No): if the unsealed key
1607: // range overlaps the offset, upgrade No → Maybe. Explicit keys take
1608: // precedence at any slot they cover (PHP keys are unique), so a
1609: // non-No $result already reflects the strongest answer the unsealed
1610: // extras could contribute.
1611: if ($result->no() && $this->isUnsealed()->yes() && $this->unsealed !== null) {
1612: [$unsealedKeyType] = $this->unsealed;
1613: if (!$unsealedKeyType->isSuperTypeOf($offsetType)->no()) {
1614: $result = TrinaryLogic::createMaybe();
1615: }
1616: }
1617:
1618: return $result;
1619: }
1620:
1621: public function getOffsetValueType(Type $offsetType): Type
1622: {
1623: if (count($this->keyTypes) === 0 && !$this->isUnsealed()->yes()) {
1624: return new ErrorType();
1625: }
1626:
1627: $offsetType = $offsetType->toArrayKey();
1628: if (count($this->keyTypes) > 1) {
1629: // Same result as the scan below for a verified hit: exactly one explicit
1630: // key matches a constant offset, so neither the all-keys nor the
1631: // maybe-all fallbacks apply and the unsealed extras cannot contribute.
1632: $index = $this->findVerifiedKeyIndex($offsetType);
1633: if ($index !== null) {
1634: // The shape is immutable, so the normalized value at an index is
1635: // computed once. Comparing nested shapes asks for the same offsets
1636: // over and over, and normalizing a union of shapes is not cheap.
1637: $type = $this->normalizedValueTypes[$index] ??= TypeCombinator::union($this->valueTypes[$index]);
1638: if ($type instanceof ErrorType) {
1639: return new MixedType();
1640: }
1641:
1642: return $type;
1643: }
1644: }
1645:
1646: $matchingValueTypes = [];
1647: $all = true;
1648: $maybeAll = true;
1649: $keyIndexMiss = count($this->keyTypes) > 0 && $this->isKeyIndexMiss($offsetType);
1650: if ($keyIndexMiss) {
1651: // What the scan below concludes for an offset no key's value
1652: // collides with: every key misses it, and a constant offset cannot
1653: // be a decimal-integer string hitting an integer key.
1654: $all = false;
1655: $maybeAll = false;
1656: }
1657: foreach ($keyIndexMiss ? [] : $this->keyTypes as $i => $keyType) {
1658: if ($keyType->isSuperTypeOf($offsetType)->no()) {
1659: $all = false;
1660:
1661: if (
1662: $keyType instanceof ConstantIntegerType
1663: && !$offsetType->isString()->no()
1664: && $offsetType->isConstantScalarValue()->no()
1665: ) {
1666: continue;
1667: }
1668: $maybeAll = false;
1669: continue;
1670: }
1671:
1672: $matchingValueTypes[] = $this->valueTypes[$i];
1673: }
1674:
1675: // Unsealed extras describe entries at keys NOT in the explicit set —
1676: // PHP array keys are unique, so an explicit key fully owns its slot.
1677: // Only include the unsealed value when the offset has parts not
1678: // covered by any explicit key AND those parts overlap the unsealed
1679: // key range.
1680: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
1681: [$unsealedKeyType, $unsealedValueType] = $this->unsealed;
1682: if (!$this->getKeyTypesUnion()->isSuperTypeOf($offsetType)->yes() && !$unsealedKeyType->isSuperTypeOf($offsetType)->no()) {
1683: $keyTemplate = $this->getUnsealedKeyTemplate();
1684: $matchingValueTypes[] = $keyTemplate !== null
1685: ? ArrayKeyTemplateHelper::getValueType($keyTemplate[1], $keyTemplate[2], $keyTemplate[0], TypeCombinator::intersect($offsetType, $unsealedKeyType))
1686: : $unsealedValueType;
1687: }
1688: }
1689:
1690: if ($all && !$this->isUnsealed()->yes()) {
1691: return $this->getIterableValueType();
1692: }
1693:
1694: if (count($matchingValueTypes) > 0) {
1695: $type = TypeCombinator::widen(TypeCombinator::union(...$matchingValueTypes));
1696: if ($type instanceof ErrorType) {
1697: return new MixedType();
1698: }
1699:
1700: return $type;
1701: }
1702:
1703: if ($maybeAll) {
1704: return $this->getIterableValueType();
1705: }
1706:
1707: return new ErrorType(); // undefined offset
1708: }
1709:
1710: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
1711: {
1712: if ($offsetType === null && count($this->nextAutoIndexes) === 0) {
1713: return new ErrorType();
1714: }
1715:
1716: $builder = ConstantArrayTypeBuilder::createFromConstantArray($this);
1717: $builder->setOffsetValueType($offsetType, $valueType);
1718:
1719: return $builder->getArray();
1720: }
1721:
1722: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
1723: {
1724: // an offset that is not one constant is one of the keys it can be,
1725: // so the shape keeps its keys: array{0, 0} written at an existing int
1726: // offset is array{int, int}, not an array that has more keys
1727: $offsetType = $offsetType->toArrayKey();
1728: if (
1729: !$offsetType instanceof ConstantIntegerType
1730: && !$offsetType instanceof ConstantStringType
1731: && !$this->isUnsealed()->yes()
1732: ) {
1733: $valueTypes = $this->valueTypes;
1734: $matched = false;
1735: foreach ($this->keyTypes as $i => $keyType) {
1736: if ($offsetType->isSuperTypeOf($keyType)->no()) {
1737: continue;
1738: }
1739: $valueTypes[$i] = TypeCombinator::union($valueTypes[$i], $valueType);
1740: $matched = true;
1741: }
1742: if ($matched) {
1743: return $this->recreate($this->keyTypes, $valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $this->isList, $this->unsealed);
1744: }
1745: }
1746:
1747: $builder = ConstantArrayTypeBuilder::createFromConstantArray($this);
1748: $builder->setOffsetValueType($offsetType, $valueType);
1749:
1750: return $builder->getArray();
1751: }
1752:
1753: /**
1754: * Removes or marks as optional the key(s) matching the given offset type from this constant array.
1755: *
1756: * By default, the method assumes an actual `unset()` call was made, which actively modifies the
1757: * array and weakens its list certainty to "maybe". However, in some contexts, such as the else
1758: * branch of an array_key_exists() check, the key is statically known to be absent without any
1759: * modification, so list certainty should be preserved as-is.
1760: */
1761: public function unsetOffset(Type $offsetType, bool $preserveListCertainty = false): Type
1762: {
1763: $offsetType = $offsetType->toArrayKey();
1764: if ($offsetType instanceof ConstantIntegerType || $offsetType instanceof ConstantStringType) {
1765: foreach ($this->keyTypes as $i => $keyType) {
1766: if ($keyType->getValue() !== $offsetType->getValue()) {
1767: continue;
1768: }
1769:
1770: $keyTypes = $this->keyTypes;
1771: unset($keyTypes[$i]);
1772: $valueTypes = $this->valueTypes;
1773: unset($valueTypes[$i]);
1774:
1775: $newKeyTypes = [];
1776: $newValueTypes = [];
1777: $newOptionalKeys = [];
1778:
1779: $k = 0;
1780: foreach ($keyTypes as $j => $newKeyType) {
1781: $newKeyTypes[] = $newKeyType;
1782: $newValueTypes[] = $valueTypes[$j];
1783: if (in_array($j, $this->optionalKeys, true)) {
1784: $newOptionalKeys[] = $k;
1785: }
1786: $k++;
1787: }
1788:
1789: $newIsList = self::isListAfterUnset(
1790: $newKeyTypes,
1791: $newOptionalKeys,
1792: $this->isList,
1793: in_array($i, $this->optionalKeys, true),
1794: );
1795: if (!$preserveListCertainty) {
1796: $newIsList = $newIsList->and(TrinaryLogic::createMaybe());
1797: } elseif ($this->isList->yes() && $newIsList->no()) {
1798: return new NeverType();
1799: }
1800:
1801: return $this->recreate($newKeyTypes, $newValueTypes, $this->nextAutoIndexes, $newOptionalKeys, $newIsList, $this->unsealed);
1802: }
1803:
1804: return $this;
1805: }
1806:
1807: $constantScalars = $offsetType->getConstantScalarTypes();
1808: if (count($constantScalars) > 0) {
1809: $optionalKeys = $this->optionalKeys;
1810:
1811: $arrayHasChanged = false;
1812: foreach ($constantScalars as $constantScalar) {
1813: $constantScalar = $constantScalar->toArrayKey();
1814: if (!$constantScalar instanceof ConstantIntegerType && !$constantScalar instanceof ConstantStringType) {
1815: continue;
1816: }
1817:
1818: foreach ($this->keyTypes as $i => $keyType) {
1819: if ($keyType->getValue() !== $constantScalar->getValue()) {
1820: continue;
1821: }
1822:
1823: $arrayHasChanged = true;
1824: if (in_array($i, $optionalKeys, true)) {
1825: continue 2;
1826: }
1827:
1828: $optionalKeys[] = $i;
1829: }
1830: }
1831:
1832: if (!$arrayHasChanged) {
1833: return $this;
1834: }
1835:
1836: $newIsList = self::isListAfterUnset(
1837: $this->keyTypes,
1838: $optionalKeys,
1839: $this->isList,
1840: count($optionalKeys) === count($this->optionalKeys),
1841: );
1842: if (!$preserveListCertainty) {
1843: $newIsList = $newIsList->and(TrinaryLogic::createMaybe());
1844: }
1845:
1846: return $this->recreate($this->keyTypes, $this->valueTypes, $this->nextAutoIndexes, $optionalKeys, $newIsList, $this->unsealed);
1847: }
1848:
1849: $optionalKeys = $this->optionalKeys;
1850: $arrayHasChanged = false;
1851: foreach ($this->keyTypes as $i => $keyType) {
1852: if (!$offsetType->isSuperTypeOf($keyType)->yes()) {
1853: continue;
1854: }
1855: $arrayHasChanged = true;
1856: $optionalKeys[] = $i;
1857: }
1858: $optionalKeys = array_values(array_unique($optionalKeys));
1859:
1860: if (!$arrayHasChanged) {
1861: return $this;
1862: }
1863:
1864: $newIsList = self::isListAfterUnset(
1865: $this->keyTypes,
1866: $optionalKeys,
1867: $this->isList,
1868: count($optionalKeys) === count($this->optionalKeys),
1869: );
1870: if (!$preserveListCertainty) {
1871: $newIsList = $newIsList->and(TrinaryLogic::createMaybe());
1872: } elseif ($this->isList->yes() && $newIsList->no()) {
1873: return new NeverType();
1874: }
1875:
1876: return $this->recreate($this->keyTypes, $this->valueTypes, $this->nextAutoIndexes, $optionalKeys, $newIsList, $this->unsealed);
1877: }
1878:
1879: /**
1880: * List-ness of a sealed shape from its keys and optionality: `yes` if every
1881: * realization (choice of present optional keys) is a list, `no` if none is,
1882: * `maybe` otherwise.
1883: *
1884: * @param list<ConstantIntegerType|ConstantStringType> $keyTypes
1885: * @param int[] $optionalKeys
1886: */
1887: private static function inferIsListFromShape(array $keyTypes, array $optionalKeys): TrinaryLogic
1888: {
1889: $optional = [];
1890: foreach ($optionalKeys as $optionalKey) {
1891: $optional[$optionalKey] = true;
1892: }
1893:
1894: // Prefix lengths reachable by realizations that are still a valid list.
1895: $validLengths = [0 => true];
1896: $existsInvalid = false;
1897:
1898: foreach ($keyTypes as $i => $keyType) {
1899: $isOptional = array_key_exists($i, $optional);
1900: // A numeric-string key like "1" is an integer key at runtime, so
1901: // normalize before deciding whether it continues the list.
1902: $arrayKey = $keyType->toArrayKey();
1903: $value = $arrayKey instanceof ConstantIntegerType ? $arrayKey->getValue() : null;
1904:
1905: $newValidLengths = [];
1906: foreach (array_keys($validLengths) as $length) {
1907: if ($isOptional) {
1908: $newValidLengths[$length] = true;
1909: }
1910:
1911: // A key equal to the current length extends the prefix; anything
1912: // else is a non-list realization.
1913: if ($value === $length) {
1914: $newValidLengths[$length + 1] = true;
1915: } else {
1916: $existsInvalid = true;
1917: }
1918: }
1919:
1920: $validLengths = $newValidLengths;
1921: if ($validLengths === []) {
1922: return TrinaryLogic::createNo();
1923: }
1924: }
1925:
1926: return $existsInvalid ? TrinaryLogic::createMaybe() : TrinaryLogic::createYes();
1927: }
1928:
1929: /**
1930: * When we're unsetting something not on the array, it will be untouched,
1931: * So the nextAutoIndexes won't change, and the array might still be a list even with PHPStan definition.
1932: *
1933: * @param list<ConstantIntegerType|ConstantStringType> $newKeyTypes
1934: * @param int[] $newOptionalKeys
1935: */
1936: private static function isListAfterUnset(array $newKeyTypes, array $newOptionalKeys, TrinaryLogic $arrayIsList, bool $unsetOptionalKey): TrinaryLogic
1937: {
1938: if (!$unsetOptionalKey || $arrayIsList->no()) {
1939: return TrinaryLogic::createNo();
1940: }
1941:
1942: $isListOnlyIfKeysAreOptional = false;
1943: foreach ($newKeyTypes as $k2 => $newKeyType2) {
1944: // A numeric-string key like "1" is an integer key at runtime, so
1945: // normalize before deciding whether it continues the list.
1946: $newKeyType2 = $newKeyType2->toArrayKey();
1947: if (!$newKeyType2 instanceof ConstantIntegerType || $newKeyType2->getValue() !== $k2) {
1948: // We found a non-optional key that implies that the array is never a list.
1949: if (!in_array($k2, $newOptionalKeys, true)) {
1950: return TrinaryLogic::createNo();
1951: }
1952:
1953: // The array can still be a list if all the following keys are also optional.
1954: $isListOnlyIfKeysAreOptional = true;
1955: continue;
1956: }
1957:
1958: if ($isListOnlyIfKeysAreOptional && !in_array($k2, $newOptionalKeys, true)) {
1959: return TrinaryLogic::createNo();
1960: }
1961: }
1962:
1963: return $arrayIsList;
1964: }
1965:
1966: public function chunkArray(Type $lengthType, TrinaryLogic $preserveKeys): Type
1967: {
1968: // With real unsealed extras, we can't precisely enumerate the
1969: // chunks — the source has an unknown number of extras that
1970: // could form additional partial or full chunks. Fall back to
1971: // the general `list<chunk<sourceValues>>` shape produced by
1972: // the trait, which is correct (just less precise).
1973: if ($this->isUnsealed()->yes()) {
1974: return $this->traitChunkArray($lengthType, $preserveKeys);
1975: }
1976:
1977: if (!$this->isKeyOrderKnown() && !$preserveKeys->yes()) {
1978: // which of the values come in which chunk is not known
1979: return $this->getValuesArray()->chunkArray($lengthType, $preserveKeys);
1980: }
1981:
1982: $biggerOne = IntegerRangeType::fromInterval(1, null);
1983: $finiteTypes = $lengthType->getFiniteTypes();
1984: if ($biggerOne->isSuperTypeOf($lengthType)->yes() && count($finiteTypes) < self::CHUNK_FINITE_TYPES_LIMIT) {
1985: $results = [];
1986: foreach ($finiteTypes as $finiteType) {
1987: if (!$finiteType instanceof ConstantIntegerType || $finiteType->getValue() < 1) {
1988: return $this->traitChunkArray($lengthType, $preserveKeys);
1989: }
1990:
1991: $length = $finiteType->getValue();
1992:
1993: $builder = ConstantArrayTypeBuilder::createEmpty();
1994: if ($this->keyOrderKnown) {
1995: $builder->makeKeyOrderKnown();
1996: }
1997:
1998: $keyTypesCount = count($this->keyTypes);
1999: for ($i = 0; $i < $keyTypesCount; $i += $length) {
2000: $chunk = $this->sliceArray(new ConstantIntegerType($i), new ConstantIntegerType($length), TrinaryLogic::createYes());
2001: $builder->setOffsetValueType(null, $preserveKeys->yes() ? $chunk : $chunk->getValuesArray());
2002: }
2003:
2004: $results[] = $builder->getArray();
2005: }
2006:
2007: return TypeCombinator::union(...$results);
2008: }
2009:
2010: return $this->traitChunkArray($lengthType, $preserveKeys);
2011: }
2012:
2013: public function fillKeysArray(Type $valueType): Type
2014: {
2015: $builder = ConstantArrayTypeBuilder::createEmpty();
2016: if ($this->keyOrderKnown) {
2017: $builder->makeKeyOrderKnown();
2018: }
2019:
2020: foreach ($this->valueTypes as $i => $keyType) {
2021: if ($keyType->isInteger()->no()) {
2022: $stringKeyType = $keyType->toString();
2023: if ($stringKeyType instanceof ErrorType) {
2024: return $stringKeyType;
2025: }
2026:
2027: $builder->setOffsetValueType($stringKeyType, $valueType, $this->isOptionalKey($i) || count($stringKeyType->getConstantScalarTypes()) > 1);
2028: } else {
2029: $builder->setOffsetValueType($keyType, $valueType, $this->isOptionalKey($i) || count($keyType->getConstantScalarTypes()) > 1);
2030: }
2031: }
2032:
2033: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
2034: [, $unsealedValue] = $this->unsealed;
2035: $tailKey = $unsealedValue->toArrayKey();
2036: // See flipArray() for the rationale: install the unsealed
2037: // tail only when its key type is non-finite; otherwise let
2038: // setOffsetValueType expand it into optional explicit slots
2039: // (merged with any matching existing keys).
2040: if (count($tailKey->getFiniteTypes()) === 0) {
2041: $builder->makeUnsealed($tailKey, $valueType);
2042: }
2043: $builder->setOffsetValueType($tailKey, $valueType, true);
2044: }
2045:
2046: return $builder->getArray();
2047: }
2048:
2049: public function flipArray(): Type
2050: {
2051: $builder = ConstantArrayTypeBuilder::createEmpty();
2052: if ($this->keyOrderKnown) {
2053: $builder->makeKeyOrderKnown();
2054: }
2055:
2056: foreach ($this->keyTypes as $i => $keyType) {
2057: $valueType = $this->valueTypes[$i];
2058: $offsetType = $valueType->toArrayKey();
2059: $builder->setOffsetValueType(
2060: $offsetType,
2061: $keyType,
2062: $this->isOptionalKey($i) || count($offsetType->getConstantScalarTypes()) > 1,
2063: );
2064: }
2065:
2066: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
2067: [$unsealedKey, $unsealedValue] = $this->unsealed;
2068: $flippedKey = $unsealedValue->toArrayKey();
2069: $flippedValue = $unsealedKey;
2070: // For a non-finite tail key (e.g. `string`), install the
2071: // unsealed extras first; setOffsetValueType then widens any
2072: // overlapping explicit values with the tail's value type.
2073: // For a finite tail key (e.g. `0|1`), setOffsetValueType
2074: // expands the tail into optional explicit slots that fully
2075: // cover the tail's domain, so no residual unsealed tail is
2076: // needed.
2077: if (count($flippedKey->getFiniteTypes()) === 0) {
2078: $builder->makeUnsealed($flippedKey, $flippedValue);
2079: }
2080: $builder->setOffsetValueType($flippedKey, $flippedValue, true);
2081: }
2082:
2083: return $builder->getArray();
2084: }
2085:
2086: public function intersectKeyArray(Type $otherArraysType): Type
2087: {
2088: $builder = ConstantArrayTypeBuilder::createEmpty();
2089: if ($this->keyOrderKnown) {
2090: $builder->makeKeyOrderKnown();
2091: }
2092:
2093: foreach ($this->keyTypes as $i => $keyType) {
2094: $valueType = $this->valueTypes[$i];
2095: $has = $otherArraysType->hasOffsetValueType($keyType);
2096: if ($has->no()) {
2097: continue;
2098: }
2099: $builder->setOffsetValueType($keyType, $valueType, $this->isOptionalKey($i) || !$has->yes());
2100: }
2101:
2102: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
2103: [$unsealedKey, $unsealedValue] = $this->unsealed;
2104: // An unsealed extra at key K survives only if `$other` can
2105: // also have key K. Narrow the unsealed key to the intersection
2106: // of our extras-range and `$other`'s key type. If they don't
2107: // overlap, the unsealed slot is dropped.
2108: $narrowedKey = TypeCombinator::intersect($unsealedKey, $otherArraysType->getIterableKeyType());
2109: if (!$narrowedKey instanceof NeverType) {
2110: $builder->makeUnsealed($narrowedKey, $unsealedValue);
2111: }
2112: }
2113:
2114: return $builder->getArray();
2115: }
2116:
2117: public function popArray(): Type
2118: {
2119: if (!$this->isKeyOrderKnown()) {
2120: // the last element can be any of them
2121: return $this->makeAllArrayKeysOptional();
2122: }
2123:
2124: return $this->removeLastElements(1);
2125: }
2126:
2127: public function reverseArray(TrinaryLogic $preserveKeys): Type
2128: {
2129: if (!$this->isKeyOrderKnown() && !$preserveKeys->yes() && $this->listsIntegerKey()) {
2130: // the integer keys are renumbered by positions that are not known
2131: return $this->withoutPositionsOfKeys()->reverseArray($preserveKeys);
2132: }
2133:
2134: $builder = ConstantArrayTypeBuilder::createEmpty();
2135: if ($this->keyOrderKnown) {
2136: $builder->makeKeyOrderKnown();
2137: }
2138:
2139: for ($i = count($this->keyTypes) - 1; $i >= 0; $i--) {
2140: $offsetType = $preserveKeys->yes() || $this->keyTypes[$i]->isInteger()->no()
2141: ? $this->keyTypes[$i]
2142: : null;
2143: $builder->setOffsetValueType($offsetType, $this->valueTypes[$i], $this->isOptionalKey($i));
2144: }
2145:
2146: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
2147: // `array_reverse` only permutes positions; the unsealed slot
2148: // is "zero or more extras at unspecified positions" both
2149: // before and after.
2150: [$unsealedKey, $unsealedValue] = $this->unsealed;
2151: $builder->makeUnsealed($unsealedKey, $unsealedValue);
2152: }
2153:
2154: return $builder->getArray();
2155: }
2156:
2157: public function searchArray(Type $needleType, ?TrinaryLogic $strict = null): Type
2158: {
2159: $strict ??= TrinaryLogic::createMaybe();
2160: $matches = [];
2161: $hasIdenticalValue = false;
2162:
2163: foreach ($this->valueTypes as $index => $valueType) {
2164: if ($strict->yes()) {
2165: $isNeedleSuperType = $valueType->isSuperTypeOf($needleType);
2166: if ($isNeedleSuperType->no()) {
2167: continue;
2168: }
2169: }
2170:
2171: if ($needleType instanceof ConstantScalarType && $valueType instanceof ConstantScalarType) {
2172: // @phpstan-ignore equal.notAllowed
2173: $isLooseEqual = $needleType->getValue() == $valueType->getValue(); // phpcs:ignore
2174: if (!$isLooseEqual) {
2175: continue;
2176: }
2177: if (
2178: ($strict->no() || $needleType->getValue() === $valueType->getValue())
2179: && !$this->isOptionalKey($index)
2180: ) {
2181: $hasIdenticalValue = true;
2182: }
2183: }
2184:
2185: $matches[] = $this->keyTypes[$index];
2186:
2187: // the search stops at the first key that surely matches, unless the keys can come in any order
2188: if ($hasIdenticalValue && $this->isKeyOrderKnown()) {
2189: break;
2190: }
2191: }
2192:
2193: // Unsealed extras can host additional entries beyond the explicit
2194: // keys, so the search may also find the needle there. The unsealed
2195: // extras' presence is uncertain by definition (zero or more
2196: // entries), so they can never make the needle "definitely found"
2197: // (`hasIdenticalValue` stays false) — `false` always remains a
2198: // possible result.
2199: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
2200: [$unsealedKeyType, $unsealedValueType] = $this->unsealed;
2201: $considerUnsealed = true;
2202: if ($strict->yes()) {
2203: $considerUnsealed = !$unsealedValueType->isSuperTypeOf($needleType)->no();
2204: }
2205: if ($considerUnsealed) {
2206: $matches[] = $unsealedKeyType;
2207: }
2208: }
2209:
2210: if (count($matches) > 0) {
2211: if ($hasIdenticalValue) {
2212: return TypeCombinator::union(...$matches);
2213: }
2214:
2215: return TypeCombinator::union(new ConstantBooleanType(false), ...$matches);
2216: }
2217:
2218: return new ConstantBooleanType(false);
2219: }
2220:
2221: public function shiftArray(): Type
2222: {
2223: if (!$this->isKeyOrderKnown()) {
2224: // the first element can be any of them, and the integer keys are renumbered by positions that are not known
2225: return $this->listsIntegerKey()
2226: ? $this->withoutPositionsOfKeys()->shiftArray()
2227: : $this->makeAllArrayKeysOptional();
2228: }
2229:
2230: return $this->removeFirstElements(1);
2231: }
2232:
2233: public function shuffleArray(): Type
2234: {
2235: return $this->getValuesArray()->degradeToGeneralArray();
2236: }
2237:
2238: public function sliceArray(Type $offsetType, Type $lengthType, TrinaryLogic $preserveKeys): Type
2239: {
2240: $keyTypesCount = count($this->keyTypes);
2241: if ($keyTypesCount === 0) {
2242: return $this;
2243: }
2244:
2245: if (!$this->isKeyOrderKnown()) {
2246: // which of the keys come at the positions is not known, and the integer keys are renumbered by them
2247: return $preserveKeys->yes() || !$this->listsIntegerKey()
2248: ? $this->makeAllArrayKeysOptional()
2249: : $this->withoutPositionsOfKeys()->sliceArray($offsetType, $lengthType, $preserveKeys);
2250: }
2251:
2252: $offset = $offsetType instanceof ConstantIntegerType ? $offsetType->getValue() : null;
2253:
2254: if ($lengthType instanceof ConstantIntegerType) {
2255: $length = $lengthType->getValue();
2256: } elseif ($lengthType->isNull()->yes()) {
2257: $length = $keyTypesCount;
2258: } else {
2259: $length = null;
2260: }
2261:
2262: if ($offset === null || $length === null) {
2263: return $this->degradeToGeneralArray()
2264: ->sliceArray($offsetType, $lengthType, $preserveKeys);
2265: }
2266:
2267: if ($keyTypesCount + $offset <= 0) {
2268: // A negative offset cannot reach left outside the array twice
2269: $offset = 0;
2270: }
2271:
2272: if ($keyTypesCount + $length <= 0) {
2273: // A negative length cannot reach left outside the array twice
2274: $length = 0;
2275: }
2276:
2277: if ($length === 0 || ($offset < 0 && $length < 0 && $offset - $length >= 0)) {
2278: // 0 / 0, 3 / 0 or e.g. -3 / -3 or -3 / -4 and so on never extract anything
2279: return $this->recreate([], [], [0], [], null, [new NeverType(true), new NeverType(true)]);
2280: }
2281:
2282: if ($length < 0) {
2283: // Negative lengths prevent access to the most right n elements
2284: return $this->removeLastElements($length * -1)
2285: ->sliceArray($offsetType, new NullType(), $preserveKeys);
2286: }
2287:
2288: if ($offset < 0) {
2289: /*
2290: * Transforms the problem with the negative offset in one with a positive offset using array reversion.
2291: * The reason is below handling of optional keys which works only from left to right.
2292: *
2293: * e.g.
2294: * array{a: 0, b: 1, c: 2, d: 3, e: 4}
2295: * with offset -4 and length 2 (which would be sliced to array{b: 1, c: 2})
2296: *
2297: * is transformed via reversion to
2298: *
2299: * array{e: 4, d: 3, c: 2, b: 1, a: 0}
2300: * with offset 2 and length 2 (which will be sliced to array{c: 2, b: 1} and then reversed again)
2301: */
2302: $offset *= -1;
2303: $reversedLength = min($length, $offset);
2304: $reversedOffset = $offset - $reversedLength;
2305: return $this->reverseArray(TrinaryLogic::createYes())
2306: ->sliceArray(new ConstantIntegerType($reversedOffset), new ConstantIntegerType($reversedLength), $preserveKeys)
2307: ->reverseArray(TrinaryLogic::createYes());
2308: }
2309:
2310: if ($offset > 0) {
2311: return $this->removeFirstElements($offset, false)
2312: ->sliceArray(new ConstantIntegerType(0), $lengthType, $preserveKeys);
2313: }
2314:
2315: $builder = ConstantArrayTypeBuilder::createEmpty();
2316: if ($this->keyOrderKnown) {
2317: $builder->makeKeyOrderKnown();
2318: }
2319:
2320: $nonOptionalElementsCount = 0;
2321: $hasOptional = false;
2322: for ($i = 0; $nonOptionalElementsCount < $length && $i < $keyTypesCount; $i++) {
2323: $isOptional = $this->isOptionalKey($i);
2324: if (!$isOptional) {
2325: $nonOptionalElementsCount++;
2326: } else {
2327: $hasOptional = true;
2328: }
2329:
2330: $isLastElement = $nonOptionalElementsCount >= $length || $i + 1 >= $keyTypesCount;
2331: if ($isLastElement && $length < $keyTypesCount && $hasOptional) {
2332: // If the slice is not full yet, but has at least one optional key
2333: // the last non-optional element is going to be optional.
2334: // Otherwise, it would not fit into the slice if previous non-optional keys are there.
2335: $isOptional = true;
2336: }
2337:
2338: $offsetType = $preserveKeys->yes() || $this->keyTypes[$i]->isInteger()->no()
2339: ? $this->keyTypes[$i]
2340: : null;
2341:
2342: $builder->setOffsetValueType($offsetType, $this->valueTypes[$i], $isOptional);
2343: }
2344:
2345: // When the requested length runs past the explicit keys, the
2346: // missing trailing slots could be filled by the source's
2347: // unsealed extras (or be absent). Carry the unsealed slot
2348: // through so the result still describes those potential extras.
2349: if (
2350: $this->isUnsealed()->yes()
2351: && $this->unsealed !== null
2352: && $nonOptionalElementsCount < $length
2353: ) {
2354: [$unsealedKey, $unsealedValue] = $this->unsealed;
2355: $builder->makeUnsealed($unsealedKey, $unsealedValue);
2356: }
2357:
2358: return $builder->getArray();
2359: }
2360:
2361: public function spliceArray(Type $offsetType, Type $lengthType, Type $replacementType): Type
2362: {
2363: $keyTypesCount = count($this->keyTypes);
2364: if ($keyTypesCount === 0) {
2365: return $this;
2366: }
2367:
2368: if (!$this->isKeyOrderKnown()) {
2369: // which of the keys come at the positions is not known
2370: return $this->degradeToGeneralArray()->spliceArray($offsetType, $lengthType, $replacementType);
2371: }
2372:
2373: $offset = $offsetType instanceof ConstantIntegerType ? $offsetType->getValue() : null;
2374:
2375: if ($lengthType instanceof ConstantIntegerType) {
2376: $length = $lengthType->getValue();
2377: } elseif ($lengthType->isNull()->yes()) {
2378: $length = $keyTypesCount;
2379: } else {
2380: $length = null;
2381: }
2382:
2383: if ($offset === null || $length === null) {
2384: return $this->degradeToGeneralArray()
2385: ->spliceArray($offsetType, $lengthType, $replacementType);
2386: }
2387:
2388: $allKeysInteger = $this->getIterableKeyType()->isInteger()->yes();
2389:
2390: if ($keyTypesCount + $offset <= 0) {
2391: // A negative offset cannot reach left outside the array twice
2392: $offset = 0;
2393: }
2394:
2395: if ($keyTypesCount + $length <= 0) {
2396: // A negative length cannot reach left outside the array twice
2397: $length = 0;
2398: }
2399:
2400: $offsetWasNegative = false;
2401: if ($offset < 0) {
2402: $offsetWasNegative = true;
2403: $offset = $keyTypesCount + $offset;
2404: }
2405:
2406: if ($length < 0) {
2407: $length = $keyTypesCount - $offset + $length;
2408: }
2409:
2410: $extractType = $this->sliceArray($offsetType, $lengthType, TrinaryLogic::createYes());
2411:
2412: $types = [];
2413: foreach ($replacementType->toArray()->getArrays() as $replacementArrayType) {
2414: $removeKeysCount = 0;
2415: $optionalKeysBeforeReplacement = 0;
2416:
2417: $builder = ConstantArrayTypeBuilder::createEmpty();
2418: if ($this->keyOrderKnown) {
2419: $builder->makeKeyOrderKnown();
2420: }
2421: for ($i = 0;; $i++) {
2422: $isOptional = $this->isOptionalKey($i);
2423:
2424: if (!$offsetWasNegative && $i < $offset && $isOptional) {
2425: $optionalKeysBeforeReplacement++;
2426: }
2427:
2428: if ($i === $offset + $optionalKeysBeforeReplacement) {
2429: // When the offset is reached we have to a) put the replacement array in and b) remove $length elements
2430: $removeKeysCount = $length;
2431:
2432: if ($replacementArrayType instanceof self) {
2433: $valuesArray = $replacementArrayType->getValuesArray();
2434: for ($j = 0, $jMax = count($valuesArray->keyTypes); $j < $jMax; $j++) {
2435: $builder->setOffsetValueType(null, $valuesArray->valueTypes[$j], $valuesArray->isOptionalKey($j));
2436: }
2437: } else {
2438: $builder->degradeToGeneralArray();
2439: $builder->setOffsetValueType($replacementArrayType->getValuesArray()->getIterableKeyType(), $replacementArrayType->getIterableValueType(), true);
2440: }
2441: }
2442:
2443: if (!isset($this->keyTypes[$i])) {
2444: break;
2445: }
2446:
2447: if ($removeKeysCount > 0) {
2448: $extractTypeHasOffsetValueType = $extractType->hasOffsetValueType($this->keyTypes[$i]);
2449:
2450: if (
2451: (!$isOptional && $extractTypeHasOffsetValueType->yes())
2452: || ($isOptional && $extractTypeHasOffsetValueType->maybe())
2453: ) {
2454: $removeKeysCount--;
2455: continue;
2456: }
2457: }
2458:
2459: if (!$isOptional && $extractType->hasOffsetValueType($this->keyTypes[$i])->maybe()) {
2460: $isOptional = true;
2461: }
2462:
2463: $builder->setOffsetValueType(
2464: $this->keyTypes[$i]->isInteger()->no() ? $this->keyTypes[$i] : null,
2465: $this->valueTypes[$i],
2466: $isOptional,
2467: );
2468: }
2469:
2470: // `array_splice` removes a slice at an explicit offset and
2471: // inserts a replacement there. Real unsealed extras live at
2472: // positions past the explicit keys, so they're unaffected
2473: // by the operation (re-indexing of int keys keeps the
2474: // `<int, V>` range intact). Carry the slot through.
2475: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
2476: [$unsealedKey, $unsealedValue] = $this->unsealed;
2477: $builder->makeUnsealed($unsealedKey, $unsealedValue);
2478: }
2479:
2480: $builtType = $builder->getArray();
2481: if ($allKeysInteger && !$builtType->isList()->yes()) {
2482: $builtType = TypeCombinator::intersect($builtType, new AccessoryArrayListType());
2483: }
2484: $types[] = $builtType;
2485: }
2486:
2487: return TypeCombinator::union(...$types);
2488: }
2489:
2490: public function truncateListToSize(Type $sizeType): Type
2491: {
2492: [$min, $max] = self::extractTruncateListBounds($sizeType);
2493:
2494: // `getMin() === null` ↔ unbounded below; the narrowing has no anchor
2495: // to start from. Also bail out when the required prefix would exceed
2496: // the array-shape limit — we can't enumerate that many keys.
2497: // `isList()` is intentionally NOT checked here: the call site
2498: // (`TypeSpecifier`) only invokes this when the *outer* aggregate is
2499: // already a list, but a CAT inside a `non-empty-list` intersection
2500: // may have its own `isList()` weakened to `Maybe`.
2501: if (
2502: $min === null
2503: || $min >= ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT
2504: || !$this->getKeyType()->isSuperTypeOf(IntegerRangeType::fromInterval(0, ($max ?? $min) - 1))->yes()
2505: ) {
2506: return TypeCombinator::intersect($this, new NonEmptyArrayType());
2507: }
2508:
2509: // Required prefix `[0, $min)`: every value definitely present.
2510: $builderData = [];
2511: for ($i = 0; $i < $min; $i++) {
2512: $offsetType = new ConstantIntegerType($i);
2513: $builderData[] = [$offsetType, $this->getOffsetValueType($offsetType), false];
2514: }
2515:
2516: if ($max !== null) {
2517: // Optional middle `[$min, $max)`.
2518: if ($max - $min > ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT) {
2519: return TypeCombinator::intersect($this, new NonEmptyArrayType());
2520: }
2521: for ($i = $min; $i < $max; $i++) {
2522: $offsetType = new ConstantIntegerType($i);
2523: $builderData[] = [$offsetType, $this->getOffsetValueType($offsetType), true];
2524: }
2525: } else {
2526: // Unbounded max: probe explicit keys from `$min` onward until
2527: // `hasOffsetValueType` answers `no`. Each probe contributes one
2528: // optional (or required, when `hasOffsetValueType` is `yes`) slot.
2529: $isUnsealed = $this->isUnsealed()->yes();
2530: for ($i = $min;; $i++) {
2531: $offsetType = new ConstantIntegerType($i);
2532: $hasOffset = $this->hasOffsetValueType($offsetType);
2533: if ($hasOffset->no()) {
2534: break;
2535: }
2536: // Real unsealed extras make `hasOffsetValueType` answer
2537: // `Maybe` for *any* in-range key, so the probe would
2538: // otherwise run until `ARRAY_COUNT_LIMIT` bails (slow +
2539: // lossy). Stop once the explicit keys are exhausted; the
2540: // unsealed slot attached below covers further entries.
2541: if ($isUnsealed && !$hasOffset->yes()) {
2542: break;
2543: }
2544: $builderData[] = [$offsetType, $this->getOffsetValueType($offsetType), !$hasOffset->yes()];
2545: }
2546: }
2547:
2548: if (count($builderData) > ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT) {
2549: return TypeCombinator::intersect($this, new NonEmptyArrayType());
2550: }
2551:
2552: $builder = ConstantArrayTypeBuilder::createEmpty();
2553: if ($this->keyOrderKnown) {
2554: $builder->makeKeyOrderKnown();
2555: }
2556: foreach ($builderData as [$offsetType, $valueType, $optional]) {
2557: $builder->setOffsetValueType($offsetType, $valueType, $optional);
2558: }
2559:
2560: // Carry the unsealed slot through only for the unbounded-max
2561: // branch — a bounded-max range caps the result size and the
2562: // unsealed extras can't fit.
2563: if ($max === null && $this->isUnsealed()->yes() && $this->unsealed !== null) {
2564: $builder->makeUnsealed($this->unsealed[0], $this->unsealed[1]);
2565: }
2566:
2567: $builtArray = $builder->getArray();
2568: // `setOffsetValueType` on a brand-new builder produces a list when
2569: // the resulting offsets are sequential ints — but it may not preserve
2570: // list-ness in every shape. Reattach it for the single-CAT case.
2571: if (!$builder->isList()) {
2572: $constantArrays = $builtArray->getConstantArrays();
2573: if (count($constantArrays) === 1) {
2574: $builtArray = $constantArrays[0]->makeList();
2575: }
2576: }
2577:
2578: return $builtArray;
2579: }
2580:
2581: /**
2582: * Extracts (min, max) bounds from a size type for `truncateListToSize`:
2583: * the smallest and the largest size. A size type without integers returns
2584: * `[null, null]` and the caller falls back to the non-precise path.
2585: *
2586: * @return array{?int, ?int}
2587: */
2588: public static function extractTruncateListBounds(Type $sizeType): array
2589: {
2590: $numbers = $sizeType->toNumberSet();
2591: if ($numbers === null) {
2592: return [null, null];
2593: }
2594:
2595: return $numbers->getIntegerBounds() ?? [null, null];
2596: }
2597:
2598: public function isIterableAtLeastOnce(): TrinaryLogic
2599: {
2600: $keysCount = count($this->keyTypes);
2601: if ($keysCount === 0) {
2602: if (!$this->isUnsealed()->yes()) {
2603: return TrinaryLogic::createNo();
2604: }
2605: return TrinaryLogic::createMaybe();
2606: }
2607:
2608: $optionalKeysCount = count($this->optionalKeys);
2609: if ($optionalKeysCount < $keysCount) {
2610: return TrinaryLogic::createYes();
2611: }
2612:
2613: return TrinaryLogic::createMaybe();
2614: }
2615:
2616: public function getArraySize(): Type
2617: {
2618: $optionalKeysCount = count($this->optionalKeys);
2619: $totalKeysCount = count($this->getKeyTypes());
2620: if (!$this->isUnsealed()->yes()) {
2621: if ($optionalKeysCount === 0) {
2622: return new ConstantIntegerType($totalKeysCount);
2623: }
2624: $max = $totalKeysCount;
2625: } else {
2626: $max = null;
2627: }
2628:
2629: return IntegerRangeType::fromInterval($totalKeysCount - $optionalKeysCount, $max);
2630: }
2631:
2632: public function getFirstIterableKeyType(): Type
2633: {
2634: if (!$this->isKeyOrderKnown()) {
2635: return $this->getIterableKeyType();
2636: }
2637:
2638: $keyTypes = [];
2639: foreach ($this->keyTypes as $i => $keyType) {
2640: $keyTypes[] = $keyType;
2641: if (!$this->isOptionalKey($i)) {
2642: break;
2643: }
2644: }
2645:
2646: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
2647: $unsealedKeyType = $this->unsealed[0];
2648: if ($unsealedKeyType instanceof MixedType && !$unsealedKeyType instanceof TemplateMixedType) {
2649: $unsealedKeyType = (new BenevolentUnionType([new IntegerType(), new StringType()]))->toArrayKey();
2650: } elseif ($unsealedKeyType instanceof StrictMixedType && !$unsealedKeyType instanceof TemplateStrictMixedType) {
2651: $unsealedKeyType = (new BenevolentUnionType([new IntegerType(), new StringType()]))->toArrayKey();
2652: }
2653: $keyTypes[] = $unsealedKeyType;
2654: }
2655:
2656: return TypeCombinator::union(...$keyTypes);
2657: }
2658:
2659: public function getLastIterableKeyType(): Type
2660: {
2661: if (!$this->isKeyOrderKnown()) {
2662: return $this->getIterableKeyType();
2663: }
2664:
2665: $keyTypes = [];
2666: for ($i = count($this->keyTypes) - 1; $i >= 0; $i--) {
2667: $keyTypes[] = $this->keyTypes[$i];
2668: if (!$this->isOptionalKey($i)) {
2669: break;
2670: }
2671: }
2672:
2673: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
2674: $unsealedKeyType = $this->unsealed[0];
2675: if ($unsealedKeyType instanceof MixedType && !$unsealedKeyType instanceof TemplateMixedType) {
2676: $unsealedKeyType = (new BenevolentUnionType([new IntegerType(), new StringType()]))->toArrayKey();
2677: } elseif ($unsealedKeyType instanceof StrictMixedType && !$unsealedKeyType instanceof TemplateStrictMixedType) {
2678: $unsealedKeyType = (new BenevolentUnionType([new IntegerType(), new StringType()]))->toArrayKey();
2679: }
2680: $keyTypes[] = $unsealedKeyType;
2681: }
2682:
2683: return TypeCombinator::union(...$keyTypes);
2684: }
2685:
2686: public function getFirstIterableValueType(): Type
2687: {
2688: if (!$this->isKeyOrderKnown()) {
2689: return $this->getIterableValueType();
2690: }
2691:
2692: $valueTypes = [];
2693: foreach ($this->valueTypes as $i => $valueType) {
2694: $valueTypes[] = $valueType;
2695: if (!$this->isOptionalKey($i)) {
2696: break;
2697: }
2698: }
2699:
2700: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
2701: $valueTypes[] = $this->unsealed[1];
2702: }
2703:
2704: return TypeCombinator::union(...$valueTypes);
2705: }
2706:
2707: public function getLastIterableValueType(): Type
2708: {
2709: if (!$this->isKeyOrderKnown()) {
2710: return $this->getIterableValueType();
2711: }
2712:
2713: $valueTypes = [];
2714: for ($i = count($this->keyTypes) - 1; $i >= 0; $i--) {
2715: $valueTypes[] = $this->valueTypes[$i];
2716: if (!$this->isOptionalKey($i)) {
2717: break;
2718: }
2719: }
2720:
2721: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
2722: $valueTypes[] = $this->unsealed[1];
2723: }
2724:
2725: return TypeCombinator::union(...$valueTypes);
2726: }
2727:
2728: public function isConstantArray(): TrinaryLogic
2729: {
2730: return TrinaryLogic::createYes();
2731: }
2732:
2733: public function isList(): TrinaryLogic
2734: {
2735: return $this->isList;
2736: }
2737:
2738: /** @param positive-int $length */
2739: private function removeLastElements(int $length): self
2740: {
2741: $keyTypesCount = count($this->keyTypes);
2742: if ($keyTypesCount === 0) {
2743: return $this;
2744: }
2745:
2746: // With real unsealed extras on the source, the elements being
2747: // "removed" might come from the unsealed range rather than from
2748: // the trailing explicit keys — the array might have zero extras
2749: // (so the trailing explicit keys are popped) or one+ extras (so
2750: // they're popped instead, leaving the explicit keys intact).
2751: // Encode this by marking the trailing keys as optional and
2752: // keeping the unsealed slot in place.
2753: if ($this->isUnsealed()->yes()) {
2754: $optionalKeys = $this->optionalKeys;
2755: $newLength = $keyTypesCount - $length;
2756: for ($i = $keyTypesCount - 1; $i >= max($newLength, 0); $i--) {
2757: if (in_array($i, $optionalKeys, true)) {
2758: continue;
2759: }
2760: $optionalKeys[] = $i;
2761: }
2762:
2763: return $this->recreate(
2764: $this->keyTypes,
2765: $this->valueTypes,
2766: $this->nextAutoIndexes,
2767: array_values($optionalKeys),
2768: $this->isList,
2769: $this->unsealed,
2770: );
2771: }
2772:
2773: $keyTypes = $this->keyTypes;
2774: $valueTypes = $this->valueTypes;
2775: $optionalKeys = $this->optionalKeys;
2776: $nextAutoindexes = $this->nextAutoIndexes;
2777:
2778: $optionalKeysRemoved = 0;
2779: $newLength = $keyTypesCount - $length;
2780: for ($i = $keyTypesCount - 1; $i >= 0; $i--) {
2781: $isOptional = $this->isOptionalKey($i);
2782:
2783: if ($i >= $newLength) {
2784: if ($isOptional) {
2785: $optionalKeysRemoved++;
2786: foreach ($optionalKeys as $key => $value) {
2787: if ($value === $i) {
2788: unset($optionalKeys[$key]);
2789: break;
2790: }
2791: }
2792: }
2793:
2794: $removedKeyType = array_pop($keyTypes);
2795: array_pop($valueTypes);
2796: $nextAutoindexes = $removedKeyType instanceof ConstantIntegerType
2797: ? [$removedKeyType->getValue()]
2798: : $this->nextAutoIndexes;
2799: continue;
2800: }
2801:
2802: if ($isOptional || $optionalKeysRemoved <= 0) {
2803: continue;
2804: }
2805:
2806: $optionalKeys[] = $i;
2807: $optionalKeysRemoved--;
2808: }
2809:
2810: return $this->recreate(
2811: $keyTypes,
2812: $valueTypes,
2813: $nextAutoindexes,
2814: array_values($optionalKeys),
2815: $this->isList,
2816: $this->unsealed,
2817: );
2818: }
2819:
2820: /** @param positive-int $length */
2821: private function removeFirstElements(int $length, bool $reindex = true): Type
2822: {
2823: $builder = ConstantArrayTypeBuilder::createEmpty();
2824: if ($this->keyOrderKnown) {
2825: $builder->makeKeyOrderKnown();
2826: }
2827:
2828: $optionalKeysIgnored = 0;
2829: foreach ($this->keyTypes as $i => $keyType) {
2830: $isOptional = $this->isOptionalKey($i);
2831: if ($i <= $length - 1) {
2832: if ($isOptional) {
2833: $optionalKeysIgnored++;
2834: }
2835: continue;
2836: }
2837:
2838: if (!$isOptional && $optionalKeysIgnored > 0) {
2839: $isOptional = true;
2840: $optionalKeysIgnored--;
2841: }
2842:
2843: $valueType = $this->valueTypes[$i];
2844: if ($reindex && $keyType instanceof ConstantIntegerType) {
2845: $keyType = null;
2846: }
2847:
2848: $builder->setOffsetValueType($keyType, $valueType, $isOptional);
2849: }
2850:
2851: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
2852: // `array_shift` removes the *first* element. The explicit
2853: // keys precede the unsealed extras in insertion order, so
2854: // the shift always lands on an explicit key (when there is
2855: // one); the unsealed slot is unaffected. Re-indexing of int
2856: // keys doesn't change the unsealed range — it stays `<int, V>`.
2857: [$unsealedKey, $unsealedValue] = $this->unsealed;
2858: $builder->makeUnsealed($unsealedKey, $unsealedValue);
2859: }
2860:
2861: return $builder->getArray();
2862: }
2863:
2864: public function toBoolean(): BooleanType
2865: {
2866: return $this->getArraySize()->toBoolean();
2867: }
2868:
2869: public function toInteger(): Type
2870: {
2871: return $this->toBoolean()->toInteger();
2872: }
2873:
2874: public function toFloat(): Type
2875: {
2876: return $this->toBoolean()->toFloat();
2877: }
2878:
2879: public function generalize(GeneralizePrecision $precision): Type
2880: {
2881: // No explicit keys and no real extras — actually empty, return as-is.
2882: if (count($this->keyTypes) === 0 && !$this->isUnsealed()->yes()) {
2883: return $this;
2884: }
2885:
2886: // The shape is immutable, so it generalizes the same way every time.
2887: // Shapes nested in each other share their members (`$a['parent'] = $a`),
2888: // and without remembering the result every path to a shared member
2889: // generalizes it again - exponential in the nesting depth.
2890: return $this->generalizedTypes[spl_object_id($precision)] ??= $this->doGeneralize($precision);
2891: }
2892:
2893: private function doGeneralize(GeneralizePrecision $precision): Type
2894: {
2895: if ($precision->isTemplateArgument()) {
2896: return $this->traverse(static fn (Type $type) => $type->generalize($precision));
2897: }
2898:
2899: $arrayType = new ArrayType(
2900: $this->getIterableKeyType()->generalize($precision),
2901: $this->getIterableValueType()->generalize($precision),
2902: );
2903:
2904: $keyTypesCount = count($this->keyTypes);
2905: $optionalKeysCount = count($this->optionalKeys);
2906:
2907: $accessoryTypes = [];
2908: if ($precision->isMoreSpecific() && ($keyTypesCount - $optionalKeysCount) < 32) {
2909: foreach ($this->keyTypes as $i => $keyType) {
2910: if ($this->isOptionalKey($i)) {
2911: continue;
2912: }
2913:
2914: $accessoryTypes[] = new HasOffsetValueType($keyType, $this->valueTypes[$i]->generalize($precision));
2915: }
2916: } elseif ($this->isIterableAtLeastOnce()->yes()) {
2917: // Previously gated on `keyTypesCount > optionalKeysCount`,
2918: // which mishandles "no explicit keys + real unsealed
2919: // extras" (`isIterableAtLeastOnce()` answers `Maybe` —
2920: // extras might be empty — and correctly skips
2921: // `NonEmptyArrayType`). The new gate also covers the
2922: // usual sealed-with-required-keys case, so behaviour for
2923: // existing CAT shapes is unchanged.
2924: $accessoryTypes[] = new NonEmptyArrayType();
2925: }
2926:
2927: if ($this->isList()->yes()) {
2928: $arrayType = TypeCombinator::intersect($arrayType, new AccessoryArrayListType());
2929: }
2930:
2931: if (count($accessoryTypes) > 0) {
2932: return TypeCombinator::intersect($arrayType, ...$accessoryTypes);
2933: }
2934:
2935: return $arrayType;
2936: }
2937:
2938: public function generalizeValues(): self
2939: {
2940: $valueTypes = [];
2941: foreach ($this->valueTypes as $valueType) {
2942: $valueTypes[] = $valueType->generalize(GeneralizePrecision::lessSpecific());
2943: }
2944:
2945: $unsealed = $this->unsealed;
2946: if ($unsealed !== null) {
2947: [$unsealedKey, $unsealedValue] = $unsealed;
2948: $unsealed = [$unsealedKey, $unsealedValue->generalize(GeneralizePrecision::lessSpecific())];
2949: }
2950:
2951: return $this->recreate($this->keyTypes, $valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $this->isList, $unsealed);
2952: }
2953:
2954: private function degradeToGeneralArray(): Type
2955: {
2956: $builder = ConstantArrayTypeBuilder::createFromConstantArray($this);
2957: $builder->degradeToGeneralArray();
2958:
2959: return $builder->getArray();
2960: }
2961:
2962: public function getKeysArrayFiltered(Type $filterValueType, TrinaryLogic $strict): Type
2963: {
2964: $keysArray = $this->getKeysOrValuesArray($this->keyTypes, $this->unsealed[0] ?? null);
2965:
2966: return new IntersectionType([
2967: new ArrayType(
2968: IntegerRangeType::createAllGreaterThanOrEqualTo(0),
2969: $keysArray->getIterableValueType(),
2970: ),
2971: new AccessoryArrayListType(),
2972: ]);
2973: }
2974:
2975: public function getKeysArray(): self
2976: {
2977: return $this->getKeysOrValuesArray($this->keyTypes, $this->unsealed[0] ?? null);
2978: }
2979:
2980: public function getValuesArray(): self
2981: {
2982: return $this->getKeysOrValuesArray($this->valueTypes, $this->unsealed[1] ?? null);
2983: }
2984:
2985: /**
2986: * The values in the order the array has them, for code that walks the values by position: this shape when it
2987: * knows its key order, otherwise the list of the values that can come at each position.
2988: */
2989: public function getValuesInKeyOrder(): self
2990: {
2991: return $this->isKeyOrderKnown() ? $this : $this->getValuesArray();
2992: }
2993:
2994: /**
2995: * This shape as code that renumbers its integer keys by their positions, like array_merge() and unpacking, sees
2996: * it: when it does not know its key order, each of the integer keys holds any of their values, the required
2997: * ones listed first. The string keys keep their values.
2998: */
2999: public function inRenumberingOrder(): self
3000: {
3001: if ($this->isKeyOrderKnown()) {
3002: return $this;
3003: }
3004:
3005: $integerValueTypes = [];
3006: $requiredIntegerKeys = [];
3007: $optionalIntegerKeys = [];
3008: foreach ($this->keyTypes as $i => $keyType) {
3009: if (!$keyType instanceof ConstantIntegerType) {
3010: continue;
3011: }
3012:
3013: $integerValueTypes[] = $this->valueTypes[$i];
3014: if ($this->isOptionalKey($i)) {
3015: $optionalIntegerKeys[] = $keyType;
3016: } else {
3017: $requiredIntegerKeys[] = $keyType;
3018: }
3019: }
3020: if (count($integerValueTypes) < 2) {
3021: return $this;
3022: }
3023:
3024: $integerValueType = TypeCombinator::union(...$integerValueTypes);
3025: $integerKeys = array_merge($requiredIntegerKeys, $optionalIntegerKeys);
3026: $keyTypes = [];
3027: $valueTypes = [];
3028: $optionalKeys = [];
3029: foreach ($this->keyTypes as $i => $keyType) {
3030: if ($keyType instanceof ConstantIntegerType) {
3031: $keyType = array_shift($integerKeys);
3032: if ($keyType === null) {
3033: throw new ShouldNotHappenException();
3034: }
3035: $valueTypes[] = $integerValueType;
3036: $isOptional = in_array($keyType, $optionalIntegerKeys, true);
3037: } else {
3038: $valueTypes[] = $this->valueTypes[$i];
3039: $isOptional = $this->isOptionalKey($i);
3040: }
3041: $keyTypes[] = $keyType;
3042: if (!$isOptional) {
3043: continue;
3044: }
3045:
3046: $optionalKeys[] = count($keyTypes) - 1;
3047: }
3048:
3049: $renumbered = $this->recreate($keyTypes, $valueTypes, $this->nextAutoIndexes, $optionalKeys, $this->isList, $this->unsealed);
3050:
3051: // with only integer keys, each position holds any of the values, so the positions are all the order there is
3052: return count($integerValueTypes) === count($this->keyTypes) ? $renumbered->knowKeyOrder() : $renumbered;
3053: }
3054:
3055: private function listsIntegerKey(): bool
3056: {
3057: foreach ($this->keyTypes as $keyType) {
3058: if ($keyType instanceof ConstantIntegerType) {
3059: return true;
3060: }
3061: }
3062:
3063: return false;
3064: }
3065:
3066: /**
3067: * The values at positions any of them can come at, for operations that renumber integer keys by position:
3068: * the list of the values when every key is an integer, a general array otherwise.
3069: */
3070: private function withoutPositionsOfKeys(): Type
3071: {
3072: return $this->getIterableKeyType()->isInteger()->yes()
3073: ? $this->getValuesArray()
3074: : $this->degradeToGeneralArray();
3075: }
3076:
3077: /**
3078: * @param array<int, Type> $types
3079: */
3080: private function getKeysOrValuesArray(array $types, ?Type $unsealedSourceType): self
3081: {
3082: $count = count($types);
3083: $autoIndexes = range($count - count($this->optionalKeys), $count);
3084:
3085: // The result is always a list — the source's keys/values are
3086: // numbered sequentially. The new unsealed slot (if the source
3087: // has real extras) describes "zero or more extras at int
3088: // positions >= 0 whose values are the source's unsealed
3089: // key/value type". `int<0, max>` is the conventional unsealed
3090: // key for list-shaped extras; it also enables the short-form
3091: // `<value>` describe.
3092: $resultUnsealed = null;
3093: if ($this->isUnsealed()->yes() && $unsealedSourceType !== null) {
3094: $resultUnsealed = [IntegerRangeType::createAllGreaterThanOrEqualTo(0), $unsealedSourceType];
3095: }
3096:
3097: if (!$this->isKeyOrderKnown()) {
3098: // any of the keys, and any of the extras, can come at any position
3099: $valueType = TypeCombinator::union(...$types, ...($resultUnsealed !== null ? [$resultUnsealed[1]] : []));
3100: $requiredCount = $count - count($this->optionalKeys);
3101: $keyTypes = [];
3102: $valueTypes = [];
3103: $optionalKeys = [];
3104: for ($i = 0; $i < $count; $i++) {
3105: $keyTypes[] = new ConstantIntegerType($i);
3106: $valueTypes[] = $valueType;
3107: if ($i < $requiredCount) {
3108: continue;
3109: }
3110:
3111: $optionalKeys[] = $i;
3112: }
3113:
3114: return $this->recreate($keyTypes, $valueTypes, $autoIndexes, $optionalKeys, TrinaryLogic::createYes(), $resultUnsealed);
3115: }
3116:
3117: if ($this->isList->yes()) {
3118: // Optimized version for lists: Assume that if a later key exists, then earlier keys also exist.
3119: $keyTypes = array_map(
3120: static fn (int $i): ConstantIntegerType => new ConstantIntegerType($i),
3121: array_keys($types),
3122: );
3123: return $this->recreate($keyTypes, $types, $autoIndexes, $this->optionalKeys, TrinaryLogic::createYes(), $resultUnsealed);
3124: }
3125:
3126: $keyTypes = [];
3127: $valueTypes = [];
3128: $optionalKeys = [];
3129: $maxIndex = 0;
3130:
3131: // Position $i of the result can hold any source value from $i up to
3132: // $maxIndex. Both ends of that window only move forward, so the
3133: // window unions are kept as a two-stack queue: $suffixUnions[$j] is
3134: // the union of $types[$j..$suffixEnd] and $tailUnion the union of
3135: // the values added after $suffixEnd. Each value enters the suffix
3136: // unions once, which keeps this linear in the number of keys instead
3137: // of unioning every window from scratch.
3138: $suffixUnions = [];
3139: $suffixEnd = -1;
3140: $tailUnion = null;
3141: $tailEnd = -1;
3142:
3143: foreach ($types as $i => $type) {
3144: $keyTypes[] = new ConstantIntegerType($i);
3145:
3146: if ($this->isOptionalKey($maxIndex)) {
3147: // move $maxIndex to next non-optional key
3148: do {
3149: $maxIndex++;
3150: } while ($maxIndex < $count && $this->isOptionalKey($maxIndex));
3151: }
3152:
3153: if ($i === $maxIndex) {
3154: $valueTypes[] = $type;
3155: } else {
3156: $windowEnd = min($maxIndex, $count - 1);
3157: if ($i === $windowEnd) {
3158: $valueTypes[] = TypeCombinator::union($type);
3159: } else {
3160: if ($i > $suffixEnd) {
3161: $suffixEnd = $windowEnd;
3162: $suffixUnions = [$suffixEnd => $types[$suffixEnd]];
3163: for ($j = $suffixEnd - 1; $j >= $i; $j--) {
3164: $suffixUnions[$j] = TypeCombinator::union($types[$j], $suffixUnions[$j + 1]);
3165: }
3166: $tailUnion = null;
3167: $tailEnd = $suffixEnd;
3168: }
3169: for ($j = $tailEnd + 1; $j <= $windowEnd; $j++) {
3170: $tailUnion = $tailUnion === null ? $types[$j] : TypeCombinator::union($tailUnion, $types[$j]);
3171: }
3172: $tailEnd = $windowEnd;
3173:
3174: $valueTypes[] = $tailUnion === null ? $suffixUnions[$i] : TypeCombinator::union($suffixUnions[$i], $tailUnion);
3175: }
3176: if ($maxIndex >= $count) {
3177: $optionalKeys[] = $i;
3178: }
3179: }
3180: $maxIndex++;
3181: }
3182:
3183: return $this->recreate($keyTypes, $valueTypes, $autoIndexes, $optionalKeys, TrinaryLogic::createYes(), $resultUnsealed);
3184: }
3185:
3186: public function describe(VerbosityLevel $level): string
3187: {
3188: $arrayName = $this->shouldBeDescribedAsAList(true) ? 'list' : 'array';
3189: $typeOnlyArrayName = $this->shouldBeDescribedAsAList(false) ? 'list' : 'array';
3190:
3191: $describeValue = function (bool $truncate) use ($level, $arrayName): string {
3192: $items = [];
3193: $values = [];
3194: $exportValuesOnly = !$this->shouldNameItsKeys();
3195: foreach ($this->keyTypes as $i => $keyType) {
3196: $valueType = $this->valueTypes[$i];
3197: if ($keyType->getValue() !== $i) {
3198: $exportValuesOnly = false;
3199: }
3200:
3201: $isOptional = $this->isOptionalKey($i);
3202: if ($isOptional) {
3203: $exportValuesOnly = false;
3204: }
3205:
3206: $keyDescription = $keyType->getValue();
3207: if (is_string($keyDescription)) {
3208: if (str_contains($keyDescription, '"')) {
3209: $keyDescription = sprintf('\'%s\'', $keyDescription);
3210: } elseif (str_contains($keyDescription, '\'')) {
3211: $keyDescription = sprintf('"%s"', $keyDescription);
3212: } elseif (!self::isValidIdentifier($keyDescription)) {
3213: $keyDescription = sprintf('\'%s\'', $keyDescription);
3214: }
3215: }
3216:
3217: $valueTypeDescription = $valueType->describe($level);
3218: $items[] = sprintf('%s%s: %s', $keyDescription, $isOptional ? '?' : '', $valueTypeDescription);
3219: $values[] = $valueTypeDescription;
3220: }
3221:
3222: $append = '';
3223: if ($truncate && count($items) > self::DESCRIBE_LIMIT) {
3224: $items = array_slice($items, 0, self::DESCRIBE_LIMIT);
3225: $values = array_slice($values, 0, self::DESCRIBE_LIMIT);
3226: $append = ', ...';
3227: }
3228:
3229: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
3230: if (count($items) > 0) {
3231: $append .= ', ';
3232: }
3233: $append .= '...';
3234: $keyTemplate = $this->getUnsealedKeyTemplate();
3235: $keyDescription = $this->unsealed[0]->describe(VerbosityLevel::precise());
3236: $isMixedKeyType = MixedType::isBareMixed($this->unsealed[0], $level) && !$this->unsealed[0]->isExplicitMixed();
3237: $isMixedItemType = MixedType::isBareMixed($this->unsealed[1], $level) && !$this->unsealed[1]->isExplicitMixed();
3238: if ($keyTemplate !== null) {
3239: $append .= sprintf('<%s of %s, %s>', $keyTemplate[0]->getName(), $keyTemplate[0]->getBound()->describe($level->isTypeOnly() ? VerbosityLevel::value() : $level), $keyTemplate[2]->describe($level));
3240: } elseif ($isMixedKeyType || ($this->isList()->yes() && $keyDescription === 'int<0, max>')) {
3241: if (!$isMixedItemType) {
3242: $append .= sprintf('<%s>', $this->unsealed[1]->describe($level));
3243: }
3244: } else {
3245: $append .= sprintf('<%s, %s>', $this->unsealed[0]->describe($level), $this->unsealed[1]->describe($level));
3246: }
3247: }
3248:
3249: return sprintf(
3250: '%s{%s%s}%s',
3251: $arrayName,
3252: implode(', ', $exportValuesOnly ? $values : $items),
3253: $append,
3254: $level->isCache() && !$this->isKeyOrderKnown() ? '(unordered)' : '',
3255: );
3256: };
3257: return $level->handle(
3258: function () use ($typeOnlyArrayName, $level): string {
3259: $arrayName = $typeOnlyArrayName;
3260: if ($this->isIterableAtLeastOnce()->no()) {
3261: return $arrayName;
3262: }
3263: $keyType = $this->getIterableKeyType();
3264: // Only a BenevolentUnionType describes with the surrounding parentheses of
3265: // '(int|string)' / '(int|non-decimal-int-string)', so skip the describe()
3266: // call for every other key type.
3267: if ($keyType instanceof BenevolentUnionType && in_array($keyType->describe(VerbosityLevel::value()), ['(int|string)', '(int|non-decimal-int-string)'], true)) {
3268: return sprintf('%s<%s>', $arrayName, $this->getIterableValueType()->describe($level));
3269: }
3270: return sprintf('%s<%s, %s>', $arrayName, $keyType->describe($level), $this->getIterableValueType()->describe($level));
3271: },
3272: static fn (): string => $describeValue(true),
3273: static fn (): string => $describeValue(false),
3274: );
3275: }
3276:
3277: /** With bleeding edge, array{X, Y} is a list, so a shape that might not be one names its keys. */
3278: private function shouldNameItsKeys(): bool
3279: {
3280: return count($this->keyTypes) > 1 && !$this->isList->yes() && BleedingEdgeToggle::isBleedingEdge();
3281: }
3282:
3283: /** @param bool $namingKeys whether the description names the keys, as a shape does */
3284: private function shouldBeDescribedAsAList(bool $namingKeys = true): bool
3285: {
3286: if (!$this->isList->yes()) {
3287: return false;
3288: }
3289:
3290: if (count($this->optionalKeys) === 0) {
3291: return false;
3292: }
3293:
3294: // with bleeding edge, a shape that lists two or more keys is not a list
3295: if (count($this->optionalKeys) > 1 || ($namingKeys && count($this->keyTypes) > 1 && BleedingEdgeToggle::isBleedingEdge())) {
3296: return true;
3297: }
3298:
3299: return $this->optionalKeys[0] !== count($this->keyTypes) - 1;
3300: }
3301:
3302: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
3303: {
3304: if ($receivedType instanceof UnionType || $receivedType instanceof IntersectionType) {
3305: return $receivedType->inferTemplateTypesOn($this);
3306: }
3307:
3308: if ($receivedType instanceof self) {
3309: $typeMap = TemplateTypeMap::createEmpty();
3310: foreach ($this->keyTypes as $i => $keyType) {
3311: $valueType = $this->valueTypes[$i];
3312: if ($receivedType->hasOffsetValueType($keyType)->no()) {
3313: continue;
3314: }
3315: $receivedValueType = $receivedType->getOffsetValueType($keyType);
3316: $typeMap = $typeMap->union($valueType->inferTemplateTypes($receivedValueType));
3317: }
3318:
3319: $unsealed = $this->getUnsealedTypes();
3320: if ($unsealed !== null) {
3321: [$unsealedKeyType, $unsealedValueType] = $unsealed;
3322:
3323: // Received's explicit keys not in $this's explicit keys are
3324: // candidates for matching $this's unsealed extras pattern.
3325: // Only contribute when the key type matches; mismatched explicit
3326: // keys are extra entries the parameter wouldn't accept anyway,
3327: // surfaced by the regular argument-type check.
3328: $receivedKeyTypes = $receivedType->getKeyTypes();
3329: $receivedValueTypes = $receivedType->getValueTypes();
3330: foreach ($receivedKeyTypes as $j => $receivedKeyType) {
3331: if ($this->hasOffsetValueType($receivedKeyType)->yes()) {
3332: continue;
3333: }
3334: if (!$unsealedKeyType->isSuperTypeOf($receivedKeyType)->yes()) {
3335: continue;
3336: }
3337: $typeMap = $typeMap->union($unsealedKeyType->inferTemplateTypes($receivedKeyType));
3338: $typeMap = $typeMap->union($unsealedValueType->inferTemplateTypes($receivedValueTypes[$j]));
3339: }
3340:
3341: // Received's own unsealed extras describe "all the rest" — when
3342: // the key type doesn't fit $this's unsealed key pattern there
3343: // is no valid template assignment, so force NEVER.
3344: $receivedUnsealed = $receivedType->getUnsealedTypes();
3345: if ($receivedUnsealed !== null) {
3346: [$receivedUnsealedKey, $receivedUnsealedValue] = $receivedUnsealed;
3347: if ($unsealedKeyType->isSuperTypeOf($receivedUnsealedKey)->no()) {
3348: $typeMap = $typeMap->union($unsealedValueType->inferTemplateTypes(new NeverType()));
3349: } else {
3350: $typeMap = $typeMap->union($unsealedKeyType->inferTemplateTypes($receivedUnsealedKey));
3351: $typeMap = $typeMap->union($unsealedValueType->inferTemplateTypes($receivedUnsealedValue));
3352: }
3353: }
3354: }
3355:
3356: return $typeMap;
3357: }
3358:
3359: if ($receivedType->isArray()->yes()) {
3360: $keyTypeMap = $this->getIterableKeyType()->inferTemplateTypes($receivedType->getIterableKeyType());
3361: $itemTypeMap = $this->getIterableValueType()->inferTemplateTypes($receivedType->getIterableValueType());
3362:
3363: return $keyTypeMap->union($itemTypeMap);
3364: }
3365:
3366: return TemplateTypeMap::createEmpty();
3367: }
3368:
3369: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
3370: {
3371: $variance = $positionVariance->compose(TemplateTypeVariance::createCovariant());
3372: if ($this->referencedTemplateTypes !== null && $this->referencedTemplateTypes[0]->equals($variance)) {
3373: return $this->referencedTemplateTypes[1];
3374: }
3375:
3376: $references = [];
3377:
3378: foreach ($this->keyTypes as $type) {
3379: foreach ($type->getReferencedTemplateTypes($variance) as $reference) {
3380: $references[] = $reference;
3381: }
3382: }
3383:
3384: foreach ($this->valueTypes as $type) {
3385: foreach ($type->getReferencedTemplateTypes($variance) as $reference) {
3386: $references[] = $reference;
3387: }
3388: }
3389:
3390: if ($this->unsealed !== null) {
3391: [$unsealedKeyType, $unsealedValueType] = $this->unsealed;
3392: foreach ($unsealedKeyType->getReferencedTemplateTypes($variance) as $reference) {
3393: $references[] = $reference;
3394: }
3395: foreach ($unsealedValueType->getReferencedTemplateTypes($variance) as $reference) {
3396: $references[] = $reference;
3397: }
3398: }
3399:
3400: $this->referencedTemplateTypes = [$variance, $references];
3401:
3402: return $references;
3403: }
3404:
3405: public function tryRemove(Type $typeToRemove): ?Type
3406: {
3407: if ($typeToRemove->isConstantArray()->yes() && $typeToRemove->isIterableAtLeastOnce()->no()) {
3408: return TypeCombinator::intersect($this, new NonEmptyArrayType());
3409: }
3410:
3411: if ($typeToRemove instanceof NonEmptyArrayType) {
3412: return new ConstantArrayType([], []);
3413: }
3414:
3415: if ($typeToRemove instanceof HasOffsetValueType) {
3416: $offsetType = $typeToRemove->getOffsetType();
3417: $valueTypeToRemove = $typeToRemove->getValueType();
3418:
3419: foreach ($this->keyTypes as $i => $keyType) {
3420: if ($keyType->getValue() !== $offsetType->getValue()) {
3421: continue;
3422: }
3423:
3424: $currentValueType = $this->valueTypes[$i];
3425: $valueIsSuperType = $valueTypeToRemove->isSuperTypeOf($currentValueType);
3426:
3427: if ($valueIsSuperType->no()) {
3428: return null;
3429: }
3430:
3431: if ($valueIsSuperType->yes()) {
3432: return $this->removeOffset($offsetType);
3433: }
3434:
3435: $newValueType = TypeCombinator::remove($currentValueType, $valueTypeToRemove);
3436: $valueTypes = $this->valueTypes;
3437: $valueTypes[$i] = $newValueType;
3438:
3439: return $this->recreate(
3440: $this->keyTypes,
3441: $valueTypes,
3442: $this->nextAutoIndexes,
3443: $this->optionalKeys,
3444: $this->isList,
3445: $this->unsealed,
3446: );
3447: }
3448:
3449: return null;
3450: }
3451:
3452: if ($typeToRemove instanceof HasOffsetType) {
3453: return $this->removeOffset($typeToRemove->getOffsetType());
3454: }
3455:
3456: return null;
3457: }
3458:
3459: /**
3460: * The values of this shape lacking the offset. Unlike unsetOffset(), an
3461: * explicit key the unsealed extras can also hold becomes an optional never
3462: * key - dropping it would let the extras supply it again, widening the
3463: * shape instead of subtracting from it.
3464: */
3465: private function removeOffset(Type $offsetType): Type
3466: {
3467: $unsetResult = $this->unsetOffset($offsetType, true);
3468: // When the source was definitely a list but the post-unset shape
3469: // definitely isn't (e.g. unsetting a non-optional leading key
3470: // creates a hole), no value of $this could have lacked the
3471: // removed key — the subtraction yields the empty set.
3472: if ($this->isList->yes() && $unsetResult->isList()->no()) {
3473: return new NeverType();
3474: }
3475:
3476: if ($this->unsealed === null || !$this->isUnsealed()->yes()) {
3477: return $unsetResult;
3478: }
3479:
3480: $offsetType = $offsetType->toArrayKey();
3481: $offsetValues = $offsetType->getConstantScalarValues();
3482: if (count($offsetValues) !== 1 || $this->unsealed[0]->isSuperTypeOf($offsetType)->no()) {
3483: return $unsetResult;
3484: }
3485:
3486: $offsetValue = $offsetValues[0];
3487: if (!is_int($offsetValue) && !is_string($offsetValue)) {
3488: return $unsetResult;
3489: }
3490:
3491: $i = $this->getKeyIndexMap()[$offsetValue] ?? null;
3492: if ($i === null) {
3493: return $unsetResult;
3494: }
3495:
3496: $valueTypes = $this->valueTypes;
3497: $valueTypes[$i] = new NonAcceptingNeverType();
3498: $optionalKeys = $this->optionalKeys;
3499: if (!in_array($i, $optionalKeys, true)) {
3500: $optionalKeys[] = $i;
3501: }
3502:
3503: return $this->recreate($this->keyTypes, $valueTypes, $this->nextAutoIndexes, $optionalKeys, $unsetResult->isList(), $this->unsealed);
3504: }
3505:
3506: public function traverse(callable $cb): Type
3507: {
3508: $valueTypes = [];
3509:
3510: $stillOriginal = true;
3511: foreach ($this->valueTypes as $valueType) {
3512: $transformedValueType = $cb($valueType);
3513: if ($transformedValueType !== $valueType) {
3514: $stillOriginal = false;
3515: }
3516:
3517: $valueTypes[] = $transformedValueType;
3518: }
3519:
3520: $unsealed = $this->unsealedDeclaration ?? $this->unsealed;
3521: if ($unsealed !== null) {
3522: [$unsealedKeyType, $unsealedValueType] = $unsealed;
3523: $transformedUnsealedKeyType = $cb($unsealedKeyType);
3524: $transformedUnsealedValueType = $cb($unsealedValueType);
3525: if ($transformedUnsealedKeyType !== $unsealedKeyType || $transformedUnsealedValueType !== $unsealedValueType) {
3526: $stillOriginal = false;
3527: $unsealed = [$transformedUnsealedKeyType, $transformedUnsealedValueType];
3528: }
3529: }
3530:
3531: if ($stillOriginal) {
3532: return $this;
3533: }
3534:
3535: return $this->recreate($this->keyTypes, $valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $this->isList, $unsealed);
3536: }
3537:
3538: public function traverseSimultaneously(Type $right, callable $cb): Type
3539: {
3540: if (!$right->isArray()->yes()) {
3541: return $this;
3542: }
3543:
3544: $valueTypes = [];
3545:
3546: $stillOriginal = true;
3547: foreach ($this->valueTypes as $i => $valueType) {
3548: $keyType = $this->keyTypes[$i];
3549: $transformedValueType = $cb($valueType, $right->getOffsetValueType($keyType));
3550: if ($transformedValueType !== $valueType) {
3551: $stillOriginal = false;
3552: }
3553:
3554: $valueTypes[] = $transformedValueType;
3555: }
3556:
3557: $unsealed = $this->unsealed;
3558: if ($unsealed !== null) {
3559: [$unsealedKeyType, $unsealedValueType] = $unsealed;
3560: $transformedUnsealedKeyType = $cb($unsealedKeyType, $right->getIterableKeyType());
3561: $transformedUnsealedValueType = $cb($unsealedValueType, $right->getIterableValueType());
3562: if ($transformedUnsealedKeyType !== $unsealedKeyType || $transformedUnsealedValueType !== $unsealedValueType) {
3563: $stillOriginal = false;
3564: $unsealed = [$transformedUnsealedKeyType, $transformedUnsealedValueType];
3565: }
3566: }
3567:
3568: if ($stillOriginal) {
3569: return $this;
3570: }
3571:
3572: return $this->recreate($this->keyTypes, $valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $this->isList, $unsealed);
3573: }
3574:
3575: public function isKeysSupersetOf(self $otherArray): bool
3576: {
3577: if ($this->unsealed === null || $otherArray->unsealed === null) {
3578: return $this->legacyIsKeysSupersetOf($otherArray);
3579: }
3580:
3581: [$thisUnsealedKey, $thisUnsealedValue] = $this->unsealed;
3582: [$otherUnsealedKey, $otherUnsealedValue] = $otherArray->unsealed;
3583: $thisHasExtras = $this->isUnsealed()->yes();
3584: $otherHasExtras = $otherArray->isUnsealed()->yes();
3585:
3586: $otherHasRequiredKeys = false;
3587: foreach (array_keys($otherArray->keyTypes) as $j) {
3588: if ($otherArray->isOptionalKey($j)) {
3589: continue;
3590: }
3591: $otherHasRequiredKeys = true;
3592: break;
3593: }
3594:
3595: // Sealed empty $other (no keys, no extras): absorbing it is lossless iff $this
3596: // already accepts []. i.e., all of $this's known keys are optional. Otherwise
3597: // merge would add [] as a new instance.
3598: if (!$otherHasRequiredKeys && !$otherHasExtras && count($otherArray->keyTypes) === 0) {
3599: foreach (array_keys($this->keyTypes) as $i) {
3600: if (!$this->isOptionalKey($i)) {
3601: return false;
3602: }
3603: }
3604: return true;
3605: }
3606:
3607: // With real unsealed extras on both sides that can absorb each other's
3608: // required keys, merging is acceptable regardless of which keys overlap.
3609: if ($thisHasExtras && $otherHasExtras) {
3610: return true;
3611: }
3612:
3613: // Asymmetric extras: one side has real extras that can absorb the other's keys.
3614: if ($thisHasExtras) {
3615: if ($this->legacyIsKeysSupersetOf($otherArray)) {
3616: return true;
3617: }
3618: foreach ($otherArray->keyTypes as $j => $keyType) {
3619: if ($otherArray->isOptionalKey($j)) {
3620: continue;
3621: }
3622: if ($thisUnsealedKey->isSuperTypeOf($keyType)->no()) {
3623: return false;
3624: }
3625: if ($thisUnsealedValue->isSuperTypeOf($otherArray->valueTypes[$j])->no()) {
3626: return false;
3627: }
3628: }
3629: return true;
3630: }
3631:
3632: if ($otherHasExtras) {
3633: if ($this->legacyIsKeysSupersetOf($otherArray)) {
3634: return true;
3635: }
3636: foreach ($this->keyTypes as $i => $keyType) {
3637: if ($this->isOptionalKey($i)) {
3638: continue;
3639: }
3640: if ($otherUnsealedKey->isSuperTypeOf($keyType)->no()) {
3641: return false;
3642: }
3643: if ($otherUnsealedValue->isSuperTypeOf($this->valueTypes[$i])->no()) {
3644: return false;
3645: }
3646: }
3647: return true;
3648: }
3649:
3650: // Both sealed: fall back to the legacy key/value shape check.
3651: return $this->legacyIsKeysSupersetOf($otherArray);
3652: }
3653:
3654: private function legacyIsKeysSupersetOf(self $otherArray): bool
3655: {
3656: $keyTypesCount = count($this->keyTypes);
3657: $otherKeyTypesCount = count($otherArray->keyTypes);
3658:
3659: if ($keyTypesCount < $otherKeyTypesCount) {
3660: return false;
3661: }
3662:
3663: if ($otherKeyTypesCount === 0) {
3664: return $keyTypesCount === 0;
3665: }
3666:
3667: // The keys decide most pairs, so they are checked before the values,
3668: // whose isSuperTypeOf() costs far more.
3669: $keyIndexMap = $this->getKeyIndexMap();
3670: foreach ($otherArray->keyTypes as $keyType) {
3671: if (!isset($keyIndexMap[$keyType->getValue()])) {
3672: return false;
3673: }
3674: }
3675:
3676: $otherKeyIndexMap = $otherArray->getKeyIndexMap();
3677: $requiredKeyCount = 0;
3678: foreach ($this->keyTypes as $i => $keyType) {
3679: if (isset($otherKeyIndexMap[$keyType->getValue()])) {
3680: continue;
3681: }
3682: if ($this->isOptionalKey($i)) {
3683: continue;
3684: }
3685:
3686: $requiredKeyCount++;
3687: if ($requiredKeyCount > 1) {
3688: return false;
3689: }
3690: }
3691:
3692: $failOnDifferentValueType = $keyTypesCount !== $otherKeyTypesCount || $keyTypesCount < 2;
3693: foreach ($otherArray->keyTypes as $j => $keyType) {
3694: $valueType = $this->valueTypes[$keyIndexMap[$keyType->getValue()]];
3695: $otherValueType = $otherArray->valueTypes[$j];
3696: if (!$otherValueType->isSuperTypeOf($valueType)->no()) {
3697: continue;
3698: }
3699:
3700: if ($failOnDifferentValueType) {
3701: return false;
3702: }
3703: $failOnDifferentValueType = true;
3704: }
3705:
3706: return true;
3707: }
3708:
3709: public function mergeWith(self $otherArray): self
3710: {
3711: // only call this after verifying isKeysSupersetOf, or if losing tagged unions is not an issue
3712: if ($this->unsealed === null || $otherArray->unsealed === null) {
3713: return $this->legacyMergeWith($otherArray);
3714: }
3715:
3716: // the extras keep the template their key declares when they have all the others
3717: $mergedUnsealed = ArrayKeyTemplateHelper::unionEntryTypes($this->unsealedDeclaration ?? $this->unsealed, $otherArray->unsealedDeclaration ?? $otherArray->unsealed);
3718:
3719: $absorbIntoExtras = static function (Type $keyType, Type $valueType) use (&$mergedUnsealed): void {
3720: $mergedUnsealed = ArrayKeyTemplateHelper::unionEntryTypes($mergedUnsealed, [$keyType, $valueType]);
3721: };
3722:
3723: $canAbsorb = static function (self $side, Type $keyType, Type $valueType): bool {
3724: if (!$side->isUnsealed()->yes()) {
3725: return false;
3726: }
3727: if ($side->unsealed === null) {
3728: return false;
3729: }
3730: [$sideUnsealedKey, $sideUnsealedValue] = $side->unsealed;
3731: if ($sideUnsealedKey->isSuperTypeOf($keyType)->no()) {
3732: return false;
3733: }
3734: if ($sideUnsealedValue->isSuperTypeOf($valueType)->no()) {
3735: return false;
3736: }
3737: return true;
3738: };
3739:
3740: $keyTypes = [];
3741: $valueTypes = [];
3742: $optionalKeys = [];
3743:
3744: $otherKeyIndexMap = $otherArray->getKeyIndexMap();
3745: $processed = [];
3746: // Keys written through a union offset share their value type: union
3747: // each pair of value types once, which also keeps the merged keys
3748: // sharing the result.
3749: $mergedValues = [];
3750:
3751: foreach ($this->keyTypes as $i => $keyType) {
3752: $keyValue = $keyType->getValue();
3753: $processed[$keyValue] = true;
3754: $valueType = $this->valueTypes[$i];
3755:
3756: if (array_key_exists($keyValue, $otherKeyIndexMap)) {
3757: $j = $otherKeyIndexMap[$keyValue];
3758: $otherValueType = $otherArray->valueTypes[$j];
3759: $mergedValue = $mergedValues[spl_object_id($valueType) . ':' . spl_object_id($otherValueType)] ??= TypeCombinator::union($valueType, $otherValueType);
3760: $optional = $this->isOptionalKey($i) || $otherArray->isOptionalKey($j);
3761:
3762: $keyTypes[] = $keyType;
3763: $valueTypes[] = $mergedValue;
3764: if ($optional) {
3765: $optionalKeys[] = count($keyTypes) - 1;
3766: }
3767: continue;
3768: }
3769:
3770: if ($canAbsorb($otherArray, $keyType, $valueType)) {
3771: $absorbIntoExtras($keyType, $valueType);
3772: continue;
3773: }
3774:
3775: $keyTypes[] = $keyType;
3776: $valueTypes[] = $valueType;
3777: $optionalKeys[] = count($keyTypes) - 1;
3778: }
3779:
3780: foreach ($otherArray->keyTypes as $j => $keyType) {
3781: $keyValue = $keyType->getValue();
3782: if (array_key_exists($keyValue, $processed)) {
3783: continue;
3784: }
3785: $valueType = $otherArray->valueTypes[$j];
3786:
3787: if ($canAbsorb($this, $keyType, $valueType)) {
3788: $absorbIntoExtras($keyType, $valueType);
3789: continue;
3790: }
3791:
3792: $keyTypes[] = $keyType;
3793: $valueTypes[] = $valueType;
3794: $optionalKeys[] = count($keyTypes) - 1;
3795: }
3796:
3797: $resultUnsealed = $mergedUnsealed;
3798:
3799: $nextAutoIndexes = array_values(array_unique(array_merge($this->nextAutoIndexes, $otherArray->nextAutoIndexes)));
3800: sort($nextAutoIndexes);
3801:
3802: $optionalKeys = array_values(array_unique($optionalKeys));
3803:
3804: /** @var list<ConstantIntegerType|ConstantStringType> $keyTypes */
3805: $keyTypes = $keyTypes;
3806:
3807: // Merging widens single-side keys to optional, so a sealed result may gain
3808: // list realizations (e.g. `[]`) the naive `and` misses. `or`-ing in the
3809: // shape's own list-ness lifts a `no`/`maybe`. The `or` also keeps a genuine
3810: // `yes`: widening forgets which keys can appear together, so the shape read
3811: // on its own counts realizations neither input admits and answers `maybe`
3812: // where two list inputs guarantee `yes`.
3813: $naiveIsList = $this->isList->and($otherArray->isList);
3814: $mergedIsSealed = $mergedUnsealed[0] instanceof NeverType && $mergedUnsealed[0]->isExplicit();
3815: $isList = $mergedIsSealed
3816: ? $naiveIsList->or(self::inferIsListFromShape($keyTypes, $optionalKeys))
3817: : $naiveIsList;
3818: $sharesKeyOrder = $this->sharesKeyOrderWith($otherArray);
3819: if (!$sharesKeyOrder) {
3820: // the keys do not come in one known order: a list in one order may not be one in the other
3821: $isList = TrinaryLogic::extremeIdentity($this->isList, $otherArray->isList);
3822: }
3823:
3824: $merged = $this->recreate(
3825: $keyTypes,
3826: $valueTypes,
3827: $nextAutoIndexes,
3828: $optionalKeys,
3829: $isList,
3830: $resultUnsealed,
3831: );
3832:
3833: // the merged shape knows its key order only when both shapes it merges know the same one
3834: return !$sharesKeyOrder && $merged instanceof TemplateType ? $merged : $merged->inMergedKeyOrderOf($this, $otherArray);
3835: }
3836:
3837: /**
3838: * This shape, holding the keys of two shapes merged into one, with its keys in an order both of them keep:
3839: * a key only one of them lists stays between the keys it is listed between there. Without a known key order
3840: * when the shapes do not list the keys they share in one known order.
3841: */
3842: public function inMergedKeyOrderOf(self $a, self $b): self
3843: {
3844: $mergedKeyTypes = $a->getKeyTypesInMergedOrderWith($b);
3845: if ($mergedKeyTypes === null) {
3846: return $this->forgetKeyOrder();
3847: }
3848:
3849: $positions = [];
3850: foreach ($mergedKeyTypes as $position => $keyType) {
3851: $positions[$keyType->getValue()] = $position;
3852: }
3853:
3854: $indices = [];
3855: foreach ($this->keyTypes as $k => $keyType) {
3856: $indices[$positions[$keyType->getValue()]] = $k;
3857: }
3858: ksort($indices);
3859:
3860: return $this->reorderKeys(array_values($indices));
3861: }
3862:
3863: /**
3864: * The keys of both shapes in an order both of them keep: a key only one of them lists stays between the keys
3865: * it is listed between there. Null when the shapes do not list the keys they share in one known order.
3866: *
3867: * @return list<ConstantIntegerType|ConstantStringType>|null
3868: */
3869: public function getKeyTypesInMergedOrderWith(self $other): ?array
3870: {
3871: if (!$this->sharesKeyOrderWith($other)) {
3872: return null;
3873: }
3874:
3875: $keyIndexMap = $this->getKeyIndexMap();
3876: $otherKeyIndexMap = $other->getKeyIndexMap();
3877: $keyTypes = [];
3878: $i = 0;
3879: $j = 0;
3880: $count = count($this->keyTypes);
3881: $otherCount = count($other->keyTypes);
3882: while ($i < $count || $j < $otherCount) {
3883: if ($i < $count && !array_key_exists($this->keyTypes[$i]->getValue(), $otherKeyIndexMap)) {
3884: $keyTypes[] = $this->keyTypes[$i];
3885: $i++;
3886: continue;
3887: }
3888: if ($j < $otherCount && !array_key_exists($other->keyTypes[$j]->getValue(), $keyIndexMap)) {
3889: $keyTypes[] = $other->keyTypes[$j];
3890: $j++;
3891: continue;
3892: }
3893: // the next key of both is the same shared key
3894: $keyTypes[] = $this->keyTypes[$i];
3895: $i++;
3896: $j++;
3897: }
3898:
3899: return $keyTypes;
3900: }
3901:
3902: private function legacyMergeWith(self $otherArray): self
3903: {
3904: $valueTypes = $this->valueTypes;
3905: $optionalKeys = $this->optionalKeys;
3906: // union each pair of value types once, see mergeWith()
3907: $mergedValues = [];
3908: foreach ($this->keyTypes as $i => $keyType) {
3909: $otherIndex = $otherArray->getKeyIndex($keyType);
3910: if ($otherIndex === null) {
3911: $optionalKeys[] = $i;
3912: continue;
3913: }
3914: if ($otherArray->isOptionalKey($otherIndex)) {
3915: $optionalKeys[] = $i;
3916: }
3917: $otherValueType = $otherArray->valueTypes[$otherIndex];
3918: $valueTypes[$i] = $mergedValues[spl_object_id($valueTypes[$i]) . ':' . spl_object_id($otherValueType)] ??= TypeCombinator::union($valueTypes[$i], $otherValueType);
3919: }
3920:
3921: $optionalKeys = array_values(array_unique($optionalKeys));
3922:
3923: $nextAutoIndexes = array_values(array_unique(array_merge($this->nextAutoIndexes, $otherArray->nextAutoIndexes)));
3924: sort($nextAutoIndexes);
3925:
3926: // Same recompute as mergeWith(), over `$this`'s keys only — this legacy
3927: // path drops the other side's extra keys.
3928: $naiveIsList = $this->isList->and($otherArray->isList);
3929: $mergedIsSealed = $this->unsealed === null
3930: || ($this->unsealed[0] instanceof NeverType && $this->unsealed[0]->isExplicit());
3931: $isList = $mergedIsSealed
3932: ? $naiveIsList->or(self::inferIsListFromShape($this->keyTypes, $optionalKeys))
3933: : $naiveIsList;
3934: $sharesKeyOrder = $this->sharesKeyOrderWith($otherArray);
3935: if (!$sharesKeyOrder) {
3936: $isList = TrinaryLogic::extremeIdentity($this->isList, $otherArray->isList);
3937: }
3938:
3939: $merged = $this->recreate($this->keyTypes, $valueTypes, $nextAutoIndexes, $optionalKeys, $isList, $this->unsealed);
3940:
3941: // the merged shape knows its key order only when both shapes it merges know the same one
3942: return !$sharesKeyOrder && $merged instanceof TemplateType ? $merged : $merged->inMergedKeyOrderOf($this, $otherArray);
3943: }
3944:
3945: /**
3946: * @return array<int|string, int>
3947: */
3948: private function getKeyIndexMap(): array
3949: {
3950: if ($this->keyIndexMap !== null) {
3951: return $this->keyIndexMap;
3952: }
3953:
3954: $map = [];
3955: foreach ($this->keyTypes as $i => $keyType) {
3956: $map[$keyType->getValue()] = $i;
3957: }
3958:
3959: return $this->keyIndexMap = $map;
3960: }
3961:
3962: /**
3963: * Index of the explicit key a constant scalar offset (already passed through
3964: * toArrayKey()) resolves to, or null when the offset is not a constant scalar
3965: * or no explicit key is a supertype of it.
3966: */
3967: private function findVerifiedKeyIndex(Type $offsetType): ?int
3968: {
3969: if (!$offsetType->isConstantScalarValue()->yes()) {
3970: return null;
3971: }
3972:
3973: $value = $offsetType->getConstantScalarValues()[0] ?? null;
3974: if (!is_int($value) && !is_string($value)) {
3975: return null;
3976: }
3977:
3978: $index = $this->getKeyIndexMap()[$value] ?? null;
3979: if ($index === null || !$this->keyTypes[$index]->isSuperTypeOf($offsetType)->yes()) {
3980: return null;
3981: }
3982:
3983: return $index;
3984: }
3985:
3986: /**
3987: * Whether a constant integer or string offset (already passed through
3988: * toArrayKey()) has a value no explicit key's value collides with as an
3989: * array key - then no explicit key is a supertype of it, so scanning the
3990: * keys for one is pointless. A CompoundType offset (a template, an
3991: * intersection) is left to the scan: its isSubTypeOf() may answer maybe.
3992: */
3993: private function isKeyIndexMiss(Type $offsetType): bool
3994: {
3995: if ($offsetType instanceof CompoundType) {
3996: return false;
3997: }
3998:
3999: $values = $offsetType->getConstantScalarValues();
4000: if (count($values) !== 1 || (!is_int($values[0]) && !is_string($values[0]))) {
4001: return false;
4002: }
4003:
4004: return !array_key_exists($values[0], $this->getKeyIndexMap());
4005: }
4006:
4007: private function hasRequiredKeyMissingIn(self $other): bool
4008: {
4009: foreach ($this->keyTypes as $i => $keyType) {
4010: if (!$this->isOptionalKey($i) && $other->isKeyIndexMiss($keyType)) {
4011: return true;
4012: }
4013: }
4014:
4015: return false;
4016: }
4017:
4018: /**
4019: * @param ConstantIntegerType|ConstantStringType $otherKeyType
4020: */
4021: private function getKeyIndex($otherKeyType): ?int
4022: {
4023: return $this->getKeyIndexMap()[$otherKeyType->getValue()] ?? null;
4024: }
4025:
4026: public function makeOffsetRequired(Type $offsetType): self
4027: {
4028: $offsetType = $offsetType->toArrayKey();
4029: $optionalKeys = $this->optionalKeys;
4030: $isList = $this->isList->yes();
4031: foreach ($this->keyTypes as $i => $keyType) {
4032: if (!$keyType->equals($offsetType)) {
4033: continue;
4034: }
4035:
4036: $keyValue = $keyType->getValue();
4037: foreach ($optionalKeys as $j => $key) {
4038: if (
4039: $i !== $key
4040: && (
4041: !$isList
4042: || !is_int($keyValue)
4043: || !is_int($this->keyTypes[$key]->getValue())
4044: || $this->keyTypes[$key]->getValue() >= $keyValue
4045: )
4046: ) {
4047: continue;
4048: }
4049:
4050: unset($optionalKeys[$j]);
4051: }
4052:
4053: if (count($this->optionalKeys) !== count($optionalKeys)) {
4054: return $this->recreate($this->keyTypes, $this->valueTypes, $this->nextAutoIndexes, array_values($optionalKeys), $this->isList, $this->unsealed);
4055: }
4056:
4057: return $this;
4058: }
4059:
4060: // Offset isn't in the explicit set. If the unsealed extras' key range
4061: // covers it (e.g. `array{a: int, ...<string, float>}` narrowing on
4062: // `array_key_exists('b', $arr)`), promote it into the explicit set as
4063: // a required slot with the unsealed value type. The unsealed extras
4064: // stay around — additional entries at other matching keys are still
4065: // possible.
4066: if (
4067: $this->isUnsealed()->yes()
4068: && $this->unsealed !== null
4069: && ($offsetType instanceof ConstantIntegerType || $offsetType instanceof ConstantStringType)
4070: ) {
4071: [$unsealedKeyType, $unsealedValueType] = $this->unsealed;
4072: if (!$unsealedKeyType->isSuperTypeOf($offsetType)->no()) {
4073: $keyTypes = $this->keyTypes;
4074: $valueTypes = $this->valueTypes;
4075: $keyTypes[] = $offsetType;
4076: $keyTemplate = $this->getUnsealedKeyTemplate();
4077: $valueTypes[] = $keyTemplate !== null
4078: ? ArrayKeyTemplateHelper::getValueType($keyTemplate[1], $keyTemplate[2], $keyTemplate[0], $offsetType)
4079: : $unsealedValueType;
4080:
4081: return $this->recreate(
4082: $keyTypes,
4083: $valueTypes,
4084: $this->nextAutoIndexes,
4085: $this->optionalKeys,
4086: TrinaryLogic::createNo(),
4087: $this->unsealed,
4088: );
4089: }
4090: }
4091:
4092: return $this;
4093: }
4094:
4095: public function makeList(): Type
4096: {
4097: if ($this->isList->yes()) {
4098: return $this;
4099: }
4100:
4101: if ($this->isList->no()) {
4102: return new NeverType();
4103: }
4104:
4105: if (!$this->isKeyOrderKnown()) {
4106: // a list has its keys in ascending order
4107: $sorted = $this->sortKeys();
4108: return (new self($sorted->keyTypes, $sorted->valueTypes, $sorted->nextAutoIndexes, $sorted->optionalKeys, $sorted->isList, $sorted->unsealedDeclaration ?? $sorted->unsealed, true))->makeList();
4109: }
4110:
4111: // isList is Maybe. In a sealed shape a key past a gap in the 0..n sequence
4112: // (or any non-integer key) can never appear in a list, so keep only the
4113: // contiguous 0..m prefix. Unsealed extras may fill the gaps, so keep every
4114: // key there.
4115: if ($this->isUnsealed()->no()) {
4116: $positionByIndex = [];
4117: foreach ($this->keyTypes as $position => $keyType) {
4118: if (!$keyType instanceof ConstantIntegerType) {
4119: continue;
4120: }
4121: $positionByIndex[$keyType->getValue()] = $position;
4122: }
4123:
4124: $keptPositions = [];
4125: for ($index = 0; array_key_exists($index, $positionByIndex); $index++) {
4126: $keptPositions[] = $positionByIndex[$index];
4127: }
4128:
4129: if (count($keptPositions) < count($this->keyTypes)) {
4130: $builder = ConstantArrayTypeBuilder::createEmpty();
4131: if ($this->keyOrderKnown) {
4132: $builder->makeKeyOrderKnown();
4133: }
4134: foreach ($keptPositions as $position) {
4135: $builder->setOffsetValueType(
4136: $this->keyTypes[$position],
4137: $this->valueTypes[$position],
4138: $this->isOptionalKey($position),
4139: );
4140: }
4141:
4142: return $builder->getArray();
4143: }
4144: }
4145:
4146: return $this->recreate($this->keyTypes, $this->valueTypes, $this->nextAutoIndexes, $this->optionalKeys, TrinaryLogic::createYes(), $this->unsealed);
4147: }
4148:
4149: public function makeListMaybe(): Type
4150: {
4151: if (!$this->isList->yes()) {
4152: return $this;
4153: }
4154:
4155: return $this->recreate(
4156: $this->keyTypes,
4157: $this->valueTypes,
4158: $this->nextAutoIndexes,
4159: $this->optionalKeys,
4160: TrinaryLogic::createMaybe(),
4161: $this->unsealed,
4162: );
4163: }
4164:
4165: public function mapValueType(callable $cb): Type
4166: {
4167: $newValueTypes = [];
4168: foreach ($this->valueTypes as $valueType) {
4169: $newValueTypes[] = $cb($valueType);
4170: }
4171:
4172: $newUnsealed = $this->unsealed === null
4173: ? null
4174: : [$this->unsealed[0], $cb($this->unsealed[1])];
4175:
4176: return $this->recreate(
4177: $this->keyTypes,
4178: $newValueTypes,
4179: $this->nextAutoIndexes,
4180: $this->optionalKeys,
4181: $this->isList,
4182: $newUnsealed,
4183: );
4184: }
4185:
4186: public function mapKeyType(callable $cb): Type
4187: {
4188: // Constant array shapes already encode precise per-slot keys; a
4189: // blanket key-type rewrite (the prior `TypeTraverser`-based pattern
4190: // in `NodeScopeResolver`) would coerce constants into a broader
4191: // type and lose precision. Pass through unchanged.
4192: return $this;
4193: }
4194:
4195: public function makeAllArrayKeysOptional(): Type
4196: {
4197: $keyCount = count($this->keyTypes);
4198: if ($keyCount === 0) {
4199: return $this;
4200: }
4201:
4202: return $this->recreate(
4203: $this->keyTypes,
4204: $this->valueTypes,
4205: $this->nextAutoIndexes,
4206: range(0, $keyCount - 1),
4207: $this->isList,
4208: $this->unsealed,
4209: );
4210: }
4211:
4212: public function changeKeyCaseArray(?int $case): Type
4213: {
4214: $builder = ConstantArrayTypeBuilder::createEmpty();
4215: if ($this->keyOrderKnown) {
4216: $builder->makeKeyOrderKnown();
4217: }
4218: foreach ($this->keyTypes as $i => $keyType) {
4219: if ($keyType instanceof ConstantStringType) {
4220: $newKeyType = self::foldConstantStringKeyCase($keyType, $case);
4221: } else {
4222: $newKeyType = $keyType;
4223: }
4224: $builder->setOffsetValueType($newKeyType, $this->valueTypes[$i], $this->isOptionalKey($i));
4225: }
4226:
4227: if ($this->unsealed !== null) {
4228: $builder->makeUnsealed(self::foldUnsealedKeyCase($this->unsealed[0], $case), $this->unsealed[1]);
4229: }
4230:
4231: $result = $builder->getArray();
4232: if ($this->isList()->yes()) {
4233: $result = TypeCombinator::intersect($result, new AccessoryArrayListType());
4234: }
4235: return $result;
4236: }
4237:
4238: public function filterArrayRemovingFalsey(): Type
4239: {
4240: $falseyTypes = StaticTypeFactory::falsey();
4241: $builder = ConstantArrayTypeBuilder::createEmpty();
4242: if ($this->keyOrderKnown) {
4243: $builder->makeKeyOrderKnown();
4244: }
4245: foreach ($this->keyTypes as $i => $keyType) {
4246: $value = $this->valueTypes[$i];
4247: $isFalsey = $falseyTypes->isSuperTypeOf($value);
4248: if ($isFalsey->yes()) {
4249: continue;
4250: }
4251: if ($isFalsey->maybe()) {
4252: $builder->setOffsetValueType($keyType, TypeCombinator::remove($value, $falseyTypes), true);
4253: continue;
4254: }
4255: $builder->setOffsetValueType($keyType, $value, $this->isOptionalKey($i));
4256: }
4257:
4258: // removing the falsey values leaves the value at each extra key what it is for that key
4259: $unsealed = $this->unsealedDeclaration ?? $this->unsealed;
4260: if ($unsealed !== null) {
4261: $unsealedValue = TypeCombinator::remove($unsealed[1], $falseyTypes);
4262: if (!$unsealedValue instanceof NeverType) {
4263: $builder->makeUnsealed($unsealed[0], $unsealedValue);
4264: }
4265: }
4266:
4267: return $builder->getArray();
4268: }
4269:
4270: private static function foldConstantStringKeyCase(ConstantStringType $type, ?int $case): Type
4271: {
4272: if ($case === CASE_LOWER) {
4273: return new ConstantStringType(strtolower($type->getValue()));
4274: }
4275: if ($case === CASE_UPPER) {
4276: return new ConstantStringType(strtoupper($type->getValue()));
4277: }
4278:
4279: return TypeCombinator::union(
4280: new ConstantStringType(strtolower($type->getValue())),
4281: new ConstantStringType(strtoupper($type->getValue())),
4282: );
4283: }
4284:
4285: private static function foldUnsealedKeyCase(Type $key, ?int $case): Type
4286: {
4287: if ($key instanceof ConstantStringType) {
4288: return self::foldConstantStringKeyCase($key, $case);
4289: }
4290:
4291: if ($key instanceof UnionType) {
4292: $folded = [];
4293: foreach ($key->getTypes() as $innerKey) {
4294: $folded[] = self::foldUnsealedKeyCase($innerKey, $case);
4295: }
4296:
4297: return TypeCombinator::union(...$folded);
4298: }
4299:
4300: // `array_change_key_case` only folds string keys — int keys
4301: // (e.g. `...<int, ...>`) pass through unchanged.
4302: if (!$key->isString()->yes()) {
4303: return $key;
4304: }
4305:
4306: // Rebuild from a clean `string` plus the non-case accessories that
4307: // case-folding preserves (length is unchanged, so numeric / non-
4308: // falsy / non-empty all survive). Any prior lowercase/uppercase
4309: // accessory is dropped — matches the `ArrayType::changeKeyCaseArray`
4310: // behavior where `strtoupper(lowercase-string)` reads as
4311: // `uppercase-string`, not the contradictory intersection.
4312: $preserved = [new StringType()];
4313: if ($key->isNumericString()->yes()) {
4314: $preserved[] = new AccessoryNumericStringType();
4315: } elseif ($key->isNonFalsyString()->yes()) {
4316: $preserved[] = new AccessoryNonFalsyStringType();
4317: } elseif ($key->isNonEmptyString()->yes()) {
4318: $preserved[] = new AccessoryNonEmptyStringType();
4319: }
4320:
4321: if ($case === CASE_LOWER) {
4322: return new IntersectionType([...$preserved, new AccessoryLowercaseStringType()]);
4323: }
4324: if ($case === CASE_UPPER) {
4325: return new IntersectionType([...$preserved, new AccessoryUppercaseStringType()]);
4326: }
4327:
4328: // `null` (PHP <8.4 / unspecified) yields lower- or upper-case
4329: // keys; record both as a union.
4330: return TypeCombinator::union(
4331: new IntersectionType([...$preserved, new AccessoryLowercaseStringType()]),
4332: new IntersectionType([...$preserved, new AccessoryUppercaseStringType()]),
4333: );
4334: }
4335:
4336: public function toPhpDocNode(): TypeNode
4337: {
4338: $items = [];
4339: $values = [];
4340: $exportValuesOnly = !$this->shouldNameItsKeys();
4341: foreach ($this->keyTypes as $i => $keyType) {
4342: if ($keyType->getValue() !== $i) {
4343: $exportValuesOnly = false;
4344: }
4345: $keyPhpDocNode = $keyType->toPhpDocNode();
4346: if (!$keyPhpDocNode instanceof ConstTypeNode) {
4347: continue;
4348: }
4349: $valueType = $this->valueTypes[$i];
4350:
4351: /** @var ConstExprStringNode|ConstExprIntegerNode $keyNode */
4352: $keyNode = $keyPhpDocNode->constExpr;
4353: if ($keyNode instanceof ConstExprStringNode) {
4354: $value = $keyNode->value;
4355: if (self::isValidIdentifier($value)) {
4356: $keyNode = new IdentifierTypeNode($value);
4357: }
4358: }
4359:
4360: $isOptional = $this->isOptionalKey($i);
4361: if ($isOptional) {
4362: $exportValuesOnly = false;
4363: }
4364: // one of the two lists is returned, so they share the value node: describing it
4365: // once per list would describe a value nested N shapes deep 2^N times
4366: $valuePhpDocNode = $valueType->toPhpDocNode();
4367: $items[] = new ArrayShapeItemNode(
4368: $keyNode,
4369: $isOptional,
4370: $valuePhpDocNode,
4371: );
4372: $values[] = new ArrayShapeItemNode(
4373: null,
4374: $isOptional,
4375: $valuePhpDocNode,
4376: );
4377: }
4378:
4379: $keyTemplate = $this->getUnsealedKeyTemplate();
4380: if ($keyTemplate !== null && $this->isUnsealed()->yes()) {
4381: return ArrayShapeNode::createUnsealed(
4382: $exportValuesOnly ? $values : $items,
4383: new ArrayShapeUnsealedTypeNode(
4384: $keyTemplate[2]->toPhpDocNode(),
4385: new TemplateDeclarationTypeNode($keyTemplate[0]->getName(), $keyTemplate[0]->getBound()->toPhpDocNode()),
4386: ),
4387: ArrayShapeNode::KIND_ARRAY,
4388: );
4389: }
4390:
4391: if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
4392: $unsealedKeyTypeDescription = $this->unsealed[0]->describe(VerbosityLevel::precise());
4393: $isMixedUnsealedKeyType = MixedType::isBareMixed($this->unsealed[0], VerbosityLevel::value()) && !$this->unsealed[0]->isExplicitMixed();
4394: $isMixedUnsealedItemType = MixedType::isBareMixed($this->unsealed[1], VerbosityLevel::value()) && !$this->unsealed[1]->isExplicitMixed();
4395: if ($isMixedUnsealedKeyType || ($this->isList()->yes() && $unsealedKeyTypeDescription === 'int<0, max>')) {
4396: if ($isMixedUnsealedItemType) {
4397: return ArrayShapeNode::createUnsealed(
4398: $exportValuesOnly ? $values : $items,
4399: null,
4400: $this->shouldBeDescribedAsAList() ? ArrayShapeNode::KIND_LIST : ArrayShapeNode::KIND_ARRAY,
4401: );
4402: }
4403:
4404: return ArrayShapeNode::createUnsealed(
4405: $exportValuesOnly ? $values : $items,
4406: new ArrayShapeUnsealedTypeNode($this->unsealed[1]->toPhpDocNode(), null),
4407: $this->shouldBeDescribedAsAList() ? ArrayShapeNode::KIND_LIST : ArrayShapeNode::KIND_ARRAY,
4408: );
4409: }
4410:
4411: return ArrayShapeNode::createUnsealed(
4412: $exportValuesOnly ? $values : $items,
4413: new ArrayShapeUnsealedTypeNode($this->unsealed[1]->toPhpDocNode(), $this->unsealed[0]->toPhpDocNode()),
4414: ArrayShapeNode::KIND_ARRAY,
4415: );
4416: }
4417:
4418: return ArrayShapeNode::createSealed(
4419: $exportValuesOnly ? $values : $items,
4420: $this->shouldBeDescribedAsAList() ? ArrayShapeNode::KIND_LIST : ArrayShapeNode::KIND_ARRAY,
4421: );
4422: }
4423:
4424: public function toNativePhpTypeNode(NativeTypePosition $position)
4425: {
4426: return $position->isArrayAllowed() ? new Identifier('array') : null;
4427: }
4428:
4429: public static function isValidIdentifier(string $value): bool
4430: {
4431: $result = Strings::match($value, '~^(?:[\\\\]?+[a-z_\\x80-\\xFF][0-9a-z_\\x80-\\xFF-]*+)++$~si');
4432:
4433: return $result !== null;
4434: }
4435:
4436: public function getFiniteTypes(): array
4437: {
4438: if ($this->isUnsealed()->yes()) {
4439: return [];
4440: }
4441:
4442: $limit = InitializerExprTypeResolver::CALCULATE_SCALARS_LIMIT;
4443:
4444: // Build finite array types incrementally, processing one key at a time.
4445: // For optional keys, fork each partial result into with/without variants.
4446: // This avoids generating 2^N ConstantArrayType objects via getAllArrays().
4447: // Count first: a shape with many optional keys overflows the limit after a
4448: // handful of keys, and building the partial arrays up to that point costs
4449: // hundreds of builder clones per call for a result that is thrown away.
4450: $finiteValueTypesPerKey = [];
4451: $count = 1;
4452: foreach ($this->valueTypes as $i => $valueType) {
4453: $finiteValueTypes = $valueType->getFiniteTypes();
4454: if ($finiteValueTypes === []) {
4455: return [];
4456: }
4457:
4458: $finiteValueTypesPerKey[$i] = $finiteValueTypes;
4459: $count *= count($finiteValueTypes) + ($this->isOptionalKey($i) ? 1 : 0);
4460: if ($count > $limit) {
4461: return [];
4462: }
4463: }
4464:
4465: $emptyPartial = ConstantArrayTypeBuilder::createEmpty();
4466: if ($this->keyOrderKnown) {
4467: $emptyPartial->makeKeyOrderKnown();
4468: }
4469:
4470: /** @var list<ConstantArrayTypeBuilder> $partials */
4471: $partials = [$emptyPartial];
4472:
4473: foreach ($this->keyTypes as $i => $keyType) {
4474: $finiteValueTypes = $finiteValueTypesPerKey[$i];
4475: $isOptional = $this->isOptionalKey($i);
4476: $newPartials = [];
4477:
4478: foreach ($partials as $partial) {
4479: if ($isOptional) {
4480: $newPartials[] = clone $partial;
4481: }
4482: foreach ($finiteValueTypes as $finiteValueType) {
4483: $newPartial = clone $partial;
4484: $newPartial->setOffsetValueType($keyType, $finiteValueType);
4485: $newPartials[] = $newPartial;
4486: }
4487: }
4488:
4489: $partials = $newPartials;
4490: }
4491:
4492: $finiteTypes = [];
4493: foreach ($partials as $partial) {
4494: $finiteTypes[] = $partial->getArray();
4495: }
4496:
4497: return $finiteTypes;
4498: }
4499:
4500: public function hasTemplateOrLateResolvableType(): bool
4501: {
4502: if ($this->hasTemplateOrLateResolvableType !== null) {
4503: return $this->hasTemplateOrLateResolvableType;
4504: }
4505:
4506: foreach ($this->valueTypes as $valueType) {
4507: if (!$valueType->hasTemplateOrLateResolvableType()) {
4508: continue;
4509: }
4510:
4511: return $this->hasTemplateOrLateResolvableType = true;
4512: }
4513:
4514: foreach ($this->keyTypes as $keyType) {
4515: if (!$keyType instanceof TemplateType) {
4516: continue;
4517: }
4518:
4519: return $this->hasTemplateOrLateResolvableType = true;
4520: }
4521:
4522: if ($this->unsealed !== null) {
4523: if ($this->unsealed[0]->hasTemplateOrLateResolvableType()) {
4524: return $this->hasTemplateOrLateResolvableType = true;
4525: }
4526: if ($this->unsealed[1]->hasTemplateOrLateResolvableType()) {
4527: return $this->hasTemplateOrLateResolvableType = true;
4528: }
4529: }
4530:
4531: return $this->hasTemplateOrLateResolvableType = false;
4532: }
4533:
4534: public function hasUnresolvedTemplateArgumentType(): bool
4535: {
4536: foreach ($this->valueTypes as $type) {
4537: if ($type->hasUnresolvedTemplateArgumentType()) {
4538: return true;
4539: }
4540: }
4541:
4542: if ($this->unsealed === null) {
4543: return false;
4544: }
4545:
4546: return $this->unsealed[0]->hasUnresolvedTemplateArgumentType() || $this->unsealed[1]->hasUnresolvedTemplateArgumentType();
4547: }
4548:
4549: public function tryUnion(Type $otherType): ?Type
4550: {
4551: return ArrayAlgebra::tryUnionConstantArray($this, $otherType);
4552: }
4553:
4554: public function tryIntersect(Type $otherType): ?Type
4555: {
4556: return ArrayAlgebra::tryIntersectConstantArray($this, $otherType);
4557: }
4558:
4559: }
4560: