Repository navigation
Expand file tree
/
Copy pathArrayAlgebra.php
More file actions
855 lines (776 loc) · 30 KB
/
Copy pathArrayAlgebra.php
File metadata and controls
855 lines (776 loc) · 30 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
<?php declare(strict_types = 1);
namespace PHPStan\Type;
use PHPStan\Turbo\ReferencedByTurboExtension;
use PHPStan\Type\Accessory\AccessoryArrayListType;
use PHPStan\Type\Accessory\HasOffsetType;
use PHPStan\Type\Accessory\HasOffsetValueType;
use PHPStan\Type\Accessory\NonEmptyArrayType;
use PHPStan\Type\Accessory\OversizedArrayType;
use PHPStan\Type\Combinator\SingleValueUnionRule;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
use PHPStan\Type\Generic\ArrayKeyTemplateHelper;
use PHPStan\Type\Generic\TemplateType;
use function array_key_exists;
use function array_map;
use function array_merge;
use function count;
use function get_class;
use function min;
/**
* The unions of two shapes as one shape, and the intersections of an array
* with an accessory type that the array takes in whole: the tryUnion() of
* ConstantArrayType, and the tryIntersect() of ConstantArrayType and
* OversizedArrayType.
*
* The intersections apply where neither side holds the other - where one does,
* intersect() keeps the subtype as it is.
*
* @internal
*/
#[ReferencedByTurboExtension(key: 'arrayAlgebra')]
final class ArrayAlgebra
{
/** The most optional keys whose sets tryUnionConstantArrayBesideEmptyArray() counts in an integer. */
private const KEY_SETS_COUNTED_LIMIT = 62;
/** The most shapes splitConstantArrayAtFiniteValue() splits a shape into, over all of its keys. */
private const SPLIT_SHAPES_LIMIT = 64;
/**
* The shapes of a shape, one per value of its first key whose value is a
* union, or one per member of the union when it is not of finitely many
* values: `array{type: 'a'|'b', x: int}` is `array{type: 'a', x: int}` and
* `array{type: 'b', x: int}`, and `array{int|string}` is `array{int}` and
* `array{string}`.
*
* tryUnionConstantArray() merges shapes that differ at one key into one
* shape, which a union of the shapes it merged no longer accepts member by
* member - UnionType::accepts() splits it back with this, as it accepts
* `array{int|string}` by `list<int>|list<string>`. Null when no key
* has such a value, or when the shape splits into more than
* SPLIT_SHAPES_LIMIT shapes over all of its keys.
*
* @return list<ConstantArrayType>|null
*/
public static function splitConstantArrayAtFiniteValue(ConstantArrayType $array): ?array
{
$valueTypes = $array->getValueTypes();
$splitIndex = null;
$splitValues = [];
$shapesCount = 1;
foreach ($valueTypes as $i => $valueType) {
if (!$valueType instanceof UnionType || $valueType instanceof TemplateType) {
continue;
}
// unions of constant scalars, the values tryUnionConstantArray() unions at one key,
// split into each value, and other unions into their members
if ($valueType->isConstantScalarValue()->yes()) {
$finiteTypes = $valueType->getFiniteTypes();
} elseif ($valueType->isArray()->no()) {
// a split shape is accepted member by member, which splits the
// arrays among its values again: arrays nested in each other
// would split into exponentially many shapes
$finiteTypes = $valueType->getTypes();
} else {
continue;
}
if (count($finiteTypes) < 2) {
continue;
}
$shapesCount *= count($finiteTypes);
if ($shapesCount > self::SPLIT_SHAPES_LIMIT) {
return null;
}
if ($splitIndex !== null) {
continue;
}
$splitIndex = $i;
$splitValues = $finiteTypes;
}
if ($splitIndex === null) {
return null;
}
$shapes = [];
foreach ($splitValues as $splitValue) {
$valueTypes[$splitIndex] = $splitValue;
$shapes[] = new ConstantArrayType(
$array->getKeyTypes(),
$valueTypes,
$array->getNextAutoIndexes(),
$array->getOptionalKeys(),
$array->isList(),
$array->getUnsealedTypes(),
$array->isKeyOrderKnown(),
);
}
return $shapes;
}
/** @see Type::tryIntersect() */
public static function tryIntersectConstantArray(ConstantArrayType $array, Type $otherType): ?Type
{
if ($otherType instanceof ConstantArrayType || $otherType instanceof ArrayType) {
return self::tryIntersectShapeWithArray($array, $otherType);
}
if ($otherType instanceof IterableType) {
return self::tryIntersectIterables($array, $otherType);
}
if (
!$otherType instanceof HasOffsetType
&& !$otherType instanceof HasOffsetValueType
&& !$otherType instanceof AccessoryArrayListType
&& !$otherType instanceof NonEmptyArrayType
) {
return null;
}
if (!self::overlapsWithoutContaining($array, $otherType)) {
return null;
}
if ($otherType instanceof HasOffsetType) {
return $array->makeOffsetRequired($otherType->getOffsetType());
}
if ($otherType instanceof AccessoryArrayListType) {
return $array->makeList();
}
if ($otherType instanceof NonEmptyArrayType) {
// the one key that can make it non-empty
if (
(count($array->getKeyTypes()) === 1 || $array->isList()->yes())
&& $array->isOptionalKey(0)
&& !$array->isUnsealed()->yes()
) {
return $array->makeOffsetRequired($array->getKeyTypes()[0]);
}
return null;
}
$offsetType = $otherType->getOffsetType();
$valueType = TypeCombinator::intersect($array->getOffsetValueType($offsetType), $otherType->getValueType());
if ($valueType instanceof NeverType) {
return $valueType;
}
return $array->setOffsetValueType($offsetType, $valueType);
}
/**
* An array with a value of A or one of B at an offset is an array with a
* value of A|B there.
*
* @see Type::tryUnion()
*/
public static function tryUnionHasOffsetValue(HasOffsetValueType $type, Type $otherType): ?Type
{
if (!$otherType instanceof HasOffsetValueType || !$type->getOffsetType()->equals($otherType->getOffsetType())) {
return null;
}
return new HasOffsetValueType($type->getOffsetType(), TypeCombinator::union($type->getValueType(), $otherType->getValueType()));
}
/**
* Two arrays or iterables neither holding the other are the one of the
* keys and the values both allow, and a general array is a list of the
* keys a list allows.
*
* @see Type::tryIntersect()
*/
public static function tryIntersectArray(ArrayType $array, Type $otherType): ?Type
{
if ($otherType instanceof ArrayType || $otherType instanceof IterableType) {
return self::tryIntersectIterables($array, $otherType);
}
if (
!$otherType instanceof AccessoryArrayListType
|| get_class($array) !== ArrayType::class
|| !self::overlapsNeitherContaining($array, $otherType)
|| $otherType->getIterableKeyType()->isSuperTypeOf($array->getIterableKeyType())->yes()
) {
return null;
}
$keyType = TypeCombinator::intersect($array->getIterableKeyType(), $otherType->getIterableKeyType());
if ($keyType instanceof NeverType) {
return $keyType;
}
return TypeCombinator::intersect(new ArrayType($keyType, $array->getItemType()), $otherType);
}
/** @see Type::tryIntersect() */
public static function tryIntersectIterable(IterableType $iterable, Type $otherType): ?Type
{
if (!$otherType instanceof ArrayType && !$otherType instanceof ConstantArrayType && !$otherType instanceof IterableType) {
return null;
}
return self::tryIntersectIterables($iterable, $otherType);
}
/**
* Of an array or iterable and another, the one of the keys and the values
* both allow: an iterable of two iterables, an array otherwise.
*/
private static function tryIntersectIterables(ArrayType|ConstantArrayType|IterableType $type, ArrayType|ConstantArrayType|IterableType $otherType): ?Type
{
// two equal arrays or iterables hold each other: the other one stands
// for both, as it does when a member holding another gives way to it
if (
get_class($type) === get_class($otherType)
&& (get_class($type) === ArrayType::class || get_class($type) === IterableType::class)
&& $type->equals($otherType)
) {
return $otherType;
}
if (!self::overlapsNeitherContaining($type, $otherType)) {
return null;
}
$keyType = TypeCombinator::intersect($otherType->getIterableKeyType(), $type->getKeyType());
$itemType = TypeCombinator::intersect($otherType->getItemType(), $type->getItemType());
if ($type instanceof IterableType && $otherType instanceof IterableType) {
return new IterableType($keyType, $itemType);
}
return new ArrayType($keyType, $itemType);
}
/**
* A shape and an array: the one the other holds, as both are compared
* anyway, and of two neither holding the other the shape with the values at
* its keys narrowed to the values the other array allows there, or never
* when one of its required keys cannot be there.
*/
private static function tryIntersectShapeWithArray(ConstantArrayType $constArray, Type $otherArray): ?Type
{
$isSuperTypeA = $otherArray->isSuperTypeOf($constArray);
if ($isSuperTypeA->yes()) {
return $constArray;
}
$isSuperTypeB = $constArray->isSuperTypeOf($otherArray);
if ($isSuperTypeB->yes()) {
return $otherArray;
}
if ($isSuperTypeA->no() && $isSuperTypeB->no()) {
return null;
}
$otherConstantArray = $otherArray instanceof ConstantArrayType ? $otherArray : null;
if (
$otherConstantArray !== null
&& !$constArray->isUnsealed()->maybe()
&& !$otherConstantArray->isUnsealed()->maybe()
) {
$merged = self::intersectDefiniteConstantArrays($constArray, $otherConstantArray);
if ($merged instanceof NeverType && $merged->getReason() === null) {
$reasons = array_merge($isSuperTypeA->getReasons(), $isSuperTypeB->getReasons());
if ($reasons !== []) {
return new NeverType(reason: $reasons[0]);
}
}
return $merged;
}
$newArray = ConstantArrayTypeBuilder::createEmpty();
$newArray->makeKeyOrderKnown();
// Preserve unsealed extras from the source shape so the
// rebuild doesn't silently turn `array{k: int, ...} & X`
// into a sealed `array{k: int}` — intersect with the other
// side's iterable key/value so the open part keeps both
// sides' refinements.
$constUnsealed = $constArray->getUnsealedTypes();
if ($constUnsealed !== null && $constArray->isUnsealed()->yes()) {
$newUnsealedKey = TypeCombinator::intersect($constUnsealed[0], $otherArray->getIterableKeyType());
$newUnsealedValue = TypeCombinator::intersect($constUnsealed[1], $otherArray->getIterableValueType());
if (!$newUnsealedKey instanceof NeverType && !$newUnsealedValue instanceof NeverType) {
$newArray->makeUnsealed($newUnsealedKey, $newUnsealedValue);
}
}
$valueTypes = $constArray->getValueTypes();
foreach ($constArray->getKeyTypes() as $k => $keyType) {
$hasOffset = $otherArray->hasOffsetValueType($keyType);
if ($hasOffset->no()) {
// a shape that may have keys it does not list answers No for them too
if ($otherConstantArray !== null && $otherConstantArray->isUnsealed()->maybe()) {
$newArray->setOffsetValueType($keyType, $valueTypes[$k], $constArray->isOptionalKey($k));
continue;
}
if (!$constArray->isOptionalKey($k)) {
return new NeverType();
}
continue;
}
$newArray->setOffsetValueType(
TypeCombinator::intersect($keyType, $otherArray->getIterableKeyType()),
TypeCombinator::intersect($valueTypes[$k], $otherArray->getOffsetValueType($keyType)),
$constArray->isOptionalKey($k) && !$hasOffset->yes(),
);
}
if ($otherConstantArray !== null && $constArray->isUnsealed()->maybe()) {
// keys the shape does not list keep the other shape's values
$otherValueTypes = $otherConstantArray->getValueTypes();
foreach ($otherConstantArray->getKeyTypes() as $k => $keyType) {
if (!$constArray->hasOffsetValueType($keyType)->no()) {
continue;
}
$newArray->setOffsetValueType($keyType, $otherValueTypes[$k], $otherConstantArray->isOptionalKey($k));
}
}
$newArrayType = self::inKeyOrderOf($newArray->getArray(), $constArray, ...($otherConstantArray !== null ? [$otherConstantArray] : []));
if ($constArray->isList()->yes()) {
$newArrayType = TypeCombinator::intersect($newArrayType, new AccessoryArrayListType());
}
return $newArrayType;
}
private static function intersectDefiniteConstantArrays(ConstantArrayType $a, ConstantArrayType $b): Type
{
$aSealed = $a->isUnsealed()->no();
$bSealed = $b->isUnsealed()->no();
$aUnsealed = $a->getUnsealedDeclaredTypes();
$bUnsealed = $b->getUnsealedDeclaredTypes();
$bothUnsealed = !$aSealed && !$bSealed && $aUnsealed !== null && $bUnsealed !== null;
$aKeyByValue = [];
foreach ($a->getKeyTypes() as $k => $keyType) {
$aKeyByValue[$keyType->getValue()] = $k;
}
$bKeyByValue = [];
foreach ($b->getKeyTypes() as $k => $keyType) {
$bKeyByValue[$keyType->getValue()] = $k;
}
if ($aSealed && $bSealed) {
foreach ($aKeyByValue as $keyValue => $k) {
if (!$a->isOptionalKey($k) && !array_key_exists($keyValue, $bKeyByValue)) {
return new NeverType();
}
}
foreach ($bKeyByValue as $keyValue => $k) {
if (!$b->isOptionalKey($k) && !array_key_exists($keyValue, $aKeyByValue)) {
return new NeverType();
}
}
}
$newArray = ConstantArrayTypeBuilder::createEmpty();
$newArray->makeKeyOrderKnown();
if ($bothUnsealed) {
[$unsealedKey, $unsealedValue] = ArrayKeyTemplateHelper::intersectEntryTypes($aUnsealed, $bUnsealed);
if ($unsealedKey instanceof NeverType || $unsealedValue instanceof NeverType) {
return new NeverType();
}
$newArray->makeUnsealed($unsealedKey, $unsealedValue);
} else {
$never = new NeverType(true);
$newArray->makeUnsealed($never, $never);
}
$resolveOtherValue = static function (ConstantArrayType $other, Type $keyType): ?Type {
if ($other->hasOffsetValueType($keyType)->yes()) {
return $other->getOffsetValueType($keyType);
}
$otherUnsealed = $other->getUnsealedTypes();
if ($otherUnsealed === null) {
return null;
}
[$unsealedKey, $unsealedValue] = $otherUnsealed;
if ($unsealedKey instanceof NeverType && $unsealedKey->isExplicit()) {
return null;
}
if ($unsealedKey->isSuperTypeOf($keyType)->no()) {
return null;
}
// the value of the extras at the key, which their key may declare a template for
return $other->getUnsealedDeclaredTypes() !== $otherUnsealed ? $other->getOffsetValueType($keyType) : $unsealedValue;
};
$keysToProcess = [];
foreach ($aKeyByValue as $keyValue => $k) {
$keysToProcess[$keyValue] = [$k, $bKeyByValue[$keyValue] ?? null];
}
foreach ($bKeyByValue as $keyValue => $k) {
if (array_key_exists($keyValue, $keysToProcess)) {
continue;
}
$keysToProcess[$keyValue] = [null, $k];
}
foreach ($keysToProcess as [$aIdx, $bIdx]) {
if ($aIdx !== null && $bIdx !== null) {
$keyType = $a->getKeyTypes()[$aIdx];
$value = TypeCombinator::intersect($a->getValueTypes()[$aIdx], $b->getValueTypes()[$bIdx]);
$optional = $a->isOptionalKey($aIdx) && $b->isOptionalKey($bIdx);
} elseif ($aIdx !== null) {
$keyType = $a->getKeyTypes()[$aIdx];
$aValue = $a->getValueTypes()[$aIdx];
$bValue = $resolveOtherValue($b, $keyType);
if ($bValue === null) {
if ($a->isOptionalKey($aIdx)) {
continue;
}
return new NeverType();
}
$value = TypeCombinator::intersect($aValue, $bValue);
$optional = $a->isOptionalKey($aIdx);
} else {
/** @var int<0, max> $bIdx */
$keyType = $b->getKeyTypes()[$bIdx];
$bValue = $b->getValueTypes()[$bIdx];
$aValue = $resolveOtherValue($a, $keyType);
if ($aValue === null) {
if ($b->isOptionalKey($bIdx)) {
continue;
}
return new NeverType();
}
$value = TypeCombinator::intersect($aValue, $bValue);
$optional = $b->isOptionalKey($bIdx);
}
if ($value instanceof NeverType) {
if ($optional) {
continue;
}
return new NeverType();
}
$newArray->setOffsetValueType($keyType, $value, $optional);
}
$newArrayType = self::inKeyOrderOf($newArray->getArray(), $a, $b);
// optional keys rebuilt one by one may each be left out alone, so the
// builder cannot tell a list from the keys - the inputs can
if ($a->isList()->yes() || $b->isList()->yes()) {
$newArrayType = TypeCombinator::intersect($newArrayType, new AccessoryArrayListType());
}
return $newArrayType;
}
/**
* The intersection of shapes built key by key, with its keys in the order of a shape
* that knows it and lists them all.
*/
private static function inKeyOrderOf(Type $intersection, ConstantArrayType ...$shapes): Type
{
if (!$intersection->isConstantArray()->yes()) {
return $intersection;
}
return TypeCombinator::union(...array_map(
static fn (ConstantArrayType $array): ConstantArrayType => $array->inKeyOrderOf(...$shapes),
$intersection->getConstantArrays(),
));
}
/** @see Type::tryIntersect() */
public static function tryIntersectOversizedArray(OversizedArrayType $array, Type $otherType): ?Type
{
// an oversized array no longer tracks its offsets
if (!$otherType instanceof HasOffsetValueType || !self::overlapsWithoutContaining($array, $otherType)) {
return null;
}
return $array;
}
/**
* The union of two shapes as one shape when that loses nothing: when one
* holds the other, or when they differ at a single key only - in its value,
* whether it is optional, or whether it is there at all - where the merged
* shape has the union of the values, optional unless both require it.
* Shapes differing at more keys stay a tagged union.
*
* An empty array merges only into a shape that already holds it:
* `array{}|array{a: int}` keeps it apart. Operations on a shape, such as
* appending to a list, are exact on each member of a union but not on
* optional keys, and `$a = []; if (...) { $a[] = 1; }` is the most common
* union of shapes.
*
* Shapes with unsealed extras are left to TypeCombinator.
*
* @see Type::tryUnion()
*/
public static function tryUnionConstantArray(ConstantArrayType $array, Type $otherType): ?Type
{
// a bare ConstantArrayType is the only type whose getConstantArrays() is itself
$otherShapes = $otherType->getConstantArrays();
if ($otherShapes !== [$otherType]) {
return null;
}
$otherType = $otherShapes[0];
if (
$array instanceof TemplateType
|| $otherType instanceof TemplateType
|| $array->isUnsealed()->yes()
|| $otherType->isUnsealed()->yes()
) {
return null;
}
// literal arrays with their keys in different orders merge as shapes whose keys come in any order
if ($array->isKeyOrderKnown() && $otherType->isKeyOrderKnown() && !$array->sharesKeyOrderWith($otherType)) {
return self::tryUnionConstantArray($array->forgetKeyOrder(), $otherType->forgetKeyOrder());
}
// $bigger has every key of $smaller, or they cannot merge
[$bigger, $smaller] = count($array->getKeyTypes()) >= count($otherType->getKeyTypes())
? [$array, $otherType]
: [$otherType, $array];
$smallerKeys = [];
foreach ($smaller->getKeyTypes() as $j => $keyType) {
$smallerKeys[$keyType->getValue()] = $j;
}
$smallerValueTypes = $smaller->getValueTypes();
$biggerValueTypes = $bigger->getValueTypes();
$matchedKeys = 0;
$differingKeys = 0;
// a key of $bigger only it requires keeps it from holding $smaller
$biggerRequiresOtherKey = false;
// two different single values at a key keep either from holding the other
$hasDifferentValues = false;
foreach ($bigger->getKeyTypes() as $i => $keyType) {
$j = $smallerKeys[$keyType->getValue()] ?? null;
if ($j === null) {
$differingKeys++;
$biggerRequiresOtherKey = $biggerRequiresOtherKey || !$bigger->isOptionalKey($i);
continue;
}
$matchedKeys++;
if (
$bigger->isOptionalKey($i) === $smaller->isOptionalKey($j)
&& $biggerValueTypes[$i]->equals($smallerValueTypes[$j])
) {
continue;
}
$differingKeys++;
// a union is not a single value, and asking would visit its members
if ($hasDifferentValues || $biggerValueTypes[$i] instanceof UnionType || $smallerValueTypes[$j] instanceof UnionType) {
continue;
}
$biggerValueKey = SingleValueUnionRule::getValueKey($biggerValueTypes[$i]);
$smallerValueKey = $biggerValueKey !== null ? SingleValueUnionRule::getValueKey($smallerValueTypes[$j]) : null;
$hasDifferentValues = $smallerValueKey !== null && $biggerValueKey !== $smallerValueKey;
}
if ($matchedKeys !== count($smallerKeys)) {
return null;
}
if ($differingKeys === 0) {
if ($bigger->sharesKeyOrderWith($smaller)) {
return $bigger;
}
// the same keys and values in another order, or in an order one does not know: the keys come in any order
return $bigger->isKeyOrderKnown() ? $smaller->mergeWith($bigger) : $bigger->mergeWith($smaller);
}
if ($differingKeys === 1 && $smallerKeys !== []) {
$merged = $bigger->mergeWith($smaller);
if (
count($biggerValueTypes) === 1
&& $merged->getValueTypes()[0] instanceof UnionType
// values told apart only by the order of the keys of arrays in them merge; asked both ways, so that
// the union does not depend on which shape is the bigger one
&& self::withoutKeyOrder($biggerValueTypes[0])->isSuperTypeOf(self::withoutKeyOrder($smallerValueTypes[0]))
->and(self::withoutKeyOrder($smallerValueTypes[0])->isSuperTypeOf(self::withoutKeyOrder($biggerValueTypes[0])))
->no()
) {
// `array{'a'}|array{'b'}` stays apart: functions that make keys of the
// values, such as array_fill_keys(), tell the shapes apart by them
return null;
}
return $merged;
}
if (self::areListsOfOneLengthRange($bigger, $smaller)) {
return $bigger->mergeWith($smaller);
}
if ($hasDifferentValues) {
return null;
}
// a shape that knows its key order holds one in another order, or one that does not know it, after
// forgetting its order: `array{a: mixed, b: mixed}` written in code and `array{a: int, b: int}`
// written in PHPDoc are one unordered shape
if (!$biggerRequiresOtherKey) {
$merged = self::holdShape($bigger->sharesKeyOrderWith($smaller) || !$bigger->isKeyOrderKnown() ? $bigger : $bigger->forgetKeyOrder(), $smaller);
if ($merged !== null) {
return $merged;
}
}
if ($matchedKeys === count($bigger->getKeyTypes())) {
return self::holdShape($smaller->sharesKeyOrderWith($bigger) || !$smaller->isKeyOrderKnown() ? $smaller : $smaller->forgetKeyOrder(), $bigger);
}
return null;
}
/**
* Whether the union of the shapes is $holder, which has every key of $held.
* isSuperTypeOf() alone does not tell: it lets a shape hold one with more
* keys, so at a key holding shapes, `array{}|array{string}` would hold
* `array{0: string, 1?: string}` and the union would lose the lists of two.
* Merging $held into $holder unions their values at each key exactly.
*
* Returns the union when $holder holds $held: $holder, or the merged shape
* when it differs from $holder only in the witness types of mixed values,
* which take no part in what the shapes hold but are kept.
*/
private static function holdShape(ConstantArrayType $holder, ConstantArrayType $held): ?ConstantArrayType
{
if ($holder->isSuperTypeOf($held)->yes()) {
$merged = $holder->mergeWith($held);
if ($merged->equals($holder)) {
return $holder;
}
if (self::withoutWitnessTypes($merged)->equals(self::withoutWitnessTypes($holder))) {
return $merged;
}
}
return null;
}
/** Whether the union of the values is $holder, see holdShape(). */
private static function holdsValue(Type $holder, Type $held): bool
{
if ($holder->isSuperTypeOf($held)->yes()) {
$union = TypeCombinator::union($holder, $held);
return $union->equals($holder) || self::withoutWitnessTypes($union)->equals(self::withoutWitnessTypes($holder));
}
return false;
}
/** The type with the arrays in it, at any depth, not knowing their key order. */
private static function withoutKeyOrder(Type $type): Type
{
return TypeTraverser::map($type, static function (Type $type, callable $traverse): Type {
// rebuilding a recursive type unions its body, which merges shapes through here again
if ($type instanceof RecursiveType || $type instanceof RecursiveTypeReference) {
return $type;
}
if ($type instanceof ConstantArrayType && !$type instanceof TemplateType && $type->isKeyOrderKnown()) {
return $traverse($type->forgetKeyOrder());
}
return $traverse($type);
});
}
private static function withoutWitnessTypes(Type $type): Type
{
return TypeTraverser::map($type, static function (Type $type, callable $traverse): Type {
if ($type instanceof MixedType && $type->getWitnessType() !== null) {
return $type->changeWitnessType(null);
}
return $traverse($type);
});
}
/**
* The union of two shapes as one shape in a union that holds the empty
* array as well: when the merged shape holds the two and at most the empty
* array besides, such as `array{a: 1}|array{a?: 1, b: 2}` beside
* `array{}`, which together are `array{a?: 1, b?: 2}`.
*
* The shapes are not empty and not lists - a list holds the lists of its lengths, which
* tryUnionConstantArray() merges - and have the same value at each key
* they share, so the shapes they hold are the sets of keys from their
* required keys to all their keys, and counting those sets tells whether
* the merged shape holds any other.
*/
public static function tryUnionConstantArrayBesideEmptyArray(ConstantArrayType $array, ConstantArrayType $otherType): ?ConstantArrayType
{
if (
$array instanceof TemplateType
|| $otherType instanceof TemplateType
|| $array->isUnsealed()->yes()
|| $otherType->isUnsealed()->yes()
|| $array->isList()->yes()
|| $otherType->isList()->yes()
// the empty array itself stays apart, see tryUnionConstantArray()
|| $array->getKeyTypes() === []
|| $otherType->getKeyTypes() === []
) {
return null;
}
[$bigger, $smaller] = count($array->getKeyTypes()) >= count($otherType->getKeyTypes())
? [$array, $otherType]
: [$otherType, $array];
$biggerKeys = [];
foreach ($bigger->getKeyTypes() as $i => $keyType) {
$biggerKeys[$keyType->getValue()] = $i;
}
$biggerValueTypes = $bigger->getValueTypes();
$smallerValueTypes = $smaller->getValueTypes();
$biggerRequired = count($biggerKeys) - count($bigger->getOptionalKeys());
$smallerRequired = 0;
// the keys both require, and the keys either requires
$bothRequire = 0;
$eitherRequires = $biggerRequired;
$biggerRequiredInSmaller = 0;
foreach ($smaller->getKeyTypes() as $j => $keyType) {
$i = $biggerKeys[$keyType->getValue()] ?? null;
if ($i === null || !$biggerValueTypes[$i]->equals($smallerValueTypes[$j])) {
return null;
}
if (!$bigger->isOptionalKey($i)) {
$biggerRequiredInSmaller++;
}
if ($smaller->isOptionalKey($j)) {
continue;
}
$smallerRequired++;
if ($bigger->isOptionalKey($i)) {
$eitherRequires++;
} else {
$bothRequire++;
}
}
// the sets of keys of the merged shape and those of both, without the empty one
$biggerCount = count($biggerKeys);
$smallerCount = count($smaller->getKeyTypes());
if ($biggerCount - $bothRequire > self::KEY_SETS_COUNTED_LIMIT) {
return null;
}
$merged = (1 << $biggerCount - $bothRequire) - ($bothRequire === 0 ? 1 : 0);
// the sets of keys both hold: from the keys either requires to the
// keys of the smaller one, when it has all the keys the bigger requires
$shared = $biggerRequiredInSmaller === $biggerRequired ? 1 << $smallerCount - $eitherRequires : 0;
$union = (1 << $biggerCount - $biggerRequired)
+ (1 << $smallerCount - $smallerRequired)
- $shared
- ($biggerRequired === 0 || $smallerRequired === 0 ? 1 : 0);
if ($merged !== $union) {
return null;
}
return $bigger->mergeWith($smaller);
}
/**
* Whether two lists are one list of the lengths of both: a list shape holds
* the lists of each length from its required keys to all its keys, the
* value at each position being its value type there. The merged list,
* with the union of the values at each position, holds exactly the two when
* at each length it holds, the lists of that length the two hold are one
* product of values: one list's, or both when one holds the other's or
* they differ at one position below that length only.
*
* $bigger has every key of $smaller.
*/
private static function areListsOfOneLengthRange(ConstantArrayType $bigger, ConstantArrayType $smaller): bool
{
if (!$bigger->isList()->yes() || !$smaller->isList()->yes()) {
return false;
}
$biggerMax = count($bigger->getKeyTypes());
$smallerMax = count($smaller->getKeyTypes());
$biggerMin = $biggerMax - count($bigger->getOptionalKeys());
$smallerMin = $smallerMax - count($smaller->getOptionalKeys());
if ($smallerMax === 0 || $smallerMax < $biggerMin - 1) {
// the empty array stays apart, see tryUnionConstantArray(); or a
// length of neither between them
return false;
}
// a list's keys are its positions in order
$biggerValueTypes = $bigger->getValueTypes();
$smallerValueTypes = $smaller->getValueTypes();
$minLength = min($biggerMin, $smallerMin);
// over the positions below the length
$differingPositions = 0;
$biggerHoldsSmaller = true;
$smallerHoldsBigger = true;
for ($length = 1; $length <= $biggerMax; $length++) {
$i = $length - 1;
if ($i < $smallerMax && !$biggerValueTypes[$i]->equals($smallerValueTypes[$i])) {
$differingPositions++;
$biggerHoldsSmaller = $biggerHoldsSmaller && self::holdsValue($biggerValueTypes[$i], $smallerValueTypes[$i]);
$smallerHoldsBigger = $smallerHoldsBigger && self::holdsValue($smallerValueTypes[$i], $biggerValueTypes[$i]);
}
if ($length < $minLength) {
continue;
}
$inBigger = $length >= $biggerMin;
$inSmaller = $length >= $smallerMin && $length <= $smallerMax;
if ($inBigger && $inSmaller) {
if ($differingPositions > 1 && !$biggerHoldsSmaller && !$smallerHoldsBigger) {
return false;
}
} elseif ($inBigger) {
if (!$biggerHoldsSmaller) {
return false;
}
} elseif (!$smallerHoldsBigger) {
return false;
}
}
return true;
}
private static function overlapsWithoutContaining(Type $array, Type $otherType): bool
{
return !$otherType->isSuperTypeOf($array)->yes() && $array->isSuperTypeOf($otherType)->maybe();
}
/** Whether the two types may have values in common and neither holds the other. */
private static function overlapsNeitherContaining(Type $type, Type $otherType): bool
{
$isSuperType = $type->isSuperTypeOf($otherType);
if ($isSuperType->yes()) {
return false;
}
$isSubType = $otherType->isSuperTypeOf($type);
return !$isSubType->yes() && ($isSuperType->maybe() || $isSubType->maybe());
}
}