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