Repository navigation
Expand file tree
/
Copy pathTypeCombinator.cpp
More file actions
4513 lines (4089 loc) · 161 KB
/
Copy pathTypeCombinator.cpp
File metadata and controls
4513 lines (4089 loc) · 161 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\TypeCombinator — native implementation of
* PHPStan\Type\TypeCombinator.
*
* Declared as PHPStan\Type\TypeCombinator itself at activation: final, a
* class of static methods with the twin's one `private static ?bool
* $cacheEnabled` slot. The public entry points union(), intersect() and
* remove() consult that slot the way the twin does (lazily asking
* TurboExtensionEnabler::isTypeCombinatorCacheEnabled()) and route through
* the memo in TypeCombinatorCache.cpp when it says so; the memo computes a
* miss with the doUnion()/doIntersect()/doRemove() bodies below through a
* direct C++ call. The other native Type classes reach the class through
* the exported pt_type_combinator_*() entry points (support.h) — no engine
* frame, no class-map lookup.
*
* The logic lives in the TypeCombinator handle class below, structured to
* mirror src/Type/TypeCombinator.php method for method (the private helpers
* included, as plain C++ members: nothing can override a private static of
* a final class). Lists of types are owned zval vectors; the twin's keyed
* arrays — the description-keyed scalar/enum/accessory maps, the index-keyed
* arrays-to-process of reduceArrays() — stay PHP arrays so key coercion,
* insertion order and replace-in-place semantics are the engine's own. The
* twin's usort() calls run the engine's sort (zend_sort with usort()'s
* stable fallback) over the same comparison results. Everything a Type
* answers is asked through its class entry; the shadowed classes are
* instantiated through their exported constructors, the others
* (ConstantArrayTypeBuilder, TypeTraverser, TemplateTypeFactory, the
* template types) through the class map.
*/
#include "TypeTraits.h"
#include "generated/TypeCombinator.h"
namespace sigs = ptdecl::TypeCombinator::sig;
#include <vector>
zend_class_entry *pt_ce_type_combinator = nullptr;
/* an UNDEF zv::Val / a negative int = pending exception */
#define PT_FAIL_IF_UNDEF(v) \
do { \
if (UNEXPECTED((v).isUndef())) { \
return zv::Val(); \
} \
} while (0)
#define PT_FAIL_IF_NEG(x) \
do { \
if (UNEXPECTED((x) < 0)) { \
return zv::Val(); \
} \
} while (0)
namespace phpstanturbo {
/* a list of owned types; its data() is a contiguous zval vector (zv::Val
* wraps exactly one zval), so it spreads into an argument vector as is */
typedef std::vector<zv::Val> TypeList;
static_assert(sizeof(zv::Val) == sizeof(zval), "zv::Val must wrap exactly one zval");
static zval *argvOf(TypeList &list)
{
return list.empty() ? NULL : reinterpret_cast<zval *>(list.data());
}
/* {{{ helpers */
static zv::Val copy(zval *value)
{
return zv::Val::copyOf(zv::Ref(value));
}
static bool isNull(const zv::Val &value)
{
return Z_TYPE_P(const_cast<zv::Val &>(value).raw()) == IS_NULL;
}
static bool isInstance(zval *value, zend_class_entry *ce)
{
return Z_TYPE_P(value) == IS_OBJECT && instanceof_function(Z_OBJCE_P(value), ce);
}
/* $value instanceof <class-map class>; -1 = pending exception */
static int isInstanceMap(zval *value, int classIdx)
{
bool out;
if (UNEXPECTED(!pt_type_instanceof(value, classIdx, out))) return -1;
return out ? 1 : 0;
}
static bool sameObject(zval *a, zval *b)
{
return Z_TYPE_P(a) == IS_OBJECT && Z_TYPE_P(b) == IS_OBJECT && Z_OBJ_P(a) == Z_OBJ_P(b);
}
/* $object->method(...$args); UNDEF = pending exception */
static zv::Val call(zval *object, const char *lcname, size_t len, uint32_t argc = 0, zval *argv = NULL)
{
return pt_type_call(Z_OBJ_P(object), lcname, len, argc, argv);
}
/* $object->method(...)'s TrinaryLogic value; -1 = pending exception */
[[nodiscard]] static zend_long callTrinary(zval *object, const char *lcname, size_t len, uint32_t argc = 0, zval *argv = NULL)
{
return pt_type_call_trinary(Z_OBJ_P(object), lcname, len, argc, argv);
}
/* the PT_TRI_* value of $object->method(...)'s result object; -1 = pending
* exception */
[[nodiscard]] static zend_long callResultTrinary(zval *object, const char *lcname, size_t len, uint32_t argc, zval *argv)
{
zv::Val result = call(object, lcname, len, argc, argv);
if (UNEXPECTED(result.isUndef())) return -1;
return pt_type_result_trinary(result.raw());
}
/* $object->isSuperTypeOf($other)->yes(); -1 = pending exception */
static int isSuperTypeYes(zval *object, zval *other)
{
zend_long value = callResultTrinary(object, PT_LC("issupertypeof"), 1, other);
if (UNEXPECTED(value < 0)) return -1;
return value == PT_TRI_YES ? 1 : 0;
}
/* $object->method(...) returning bool; -1 = pending exception */
static int callBool(zval *object, const char *lcname, size_t len, uint32_t argc = 0, zval *argv = NULL)
{
zv::Val result = call(object, lcname, len, argc, argv);
if (UNEXPECTED(result.isUndef())) return -1;
return zend_is_true(result.raw()) ? 1 : 0;
}
/* $a->equals($b); -1 = pending exception */
static int typeEquals(zval *a, zval *b)
{
return callBool(a, PT_LC("equals"), 1, b);
}
/* count($array) of an array-valued zval */
static uint32_t countOf(zval *array)
{
return Z_TYPE_P(array) == IS_ARRAY ? zend_hash_num_elements(Z_ARRVAL_P(array)) : 0;
}
/* $array[$index] (borrowed); NULL when absent */
static zval *indexOf(zval *array, zend_ulong index)
{
return Z_TYPE_P(array) == IS_ARRAY ? zend_hash_index_find(Z_ARRVAL_P(array), index) : NULL;
}
/* $compound->getTypes(); UNDEF = pending exception */
static zv::Val getTypes(zval *compound)
{
return call(compound, PT_LC("gettypes"));
}
/* VerbosityLevel::<factory>(); UNDEF = pending exception */
static zv::Val verbosityLevel(const char *lcname, size_t len)
{
/* the twin's singletons for the factories the bodies name
* (VerbosityLevel.cpp), any other name through the engine */
zend_long value = 0;
if (len == 5 && memcmp(lcname, "cache", 5) == 0) {
value = PT_VERBOSITY_LEVEL_CACHE;
} else if (len == 7 && memcmp(lcname, "precise", 7) == 0) {
value = PT_VERBOSITY_LEVEL_PRECISE;
} else if (len == 5 && memcmp(lcname, "value", 5) == 0) {
value = PT_VERBOSITY_LEVEL_VALUE;
} else if (len == 8 && memcmp(lcname, "typeonly", 8) == 0) {
value = PT_VERBOSITY_LEVEL_TYPE_ONLY;
}
if (UNEXPECTED(value == 0)) return pt_type_call_static_ce(pt_ce_verbosity_level, lcname, len, 0, NULL);
zval *level = pt_verbosity_level_singleton(value);
return level == NULL ? zv::Val() : zv::Val::copyOf(zv::Ref(level));
}
/* $type->describe($level), the level created on first use (a lazily filled
* VerbosityLevel::<factory>() holder); an owned string, UNDEF = pending
* exception */
struct Level
{
const char *lcname;
size_t len;
zv::Val value;
Level(const char *lcname, size_t len) : lcname(lcname), len(len) {}
zval *get()
{
if (value.isUndef()) {
value = verbosityLevel(lcname, len);
}
return value.isUndef() ? NULL : value.raw();
}
};
static zv::Val describe(zval *type, Level &level)
{
zval *levelValue = level.get();
if (UNEXPECTED(levelValue == NULL)) return zv::Val();
return call(type, PT_LC("describe"), 1, levelValue);
}
/* a description as the symtable key it makes; NULL = pending exception */
[[nodiscard]] static zend_string *describedKey(zv::Val &description)
{
if (UNEXPECTED(description.isUndef())) return NULL;
if (UNEXPECTED(Z_TYPE_P(description.raw()) != IS_STRING)) {
zend_type_error("phpstan_turbo: describe() must return a string, %s returned", zend_zval_value_name(description.raw()));
return NULL;
}
return Z_STR_P(description.raw());
}
/* the copies of a PHP array's entries as a list */
static void listFrom(zval *array, TypeList &out)
{
out.reserve(out.size() + countOf(array));
for (zv::ArrayEntry entry : zv::ArrRef(array)) {
out.push_back(copy(entry.value().raw()));
}
}
/* array_values($list) as a PHP array (copies) */
static zv::Arr listOf(const TypeList &list)
{
zv::Arr result = zv::Arr::create((uint32_t) list.size());
for (const zv::Val &type : list) {
result.push(zv::Ref(const_cast<zv::Val &>(type).raw()));
}
return result;
}
/* $outer[$key][$index] = $value over an owned map of maps */
static void nestedIndexSet(zv::Arr &outer, zend_string *key, zend_ulong index, zv::Val value)
{
zval *inner = zend_symtable_find(outer.table(), key);
if (inner == NULL) {
zval fresh;
array_init(&fresh);
inner = zend_symtable_update(outer.table(), key, &fresh);
}
zval v = value.take();
zend_hash_index_update(Z_ARRVAL_P(inner), index, &v);
}
/* $outer[$key][] = $value over an owned map of lists */
static void nestedPush(zv::Arr &outer, zend_string *key, zv::Val value)
{
zval *inner = zend_symtable_find(outer.table(), key);
if (inner == NULL) {
zval fresh;
array_init(&fresh);
inner = zend_symtable_update(outer.table(), key, &fresh);
}
zval v = value.take();
zend_hash_next_index_insert(Z_ARRVAL_P(inner), &v);
}
/* $map[$keyValue] for an int|string key value (the twin's `$keyType->getValue()`
* keys), with PHP's key coercion; NULL for an unusable key with a TypeError
* pending */
static zval *symtableFind(HashTable *map, zval *keyValue)
{
if (Z_TYPE_P(keyValue) == IS_LONG) return zend_hash_index_find(map, (zend_ulong) Z_LVAL_P(keyValue));
if (EXPECTED(Z_TYPE_P(keyValue) == IS_STRING)) return zend_symtable_find(map, Z_STR_P(keyValue));
zend_type_error("phpstan_turbo: an int|string array key expected, %s given", zend_zval_value_name(keyValue));
return NULL;
}
/* $map[$keyValue] = $value the same way; false = pending exception */
[[nodiscard]] static bool symtableSet(HashTable *map, zval *keyValue, zval *value)
{
if (Z_TYPE_P(keyValue) == IS_LONG) {
zend_hash_index_update(map, (zend_ulong) Z_LVAL_P(keyValue), value);
return true;
}
if (EXPECTED(Z_TYPE_P(keyValue) == IS_STRING)) {
zend_symtable_update(map, Z_STR_P(keyValue), value);
return true;
}
zend_type_error("phpstan_turbo: an int|string array key expected, %s given", zend_zval_value_name(keyValue));
return false;
}
/* ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT — the shadowed class's
* constant, shared as a native constant; -1 = pending exception (never) */
[[nodiscard]] static zend_long arrayCountLimit()
{
return PT_CONSTANT_ARRAY_TYPE_BUILDER_ARRAY_COUNT_LIMIT;
}
/* the shadowed classes' constructors as Vals; UNDEF = pending exception */
static zv::Val adopted(bool created, zval &raw)
{
if (UNEXPECTED(!created)) return zv::Val();
return zv::Val::adopt(raw);
}
static zv::Val neverType(bool isExplicit = false)
{
zval raw;
return adopted(pt_never_type_new(&raw, isExplicit), raw);
}
/* new NeverType(reason: $reason) ($reason a string or null zval) */
static zv::Val neverTypeWithReason(zval *reason)
{
zv::Args args{false, reason};
return pt_type_new_ce(pt_ce_never_type, 2, args);
}
static zv::Val nullType()
{
zval raw;
return adopted(pt_null_type_new(&raw), raw);
}
static zv::Val booleanType()
{
zval raw;
return adopted(pt_boolean_type_new(&raw), raw);
}
static zv::Val floatType()
{
zval raw;
return adopted(pt_float_type_new(&raw), raw);
}
static zv::Val stringType()
{
zval raw;
return adopted(pt_string_type_new(&raw), raw);
}
static zv::Val integerType()
{
zval raw;
return adopted(pt_integer_type_new(&raw), raw);
}
static zv::Val unionType(zv::Arr types, bool normalized)
{
zval raw;
return adopted(pt_union_type_new(&raw, types.raw(), normalized), raw);
}
static zv::Val benevolentUnionType(zv::Arr types, bool normalized)
{
zval raw;
return adopted(pt_benevolent_union_type_new(&raw, types.raw(), normalized), raw);
}
static zv::Val intersectionType(zv::Arr types)
{
zval raw;
return adopted(pt_intersection_type_new(&raw, types.raw()), raw);
}
static zv::Val hasOffsetValueType(zval *offsetType, zval *valueType)
{
zval raw;
return adopted(pt_has_offset_value_type_new(&raw, offsetType, valueType), raw);
}
static zv::Val iterableType(zval *keyType, zval *itemType)
{
zval raw;
return adopted(pt_iterable_type_new(&raw, keyType, itemType), raw);
}
static zv::Val arrayType(zval *keyType, zval *itemType)
{
zval raw;
return adopted(pt_array_type_new(&raw, keyType, itemType), raw);
}
static zv::Val mixedTypeMinus(zval *subtractedType)
{
zval raw;
return adopted(pt_mixed_type_new(&raw, false, subtractedType), raw);
}
static zv::Val accessoryArrayListType()
{
zval raw;
return adopted(pt_accessory_array_list_type_new(&raw), raw);
}
static zv::Val nonEmptyArrayType()
{
zval raw;
return adopted(pt_non_empty_array_type_new(&raw), raw);
}
static zv::Val oversizedArrayType()
{
zval raw;
return adopted(pt_oversized_array_type_new(&raw), raw);
}
static zv::Val accessoryLowercaseStringType()
{
zval raw;
return adopted(pt_accessory_lowercase_string_type_new(&raw), raw);
}
static zv::Val accessoryUppercaseStringType()
{
zval raw;
return adopted(pt_accessory_uppercase_string_type_new(&raw), raw);
}
static zv::Val accessoryNonEmptyStringType()
{
zval raw;
return adopted(pt_accessory_non_empty_string_type_new(&raw), raw);
}
static zv::Val accessoryDecimalIntegerStringType()
{
zval raw;
return adopted(pt_accessory_decimal_integer_string_type_new(&raw), raw);
}
/* the operations over argument vectors and lists; UNDEF = pending exception */
static zv::Val unionOf(TypeList &types)
{
return pt_type_combinator_union((uint32_t) types.size(), argvOf(types));
}
static zv::Val union2(zval *a, zval *b)
{
zv::Args args{a, b};
return pt_type_combinator_union(2, args);
}
static zv::Val intersectOf(TypeList &types)
{
return pt_type_combinator_intersect((uint32_t) types.size(), argvOf(types));
}
static zv::Val intersect2(zval *a, zval *b)
{
zv::Args args{a, b};
return pt_type_combinator_intersect(2, args);
}
/* TypeCombinator::union(...$array) / intersect(...$array) over a PHP array
* (any keys, as the spread accepts) */
static zv::Val unionSpread(zval *array)
{
return pt_type_combinator_call_spread(PT_LC("union"), Z_ARRVAL_P(array));
}
/* self::intersect($first, ...$rest) */
static zv::Val intersectWith(zval *first, TypeList &rest)
{
std::vector<zval> args(rest.size() + 1);
ZVAL_COPY_VALUE(&args[0], first);
for (size_t i = 0; i < rest.size(); i++) {
ZVAL_COPY_VALUE(&args[i + 1], rest[i].raw());
}
return pt_type_combinator_intersect((uint32_t) args.size(), args.data());
}
/* $type instanceof NeverType && !$type->isExplicit(); -1 = pending
* exception */
static int isImplicitNever(zval *type)
{
if (!isInstance(type, pt_ce_never_type)) return 0;
bool isExplicit;
if (UNEXPECTED(!pt_never_type_is_explicit(Z_OBJ_P(type), isExplicit))) return -1;
return isExplicit ? 0 : 1;
}
/* $type instanceof MixedType && !$type->isExplicitMixed() && !$type
* instanceof TemplateMixedType && $type->getSubtractedType() === null; -1 =
* pending exception */
static int isPlainMixed(zval *type)
{
if (!isInstance(type, pt_ce_mixed_type)) return 0;
int isExplicitMixed = callBool(type, PT_LC("isexplicitmixed"));
if (UNEXPECTED(isExplicitMixed < 0)) return -1;
if (isExplicitMixed) return 0;
if (isInstance(type, pt_ce_template_mixed_type)) return 0;
zv::Val subtracted = call(type, PT_LC("getsubtractedtype"));
if (UNEXPECTED(subtracted.isUndef())) return -1;
return isNull(subtracted) ? 1 : 0;
}
/* }}} */
/* {{{ usort() over a list: the engine's sort (zend_sort) with usort()'s
* stable fallback on the original order, over the comparator's own -1/0/1
* answers; the comparator sets sortFailed on a pending exception */
typedef int (*ListComparator)(zval *a, zval *b);
static ListComparator sortComparator = NULL;
static bool sortFailed = false;
static int compareBuckets(Bucket *a, Bucket *b)
{
int result = sortFailed ? 0 : sortComparator(&a->val, &b->val);
if (result == 0) {
/* usort()'s stable fallback: the original order */
return Z_EXTRA(a->val) > Z_EXTRA(b->val) ? 1 : (Z_EXTRA(a->val) < Z_EXTRA(b->val) ? -1 : 0);
}
return result > 0 ? 1 : -1;
}
/* usort($list, $comparator); false = pending exception */
[[nodiscard]] static bool usortList(TypeList &list, ListComparator comparator)
{
if (list.size() < 2) return true;
zv::Arr array = listOf(list);
ListComparator previousComparator = sortComparator;
bool previousFailed = sortFailed;
sortComparator = comparator;
sortFailed = false;
zend_hash_sort_ex(array.table(), zend_sort, compareBuckets, 1);
bool failed = sortFailed || EG(exception) != NULL;
sortComparator = previousComparator;
sortFailed = previousFailed;
if (UNEXPECTED(failed)) return false;
list.clear();
listFrom(array.raw(), list);
return true;
}
/* }}} */
/* Mirrors PHPStan\Type\TypeCombinator. */
class TypeCombinator
{
public:
/* {{{ self::$cacheEnabled ??= TurboExtensionEnabler::isTypeCombinatorCacheEnabled();
* false = pending exception */
static bool cacheEnabled(bool &out)
{
zend_class_entry *ce = pt_ce_type_combinator;
if (UNEXPECTED(ce == NULL)) {
out = false;
return true;
}
if (UNEXPECTED(ce != cacheEnabledCe)) {
zend_property_info *info = (zend_property_info *) zend_hash_str_find_ptr(&PT_CE(ce, properties_info), PT_LC("cacheEnabled"));
if (UNEXPECTED(info == NULL || (info->flags & ZEND_ACC_STATIC) == 0)) {
zend_throw_error(NULL, "phpstan_turbo: %s::$cacheEnabled not found", ZSTR_VAL(ce->name));
return false;
}
cacheEnabledCe = ce;
cacheEnabledOffset = info->offset;
}
if (UNEXPECTED(CE_STATIC_MEMBERS(ce) == NULL)) {
zend_class_init_statics(ce);
}
zval *slot = &CE_STATIC_MEMBERS(ce)[cacheEnabledOffset];
ZVAL_DEREF(slot);
if (EXPECTED(Z_TYPE_P(slot) == IS_TRUE || Z_TYPE_P(slot) == IS_FALSE)) {
out = Z_TYPE_P(slot) == IS_TRUE;
return true;
}
zv::Val enabled = pt_type_call_static(PT_CLASS_TURBO_EXTENSION_ENABLER, PT_LC("istypecombinatorcacheenabled"), 0, NULL);
if (UNEXPECTED(enabled.isUndef())) return false;
out = zend_is_true(enabled.raw());
zval_ptr_dtor(slot);
ZVAL_BOOL(slot, out);
return true;
}
static zend_class_entry *cacheEnabledCe;
static uint32_t cacheEnabledOffset;
/* }}} */
/* clearCache(); false = pending exception */
[[nodiscard]] static bool clearCache()
{
bool enabled;
if (UNEXPECTED(!cacheEnabled(enabled))) return false;
if (!enabled) return true;
pt_type_combinator_cache_clear();
return true;
}
static zv::Val addNull(zval *type)
{
/* asking the type itself is both cheaper than NullType::isSuperTypeOf()
* (UnionType memoizes isNull(), isSubTypeOf() recomputes) and right for
* `never`, of which null is a supertype without never containing it */
zend_long isNull = callTrinary(type, PT_LC("isnull"));
PT_FAIL_IF_NEG(isNull);
if (isNull == PT_TRI_NO) {
zv::Val nullValue = nullType();
PT_FAIL_IF_UNDEF(nullValue);
return union2(type, nullValue.raw());
}
return copy(type);
}
static zv::Val remove(zval *fromType, zval *typeToRemove)
{
bool enabled;
if (UNEXPECTED(!cacheEnabled(enabled))) return zv::Val();
if (enabled) return pt_type_combinator_cache_remove(fromType, typeToRemove);
return doRemove(fromType, typeToRemove);
}
/* private static canRemoveUnionAtOnce(Type $fromType): bool; -1 =
* pending exception */
static int canRemoveUnionAtOnce(zval *fromType)
{
zv::Val classReflections = call(fromType, PT_LC("getobjectclassreflections"));
if (UNEXPECTED(classReflections.isUndef())) return -1;
if (countOf(classReflections.raw()) == 1) {
zval *first = indexOf(classReflections.raw(), 0);
if (UNEXPECTED(first == NULL || Z_TYPE_P(first) != IS_OBJECT)) {
zend_throw_error(NULL, "phpstan_turbo: getObjectClassReflections() must return a list of class reflections");
return -1;
}
zv::Val allowedSubTypes = call(first, PT_LC("getallowedsubtypes"));
if (UNEXPECTED(allowedSubTypes.isUndef())) return -1;
if (!isNull(allowedSubTypes)) return 1;
}
return isInstance(fromType, pt_ce_union_type) ? 1 : 0;
}
static zv::Val doRemove(zval *fromType, zval *typeToRemove)
{
if (isInstance(typeToRemove, pt_ce_union_type)) {
int atOnce = canRemoveUnionAtOnce(fromType);
PT_FAIL_IF_NEG(atOnce);
if (atOnce) {
zv::Val removed = call(fromType, PT_LC("tryremove"), 1, typeToRemove);
PT_FAIL_IF_UNDEF(removed);
if (!isNull(removed)) return removed;
}
zv::Val types = getTypes(typeToRemove);
PT_FAIL_IF_UNDEF(types);
zv::Val current = copy(fromType);
for (zv::ArrayEntry entry : zv::ArrRef(types.raw())) {
zv::Val next = remove(current.raw(), entry.value().raw());
PT_FAIL_IF_UNDEF(next);
current = std::move(next);
if (isInstance(current.raw(), pt_ce_never_type)) {
/* there is nothing left to remove from */
break;
}
}
return current;
}
zend_long isSuperType = callResultTrinary(typeToRemove, PT_LC("issupertypeof"), 1, fromType);
PT_FAIL_IF_NEG(isSuperType);
if (isSuperType == PT_TRI_YES) return neverType();
if (isSuperType == PT_TRI_NO) return copy(fromType);
if (isInstance(typeToRemove, pt_ce_mixed_type)) {
zv::Val subtractedType = call(typeToRemove, PT_LC("getsubtractedtype"));
PT_FAIL_IF_UNDEF(subtractedType);
if (!isNull(subtractedType)) return intersect2(fromType, subtractedType.raw());
}
zv::Val removed = call(fromType, PT_LC("tryremove"), 1, typeToRemove);
PT_FAIL_IF_UNDEF(removed);
if (!isNull(removed)) return removed;
zv::Val fromFiniteTypes = call(fromType, PT_LC("getfinitetypes"));
PT_FAIL_IF_UNDEF(fromFiniteTypes);
uint32_t fromCount = countOf(fromFiniteTypes.raw());
if (fromCount > 0) {
zv::Val finiteTypesToRemove = call(typeToRemove, PT_LC("getfinitetypes"));
PT_FAIL_IF_UNDEF(finiteTypesToRemove);
if (countOf(finiteTypesToRemove.raw()) > 0) {
zv::Arr result = zv::Arr::create(fromCount);
for (zv::ArrayEntry finite : zv::ArrRef(fromFiniteTypes.raw())) {
bool skip = false;
for (zv::ArrayEntry toRemove : zv::ArrRef(finiteTypesToRemove.raw())) {
int equal = typeEquals(finite.value().raw(), toRemove.value().raw());
PT_FAIL_IF_NEG(equal);
if (equal) {
skip = true;
break;
}
}
if (!skip) {
result.push(finite.value());
}
}
uint32_t resultCount = zend_hash_num_elements(result.table());
if (resultCount == fromCount) return copy(fromType);
if (resultCount == 0) return neverType();
if (resultCount == 1) return copy(zend_hash_index_find(result.table(), 0));
return unionType(std::move(result), false);
}
}
return copy(fromType);
}
static zv::Val removeNull(zval *type)
{
int contains = containsNull(type);
PT_FAIL_IF_NEG(contains);
if (contains) {
zv::Val nullValue = nullType();
PT_FAIL_IF_UNDEF(nullValue);
return remove(type, nullValue.raw());
}
return copy(type);
}
/* -1 = pending exception */
static int containsNull(zval *type)
{
if (isInstance(type, pt_ce_union_type)) {
zv::Val types = getTypes(type);
if (UNEXPECTED(types.isUndef())) return -1;
for (zv::ArrayEntry entry : zv::ArrRef(types.raw())) {
zend_long isNullType = callTrinary(entry.value().raw(), PT_LC("isnull"));
if (UNEXPECTED(isNullType < 0)) return -1;
if (isNullType == PT_TRI_YES) return 1;
}
return 0;
}
return isInstance(type, pt_ce_null_type) ? 1 : 0;
}
static zv::Val union_(uint32_t argc, zval *argv)
{
bool enabled;
if (UNEXPECTED(!cacheEnabled(enabled))) return zv::Val();
if (enabled) return pt_type_combinator_cache_union(argc, argv);
return doUnion(argc, argv);
}
/* {{{ doUnion() and its helpers */
/* the scalar groups of doUnion(): `$scalarTypes[get_class($type)][$type->describe(cache)] = $type`
* — one entry per exact class in first-insertion order, the items a
* description-keyed map until the group is normalized into a list */
struct ScalarGroup
{
zend_class_entry *ce;
zv::Arr items;
TypeList list;
bool removed;
};
/* the markers of doUnion(): `$markers[spl_object_id($site) . '#' . $templateName]`
* in first-insertion order */
struct MarkerEntry
{
zend_object *site;
zv::Val templateName;
zv::Val marker;
};
/* $marker instanceof UnresolvedTemplateArgumentType &&
* !$marker->isClosureSignature(); -1 = pending exception */
static int isTemplateArgumentMarker(zval *type)
{
if (!isInstance(type, pt_ce_unresolved_template_argument_type)) return 0;
bool closureSignature;
if (UNEXPECTED(!pt_unresolved_template_argument_type_is_closure_signature(type, closureSignature))) return -1;
return closureSignature ? 0 : 1;
}
/* addMarker(): the same variable merges into the wider of the two
* inferred types; false = pending exception */
[[nodiscard]] static bool addMarker(std::vector<MarkerEntry> &markers, zval *marker)
{
zval *site = pt_unresolved_template_argument_type_site(marker);
if (UNEXPECTED(site == NULL)) return false;
zv::Val templateName = pt_unresolved_template_argument_type_get_template_name(marker);
if (UNEXPECTED(templateName.isUndef())) return false;
MarkerEntry *existing = NULL;
for (MarkerEntry &entry : markers) {
if (entry.site == Z_OBJ_P(site) && zend_is_identical(entry.templateName.raw(), templateName.raw())) {
existing = &entry;
break;
}
}
if (existing == NULL) {
markers.push_back(MarkerEntry{Z_OBJ_P(site), std::move(templateName), copy(marker)});
return true;
}
if (sameObject(existing->marker.raw(), marker)) return true;
zv::Val existingInitial = call(existing->marker.raw(), PT_LC("getinitialtype"));
if (UNEXPECTED(existingInitial.isUndef())) return false;
zv::Val initial = call(marker, PT_LC("getinitialtype"));
if (UNEXPECTED(initial.isUndef())) return false;
if (isNull(existingInitial) || isNull(initial)) {
// nothing inferred stands for the template's default or bound
if (!isNull(existingInitial)) existing->marker = copy(marker);
return true;
}
zv::Val merged = union2(existingInitial.raw(), initial.raw());
if (UNEXPECTED(merged.isUndef())) return false;
zv::Val withMerged = call(existing->marker.raw(), PT_LC("withinitialtype"), 1, merged.raw());
if (UNEXPECTED(withMerged.isUndef())) return false;
existing->marker = std::move(withMerged);
return true;
}
static zv::Val unionWithMarkers(zv::Val rest, std::vector<MarkerEntry> &markers)
{
if (UNEXPECTED(rest.isUndef())) return zv::Val();
if (isInstance(rest.raw(), pt_ce_mixed_type) && !isInstance(rest.raw(), pt_ce_template_mixed_type)) {
zv::Val subtracted = call(rest.raw(), PT_LC("getsubtractedtype"));
if (UNEXPECTED(subtracted.isUndef())) return zv::Val();
if (isNull(subtracted)) return rest;
}
TypeList members;
bool restIsUnion = isInstance(rest.raw(), pt_ce_union_type);
int restIsTemplate = 0;
if (restIsUnion) {
restIsTemplate = isInstanceMap(rest.raw(), PT_CLASS_TEMPLATE_TYPE);
PT_FAIL_IF_NEG(restIsTemplate);
}
if (isInstance(rest.raw(), pt_ce_never_type)) {
// nothing
} else if (restIsUnion && !restIsTemplate) {
zv::Val restTypes = getTypes(rest.raw());
PT_FAIL_IF_UNDEF(restTypes);
for (zv::ArrayEntry entry : zv::ArrRef(restTypes.raw())) {
members.push_back(copy(entry.value().raw()));
}
} else {
members.push_back(copy(rest.raw()));
}
for (MarkerEntry &entry : markers) {
members.push_back(copy(entry.marker.raw()));
}
if (members.size() == 1) return std::move(members[0]);
if (isInstance(rest.raw(), pt_ce_benevolent_union_type)) {
int isTemplate = isInstanceMap(rest.raw(), PT_CLASS_TEMPLATE_TYPE);
PT_FAIL_IF_NEG(isTemplate);
if (!isTemplate) return benevolentUnionType(listOf(members), true);
}
return unionType(listOf(members), true);
}
static zv::Val doUnion(uint32_t argc, zval *argv)
{
size_t typesCount = argc;
if (typesCount == 0) return neverType();
/* Fast path for single non-union type */
if (typesCount == 1) {
zval *singleType = &argv[0];
if (!isInstance(singleType, pt_ce_union_type)) {
zend_long isArray = callTrinary(singleType, PT_LC("isarray"));
PT_FAIL_IF_NEG(isArray);
if (isArray != PT_TRI_YES) return copy(singleType);
}
}
/* Fast path for common 2-type cases */
if (typesCount == 2) {
zval *a = &argv[0];
zval *b = &argv[1];
/* union(never, X) = X and union(X, never) = X */
int aNever = isImplicitNever(a);
PT_FAIL_IF_NEG(aNever);
if (aNever) return copy(b);
int bNever = isImplicitNever(b);
PT_FAIL_IF_NEG(bNever);
if (bNever) return copy(a);
/* union(mixed, X) = mixed (non-explicit, non-template, no subtracted) */
int aMixed = isPlainMixed(a);
PT_FAIL_IF_NEG(aMixed);
if (aMixed) return copy(a);
int bMixed = isPlainMixed(b);
PT_FAIL_IF_NEG(bMixed);
if (bMixed) return copy(b);
/* union(X, X) = X — for equal array operands, not just identical
* ones (see the twin for why non-array operands keep taking the
* general path) */
if (sameObject(a, b)) return copy(a);
int equal = typeEquals(a, b);
PT_FAIL_IF_NEG(equal);
if (equal) {
zend_long isArray = callTrinary(a, PT_LC("isarray"));
PT_FAIL_IF_NEG(isArray);
if (isArray == PT_TRI_YES) return copy(a);
}
}
std::vector<zv::Val> alreadyNormalized;
zv::Arr benevolentTypes = zv::Arr::create(0);
size_t neverCount = 0;
Level valueLevel(PT_LC("value"));
TypeList types;
types.reserve(argc);
for (uint32_t i = 0; i < argc; i++) {
types.push_back(copy(&argv[i]));
}
/* A member passed more than once contributes nothing; dropping the
* repeats up front keeps the pairwise comparison below from paying
* for them (array_values() of a shape unions the same value type per
* slot). */
if (typesCount > 2) {
zv::Arr seenTypes = zv::Arr::create((uint32_t) typesCount);
TypeList uniqueTypes;
uniqueTypes.reserve(typesCount);
for (size_t i = 0; i < types.size(); i++) {
zval *type = types[i].raw();
zend_ulong typeId = Z_TYPE_P(type) == IS_OBJECT ? (zend_ulong) Z_OBJ_HANDLE_P(type) : (zend_ulong) i;
if (zend_hash_index_add_empty_element(seenTypes.table(), typeId) == NULL) continue;
uniqueTypes.push_back(std::move(types[i]));
}
if (uniqueTypes.size() == 1) return std::move(uniqueTypes[0]);
if (uniqueTypes.size() == 2) return union2(uniqueTypes[0].raw(), uniqueTypes[1].raw());
types = std::move(uniqueTypes);
}
/* transform A | (B | C) to A | B | C - in one pass, a union's members
* are never unions, implicit never or implicit mixed themselves */
TypeList flattenedTypes;
flattenedTypes.reserve(types.size());
std::vector<MarkerEntry> markers;
for (size_t i = 0; i < types.size(); i++) {
zval *type = types[i].raw();
int plainMixed = isPlainMixed(type);
PT_FAIL_IF_NEG(plainMixed);
if (plainMixed) return copy(type);
int marker = isTemplateArgumentMarker(type);
PT_FAIL_IF_NEG(marker);
if (marker) {
if (UNEXPECTED(!addMarker(markers, type))) return zv::Val();
continue;
}
int implicitNever = isImplicitNever(type);
PT_FAIL_IF_NEG(implicitNever);
if (implicitNever) {
neverCount++;
flattenedTypes.push_back(std::move(types[i]));
continue;
}
if (isInstance(type, pt_ce_benevolent_union_type)) {
int isTemplate = isInstanceMap(type, PT_CLASS_TEMPLATE_TYPE);
PT_FAIL_IF_NEG(isTemplate);
if (isTemplate) {
flattenedTypes.push_back(std::move(types[i]));
continue;
}
zv::Val typesInner = getTypes(type);
PT_FAIL_IF_UNDEF(typesInner);
for (zv::ArrayEntry entry : zv::ArrRef(typesInner.raw())) {
zv::Val description = describe(entry.value().raw(), valueLevel);
zend_string *key = describedKey(description);
if (UNEXPECTED(key == NULL)) return zv::Val();
benevolentTypes.set(key, copy(entry.value().raw()));
flattenedTypes.push_back(copy(entry.value().raw()));
}
continue;
}
if (!isInstance(type, pt_ce_union_type)) {
flattenedTypes.push_back(std::move(types[i]));
continue;
}
int isTemplate = isInstanceMap(type, PT_CLASS_TEMPLATE_TYPE);
PT_FAIL_IF_NEG(isTemplate);
if (isTemplate) {
flattenedTypes.push_back(std::move(types[i]));
continue;
}
zv::Val typesInner = getTypes(type);
PT_FAIL_IF_UNDEF(typesInner);
for (zv::ArrayEntry entry : zv::ArrRef(typesInner.raw())) {
int innerMarker = isTemplateArgumentMarker(entry.value().raw());
PT_FAIL_IF_NEG(innerMarker);
if (innerMarker) {
if (UNEXPECTED(!addMarker(markers, entry.value().raw()))) return zv::Val();
continue;
}
flattenedTypes.push_back(copy(entry.value().raw()));
}
alreadyNormalized.push_back(std::move(typesInner));
}
if (!markers.empty()) {
return unionWithMarkers(unionOf(flattenedTypes), markers);
}
types = std::move(flattenedTypes);