-
Notifications
You must be signed in to change notification settings - Fork 597
Expand file tree
/
Copy pathConstantArrayType.php
More file actions
3587 lines (3069 loc) · 109 KB
/
Copy pathConstantArrayType.php
File metadata and controls
3587 lines (3069 loc) · 109 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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php declare(strict_types = 1);
namespace PHPStan\Type\Constant;
use Nette\Utils\Strings;
use PHPStan\Analyser\OutOfClassScope;
use PHPStan\DependencyInjection\BleedingEdgeToggle;
use PHPStan\Php\PhpVersion;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode;
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode;
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeUnsealedTypeNode;
use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode;
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use PHPStan\Reflection\Callables\FunctionCallableVariant;
use PHPStan\Reflection\ClassMemberAccessAnswerer;
use PHPStan\Reflection\InaccessibleMethod;
use PHPStan\Reflection\InitializerExprTypeResolver;
use PHPStan\Reflection\PhpVersionStaticAccessor;
use PHPStan\Reflection\TrivialParametersAcceptor;
use PHPStan\Rules\Arrays\AllowedArrayKeysTypes;
use PHPStan\ShouldNotHappenException;
use PHPStan\TrinaryLogic;
use PHPStan\Type\AcceptsResult;
use PHPStan\Type\Accessory\AccessoryArrayListType;
use PHPStan\Type\Accessory\AccessoryLowercaseStringType;
use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
use PHPStan\Type\Accessory\AccessoryNonFalsyStringType;
use PHPStan\Type\Accessory\AccessoryNumericStringType;
use PHPStan\Type\Accessory\AccessoryUppercaseStringType;
use PHPStan\Type\Accessory\HasOffsetType;
use PHPStan\Type\Accessory\HasOffsetValueType;
use PHPStan\Type\Accessory\NonEmptyArrayType;
use PHPStan\Type\ArrayType;
use PHPStan\Type\BenevolentUnionType;
use PHPStan\Type\BooleanType;
use PHPStan\Type\ClassStringType;
use PHPStan\Type\CompoundType;
use PHPStan\Type\ConstantScalarType;
use PHPStan\Type\ErrorType;
use PHPStan\Type\GeneralizePrecision;
use PHPStan\Type\Generic\TemplateMixedType;
use PHPStan\Type\Generic\TemplateStrictMixedType;
use PHPStan\Type\Generic\TemplateType;
use PHPStan\Type\Generic\TemplateTypeMap;
use PHPStan\Type\Generic\TemplateTypeVariance;
use PHPStan\Type\IntegerRangeType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\IsSuperTypeOfResult;
use PHPStan\Type\MixedType;
use PHPStan\Type\NeverType;
use PHPStan\Type\NullType;
use PHPStan\Type\ObjectWithoutClassType;
use PHPStan\Type\RecursionGuard;
use PHPStan\Type\StaticTypeFactory;
use PHPStan\Type\StrictMixedType;
use PHPStan\Type\StringType;
use PHPStan\Type\Traits\ArrayTypeTrait;
use PHPStan\Type\Traits\NonObjectTypeTrait;
use PHPStan\Type\Traits\UndecidedComparisonTypeTrait;
use PHPStan\Type\Traverser\UnsafeArrayStringKeyCastingTraverser;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\UnionType;
use PHPStan\Type\VerbosityLevel;
use function array_key_exists;
use function array_keys;
use function array_map;
use function array_merge;
use function array_pop;
use function array_push;
use function array_slice;
use function array_unique;
use function array_values;
use function assert;
use function count;
use function implode;
use function in_array;
use function is_int;
use function is_string;
use function max;
use function min;
use function pow;
use function range;
use function sort;
use function sprintf;
use function str_contains;
use function strtolower;
use function strtoupper;
use function usort;
use const CASE_LOWER;
use const CASE_UPPER;
/**
* @api
*/
class ConstantArrayType implements Type
{
use ArrayTypeTrait {
chunkArray as traitChunkArray;
}
use NonObjectTypeTrait;
use UndecidedComparisonTypeTrait;
private const DESCRIBE_LIMIT = 8;
private const CHUNK_FINITE_TYPES_LIMIT = 5;
private const UNSEALED_ARRAY_SHAPES_LINK = 'https://phpstan.org/blog/phpstan-2-2-unsealed-array-shapes-safer-array-keys';
private TrinaryLogic $isList;
/** @var array{Type, Type}|null */
private ?array $unsealed; // phpcs:ignore
/** @var self[]|null */
private ?array $allArrays = null;
private ?Type $iterableKeyType = null;
private ?Type $iterableValueType = null;
private ?Type $keyTypesUnion = null;
/** @var array<int|string, int>|null */
private ?array $keyIndexMap = null;
/**
* @api
* @param list<ConstantIntegerType|ConstantStringType> $keyTypes
* @param array<int, Type> $valueTypes
* @param list<int> $nextAutoIndexes
* @param int[] $optionalKeys
* @param array{Type, Type}|null $unsealed
*/
public function __construct(
private array $keyTypes,
private array $valueTypes,
private array $nextAutoIndexes = [0],
private array $optionalKeys = [],
?TrinaryLogic $isList = null,
?array $unsealed = null,
)
{
assert(count($keyTypes) === count($valueTypes));
// Fill in `$isList` from the shape when the caller didn't pass one.
// For empty CATs the answer derives from the unsealed key type
// (no explicit keys to inspect); for non-empty ones the default
// is `No` and the caller is expected to assert list-ness via
// `makeList()` if appropriate.
if ($isList === null) {
if (count($this->keyTypes) === 0) {
if ($unsealed === null) {
$isList = TrinaryLogic::createYes();
} else {
[$unsealedKeyType] = $unsealed;
if ($unsealedKeyType instanceof NeverType && $unsealedKeyType->isExplicit()) {
$isList = TrinaryLogic::createYes();
} elseif ($unsealedKeyType->isInteger()->yes()) {
$isList = TrinaryLogic::createMaybe();
} else {
$isList = TrinaryLogic::createNo();
}
}
} else {
$isList = TrinaryLogic::createNo();
}
}
$this->isList = $isList;
if ($unsealed !== null) {
// Only a BenevolentUnionType describes with the surrounding parentheses of
// '(int|string)' / '(int|non-decimal-int-string)', so skip the describe() call
// for every other key type.
if ($unsealed[0] instanceof BenevolentUnionType && in_array($unsealed[0]->describe(VerbosityLevel::value()), ['(int|string)', '(int|non-decimal-int-string)'], true)) {
$unsealed[0] = new MixedType();
}
if ($unsealed[0] instanceof StrictMixedType && !$unsealed[0] instanceof TemplateStrictMixedType) {
$unsealed[0] = (new UnionType([new StringType(), new IntegerType()]))->toArrayKey();
}
if ($unsealed[0] instanceof NeverType && $unsealed[0]->isExplicit()) {
$unsealed[1] = new NeverType(true);
}
} elseif (BleedingEdgeToggle::isBleedingEdge()) {
$never = new NeverType(true);
$unsealed = [$never, $never];
}
$this->unsealed = $unsealed;
}
public function isSealed(): TrinaryLogic
{
return $this->isUnsealed()->negate();
}
public function isUnsealed(): TrinaryLogic
{
$unsealed = $this->unsealed;
if ($unsealed === null) {
return TrinaryLogic::createMaybe();
}
[$keyType] = $unsealed;
return TrinaryLogic::createFromBoolean(!$keyType instanceof NeverType || !$keyType->isExplicit());
}
/**
* @phpstan-pure
* @return array{Type, Type}|null
*/
public function getUnsealedTypes(): ?array
{
return $this->unsealed;
}
/**
* @internal
*/
public function dropUnsealedTypes(): self
{
return $this->recreate(
$this->keyTypes,
$this->valueTypes,
$this->nextAutoIndexes,
$this->optionalKeys,
$this->isList,
null,
);
}
/**
* @param list<ConstantIntegerType|ConstantStringType> $keyTypes
* @param array<int, Type> $valueTypes
* @param list<int> $nextAutoIndexes
* @param int[] $optionalKeys
* @param array{Type, Type}|null $unsealed
*/
protected function recreate(
array $keyTypes,
array $valueTypes,
array $nextAutoIndexes,
array $optionalKeys,
?TrinaryLogic $isList,
?array $unsealed,
): self
{
return new self($keyTypes, $valueTypes, $nextAutoIndexes, $optionalKeys, $isList, $unsealed);
}
public function getConstantArrays(): array
{
return [$this];
}
public function getReferencedClasses(): array
{
$referencedClasses = [];
foreach ($this->getKeyTypes() as $keyType) {
foreach ($keyType->getReferencedClasses() as $referencedClass) {
$referencedClasses[] = $referencedClass;
}
}
foreach ($this->getValueTypes() as $valueType) {
foreach ($valueType->getReferencedClasses() as $referencedClass) {
$referencedClasses[] = $referencedClass;
}
}
if ($this->unsealed !== null) {
[$unsealedKeyType, $unsealedValueType] = $this->unsealed;
foreach ($unsealedKeyType->getReferencedClasses() as $referencedClass) {
$referencedClasses[] = $referencedClass;
}
foreach ($unsealedValueType->getReferencedClasses() as $referencedClass) {
$referencedClasses[] = $referencedClass;
}
}
return $referencedClasses;
}
public function getIterableKeyType(): Type
{
if ($this->iterableKeyType !== null) {
return $this->iterableKeyType;
}
$keyTypesCount = count($this->keyTypes);
if ($keyTypesCount === 0) {
$keyType = new NeverType(true);
} elseif ($keyTypesCount === 1) {
$keyType = $this->keyTypes[0];
} else {
$keyType = new UnionType($this->keyTypes);
}
if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
$unsealedKeyType = $this->unsealed[0];
if ($unsealedKeyType instanceof MixedType && !$unsealedKeyType instanceof TemplateMixedType) {
$unsealedKeyType = (new BenevolentUnionType([new IntegerType(), new StringType()]))->toArrayKey();
} elseif ($unsealedKeyType instanceof StrictMixedType && !$unsealedKeyType instanceof TemplateStrictMixedType) {
$unsealedKeyType = (new BenevolentUnionType([new IntegerType(), new StringType()]))->toArrayKey();
}
$keyType = TypeCombinator::union($keyType, $unsealedKeyType);
}
return $this->iterableKeyType = UnsafeArrayStringKeyCastingTraverser::castKeyType($keyType);
}
public function getIterableValueType(): Type
{
if ($this->iterableValueType !== null) {
return $this->iterableValueType;
}
$valueType = count($this->valueTypes) > 0 ? TypeCombinator::union(...$this->valueTypes) : new NeverType(true);
if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
$valueType = TypeCombinator::union($valueType, $this->unsealed[1]);
}
return $this->iterableValueType = $valueType;
}
private function getKeyTypesUnion(): Type
{
return $this->keyTypesUnion ??= count($this->keyTypes) > 0
? TypeCombinator::union(...$this->keyTypes)
: new NeverType();
}
public function getKeyType(): Type
{
return $this->getIterableKeyType();
}
public function getItemType(): Type
{
return $this->getIterableValueType();
}
public function isConstantValue(): TrinaryLogic
{
if ($this->isUnsealed()->yes()) {
return TrinaryLogic::createNo();
}
return TrinaryLogic::createYes();
}
/**
* @return list<int>
*/
public function getNextAutoIndexes(): array
{
return $this->nextAutoIndexes;
}
/**
* @return int[]
*/
public function getOptionalKeys(): array
{
return $this->optionalKeys;
}
/**
* @return self[]
*/
public function getAllArrays(): array
{
if ($this->allArrays !== null) {
return $this->allArrays;
}
if (count($this->optionalKeys) <= 10) {
$optionalKeysCombinations = $this->powerSet($this->optionalKeys);
} else {
$optionalKeysCombinations = [
[],
array_slice($this->optionalKeys, 0, 1, true),
array_slice($this->optionalKeys, -1, 1, true),
$this->optionalKeys,
];
}
$requiredKeys = [];
foreach (array_keys($this->keyTypes) as $i) {
if (in_array($i, $this->optionalKeys, true)) {
continue;
}
$requiredKeys[] = $i;
}
$arrays = [];
foreach ($optionalKeysCombinations as $combination) {
$keys = array_merge($requiredKeys, $combination);
sort($keys);
if ($this->isList->yes() && array_keys($keys) !== $keys) {
continue;
}
if (count($keys) === 0 && $this->isUnsealed()->yes() && $this->unsealed !== null) {
// Variant with no explicit keys but real unsealed extras: the
// builder's getArray() would degrade this to a general
// ArrayType. Construct the CAT directly so the variant keeps
// its extras for downstream consumers (e.g. flattenTypes).
$arrays[] = new ConstantArrayType([], [], unsealed: $this->unsealed);
continue;
}
$builder = ConstantArrayTypeBuilder::createEmpty();
$builder->disableArrayDegradation();
foreach ($keys as $i) {
$builder->setOffsetValueType($this->keyTypes[$i], $this->valueTypes[$i]);
}
if ($this->isUnsealed()->yes() && $this->unsealed !== null) {
$builder->makeUnsealed($this->unsealed[0], $this->unsealed[1]);
}
$array = $builder->getArray();
if (!$array instanceof self) {
throw new ShouldNotHappenException();
}
$arrays[] = $array;
}
return $this->allArrays = $arrays;
}
/**
* @template T
* @param T[] $in
* @return T[][]
*/
private function powerSet(array $in): array
{
$count = count($in);
$members = pow(2, $count);
$return = [];
for ($i = 0; $i < $members; $i++) {
$b = sprintf('%0' . $count . 'b', $i);
$out = [];
for ($j = 0; $j < $count; $j++) {
if ($b[$j] !== '1') {
continue;
}
$out[] = $in[$j];
}
$return[] = $out;
}
return $return;
}
/**
* @return list<ConstantIntegerType|ConstantStringType>
*/
public function getKeyTypes(): array
{
return $this->keyTypes;
}
/**
* @return array<int, Type>
*/
public function getValueTypes(): array
{
return $this->valueTypes;
}
public function isOptionalKey(int $i): bool
{
return in_array($i, $this->optionalKeys, true);
}
public function sortKeys(): self
{
$indices = array_keys($this->keyTypes);
usort($indices, fn (int $a, int $b): int => $this->keyTypes[$a]->getValue() <=> $this->keyTypes[$b]->getValue());
$newKeyTypes = [];
$newValueTypes = [];
$indexMap = [];
foreach ($indices as $newIdx => $oldIdx) {
$newKeyTypes[] = $this->keyTypes[$oldIdx];
$newValueTypes[] = $this->valueTypes[$oldIdx];
$indexMap[$oldIdx] = $newIdx;
}
$newOptionalKeys = [];
foreach ($this->optionalKeys as $oldIdx) {
$newOptionalKeys[] = $indexMap[$oldIdx];
}
sort($newOptionalKeys);
return $this->recreate(
$newKeyTypes,
$newValueTypes,
$this->nextAutoIndexes,
$newOptionalKeys,
$this->isList,
$this->unsealed,
);
}
public function accepts(Type $type, bool $strictTypes): AcceptsResult
{
if ($type instanceof CompoundType && !$type instanceof IntersectionType) {
return $type->isAcceptedBy($this, $strictTypes);
}
$isUnsealed = $this->isUnsealed();
if (!$isUnsealed->yes()) {
if ($type instanceof self && count($this->keyTypes) === 0) {
return AcceptsResult::createFromBoolean(count($type->keyTypes) === 0);
}
}
$result = $this->checkOurKeys($type, $strictTypes)->and(new AcceptsResult($type->isArray(), []));
if ($this->unsealed === null) {
if ($type->isOversizedArray()->yes()) {
if (!$result->no()) {
return AcceptsResult::createYes();
}
}
return $result;
}
if ($result->no()) {
return $result;
}
[$unsealedKeyType, $unsealedValueType] = $this->unsealed;
if ($isUnsealed->no()) {
if (!$type->isConstantArray()->yes()) {
return $result->and(AcceptsResult::createNo([
'Sealed array shape can only accept a constant array. Extra keys are not allowed.',
]));
}
$constantArrays = $type->getConstantArrays();
if (count($constantArrays) !== 1) {
throw new ShouldNotHappenException('Type with more than one constant array occurred, should have been eliminated with `instanceof CompoundType` above.');
}
$keys = [];
foreach ($constantArrays[0]->getKeyTypes() as $otherKeyType) {
$keys[$otherKeyType->getValue()] = $otherKeyType;
}
foreach ($this->keyTypes as $keyType) {
unset($keys[$keyType->getValue()]);
}
foreach ($keys as $extraKey) {
$result = $result->and(AcceptsResult::createNo([
sprintf('Sealed array shape does not accept array with extra key %s.', $extraKey->describe(VerbosityLevel::precise())),
]));
}
if (!$constantArrays[0]->isUnsealed()->no()) {
$result = $result->and(AcceptsResult::createNo([
'Sealed array shape does not accept unsealed array shape.',
]));
}
return $result;
}
if (!$type->isConstantArray()->yes()) {
return $result->and($unsealedKeyType->accepts($type->getIterableKeyType(), $strictTypes))
->and($unsealedValueType->accepts($type->getIterableValueType(), $strictTypes));
}
$constantArrays = $type->getConstantArrays();
if (count($constantArrays) !== 1) {
throw new ShouldNotHappenException('Type with more than one constant array occurred, should have been eliminated with `instanceof CompoundType` above.');
}
$keys = [];
$constantArray = $constantArrays[0];
foreach ($constantArray->getKeyTypes() as $i => $otherKeyType) {
$keys[$otherKeyType->getValue()] = [$i, $otherKeyType];
}
foreach ($this->keyTypes as $keyType) {
unset($keys[$keyType->getValue()]);
}
foreach ($keys as [$i, $extraKeyType]) {
$acceptsKey = $unsealedKeyType->accepts($extraKeyType, $strictTypes)->decorateReasons(
static fn (string $reason) => sprintf(
'Unsealed array key type %s does not accept extra key type %s: %s',
$unsealedKeyType->describe(VerbosityLevel::value()),
$extraKeyType->describe(VerbosityLevel::value()),
$reason,
),
);
if (!$acceptsKey->yes() && count($acceptsKey->reasons) === 0) {
$acceptsKey = new AcceptsResult($acceptsKey->result, [
sprintf(
'Unsealed array key type %s does not accept extra key type %s.',
$unsealedKeyType->describe(VerbosityLevel::value()),
$extraKeyType->describe(VerbosityLevel::value()),
),
]);
}
$result = $result->and($acceptsKey);
$extraValueType = $constantArray->getValueTypes()[$i];
$acceptsValue = $unsealedValueType->accepts($extraValueType, $strictTypes)->decorateReasons(
static fn (string $reason) => sprintf(
'Unsealed array value type %s does not accept extra offset %s with value type %s: %s',
$unsealedValueType->describe(VerbosityLevel::value()),
$extraKeyType->describe(VerbosityLevel::value()),
$extraValueType->describe(VerbosityLevel::value()),
$reason,
),
);
if (!$acceptsValue->yes() && count($acceptsValue->reasons) === 0) {
$acceptsValue = new AcceptsResult($acceptsValue->result, [
sprintf(
'Unsealed array value type %s does not accept extra offset %s with value type %s.',
$unsealedValueType->describe(VerbosityLevel::value()),
$extraKeyType->describe(VerbosityLevel::value()),
$extraValueType->describe(VerbosityLevel::value()),
),
]);
}
$result = $result->and($acceptsValue);
}
$otherUnsealed = $constantArray->unsealed;
if ($otherUnsealed !== null && !$constantArray->isUnsealed()->no()) {
[$otherUnsealedKeyType, $otherUnsealedValueType] = $otherUnsealed;
$acceptsUnsealedKey = $unsealedKeyType->accepts($otherUnsealedKeyType, $strictTypes)->decorateReasons(
static fn (string $reason) => sprintf(
'Unsealed array key type %s does not accept unsealed array key type %s: %s',
$unsealedKeyType->describe(VerbosityLevel::value()),
$otherUnsealedKeyType->describe(VerbosityLevel::value()),
$reason,
),
);
if (!$acceptsUnsealedKey->yes() && count($acceptsUnsealedKey->reasons) === 0) {
$acceptsUnsealedKey = new AcceptsResult($acceptsUnsealedKey->result, [
sprintf(
'Unsealed array key type %s does not accept unsealed array key type %s.',
$unsealedKeyType->describe(VerbosityLevel::value()),
$otherUnsealedKeyType->describe(VerbosityLevel::value()),
),
]);
}
$result = $result->and($acceptsUnsealedKey);
$acceptsUnsealedValue = $unsealedValueType->accepts($otherUnsealedValueType, $strictTypes)->decorateReasons(
static fn (string $reason) => sprintf(
'Unsealed array value type %s does not accept unsealed array value type %s: %s',
$unsealedValueType->describe(VerbosityLevel::value()),
$otherUnsealedValueType->describe(VerbosityLevel::value()),
$reason,
),
);
if (!$acceptsUnsealedValue->yes() && count($acceptsUnsealedValue->reasons) === 0) {
$acceptsUnsealedValue = new AcceptsResult($acceptsUnsealedValue->result, [
sprintf(
'Unsealed array value type %s does not accept unsealed array value type %s.',
$unsealedValueType->describe(VerbosityLevel::value()),
$otherUnsealedValueType->describe(VerbosityLevel::value()),
),
]);
}
$result = $result->and($acceptsUnsealedValue);
}
return $result;
}
private function checkOurKeys(Type $type, bool $strictTypes): AcceptsResult
{
$result = AcceptsResult::createYes();
foreach ($this->keyTypes as $i => $keyType) {
$valueType = $this->valueTypes[$i];
$hasOffsetValueType = $type->hasOffsetValueType($keyType);
$hasOffset = new AcceptsResult(
$hasOffsetValueType,
$hasOffsetValueType->yes() || !$type->isConstantArray()->yes() ? [] : [sprintf('Array %s have offset %s.', $hasOffsetValueType->no() ? 'does not' : 'might not', $keyType->describe(VerbosityLevel::value()))],
);
if ($hasOffset->no()) {
if ($this->isOptionalKey($i)) {
continue;
}
return $hasOffset;
}
if ($hasOffset->maybe() && $this->isOptionalKey($i)) {
$hasOffset = AcceptsResult::createYes();
}
$result = $result->and($hasOffset);
$otherValueType = $type->getOffsetValueType($keyType);
$verbosity = VerbosityLevel::getRecommendedLevelByType($valueType, $otherValueType);
$acceptsValue = $valueType->accepts($otherValueType, $strictTypes)->decorateReasons(
static fn (string $reason) => sprintf(
'Offset %s (%s) does not accept type %s: %s',
$keyType->describe(VerbosityLevel::precise()),
$valueType->describe($verbosity),
$otherValueType->describe($verbosity),
$reason,
),
);
if (!$acceptsValue->yes() && count($acceptsValue->reasons) === 0 && $type->isConstantArray()->yes()) {
$acceptsValue = new AcceptsResult($acceptsValue->result, [
sprintf(
'Offset %s (%s) does not accept type %s.',
$keyType->describe(VerbosityLevel::precise()),
$valueType->describe($verbosity),
$otherValueType->describe($verbosity),
),
]);
}
if ($acceptsValue->no()) {
return $acceptsValue;
}
$result = $result->and($acceptsValue);
}
return $result;
}
public function isSuperTypeOf(Type $type): IsSuperTypeOfResult
{
if ($type instanceof self) {
$thisUnsealedness = $this->isUnsealed();
$typeUnsealedness = $type->isUnsealed();
$bothDefinite = $this->unsealed !== null && $type->unsealed !== null;
if (count($this->keyTypes) === 0) {
if (!$bothDefinite) {
return new IsSuperTypeOfResult($type->isIterableAtLeastOnce()->negate(), []);
}
if ($thisUnsealedness->no()) {
return new IsSuperTypeOfResult($type->isIterableAtLeastOnce()->negate(), []);
}
// $this is unsealed with no known keys — fall through to extras/unsealed-part checks below
}
$results = [];
foreach ($this->keyTypes as $i => $keyType) {
$hasOffset = $type->hasOffsetValueType($keyType);
if ($bothDefinite && $hasOffset->no() && $typeUnsealedness->yes()) {
[$typeUnsealedKey] = $type->unsealed;
if (!$typeUnsealedKey->isSuperTypeOf($keyType)->no()) {
$hasOffset = TrinaryLogic::createMaybe();
}
}
if ($hasOffset->no()) {
if (!$this->isOptionalKey($i)) {
if ($thisUnsealedness->no() && $typeUnsealedness->no()) {
return IsSuperTypeOfResult::createNo(lazyReasons: [fn (): string => $this->sealedArrayShapesCannotBeIntersectedReason($type)]);
}
return IsSuperTypeOfResult::createNo();
}
$results[] = IsSuperTypeOfResult::createYes();
continue;
} elseif ($hasOffset->maybe() && !$this->isOptionalKey($i)) {
$results[] = IsSuperTypeOfResult::createMaybe();
}
$otherValueType = $type->getOffsetValueType($keyType);
if ($otherValueType instanceof ErrorType && $bothDefinite && $typeUnsealedness->yes()) {
[, $typeUnsealedValue] = $type->unsealed;
$otherValueType = $typeUnsealedValue;
}
$isValueSuperType = $this->valueTypes[$i]->isSuperTypeOf($otherValueType);
if ($isValueSuperType->no()) {
return $isValueSuperType->decorateReasons(static fn (string $reason) => sprintf('Offset %s: %s', $keyType->describe(VerbosityLevel::value()), $reason));
}
$results[] = $isValueSuperType;
}
if ($bothDefinite) {
$thisKeyValues = [];
foreach ($this->keyTypes as $thisKeyType) {
$thisKeyValues[$thisKeyType->getValue()] = true;
}
foreach ($type->getKeyTypes() as $i => $typeKey) {
if (array_key_exists($typeKey->getValue(), $thisKeyValues)) {
continue;
}
if ($thisUnsealedness->no()) {
if (!$type->isOptionalKey($i)) {
if ($typeUnsealedness->no()) {
return IsSuperTypeOfResult::createNo(lazyReasons: [fn (): string => $this->sealedArrayShapesCannotBeIntersectedReason($type)]);
}
return IsSuperTypeOfResult::createNo();
}
$results[] = IsSuperTypeOfResult::createMaybe();
continue;
}
[$thisUnsealedKey, $thisUnsealedValue] = $this->unsealed;
$keyCheck = $thisUnsealedKey->isSuperTypeOf($typeKey);
if ($keyCheck->no()) {
if ($type->isOptionalKey($i)) {
$results[] = IsSuperTypeOfResult::createMaybe();
continue;
}
return IsSuperTypeOfResult::createNo();
}
$valueCheck = $thisUnsealedValue->isSuperTypeOf($type->getValueTypes()[$i]);
if ($valueCheck->no()) {
if ($type->isOptionalKey($i)) {
$results[] = IsSuperTypeOfResult::createMaybe();
continue;
}
return IsSuperTypeOfResult::createNo();
}
$results[] = $keyCheck->and($valueCheck);
}
if ($typeUnsealedness->yes()) {
if ($thisUnsealedness->no()) {
$results[] = IsSuperTypeOfResult::createMaybe();
} else {
[$thisUnsealedKey, $thisUnsealedValue] = $this->unsealed;
[$typeUnsealedKey, $typeUnsealedValue] = $type->unsealed;
$results[] = $thisUnsealedKey->isSuperTypeOf($typeUnsealedKey);
$results[] = $thisUnsealedValue->isSuperTypeOf($typeUnsealedValue);
}
}
}
return IsSuperTypeOfResult::createYes()->and(...$results);
}
if ($type instanceof ArrayType) {
$result = IsSuperTypeOfResult::createMaybe();
if (count($this->keyTypes) === 0) {
return $result;
}
$isKeySuperType = $this->getKeyType()->isSuperTypeOf($type->getKeyType());
if ($isKeySuperType->no()) {
return $isKeySuperType;
}
return $result->and($isKeySuperType, $this->getItemType()->isSuperTypeOf($type->getItemType()));
}
if ($type instanceof CompoundType) {
return $type->isSubTypeOf($this);
}
return IsSuperTypeOfResult::createNo();
}
/**
* Passed as a lazy reason to IsSuperTypeOfResult so the expensive describe() calls only
* run when the reason is actually rendered, never during the hot isSuperTypeOf()
* comparisons whose reasons are discarded.
*/
private function sealedArrayShapesCannotBeIntersectedReason(self $type): string
{
return sprintf(
'Sealed array shapes %s and %s cannot be intersected. Unseal at least one of them with ... syntax. Learn more: %s',
$this->describe(VerbosityLevel::value()),
$type->describe(VerbosityLevel::value()),
self::UNSEALED_ARRAY_SHAPES_LINK,
);
}
public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
{
if ($type->isInteger()->yes()) {
return new ConstantBooleanType(false);
}
if ($this->isIterableAtLeastOnce()->no()) {
if ($type->isIterableAtLeastOnce()->yes()) {
return new ConstantBooleanType(false);
}
$constantScalarValues = $type->getConstantScalarValues();
if (count($constantScalarValues) > 0) {
$results = [];
foreach ($constantScalarValues as $constantScalarValue) {
// @phpstan-ignore equal.invalid, equal.notAllowed
$results[] = TrinaryLogic::createFromBoolean($constantScalarValue == []); // phpcs:ignore
}
return TrinaryLogic::extremeIdentity(...$results)->toBooleanType();
}
}
return new BooleanType();
}
public function equals(Type $type): bool
{
if (!$type instanceof self) {
return false;
}
if (count($this->keyTypes) !== count($type->keyTypes)) {
return false;
}
foreach ($this->keyTypes as $i => $keyType) {
$valueType = $this->valueTypes[$i];
if (!$valueType->equals($type->valueTypes[$i])) {
return false;
}
if (!$keyType->equals($type->keyTypes[$i])) {
return false;
}
}
if ($this->optionalKeys !== $type->optionalKeys) {
return false;
}
// Both `unsealed === null` (legacy / pre-bleeding-edge, where
// `isUnsealed()` answers `Maybe`) and `unsealed === [explicitNever,
// explicitNever]` (the fresh bleeding-edge sealed marker, where
// `isUnsealed()` answers `No`) mean "no real extras". Treat them as
// equivalent here — use `!isUnsealed()->yes()` rather than
// `isUnsealed()->no()`, otherwise a legacy-null shape and a
// marker-sealed shape compare unequal. Only compare the actual
// extras when both sides genuinely have them.
$thisHasExtras = $this->isUnsealed()->yes();
$otherHasExtras = $type->isUnsealed()->yes();
if ($thisHasExtras !== $otherHasExtras) {
return false;
}
if ($thisHasExtras && $this->unsealed !== null && $type->unsealed !== null) {
if (!$this->unsealed[0]->equals($type->unsealed[0])) {
return false;
}
if (!$this->unsealed[1]->equals($type->unsealed[1])) {
return false;
}
}
return true;
}
public function isCallable(): TrinaryLogic
{
$result = RecursionGuard::run($this, function (): TrinaryLogic {
$hasNonExistentMethod = false;
$typeAndMethods = $this->doFindTypeAndMethodNames($hasNonExistentMethod);
if ($typeAndMethods === []) {
return TrinaryLogic::createNo();
}
$results = array_map(
static fn (ConstantArrayTypeAndMethod $typeAndMethod): TrinaryLogic => $typeAndMethod->getCertainty(),
$typeAndMethods,
);
$result = TrinaryLogic::createYes()->and(...$results);
if ($hasNonExistentMethod) {
$result = $result->and(TrinaryLogic::createMaybe());
}
return $result;
});
if ($result instanceof ErrorType) {
return TrinaryLogic::createNo();
}
return $result;
}
public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
{
$typeAndMethodNames = $this->findTypeAndMethodNames();
if ($typeAndMethodNames === []) {
throw new ShouldNotHappenException();
}
$acceptors = [];
foreach ($typeAndMethodNames as $typeAndMethodName) {
if ($typeAndMethodName->isUnknown() || !$typeAndMethodName->getCertainty()->yes()) {