1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type\Constant;
4:
5: use PHPStan\DependencyInjection\BleedingEdgeToggle;
6: use PHPStan\ShouldNotHappenException;
7: use PHPStan\TrinaryLogic;
8: use PHPStan\Turbo\ShadowedByTurboExtension;
9: use PHPStan\Type\Accessory\AccessoryArrayListType;
10: use PHPStan\Type\Accessory\NonEmptyArrayType;
11: use PHPStan\Type\Accessory\OversizedArrayType;
12: use PHPStan\Type\ArrayType;
13: use PHPStan\Type\CallableType;
14: use PHPStan\Type\ClosureType;
15: use PHPStan\Type\Generic\ArrayKeyTemplateHelper;
16: use PHPStan\Type\IntersectionType;
17: use PHPStan\Type\NeverType;
18: use PHPStan\Type\Type;
19: use PHPStan\Type\TypeCombinator;
20: use PHPStan\Type\TypeUtils;
21: use function array_filter;
22: use function array_keys;
23: use function array_map;
24: use function array_unique;
25: use function array_values;
26: use function count;
27: use function in_array;
28: use function is_float;
29: use function is_int;
30: use function max;
31: use function min;
32: use function usort;
33:
34: /**
35: * @api
36: */
37: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/ConstantArrayTypeBuilder.cpp')]
38: final class ConstantArrayTypeBuilder
39: {
40:
41: public const ARRAY_COUNT_LIMIT = 256;
42: private const CLOSURES_COUNT_LIMIT = 32;
43:
44: private bool $degradeToGeneralArray = false;
45:
46: private bool $disableArrayDegradation = false;
47:
48: private ?bool $degradeClosures = null;
49:
50: private bool $oversized = false;
51:
52: private TrinaryLogic $isNonEmpty;
53:
54: /** An empty builder does not know in which order its keys come until makeKeyOrderKnown() says so. */
55: private bool $keyOrderKnown = false;
56:
57: /**
58: * @param list<Type> $keyTypes
59: * @param array<int, Type> $valueTypes
60: * @param list<int> $nextAutoIndexes
61: * @param array<int> $optionalKeys
62: * @param array{Type, Type}|null $unsealed
63: */
64: private function __construct(
65: private array $keyTypes,
66: private array $valueTypes,
67: private array $nextAutoIndexes,
68: private array $optionalKeys,
69: private TrinaryLogic $isList,
70: private ?array $unsealed,
71: )
72: {
73: $this->isNonEmpty = TrinaryLogic::createNo();
74: }
75:
76: /** @var array{array{Type, Type}|null, array{Type, Type}}|null */
77: private ?array $unsealedDeclaration = null;
78:
79: /**
80: * @return array{Type, Type}|null
81: */
82: private function getUnsealedForArray(): ?array
83: {
84: if ($this->unsealedDeclaration !== null && $this->unsealedDeclaration[0] === $this->unsealed) {
85: return $this->unsealedDeclaration[1];
86: }
87:
88: return $this->unsealed;
89: }
90:
91: public static function createEmpty(): self
92: {
93: $unsealed = null;
94: if (BleedingEdgeToggle::isBleedingEdge()) {
95: $never = new NeverType(true);
96: $unsealed = [$never, $never];
97: }
98: return new self([], [], [0], [], TrinaryLogic::createYes(), $unsealed);
99: }
100:
101: public static function createFromConstantArray(ConstantArrayType $startArrayType): self
102: {
103: $builder = new self(
104: $startArrayType->getKeyTypes(),
105: $startArrayType->getValueTypes(),
106: $startArrayType->getNextAutoIndexes(),
107: $startArrayType->getOptionalKeys(),
108: $startArrayType->isList(),
109: $startArrayType->getUnsealedTypes(),
110: );
111: $builder->isNonEmpty = $startArrayType->isIterableAtLeastOnce();
112: $builder->keyOrderKnown = $startArrayType->isKeyOrderKnown();
113:
114: // an array built on keeps the unsealed key that declares a template for as long as its extras stay as they are
115: $unsealedEntryTypes = ($startArrayType->isUnsealed()->yes() ? $startArrayType->getUnsealedDeclaredTypes() : null);
116: if ($unsealedEntryTypes !== null && $unsealedEntryTypes !== $builder->unsealed) {
117: $builder->unsealedDeclaration = [$builder->unsealed, $unsealedEntryTypes];
118: }
119:
120: if (count($startArrayType->getKeyTypes()) > self::ARRAY_COUNT_LIMIT) {
121: $builder->degradeToGeneralArray(true);
122: }
123:
124: return $builder;
125: }
126:
127: /** The keys come in the order they are set, as in a literal array. */
128: public function makeKeyOrderKnown(): void
129: {
130: $this->keyOrderKnown = true;
131: }
132:
133: /** The array is built without the order of its keys, as a PHPDoc shape that lists them. */
134: public function forgetKeyOrder(): void
135: {
136: $this->keyOrderKnown = false;
137: }
138:
139: /**
140: * The keys come in any order, so the array can be a list when they could come in ascending
141: * order, but does not surely come as one.
142: */
143: public function forgetListKeyOrder(): void
144: {
145: // a builder that degrades has keys without a value to sort them by
146: if ($this->degradeToGeneralArray) {
147: $this->isList = $this->isList->and(TrinaryLogic::createMaybe());
148: return;
149: }
150:
151: /** @var list<ConstantIntegerType|ConstantStringType> $keyTypes */
152: $keyTypes = $this->keyTypes;
153: $indices = array_keys($keyTypes);
154: usort($indices, static fn (int $a, int $b): int => [!is_int($keyTypes[$a]->getValue()), $keyTypes[$a]->getValue()] <=> [!is_int($keyTypes[$b]->getValue()), $keyTypes[$b]->getValue()]);
155:
156: $sorted = self::createEmpty();
157: foreach ($indices as $i) {
158: $sorted->setOffsetValueType($keyTypes[$i], $this->valueTypes[$i], in_array($i, $this->optionalKeys, true));
159: }
160:
161: // a single key has no order to forget
162: $this->isList = count($this->keyTypes) < 2 ? $sorted->isList : $sorted->isList->and(TrinaryLogic::createMaybe());
163: }
164:
165: public function makeUnsealed(Type $keyType, Type $valueType): void
166: {
167: $this->setUnsealed([$keyType, $valueType]);
168: }
169:
170: /**
171: * Keeps the bound form of extras whose key declares a template, and the declared ones for the array it builds.
172: *
173: * @param array{Type, Type} $unsealed
174: */
175: private function setUnsealed(array $unsealed): void
176: {
177: $boundUnsealed = $unsealed[0]->hasTemplateOrLateResolvableType() ? ArrayKeyTemplateHelper::getBoundEntryTypes($unsealed) : $unsealed;
178: $this->unsealed = $boundUnsealed;
179: $this->unsealedDeclaration = $boundUnsealed !== $unsealed ? [$boundUnsealed, $unsealed] : null;
180: }
181:
182: /**
183: * Adds unsealed extras on top of the ones the builder already collected
184: * instead of replacing them.
185: *
186: * Offsets the builder could not give a slot of their own (a non-constant
187: * key like `string`) end up in the unsealed extras, so overwriting them
188: * would drop their value type.
189: */
190: public function mergeUnsealed(Type $keyType, Type $valueType): void
191: {
192: if ($this->unsealed === null || ($this->unsealed[0] instanceof NeverType && $this->unsealed[0]->isExplicit())) {
193: $this->setUnsealed([$keyType, $valueType]);
194: return;
195: }
196:
197: // without a template either side declares, the extras are the union of both
198: if ($this->unsealedDeclaration === null && !$keyType->hasTemplateOrLateResolvableType()) {
199: $this->unsealed = [
200: TypeCombinator::union($this->unsealed[0], $keyType),
201: TypeCombinator::union($this->unsealed[1], $valueType),
202: ];
203: return;
204: }
205:
206: $this->setUnsealed(ArrayKeyTemplateHelper::unionEntryTypes($this->getUnsealedForArray() ?? $this->unsealed, [$keyType, $valueType]));
207: }
208:
209: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $optional = false): void
210: {
211: if ($offsetType !== null) {
212: $offsetType = $offsetType->toArrayKey();
213: }
214:
215: if ($offsetType === null && count($this->nextAutoIndexes) === 0) {
216: return;
217: }
218:
219: if (!$optional) {
220: $this->isNonEmpty = TrinaryLogic::createYes();
221: }
222:
223: if (!$this->degradeToGeneralArray) {
224: if (
225: $valueType instanceof ClosureType
226: && $this->degradeClosures !== false
227: && !$this->disableArrayDegradation
228: ) {
229: $numClosures = 1;
230: foreach ($this->valueTypes as $innerType) {
231: if (!($innerType instanceof ClosureType)) {
232: continue;
233: }
234:
235: $numClosures++;
236: }
237:
238: if ($numClosures >= self::CLOSURES_COUNT_LIMIT) {
239: $this->degradeClosures = true;
240: $this->degradeToGeneralArray = true;
241: $this->oversized = true;
242: }
243: }
244:
245: if ($offsetType === null) {
246: $newAutoIndexes = $optional ? $this->nextAutoIndexes : [];
247: $hasOptional = false;
248: foreach ($this->keyTypes as $i => $keyType) {
249: if (!$keyType instanceof ConstantIntegerType) {
250: continue;
251: }
252:
253: if (!in_array($keyType->getValue(), $this->nextAutoIndexes, true)) {
254: continue;
255: }
256:
257: $this->valueTypes[$i] = TypeCombinator::union($this->valueTypes[$i], $valueType);
258:
259: if (!$hasOptional && !$optional) {
260: $this->optionalKeys = array_values(array_filter($this->optionalKeys, static fn (int $index): bool => $index !== $i));
261: }
262:
263: /** @var int|float $newAutoIndex */
264: $newAutoIndex = $keyType->getValue() + 1;
265: if (!is_float($newAutoIndex)) {
266: $newAutoIndexes[] = $newAutoIndex;
267: }
268:
269: $hasOptional = true;
270: }
271:
272: $max = max($this->nextAutoIndexes);
273:
274: $this->keyTypes[] = new ConstantIntegerType($max);
275: $this->valueTypes[] = $valueType;
276:
277: /** @var int|float $newAutoIndex */
278: $newAutoIndex = $max + 1;
279: if (!is_float($newAutoIndex)) {
280: $newAutoIndexes[] = $newAutoIndex;
281: }
282:
283: $this->nextAutoIndexes = array_values(array_unique($newAutoIndexes));
284:
285: if ($optional || $hasOptional) {
286: $this->optionalKeys[] = count($this->keyTypes) - 1;
287: }
288:
289: if (
290: !$this->disableArrayDegradation
291: && count($this->keyTypes) > self::ARRAY_COUNT_LIMIT
292: ) {
293: $this->degradeToGeneralArray = true;
294: $this->oversized = true;
295: }
296:
297: return;
298: }
299:
300: if ($offsetType instanceof ConstantIntegerType || $offsetType instanceof ConstantStringType) {
301: /** @var ConstantIntegerType|ConstantStringType $keyType */
302: foreach ($this->keyTypes as $i => $keyType) {
303: if ($keyType->getValue() !== $offsetType->getValue()) {
304: continue;
305: }
306:
307: if ($optional) {
308: $valueType = TypeCombinator::union($valueType, $this->valueTypes[$i]);
309: }
310:
311: $this->valueTypes[$i] = $valueType;
312:
313: if (!$optional) {
314: $this->optionalKeys = array_values(array_filter($this->optionalKeys, static fn (int $index): bool => $index !== $i));
315: if ($keyType instanceof ConstantIntegerType) {
316: $this->nextAutoIndexes = array_values(array_filter($this->nextAutoIndexes, static fn (int $index) => $index > $keyType->getValue()));
317: }
318: }
319: return;
320: }
321:
322: $this->keyTypes[] = $offsetType;
323: $this->valueTypes[] = $valueType;
324:
325: if ($offsetType instanceof ConstantIntegerType) {
326: if (count($this->nextAutoIndexes) > 0) {
327: $min = min($this->nextAutoIndexes);
328: $max = max($this->nextAutoIndexes);
329: $offsetValue = $offsetType->getValue();
330: if ($offsetValue >= 0) {
331: if ($offsetValue > $min) {
332: if ($offsetValue <= $max) {
333: $this->isList = $this->isList->and(TrinaryLogic::createMaybe());
334: } else {
335: $this->markNonListKey($optional);
336: }
337: }
338: } else {
339: $this->markNonListKey($optional);
340: }
341:
342: if ($offsetValue >= $max) {
343: /** @var int|float $newAutoIndex */
344: $newAutoIndex = $offsetValue + 1;
345: if (is_float($newAutoIndex)) {
346: if (!$optional) {
347: $this->nextAutoIndexes = [];
348: }
349: } elseif (!$optional) {
350: $this->nextAutoIndexes = [$newAutoIndex];
351: } else {
352: $this->nextAutoIndexes[] = $newAutoIndex;
353: }
354: }
355: } else {
356: $this->markNonListKey($optional);
357: }
358: } else {
359: $this->markNonListKey($optional);
360: }
361:
362: if ($optional) {
363: $this->optionalKeys[] = count($this->keyTypes) - 1;
364: }
365:
366: if (
367: !$this->disableArrayDegradation
368: && count($this->keyTypes) > self::ARRAY_COUNT_LIMIT
369: ) {
370: $this->degradeToGeneralArray = true;
371: $this->oversized = true;
372: }
373:
374: return;
375: }
376:
377: $scalarTypes = $offsetType->toArrayKey()->getConstantScalarTypes();
378: if (count($scalarTypes) === 0) {
379: $integerRanges = TypeUtils::getIntegerRanges($offsetType);
380: if (count($integerRanges) > 0) {
381: foreach ($integerRanges as $integerRange) {
382: $finiteTypes = $integerRange->getFiniteTypes();
383: if (count($finiteTypes) === 0) {
384: break;
385: }
386:
387: foreach ($finiteTypes as $finiteType) {
388: $scalarTypes[] = $finiteType;
389: }
390: }
391: }
392: }
393: if (count($scalarTypes) > 0 && count($scalarTypes) < self::ARRAY_COUNT_LIMIT) {
394: $valueTypes = $this->valueTypes;
395: $unmatchedScalars = [];
396: foreach ($scalarTypes as $scalarType) {
397: $offsetMatch = false;
398:
399: /** @var ConstantIntegerType|ConstantStringType $keyType */
400: foreach ($this->keyTypes as $i => $keyType) {
401: if ($keyType->getValue() !== $scalarType->getValue()) {
402: continue;
403: }
404:
405: if (!$optional && in_array($i, $this->optionalKeys, true)) {
406: $valueTypes[$i] = $valueType;
407: } else {
408: $valueTypes[$i] = TypeCombinator::union($valueTypes[$i], $valueType);
409: }
410: $offsetMatch = true;
411: }
412:
413: if ($offsetMatch) {
414: continue;
415: }
416:
417: $unmatchedScalars[] = $scalarType;
418: }
419:
420: $this->valueTypes = $valueTypes;
421:
422: if (count($unmatchedScalars) === 0) {
423: return;
424: }
425:
426: foreach ($unmatchedScalars as $scalarType) {
427: $this->keyTypes[] = $scalarType;
428: $this->valueTypes[] = $valueType;
429: $this->optionalKeys[] = count($this->keyTypes) - 1;
430:
431: if (!($scalarType instanceof ConstantIntegerType)) {
432: continue;
433: }
434:
435: if (count($this->nextAutoIndexes) === 0) {
436: continue;
437: }
438:
439: $max = max($this->nextAutoIndexes);
440: $offsetValue = $scalarType->getValue();
441: if ($offsetValue < $max) {
442: continue;
443: }
444:
445: /** @var int|float $newAutoIndex */
446: $newAutoIndex = $offsetValue + 1;
447: if (is_float($newAutoIndex)) {
448: continue;
449: }
450: $this->nextAutoIndexes[] = $newAutoIndex;
451: }
452:
453: $this->isList = TrinaryLogic::createNo();
454:
455: if (
456: !$this->disableArrayDegradation
457: && count($this->keyTypes) > self::ARRAY_COUNT_LIMIT
458: ) {
459: $this->degradeToGeneralArray = true;
460: $this->oversized = true;
461: }
462:
463: return;
464: }
465:
466: $this->isList = TrinaryLogic::createNo();
467:
468: // If the builder is already unsealed (e.g. fresh bleeding-edge
469: // builder, or a PHPDoc shape like `array{a: int, ...<int, T>}`),
470: // fold the unknown offset/value into the existing unsealed
471: // extras instead of dropping per-key precision by degrading to a
472: // general array. The actual decision between unsealed
473: // ConstantArrayType and general ArrayType is then made in
474: // getArray() based on whether any constant keys ended up
475: // alongside these extras.
476: if ($this->unsealed !== null) {
477: // Existing keys whose value the new offset could overwrite
478: // must widen to a union of (existing, new) — the assignment
479: // might or might not have hit them.
480: $residualOffset = $offsetType;
481: foreach ($this->keyTypes as $i => $keyType) {
482: if ($offsetType->isSuperTypeOf($keyType)->no()) {
483: continue;
484: }
485: $this->valueTypes[$i] = TypeCombinator::union($this->valueTypes[$i], $valueType);
486: $residualOffset = TypeCombinator::remove($residualOffset, $keyType);
487: }
488:
489: if ($residualOffset instanceof NeverType) {
490: return;
491: }
492:
493: [$existingKey, $existingValue] = $this->unsealed;
494: $isExplicitNever = $existingKey instanceof NeverType && $existingKey->isExplicit();
495: if ($isExplicitNever) {
496: $this->unsealed = [$residualOffset, $valueType];
497: } else {
498: $this->unsealed = [
499: TypeCombinator::union($existingKey, $residualOffset),
500: TypeCombinator::union($existingValue, $valueType),
501: ];
502: }
503: return;
504: }
505: }
506:
507: if ($offsetType === null) {
508: $offsetType = TypeCombinator::union(...array_map(static fn (int $index) => new ConstantIntegerType($index), $this->nextAutoIndexes));
509: } else {
510: $this->isList = TrinaryLogic::createNo();
511: }
512:
513: $this->keyTypes[] = $offsetType;
514: $this->valueTypes[] = $valueType;
515: if ($optional) {
516: $this->optionalKeys[] = count($this->keyTypes) - 1;
517: }
518: $this->degradeToGeneralArray = true;
519: }
520:
521: /**
522: * Record adding a key incompatible with list ordering. A required key breaks
523: * list-ness; an optional one only degrades Yes to Maybe (No stays No), since
524: * the array is still a list when the key is absent.
525: */
526: private function markNonListKey(bool $optional): void
527: {
528: $this->isList = $optional
529: ? $this->isList->and(TrinaryLogic::createMaybe())
530: : TrinaryLogic::createNo();
531: }
532:
533: public function degradeToGeneralArray(bool $oversized = false): void
534: {
535: if ($this->disableArrayDegradation) {
536: throw new ShouldNotHappenException();
537: }
538:
539: $this->degradeToGeneralArray = true;
540: $this->oversized = $this->oversized || $oversized;
541: }
542:
543: public function disableClosureDegradation(): void
544: {
545: $this->degradeClosures = false;
546: }
547:
548: public function disableArrayDegradation(): void
549: {
550: $this->degradeToGeneralArray = false;
551: $this->oversized = false;
552: $this->disableArrayDegradation = true;
553: }
554:
555: public function getArray(): Type
556: {
557: $keyTypesCount = count($this->keyTypes);
558: $isList = $this->getListness();
559: if ($keyTypesCount === 0) {
560: if ($this->unsealed !== null) {
561: $isExplicitNever = $this->unsealed[0] instanceof NeverType && $this->unsealed[0]->isExplicit();
562: if (!$isExplicitNever) {
563: [$unsealedKey, $unsealedValue] = $this->getUnsealedForArray() ?? $this->unsealed;
564: $arrayType = new ArrayType($unsealedKey, $unsealedValue);
565: if ($this->isNonEmpty->yes()) {
566: return TypeCombinator::intersect($arrayType, new NonEmptyArrayType());
567: }
568: return $arrayType;
569: }
570: }
571: return new ConstantArrayType([], [], unsealed: $this->getUnsealedForArray());
572: }
573:
574: if (!$this->degradeToGeneralArray) {
575: /** @var list<ConstantIntegerType|ConstantStringType> $keyTypes */
576: $keyTypes = $this->keyTypes;
577: $array = new ConstantArrayType($keyTypes, $this->valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $isList, $this->getUnsealedForArray(), $this->keyOrderKnown);
578: if ($this->isNonEmpty->yes() && !$array->isIterableAtLeastOnce()->yes()) {
579: return TypeCombinator::intersect($array, new NonEmptyArrayType());
580: }
581: return $array;
582: }
583:
584: if ($this->degradeClosures === true) {
585: $itemTypes = [];
586: $itemTypes[] = new CallableType();
587: foreach ($this->valueTypes as $valueType) {
588: if ($valueType instanceof ClosureType) {
589: continue;
590: }
591: $itemTypes[] = $valueType;
592: }
593: } else {
594: $itemTypes = $this->valueTypes;
595: }
596:
597: $keyTypesForArray = $this->keyTypes;
598: // Real unsealed extras describe additional key/value pairs that
599: // belong in the degraded `ArrayType`'s key/value unions too —
600: // otherwise the degraded type silently drops them.
601: if ($this->unsealed !== null) {
602: [$unsealedKey, $unsealedValue] = $this->unsealed;
603: $isExplicitNever = $unsealedKey instanceof NeverType && $unsealedKey->isExplicit();
604: if (!$isExplicitNever) {
605: $keyTypesForArray[] = $unsealedKey;
606: $itemTypes[] = $unsealedValue;
607: }
608: }
609:
610: $array = new ArrayType(
611: TypeCombinator::union(...$keyTypesForArray),
612: TypeCombinator::union(...$itemTypes),
613: );
614:
615: $types = [];
616: if ($this->isNonEmpty->yes() || count($this->optionalKeys) < $keyTypesCount) {
617: $types[] = new NonEmptyArrayType();
618: }
619:
620: if ($this->oversized) {
621: $types[] = new OversizedArrayType();
622: }
623:
624: if ($isList->yes()) {
625: $types[] = new AccessoryArrayListType();
626: }
627:
628: if (count($types) === 0) {
629: return $array;
630: }
631:
632: return new IntersectionType([$array, ...$types]);
633: }
634:
635: public function isList(): bool
636: {
637: return $this->getListness()->yes();
638: }
639:
640: private function getListness(): TrinaryLogic
641: {
642: // keys set in no known order do not say they come as a list, only that they can
643: if (!$this->keyOrderKnown && count($this->keyTypes) > 1 && BleedingEdgeToggle::isBleedingEdge()) {
644: return $this->isList->and(TrinaryLogic::createMaybe());
645: }
646:
647: return $this->isList;
648: }
649:
650: }
651: