Repository navigation
Expand file tree
/
Copy pathConstantArrayType.cpp
More file actions
7648 lines (6907 loc) · 324 KB
/
Copy pathConstantArrayType.cpp
File metadata and controls
7648 lines (6907 loc) · 324 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
/*
* PHPStanTurbo\ConstantArrayType — native implementation of
* PHPStan\Type\Constant\ConstantArrayType, the array-shape type.
*
* Declared as PHPStan\Type\Constant\ConstantArrayType itself at activation:
* not final (the PHP TemplateConstantArrayType extends it, overriding
* recreate() and the TemplateTypeTrait methods), implementing
* PHPStan\Type\Type. State is the twin's twelve private properties, declared
* typed property slots in the twin's order — $isList, $unsealed, the six
* memos ($allArrays, $iterableKeyType, $iterableValueType, $keyTypesUnion,
* $keyIndexMap, $optionalKeySet) and the four promoted constructor properties ($keyTypes,
* $valueTypes, $nextAutoIndexes, $optionalKeys) — so the std object
* handlers do GC/clone. The three traits the twin is composed of come from
* the shared registrars in TypeTraits.cpp, run after the class's own
* methods so the class body wins over the traits exactly as in PHP; the
* `chunkArray as traitChunkArray` alias is registered under its alias name
* with the trait's handler.
*
* Every `$this->method()` the twin makes on a public or protected method
* goes through the object's class entry — a subclass may have overridden it
* — with a direct C++ call when the object is exactly a ConstantArrayType
* (or still carries the native method); `new self(...)` and `self::`
* statics are always this class. The private slots of another instance
* (`$type->keyTypes`, `$type->unsealed`) are read directly, as the twin
* does from inside the class. The twin's closures (RecursionGuard's
* callback, the decorateReasons() formatters, the lazy reason) are native
* bodies behind pt_type_native_callback() / pt_carr_native_closure()
* (TypeTraits.cpp).
*/
#include "TypeTraits.h"
#include "generated/ConstantArrayType.h"
namespace slots = ptdecl::ConstantArrayType::slot;
namespace sigs = ptdecl::ConstantArrayType::sig;
zend_class_entry *pt_ce_constant_array_type = nullptr;
/* AcceptsResult.cpp: new <result class>($trinary, $reasons, $lazyReasons) */
bool pt_result_object_create(zval *out, zend_class_entry *ce, zval *trinary, zval *reasons, zval *lazyReasons);
/* the twin's private constants */
#define PT_CAT_DESCRIBE_LIMIT 8
#define PT_CAT_CHUNK_FINITE_TYPES_LIMIT 5
#define PT_CAT_UNSEALED_ARRAY_SHAPES_LINK "https://phpstan.org/blog/phpstan-2-2-unsealed-array-shapes-safer-array-keys"
/* the twin's inline thresholds: getAllArrays() enumerates the power set of
* up to this many optional keys, generalize() keeps per-offset accessories
* below this many required keys */
#define PT_CAT_POWER_SET_OPTIONAL_KEYS_LIMIT 10
#define PT_CAT_GENERALIZE_OFFSET_ACCESSORIES_LIMIT 32
/* PHP's CASE_LOWER / CASE_UPPER */
#define PT_CAT_CASE_LOWER 0
#define PT_CAT_CASE_UPPER 1
/* isValidIdentifier()'s pattern (a permanent interned string, made at
* MINIT) and the internal preg_match() / preg_last_error() it is matched
* with (internal functions, resolved once; the pcre extension caches the
* compiled pattern per request) */
static zend_string *pt_carr_identifier_regex = nullptr;
static zend_function *pt_carr_preg_match = nullptr;
static zend_function *pt_carr_preg_last_error = nullptr;
namespace phpstanturbo {
/* the instanceof checks the twin makes, as helpers: a class-map class
* (false = pending exception) or a shadowed class the native code holds */
[[nodiscard]] static bool isInstance(zval *value, int classIdx, bool &out)
{
return pt_type_instanceof(value, classIdx, out);
}
static bool isInstance(zval *value, zend_class_entry *ce, bool &out)
{
out = Z_TYPE_P(value) == IS_OBJECT && instanceof_function(Z_OBJCE_P(value), ce);
return true;
}
/* TypeCombinator::<method>($a, $b); UNDEF = pending exception */
static zv::Val combinator2(const char *lcname, size_t len, zval *a, zval *b)
{
zv::Args args{a, b};
return pt_type_combinator_call(lcname, len, 2, args);
}
/* TypeCombinator::<method>(...$types) over an owned array */
static zv::Val combinatorSpread(const char *lcname, size_t len, HashTable *types)
{
return pt_type_combinator_call_spread(lcname, len, types);
}
/* new IntersectionType($types) ($types consumed) */
static zv::Val intersection(zv::Arr types)
{
return pt_intersection_of(std::move(types));
}
/* the shadowed classes' constructors as owned values; UNDEF = pending
* exception */
static zv::Val nonEmptyArray()
{
return pt_val_of<pt_non_empty_array_type_new>();
}
static zv::Val accessoryList()
{
return pt_val_of<pt_accessory_array_list_type_new>();
}
static zv::Val integerType()
{
return pt_val_of<pt_integer_type_new>();
}
static zv::Val stringType()
{
return pt_val_of<pt_string_type_new>();
}
static zv::Val classStringType()
{
return pt_val_of<pt_class_string_type_new>();
}
static zv::Val objectWithoutClassType()
{
return pt_type_new_object_without_class_type();
}
static zv::Val constantBoolean(bool value)
{
zval result;
if (UNEXPECTED(!pt_constant_boolean_type_new(&result, value))) return zv::Val();
return zv::Val::adopt(result);
}
static zv::Val booleanType()
{
return pt_val_of<pt_boolean_type_new>();
}
/* new NeverType($isExplicit) */
static zv::Val neverType(bool isExplicit = false)
{
zval result;
if (UNEXPECTED(!pt_never_type_new(&result, isExplicit))) return zv::Val();
return zv::Val::adopt(result);
}
static zv::Val nullType()
{
return pt_val_of<pt_null_type_new>();
}
/* new ConstantStringType($owned) — the owned string released */
static zv::Val constantStringOf(zend_string *owned)
{
zval result;
bool created = pt_constant_string_type_new(&result, owned);
zend_string_release(owned);
if (UNEXPECTED(!created)) return zv::Val();
return zv::Val::adopt(result);
}
/* new ArrayType($keyType, $itemType) */
static zv::Val arrayType(zval *keyType, zval *itemType)
{
zval result;
if (UNEXPECTED(!pt_array_type_new(&result, keyType, itemType))) return zv::Val();
return zv::Val::adopt(result);
}
/* new HasOffsetValueType($offsetType, $valueType) */
static zv::Val newHasOffsetValueType(zval *offsetType, zval *valueType)
{
zval result;
if (UNEXPECTED(!pt_has_offset_value_type_new(&result, offsetType, valueType))) return zv::Val();
return zv::Val::adopt(result);
}
/* $object->method(...) that returns a Type: the result checked to be an
* object (the engine's return check of the PHP twin); UNDEF = pending
* exception */
static zv::Val callType(zend_object *object, const char *lcname, size_t len, uint32_t argc, zval *argv)
{
return pt_type_call_type(object, lcname, len, argc, argv);
}
/* $object->method(...) returning string; UNDEF = pending exception */
static zv::Val callString(zend_object *object, const char *lcname, size_t len, uint32_t argc, zval *argv)
{
zv::Val result = pt_type_call(object, lcname, len, argc, argv);
if (UNEXPECTED(result.isUndef())) return zv::Val();
if (UNEXPECTED(!zv::Ref(result.raw()).isString())) {
zend_type_error("phpstan_turbo: %s::%s() must return string, %s returned", ZSTR_VAL(object->ce->name), lcname, zend_zval_value_name(result.raw()));
return zv::Val();
}
return result;
}
/* $a->isSuperTypeOf($b)'s trinary value; -1 = pending exception */
[[nodiscard]] static zend_long isSuperTypeOfValue(zval *a, zval *b)
{
return pt_type_call_result_trinary(Z_OBJ_P(a), PT_LC("issupertypeof"), 1, b);
}
/* $type->describe($level) as an owned string; UNDEF = pending exception */
static zv::Val describeOf(zval *type, zval *level)
{
return callString(Z_OBJ_P(type), PT_LC("describe"), 1, level);
}
/* VerbosityLevel::value() (the shadowing class's singleton, VerbosityLevel.cpp) */
static zv::Val verbosityValue()
{
return pt_type_verbosity_level(PT_VERBOSITY_LEVEL_VALUE);
}
/* $type->describe(VerbosityLevel::value()) / (VerbosityLevel::precise()) */
static zv::Val describeValue(zval *type)
{
zv::Val level = verbosityValue();
if (UNEXPECTED(level.isUndef())) return zv::Val();
return describeOf(type, level.raw());
}
static zv::Val describePrecise(zval *type)
{
zval description;
if (UNEXPECTED(!pt_type_describe_precise(type, &description))) return zv::Val();
if (UNEXPECTED(Z_TYPE(description) != IS_STRING)) {
zval_ptr_dtor(&description);
zend_type_error("phpstan_turbo: describe() must return string");
return zv::Val();
}
return zv::Val::adopt(description);
}
/* $type instanceof MixedType && $type->describe(VerbosityLevel::precise()) === 'mixed' && !$type->isExplicitMixed();
* false = pending exception */
[[nodiscard]] static bool isImplicitMixed(zval *type, bool &out)
{
bool isMixed;
if (UNEXPECTED(!isInstance(type, pt_ce_mixed_type, isMixed))) return false;
if (!isMixed) {
out = false;
return true;
}
zv::Val description = describePrecise(type);
if (UNEXPECTED(description.isUndef())) return false;
if (!zv::Ref(description.raw()).stringEquals("mixed")) {
out = false;
return true;
}
zv::Val explicitMixed = pt_type_call(Z_OBJ_P(type), PT_LC("isexplicitmixed"), 0, NULL);
if (UNEXPECTED(explicitMixed.isUndef())) return false;
out = !zend_is_true(explicitMixed.raw());
return true;
}
/* $type instanceof NeverType && $type->isExplicit(); false = pending
* exception */
[[nodiscard]] static bool isExplicitNever(zval *type, bool &out)
{
if (Z_TYPE_P(type) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(type), pt_ce_never_type)) {
out = false;
return true;
}
return pt_never_type_is_explicit(Z_OBJ_P(type), out);
}
/* (new BenevolentUnionType([new IntegerType(), new StringType()]))->toArrayKey() */
static zv::Val benevolentArrayKey()
{
zv::Val integer = integerType();
zv::Val string = stringType();
if (UNEXPECTED(integer.isUndef() || string.isUndef())) return zv::Val();
zv::Arr types = zv::Arr::create(2);
types.push(std::move(integer));
types.push(std::move(string));
zv::Val benevolent = pt_union_benevolent_of(std::move(types));
if (UNEXPECTED(benevolent.isUndef())) return zv::Val();
return callType(Z_OBJ_P(benevolent.raw()), PT_LC("toarraykey"), 0, NULL);
}
/* the unsealed key type the iterable-key methods substitute: a MixedType
* (not a TemplateMixedType) or a StrictMixedType (not a
* TemplateStrictMixedType) becomes (int|string)->toArrayKey(); an owned
* value either way; UNDEF = pending exception */
static zv::Val substituteMixedUnsealedKey(zval *unsealedKeyType)
{
bool isMixed;
if (UNEXPECTED(!isInstance(unsealedKeyType, pt_ce_mixed_type, isMixed))) return zv::Val();
if (isMixed) {
bool isTemplateMixed;
if (UNEXPECTED(!isInstance(unsealedKeyType, pt_ce_template_mixed_type, isTemplateMixed))) return zv::Val();
if (!isTemplateMixed) return benevolentArrayKey();
return zv::Val::copyOf(zv::Ref(unsealedKeyType));
}
bool isStrictMixed;
if (UNEXPECTED(!isInstance(unsealedKeyType, pt_ce_strict_mixed_type, isStrictMixed))) return zv::Val();
if (isStrictMixed) {
bool isTemplateStrictMixed;
if (UNEXPECTED(!isInstance(unsealedKeyType, pt_ce_template_strict_mixed_type, isTemplateStrictMixed))) return zv::Val();
if (!isTemplateStrictMixed) return benevolentArrayKey();
}
return zv::Val::copyOf(zv::Ref(unsealedKeyType));
}
/* ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT — the shadowed class's
* constant, shared as a native constant */
static bool arrayCountLimit(zend_long &out)
{
out = PT_CONSTANT_ARRAY_TYPE_BUILDER_ARRAY_COUNT_LIMIT;
return true;
}
/* InitializerExprTypeResolver::CALCULATE_SCALARS_LIMIT — the shadowed
* class's constant, shared as a native constant */
static bool calculateScalarsLimit(zend_long &out)
{
out = PT_INITIALIZER_EXPR_TYPE_RESOLVER_CALCULATE_SCALARS_LIMIT;
return true;
}
/* BleedingEdgeToggle::isBleedingEdge(): the private static the final class
* returns, read through the engine's static-property path under the
* class's own scope (the same value the method returns, without the
* userland frame); false = pending exception */
[[nodiscard]] static bool isBleedingEdge(bool &out)
{
zend_class_entry *ce = pt_class(PT_CLASS_BLEEDING_EDGE_TOGGLE);
if (UNEXPECTED(ce == NULL)) return false;
auto previousScope = EG(fake_scope); /* const from PHP 8.4 */
EG(fake_scope) = ce;
zval *value = zend_read_static_property(ce, PT_LC("bleedingEdge"), 1);
EG(fake_scope) = previousScope;
if (EXPECTED(value != NULL && (Z_TYPE_P(value) == IS_TRUE || Z_TYPE_P(value) == IS_FALSE))) {
out = Z_TYPE_P(value) == IS_TRUE;
return true;
}
if (UNEXPECTED(EG(exception))) return false;
zv::Val result = pt_type_call_static(PT_CLASS_BLEEDING_EDGE_TOGGLE, PT_LC("isbleedingedge"), 0, NULL);
if (UNEXPECTED(result.isUndef())) return false;
out = zend_is_true(result.raw());
return true;
}
/* $array[$index]; NULL with an Error pending when absent — the twin's
* read of a missing index warns and then fails on the null */
[[nodiscard]] static zval *arrayIndex(zval *array, zend_long index, const char *what)
{
zval *found = zend_hash_index_find(Z_ARRVAL_P(array), (zend_ulong) index);
if (UNEXPECTED(found == NULL)) {
zend_throw_error(NULL, "phpstan_turbo: undefined array key " ZEND_LONG_FMT " in %s", index, what);
return NULL;
}
ZVAL_DEREF(found);
return found;
}
/* a Type held by an array slot; NULL with an Error pending otherwise */
[[nodiscard]] static zval *arrayIndexObject(zval *array, zend_long index, const char *what)
{
zval *found = arrayIndex(array, index, what);
if (UNEXPECTED(found != NULL && Z_TYPE_P(found) != IS_OBJECT)) {
zend_throw_error(NULL, "phpstan_turbo: %s[" ZEND_LONG_FMT "] must be a %s, %s given", what, index, ptcls::type, zend_zval_value_name(found));
return NULL;
}
return found;
}
/* count($array) */
static zend_long arrayCount(zval *array)
{
return (zend_long) zend_hash_num_elements(Z_ARRVAL_P(array));
}
/* in_array($needle, $haystack, true) for an int needle */
static bool inArrayStrictLong(zval *haystack, zend_long needle)
{
for (zv::ArrayEntry entry : zv::ArrRef(haystack)) {
zval *value = entry.value().deref().raw();
if (Z_TYPE_P(value) == IS_LONG && Z_LVAL_P(value) == needle) return true;
}
return false;
}
/* a fresh list from the values of $array (array_values()) */
static zv::Arr arrayValues(zval *array)
{
zv::Arr values = zv::Arr::create(zend_hash_num_elements(Z_ARRVAL_P(array)));
for (zv::ArrayEntry entry : zv::ArrRef(array)) {
values.push(entry.value());
}
return values;
}
/* array_values(array_unique($ints)) for a list of ints: the first
* occurrences, in order */
static zv::Arr uniqueLongs(zval *array)
{
zv::ScratchTable seen((uint32_t) zend_hash_num_elements(Z_ARRVAL_P(array)));
zv::Arr values = zv::Arr::create(zend_hash_num_elements(Z_ARRVAL_P(array)));
for (zv::ArrayEntry entry : zv::ArrRef(array)) {
zval *value = entry.value().deref().raw();
if (Z_TYPE_P(value) == IS_LONG) {
if (zend_hash_index_add_empty_element(seen.table(), (zend_ulong) Z_LVAL_P(value)) == NULL) continue;
}
values.push(zv::Ref(value));
}
return values;
}
/* sort($ints) for a list of ints (sort() compares ints numerically; equal
* ints are indistinguishable, so the algorithm does not matter) */
static int compareLongBuckets(Bucket *a, Bucket *b)
{
return Z_LVAL(a->val) < Z_LVAL(b->val) ? -1 : (Z_LVAL(a->val) > Z_LVAL(b->val) ? 1 : 0);
}
static void sortLongs(zv::Arr &ints)
{
ints.separate();
zend_hash_sort_ex(ints.table(), zend_sort, compareLongBuckets, 1);
}
/* array_pop($array): the last element in order removed, the next free
* index pulled back when it was the last appended one */
static void arrayPop(zval *array)
{
SEPARATE_ARRAY(array);
HashTable *ht = Z_ARRVAL_P(array);
if (zend_hash_num_elements(ht) == 0) return;
uint32_t idx = ht->nNumUsed;
if (HT_IS_PACKED(ht)) {
while (idx > 0) {
idx--;
zval *p = &ht->arPacked[idx];
if (Z_TYPE_P(p) != IS_UNDEF) {
if ((zend_long) idx == ht->nNextFreeElement - 1) {
ht->nNextFreeElement--;
}
zend_hash_index_del(ht, idx);
break;
}
}
} else {
while (idx > 0) {
idx--;
Bucket *p = &ht->arData[idx];
if (Z_TYPE(p->val) != IS_UNDEF) {
if (p->key == NULL) {
if ((zend_long) p->h == ht->nNextFreeElement - 1) {
ht->nNextFreeElement--;
}
zend_hash_index_del(ht, p->h);
} else {
zend_hash_del(ht, p->key);
}
break;
}
}
}
zend_hash_internal_pointer_reset(ht);
}
/* range($start, $end) over ints */
static zv::Arr rangeLongs(zend_long start, zend_long end)
{
zend_long count = (start <= end ? end - start : start - end) + 1;
zv::Arr values = zv::Arr::create((uint32_t) count);
if (start <= end) {
for (zend_long i = start; ; i++) {
values.push(zv::Val::integer(i));
if (i == end) break;
}
} else {
for (zend_long i = start; ; i--) {
values.push(zv::Val::integer(i));
if (i == end) break;
}
}
return values;
}
/* $map[$key] = $value / isset($map[$key]) / unset($map[$key]) with PHP's
* array-key semantics for an int|string key (a numeric string is an int
* key); other key kinds are the twin's getValue() contract violations */
static bool mapKeyOk(zval *key)
{
if (EXPECTED(Z_TYPE_P(key) == IS_LONG || Z_TYPE_P(key) == IS_STRING)) return true;
zend_type_error("phpstan_turbo: an array key type's getValue() must return int|string, %s returned", zend_zval_value_name(key));
return false;
}
static bool mapSet(HashTable *map, zval *key, zval *value)
{
if (UNEXPECTED(!mapKeyOk(key))) return false;
Z_TRY_ADDREF_P(value);
if (Z_TYPE_P(key) == IS_LONG) {
zend_hash_index_update(map, (zend_ulong) Z_LVAL_P(key), value);
} else {
zend_symtable_update(map, Z_STR_P(key), value);
}
return true;
}
static zval *mapFind(HashTable *map, zval *key)
{
if (Z_TYPE_P(key) == IS_LONG) return zend_hash_index_find(map, (zend_ulong) Z_LVAL_P(key));
if (Z_TYPE_P(key) == IS_STRING) return zend_symtable_find(map, Z_STR_P(key));
return NULL;
}
static void mapDel(HashTable *map, zval *key)
{
if (Z_TYPE_P(key) == IS_LONG) {
zend_hash_index_del(map, (zend_ulong) Z_LVAL_P(key));
} else if (Z_TYPE_P(key) == IS_STRING) {
zend_symtable_del(map, Z_STR_P(key));
}
}
/* $keyType->getValue() of a ConstantIntegerType|ConstantStringType key —
* the slots of the native classes, the method through the class entry
* otherwise; an owned int or string; UNDEF = pending exception */
static zv::Val keyValue(zval *keyType)
{
if (UNEXPECTED(Z_TYPE_P(keyType) != IS_OBJECT)) {
zend_type_error("phpstan_turbo: a key type must be an object, %s given", zend_zval_value_name(keyType));
return zv::Val();
}
zend_object *object = Z_OBJ_P(keyType);
if (instanceof_function(object->ce, pt_ce_constant_integer_type)) {
zend_long value;
if (UNEXPECTED(!pt_constant_integer_get_value(object, value))) return zv::Val();
return zv::Val::integer(value);
}
if (instanceof_function(object->ce, pt_ce_constant_string_type)) return pt_constant_string_get_value(object);
return pt_type_call(object, PT_LC("getvalue"), 0, NULL);
}
/* the reasons array of a result object (an AcceptsResult /
* IsSuperTypeOfResult, native or the PHP twin — its public $reasons);
* UNDEF = pending exception */
static zv::Val resultReasons(zval *result)
{
if (UNEXPECTED(Z_TYPE_P(result) != IS_OBJECT)) {
zend_type_error("phpstan_turbo: expected a result object, %s given", zend_zval_value_name(result));
return zv::Val();
}
/* the engine hands back the declared slot, or fills rv for a magic
* read — only then is rv ours to release */
zval rv;
ZVAL_UNDEF(&rv);
zval *reasons = zend_read_property(Z_OBJCE_P(result), Z_OBJ_P(result), PT_LC("reasons"), 0, &rv);
if (UNEXPECTED(reasons == NULL || EG(exception))) return zv::Val();
if (UNEXPECTED(Z_TYPE_P(reasons) != IS_ARRAY)) {
zend_type_error("phpstan_turbo: $reasons must be an array");
if (reasons == &rv) {
zval_ptr_dtor(&rv);
}
return zv::Val();
}
zv::Val copy = zv::Val::copyOf(zv::Ref(reasons));
if (reasons == &rv) {
zval_ptr_dtor(&rv);
}
return copy;
}
/* new AcceptsResult($result->result, [$reason]) — the reasons the twin
* substitutes for a reasonless non-yes result; $reason owned */
static zv::Val acceptsResultWithReason(zval *result, zv::Val reason)
{
if (UNEXPECTED(reason.isUndef())) return zv::Val();
zend_long value = pt_type_result_trinary(result);
if (UNEXPECTED(value < 0)) return zv::Val();
zv::Arr reasons = zv::Arr::create(1);
reasons.push(std::move(reason));
zval reasonsRaw = reasons.take();
zval created;
if (UNEXPECTED(!pt_accepts_result_create(&created, pt_trinary_singleton(value), &reasonsRaw))) return zv::Val();
return zv::Val::adopt(created);
}
/* AcceptsResult::createNo([$reason]); $reason owned */
static zv::Val acceptsNoWithReason(zv::Val reason)
{
if (UNEXPECTED(reason.isUndef())) return zv::Val();
zv::Arr reasons = zv::Arr::create(1);
reasons.push(std::move(reason));
zval reasonsRaw = reasons.take();
zval created;
if (UNEXPECTED(!pt_accepts_result_create(&created, pt_trinary_singleton(PT_TRI_NO), &reasonsRaw))) return zv::Val();
return zv::Val::adopt(created);
}
/* $result->decorateReasons($cb) with a native $cb over two captured
* values; UNDEF = pending exception */
static zv::Val decorateReasons(zval *result, pt_native_callback fn, zval *state0, zval *state1)
{
zv::Val callback = pt_type_native_callback(fn, state0, state1);
if (UNEXPECTED(callback.isUndef())) return zv::Val();
if (UNEXPECTED(Z_TYPE_P(result) != IS_OBJECT)) {
zend_type_error("phpstan_turbo: expected a result object, %s given", zend_zval_value_name(result));
return zv::Val();
}
return pt_type_call(Z_OBJ_P(result), PT_LC("decoratereasons"), 1, callback.raw());
}
/* the string argument of a decorateReasons() callback */
static zend_string *reasonArgument(uint32_t argc, zval *argv)
{
if (UNEXPECTED(argc < 1 || Z_TYPE_P(&argv[0]) != IS_STRING)) {
zend_type_error("phpstan_turbo: the decorateReasons() callback takes a string");
return NULL;
}
return Z_STR_P(&argv[0]);
}
/* a ConstantArrayTypeBuilder: createEmpty() / createFromConstantArray($array)
* — the shadowed class, driven through its exported helpers (direct C++
* calls) */
static zv::Val builderCreateEmpty()
{
return pt_constant_array_type_builder_create_empty();
}
static zv::Val builderCreateFromConstantArray(zval *array)
{
return pt_constant_array_type_builder_create_from_constant_array(array);
}
/* $builder->setOffsetValueType($offsetType, $valueType[, $optional]);
* offsetType NULL = the twin's null, optional -1 = the parameter left at
* its default (false); false = pending exception */
[[nodiscard]] static bool builderSet(zval *builder, zval *offsetType, zval *valueType, int optional = -1)
{
return pt_constant_array_type_builder_set_offset_value_type(builder, offsetType, valueType, optional > 0);
}
/* $builder->makeUnsealed($keyType, $valueType); false = pending exception */
[[nodiscard]] static bool builderMakeUnsealed(zval *builder, zval *keyType, zval *valueType)
{
return pt_constant_array_type_builder_make_unsealed(builder, keyType, valueType);
}
/* $builder->getArray() */
static zv::Val builderGetArray(zval *builder)
{
zv::Val array = pt_constant_array_type_builder_get_array(builder);
if (UNEXPECTED(array.isUndef())) return zv::Val();
if (UNEXPECTED(!zv::Ref(array.raw()).isObject())) {
zend_type_error("phpstan_turbo: ConstantArrayTypeBuilder::getArray() must return %s", ptcls::type);
return zv::Val();
}
return array;
}
/* $builder->degradeToGeneralArray() / ->disableArrayDegradation(); false =
* pending exception */
static bool builderCall0(zval *builder, const char *lcname, size_t len)
{
zv::Val result = pt_type_call(Z_OBJ_P(builder), lcname, len, 0, NULL);
return !result.isUndef();
}
/* $builder->isList(); false = pending exception */
[[nodiscard]] static bool builderIsList(zval *builder, bool &out)
{
return pt_type_op_bool(Z_OBJ_P(builder), PT_OP_IS_LIST, 0, NULL, out);
}
/* [$key, $value] = $unsealed: the pair's two Types (borrowed); false with
* an Error pending when the array is not a pair of objects */
static bool unsealedPair(zval *unsealed, zval *&keyType, zval *&valueType)
{
if (UNEXPECTED(Z_TYPE_P(unsealed) != IS_ARRAY)) {
zend_type_error("phpstan_turbo: $unsealed must be an array");
return false;
}
zval *k = zend_hash_index_find(Z_ARRVAL_P(unsealed), 0);
zval *v = zend_hash_index_find(Z_ARRVAL_P(unsealed), 1);
if (UNEXPECTED(k == NULL || v == NULL)) {
zend_throw_error(NULL, "phpstan_turbo: $unsealed must be a pair of %s", ptcls::type);
return false;
}
ZVAL_DEREF(k);
ZVAL_DEREF(v);
if (UNEXPECTED(Z_TYPE_P(k) != IS_OBJECT || Z_TYPE_P(v) != IS_OBJECT)) {
zend_type_error("phpstan_turbo: $unsealed must be a pair of %s", ptcls::type);
return false;
}
keyType = k;
valueType = v;
return true;
}
/* [$keyType, $valueType] as an owned pair array */
static zv::Val pairOf(zval *keyType, zval *valueType)
{
zv::Arr pair = zv::Arr::create(2);
pair.push(zv::Ref(keyType));
pair.push(zv::Ref(valueType));
return zv::Val(std::move(pair));
}
/* the PT_TRI_* value of a TrinaryLogic zval (the twin's ->yes()/->no()/
* ->maybe() reads); -1 = pending exception */
[[nodiscard]] static zend_long trinaryOf(zval *trinary)
{
return pt_type_trinary_value(trinary);
}
/* TrinaryLogic::createFromBoolean() */
static zend_long trinaryFromBoolean(bool value)
{
return value ? PT_TRI_YES : PT_TRI_NO;
}
/* TrinaryLogic::negate() — 3 >> $value */
static zend_long trinaryNegate(zend_long value)
{
return 3 >> value;
}
/* TrinaryLogic::extremeIdentity(...$values) over collected values; the
* twin throws for none */
static zend_long trinaryExtremeIdentity(const zend_long *values, size_t count)
{
if (UNEXPECTED(count == 0)) {
pt_throw_should_not_happen();
return -1;
}
zend_long min = values[0], max = values[0];
for (size_t i = 1; i < count; i++) {
if (values[i] < min) {
min = values[i];
}
if (values[i] > max) {
max = values[i];
}
}
return min == max ? min : PT_TRI_MAYBE;
}
/* $trinary->toBooleanType() */
static zv::Val trinaryToBooleanType(zend_long value)
{
if (value == PT_TRI_MAYBE) return booleanType();
return constantBoolean(value == PT_TRI_YES);
}
/* $a - $b through the engine (a float past the int range) */
static void phpSub(zend_long a, zend_long b, zval *out)
{
zval x, y;
ZVAL_LONG(&x, a);
ZVAL_LONG(&y, b);
sub_function(out, &x, &y);
}
/* the class's own handlers (defined with the registration below): the
* fast-path identities for the $this-calls a subclass could override */
} // namespace phpstanturbo
static void ZEND_FASTCALL catIsUnsealed(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catGetUnsealedTypes(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catRecreate(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catGetIterableKeyType(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catGetIterableValueType(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catGetKeyType(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catGetItemType(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catGetKeyTypes(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catGetValueTypes(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catIsOptionalKey(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catFindTypeAndMethodNames(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catHasOffsetValueType(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catGetOffsetValueType(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catUnsetOffset(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catReverseArray(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catSliceArray(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catIsIterableAtLeastOnce(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catGetArraySize(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catIsList(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catToBoolean(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catGetValuesArray(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catDescribe(INTERNAL_FUNCTION_PARAMETERS);
static void ZEND_FASTCALL catTraverse(INTERNAL_FUNCTION_PARAMETERS);
namespace phpstanturbo {
/* Mirrors PHPStan\Type\Constant\ConstantArrayType. State lives in the PHP
* object's slots. */
class ConstantArrayType
{
public:
explicit ConstantArrayType(zend_object *self) : self(self) {}
/* the twin's typed parameter checks for a `new self()` / `new
* ConstantArrayType()` from native code; false with a TypeError pending */
static bool checkArray(zval *value, int argNumber)
{
if (UNEXPECTED(Z_TYPE_P(value) != IS_ARRAY)) {
zend_argument_type_error((uint32_t) argNumber, "must be of type array, %s given", zend_zval_value_name(value));
return false;
}
return true;
}
static bool checkNullableArray(zval *value, int argNumber)
{
if (UNEXPECTED(Z_TYPE_P(value) != IS_ARRAY && Z_TYPE_P(value) != IS_NULL)) {
zend_argument_type_error((uint32_t) argNumber, "must be of type ?array, %s given", zend_zval_value_name(value));
return false;
}
return true;
}
static bool checkNullableTrinary(zval *value, int argNumber)
{
if (UNEXPECTED(Z_TYPE_P(value) != IS_NULL && (Z_TYPE_P(value) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(value), pt_ce_trinary)))) {
zend_argument_type_error((uint32_t) argNumber, "must be of type ?%s, %s given", ptcls::trinaryLogic, zend_zval_value_name(value));
return false;
}
return true;
}
/* __construct(private array $keyTypes, private array $valueTypes,
* private array $nextAutoIndexes = [0], private array $optionalKeys = [],
* ?TrinaryLogic $isList = null, ?array $unsealed = null); the NULL
* arguments stand for the defaults, an IS_NULL $isList/$unsealed for
* the twin's null; false = pending exception */
[[nodiscard]] bool construct(zval *keyTypesArg, zval *valueTypesArg, zval *nextAutoIndexesArg, zval *optionalKeysArg, zval *isListArg, zval *unsealedArg)
{
/* assert(count($keyTypes) === count($valueTypes)) — an
* AssertionError when the engine evaluates assertions */
if (UNEXPECTED(EG(assertions) > 0 && zend_hash_num_elements(Z_ARRVAL_P(keyTypesArg)) != zend_hash_num_elements(Z_ARRVAL_P(valueTypesArg)))) {
zend_string *assertionErrorName = zend_string_init(PT_LC("AssertionError"), 0);
zend_class_entry *assertionError = zend_lookup_class_ex(assertionErrorName, NULL, ZEND_FETCH_CLASS_NO_AUTOLOAD);
zend_string_release(assertionErrorName);
zend_throw_exception(assertionError != NULL ? assertionError : zend_ce_error, "assert(count($keyTypes) === count($valueTypes))", 0);
return false;
}
zv::Val unsealed = unsealedArg == NULL || Z_TYPE_P(unsealedArg) == IS_NULL ? zv::Val::null() : zv::Val::copyOf(zv::Ref(unsealedArg));
/* 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. */
zv::Val isList;
if (isListArg == NULL || Z_TYPE_P(isListArg) == IS_NULL) {
zend_long value;
if (zend_hash_num_elements(Z_ARRVAL_P(keyTypesArg)) == 0) {
if (unsealed.isNull()) {
value = PT_TRI_YES;
} else {
zval *unsealedKeyType = unsealedKeyOf(unsealed.raw());
if (UNEXPECTED(unsealedKeyType == NULL)) return false;
bool explicitNever;
if (UNEXPECTED(!isExplicitNever(unsealedKeyType, explicitNever))) return false;
if (explicitNever) {
value = PT_TRI_YES;
} else {
zend_long isInteger = pt_type_op_trinary(Z_OBJ_P(unsealedKeyType), PT_OP_IS_INTEGER, 0, NULL);
if (UNEXPECTED(isInteger < 0)) return false;
value = isInteger == PT_TRI_YES ? PT_TRI_MAYBE : PT_TRI_NO;
}
}
} else {
value = PT_TRI_NO;
}
isList = pt_type_trinary(value);
} else {
isList = zv::Val::copyOf(zv::Ref(isListArg));
}
if (!unsealed.isNull()) {
zval *unsealedKeyType = unsealedKeyOf(unsealed.raw());
if (UNEXPECTED(unsealedKeyType == NULL)) return false;
/* 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. */
bool isBenevolent;
if (UNEXPECTED(!pt_type_instanceof_ce(unsealedKeyType, pt_ce_benevolent_union_type, isBenevolent))) return false;
if (isBenevolent) {
zv::Val description = describeValue(unsealedKeyType);
if (UNEXPECTED(description.isUndef())) return false;
zv::Ref d(description.raw());
if (d.stringEquals("(int|string)") || d.stringEquals("(int|non-decimal-int-string)")) {
zv::Val mixed = pt_type_new_mixed_type();
if (UNEXPECTED(mixed.isUndef())) return false;
zv::ArrRef(unsealed.raw()).setIndex(0, zv::Ref(mixed.raw()));
unsealedKeyType = unsealedKeyOf(unsealed.raw());
}
}
bool isStrictMixed;
if (UNEXPECTED(!isInstance(unsealedKeyType, pt_ce_strict_mixed_type, isStrictMixed))) return false;
if (isStrictMixed) {
bool isTemplateStrictMixed;
if (UNEXPECTED(!isInstance(unsealedKeyType, pt_ce_template_strict_mixed_type, isTemplateStrictMixed))) return false;
if (!isTemplateStrictMixed) {
/* (new UnionType([new StringType(), new IntegerType()]))->toArrayKey() */
zv::Val string = stringType();
zv::Val integer = integerType();
if (UNEXPECTED(string.isUndef() || integer.isUndef())) return false;
zv::Arr types = zv::Arr::create(2);
types.push(std::move(string));
types.push(std::move(integer));
zv::Val unionType = pt_type_new_union(std::move(types));
if (UNEXPECTED(unionType.isUndef())) return false;
zv::Val arrayKey = callType(Z_OBJ_P(unionType.raw()), PT_LC("toarraykey"), 0, NULL);
if (UNEXPECTED(arrayKey.isUndef())) return false;
zv::ArrRef(unsealed.raw()).setIndex(0, zv::Ref(arrayKey.raw()));
unsealedKeyType = unsealedKeyOf(unsealed.raw());
}
}
bool explicitNever;
if (UNEXPECTED(!isExplicitNever(unsealedKeyType, explicitNever))) return false;
if (explicitNever) {
zv::Val never = neverType(true);
if (UNEXPECTED(never.isUndef())) return false;
zv::ArrRef(unsealed.raw()).setIndex(1, zv::Ref(never.raw()));
}
} else {
bool bleedingEdge;
if (UNEXPECTED(!isBleedingEdge(bleedingEdge))) return false;
if (bleedingEdge) {
zv::Val never = neverType(true);
if (UNEXPECTED(never.isUndef())) return false;
unsealed = pairOf(never.raw(), never.raw());
}
}
zv::ObjRef ref(self);
writeSlot(ref, slots::keyTypes, zv::Val::copyOf(zv::Ref(keyTypesArg)));
writeSlot(ref, slots::valueTypes, zv::Val::copyOf(zv::Ref(valueTypesArg)));
if (nextAutoIndexesArg != NULL) {
writeSlot(ref, slots::nextAutoIndexes, zv::Val::copyOf(zv::Ref(nextAutoIndexesArg)));
} else {
zv::Arr zero = zv::Arr::create(1);
zero.push(zv::Val::integer(0));
writeSlot(ref, slots::nextAutoIndexes, zv::Val(std::move(zero)));
}
if (optionalKeysArg != NULL) {
writeSlot(ref, slots::optionalKeys, zv::Val::copyOf(zv::Ref(optionalKeysArg)));
} else {
writeSlot(ref, slots::optionalKeys, zv::Val(zv::Arr::empty()));
}
writeSlot(ref, slots::isList, std::move(isList));
writeSlot(ref, slots::unsealed, std::move(unsealed));
return true;
}
/* new self(...) — exactly the class, with the twin's typed parameters'
* checks; the NULL/IS_NULL conventions of construct(); UNDEF = pending
* exception */
static zv::Val create(zval *keyTypes, zval *valueTypes, zval *nextAutoIndexes = NULL, zval *optionalKeys = NULL, zval *isList = NULL, zval *unsealed = NULL)
{
if (UNEXPECTED(!checkArray(keyTypes, 1) || !checkArray(valueTypes, 2)
|| (nextAutoIndexes != NULL && !checkArray(nextAutoIndexes, 3))
|| (optionalKeys != NULL && !checkArray(optionalKeys, 4))
|| (isList != NULL && !checkNullableTrinary(isList, 5))
|| (unsealed != NULL && !checkNullableArray(unsealed, 6)))) {
return zv::Val();
}
zval object;
if (UNEXPECTED(object_init_ex(&object, pt_ce_constant_array_type) != SUCCESS)) return zv::Val();
if (UNEXPECTED(!ConstantArrayType(Z_OBJ(object)).construct(keyTypes, valueTypes, nextAutoIndexes, optionalKeys, isList, unsealed))) {
zval_ptr_dtor(&object);
return zv::Val();
}
return zv::Val::adopt(object);
}
/* new ConstantArrayType([], []) */
static zv::Val createEmpty()
{
zval empty;
ZVAL_EMPTY_ARRAY(&empty);
return create(&empty, &empty);
}
/* $this->isUnsealed()->negate() — through the object's class */
zv::Val isSealed() const
{
zend_long unsealed = thisIsUnsealed();
if (UNEXPECTED(unsealed < 0)) return zv::Val();
return pt_type_trinary(trinaryNegate(unsealed));
}
/* maybe for no unsealed pair, else whether its key type is not an
* explicit never; -1 = pending exception */
[[nodiscard]] zend_long isUnsealed() const
{
zval *unsealed = unsealedSlot();
if (UNEXPECTED(unsealed == NULL)) return -1;
if (Z_TYPE_P(unsealed) == IS_NULL) return PT_TRI_MAYBE;