Repository navigation
Expand file tree
/
Copy pathScopeOps.cpp
More file actions
2432 lines (2219 loc) · 87.2 KB
/
Copy pathScopeOps.cpp
File metadata and controls
2432 lines (2219 loc) · 87.2 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\ScopeOps — native implementations of MutatingScope's hottest
* scope-table loops: merging, conditional-expression bookkeeping, expression
* invalidation (including a native replacement for the NodeFinder-based AST
* walk) and clone-based scope creation.
*
* The ScopeOps handle class below mirrors src/Analyser/ScopeOps.php method
* for method, in the same order; where a body departs from the twin's shape
* for performance the comment on the method says so. The PHP_METHOD functions
* at the bottom are only the engine ABI glue (parameter parsing + delegation).
* Not final: a PHP stub subclass extends this class, so PHP code calls the
* methods through the shadowed class.
*/
#include "support.h"
#include "zv.h"
#include <cstring>
static zend_class_entry *pt_ce_scope_ops;
/* {{{ scopeWith's cached property layout (owned by the request lifecycle) */
typedef struct _pt_scope_offsets {
int32_t expression_types;
int32_t native_expression_types;
int32_t conditional_expressions;
int32_t currently_assigned;
int32_t currently_allowed_undefined;
int32_t in_function_calls_stack;
int32_t in_first_level_statement;
int32_t after_extract_call;
/* memo props to reset (missing => -1) */
int32_t resolved_types;
int32_t truthy_scopes;
int32_t falsey_scopes;
int32_t node_callback_scope;
int32_t scope_out_of_first_level;
int32_t scope_with_promoted_native;
int32_t walk_scope; /* NodeCallbackScope */
int32_t seeded_walk_scope; /* NodeCallbackScope */
int32_t truthy_value_exprs; /* NodeCallbackScope */
int32_t falsey_value_exprs; /* NodeCallbackScope */
} pt_scope_offsets;
static HashTable pt_scope_offsets_cache;
static bool pt_scope_offsets_cache_inited = false;
static void pt_scope_offsets_free(zval *zv)
{
efree(Z_PTR_P(zv));
}
static pt_scope_offsets *pt_scope_offsets_for(zend_class_entry *ce)
{
pt_scope_offsets *off;
if (!pt_scope_offsets_cache_inited) {
zend_hash_init(&pt_scope_offsets_cache, 4, NULL, pt_scope_offsets_free, 0);
pt_scope_offsets_cache_inited = true;
}
off = (pt_scope_offsets *) zend_hash_find_ptr(&pt_scope_offsets_cache, ce->name);
if (EXPECTED(off != NULL)) {
return off;
}
off = (pt_scope_offsets *) emalloc(sizeof(pt_scope_offsets));
off->expression_types = pt_instance_prop_offset(ce, "expressionTypes", sizeof("expressionTypes") - 1);
off->native_expression_types = pt_instance_prop_offset(ce, "nativeExpressionTypes", sizeof("nativeExpressionTypes") - 1);
off->conditional_expressions = pt_instance_prop_offset(ce, "conditionalExpressions", sizeof("conditionalExpressions") - 1);
off->currently_assigned = pt_instance_prop_offset(ce, "currentlyAssignedExpressions", sizeof("currentlyAssignedExpressions") - 1);
off->currently_allowed_undefined = pt_instance_prop_offset(ce, "currentlyAllowedUndefinedExpressions", sizeof("currentlyAllowedUndefinedExpressions") - 1);
off->in_function_calls_stack = pt_instance_prop_offset(ce, "inFunctionCallsStack", sizeof("inFunctionCallsStack") - 1);
off->in_first_level_statement = pt_instance_prop_offset(ce, "inFirstLevelStatement", sizeof("inFirstLevelStatement") - 1);
off->after_extract_call = pt_instance_prop_offset(ce, "afterExtractCall", sizeof("afterExtractCall") - 1);
off->resolved_types = pt_instance_prop_offset(ce, "resolvedTypes", sizeof("resolvedTypes") - 1);
off->truthy_scopes = pt_instance_prop_offset(ce, "truthyScopes", sizeof("truthyScopes") - 1);
off->falsey_scopes = pt_instance_prop_offset(ce, "falseyScopes", sizeof("falseyScopes") - 1);
off->node_callback_scope = pt_instance_prop_offset(ce, "nodeCallbackScope", sizeof("nodeCallbackScope") - 1);
off->scope_out_of_first_level = pt_instance_prop_offset(ce, "scopeOutOfFirstLevelStatement", sizeof("scopeOutOfFirstLevelStatement") - 1);
off->scope_with_promoted_native = pt_instance_prop_offset(ce, "scopeWithPromotedNativeTypes", sizeof("scopeWithPromotedNativeTypes") - 1);
off->walk_scope = pt_instance_prop_offset(ce, "walkScope", sizeof("walkScope") - 1);
off->seeded_walk_scope = pt_instance_prop_offset(ce, "seededWalkScope", sizeof("seededWalkScope") - 1);
off->truthy_value_exprs = pt_instance_prop_offset(ce, "truthyValueExprs", sizeof("truthyValueExprs") - 1);
off->falsey_value_exprs = pt_instance_prop_offset(ce, "falseyValueExprs", sizeof("falseyValueExprs") - 1);
zend_hash_add_ptr(&pt_scope_offsets_cache, ce->name, off);
return off;
}
/* }}} */
namespace phpstanturbo {
/*
* Mirrors PHPStan\Analyser\ScopeOps. Methods returning zv::Val use UNDEF to
* signal a pending exception; a legitimate PHP null is zv::Val::null().
*/
class ScopeOps
{
public:
/* Mirrors ScopeOps::nodeKey() (pt_node_key carries the key caching). */
static zv::Val nodeKey(zend_object *node, zval *exprPrinter)
{
zend_string *key = pt_node_key(node, exprPrinter);
if (UNEXPECTED(key == NULL)) {
return zv::Val();
}
return zv::Val::adoptString(key);
}
/*
* Mirrors ScopeOps::getTypeFromCache(). *keyOut receives the computed key
* (owned by the caller) on both hit and miss, like the twin's
* unconditional `$key = ...` assignment; it stays NULL only when an
* exception is pending. A stored null counts as a miss — the twin's
* `?? null` cannot distinguish it from an absent entry either.
*/
static zv::Val getTypeFromCache(zval *scope, zend_object *node, zend_string **keyOut)
{
*keyOut = NULL;
zval *exprPrinter = scopeProp(scope, "exprPrinter", sizeof("exprPrinter") - 1);
if (UNEXPECTED(exprPrinter == NULL)) {
return zv::Val();
}
if (UNEXPECTED(Z_TYPE_P(exprPrinter) != IS_OBJECT)) {
zend_throw_error(NULL, "phpstan_turbo: exprPrinter is not an object");
return zv::Val();
}
zv::Str key = zv::Str::adopt(pt_node_key(node, exprPrinter));
if (UNEXPECTED(key.isNull())) {
return zv::Val();
}
zval *table = scopeProp(scope, "resolvedTypes", sizeof("resolvedTypes") - 1);
if (UNEXPECTED(table == NULL)) {
return zv::Val();
}
if (EXPECTED(Z_TYPE_P(table) == IS_ARRAY)) {
zval *found = zend_symtable_find(Z_ARRVAL_P(table), key.get());
if (found != NULL && Z_TYPE_P(found) != IS_NULL) {
zv::Val result = zv::Val::copyOf(zv::Ref(found));
*keyOut = key.take();
return result;
}
}
*keyOut = key.take();
return zv::Val::null();
}
/*
* Mirrors ScopeOps::expressionTypeByKey(): for non-Variable/Closure/
* ArrowFunction nodes whose entry in expressionTypes has certainty Yes,
* returns the tracked type; null otherwise.
*/
static zv::Val expressionTypeByKey(zval *scope, zend_object *node, zend_string *exprString)
{
zend_class_entry *variableCe = pt_class(PT_CLASS_VARIABLE);
zend_class_entry *closureCe = pt_class(PT_CLASS_CLOSURE_EXPR);
zend_class_entry *arrowFunctionCe = pt_class(PT_CLASS_ARROW_FUNCTION);
if (UNEXPECTED(variableCe == NULL || closureCe == NULL || arrowFunctionCe == NULL)) {
return zv::Val();
}
if (instanceof_function(node->ce, variableCe)
|| instanceof_function(node->ce, closureCe)
|| instanceof_function(node->ce, arrowFunctionCe)) {
return zv::Val::null();
}
zval *table = scopeArrayProp(scope, "expressionTypes", sizeof("expressionTypes") - 1);
if (UNEXPECTED(table == NULL)) {
return zv::Val();
}
zval *found = zend_symtable_find(Z_ARRVAL_P(table), exprString);
if (found == NULL) {
return zv::Val::null();
}
zv::Ref holder = zv::Ref(found).deref();
if (UNEXPECTED(!pt_check_holder(holder.raw()))) {
return zv::Val();
}
if (pt_holder_certainty_value(holder.asObject()) != PT_TRI_YES) {
return zv::Val::null();
}
return zv::Val::copyOf(zv::ObjRef(holder.asObject()).propAt(PT_ETH_PROP_TYPE));
}
/* Mirrors ScopeOps::hasExpressionType(). */
static zv::Val hasExpressionType(zval *scope, zend_object *node, zval *exprPrinter)
{
pt_node_class_info *info = pt_get_node_class_info(node->ce);
if (UNEXPECTED(info == NULL)) {
return zv::Val();
}
if (info->is_variable && info->name_offset >= 0) {
zv::Ref name = zv::ObjRef(node).propAtOffset((uint32_t) info->name_offset).deref();
if (name.isString()) {
return hasVariableType(scope, name.asString());
}
}
zv::Str key = zv::Str::adopt(pt_node_key(node, exprPrinter));
if (UNEXPECTED(key.isNull())) {
return zv::Val();
}
zval *table = scopeArrayProp(scope, "expressionTypes", sizeof("expressionTypes") - 1);
if (UNEXPECTED(table == NULL)) {
return zv::Val();
}
zval *found = zend_symtable_find(Z_ARRVAL_P(table), key.get());
if (found == NULL) {
return trinarySingleton(PT_TRI_NO);
}
zv::Ref holder = zv::Ref(found).deref();
if (UNEXPECTED(!pt_check_holder(holder.raw()))) {
return zv::Val();
}
return zv::Val::copyOf(zv::ObjRef(holder.asObject()).propAt(PT_ETH_PROP_CERTAINTY));
}
/* Mirrors ScopeOps::hasVariableType(). */
static zv::Val hasVariableType(zval *scope, zend_string *variableName)
{
if (pt_is_superglobal_name(variableName)) {
return trinarySingleton(PT_TRI_YES);
}
zval *table = scopeProp(scope, "expressionTypes", sizeof("expressionTypes") - 1);
if (UNEXPECTED(table == NULL)) {
return zv::Val();
}
if (EXPECTED(Z_TYPE_P(table) == IS_ARRAY)) {
zv::Str varKey = dollarPrefixed(variableName);
zval *found = zend_hash_find(Z_ARRVAL_P(table), varKey.get());
if (found != NULL) {
zv::Ref holder = zv::Ref(found).deref();
if (UNEXPECTED(!pt_check_holder(holder.raw()))) {
return zv::Val();
}
return zv::Val::copyOf(zv::ObjRef(holder.asObject()).propAt(PT_ETH_PROP_CERTAINTY));
}
}
bool canExist;
if (UNEXPECTED(!pt_call_scope_bool(scope, "cananyvariableexist", sizeof("cananyvariableexist") - 1, 0, NULL, &canExist))) {
return zv::Val();
}
return trinarySingleton(canExist ? PT_TRI_MAYBE : PT_TRI_NO);
}
/*
* Mirrors ScopeOps::scopeWith(), but natively: the hot MutatingScope
* operations end in $this->scopeFactory->create() with ~30 arguments
* where only the expression tables and a couple of flags differ from the
* current scope. Cloning the scope and overwriting exactly those
* properties produces an identical object (the constructor is pure
* property promotion) while skipping the factory call, 30-argument
* dispatch and re-verification. Per-instance memo properties are reset
* to their fresh-constructor defaults.
*/
static zv::Val scopeWith(
zval *scope,
HashTable *expressionTypes,
HashTable *nativeExpressionTypes,
HashTable *conditionalExpressions,
HashTable *currentlyAssignedExpressions,
HashTable *currentlyAllowedUndefinedExpressions,
HashTable *inFunctionCallsStack,
bool inFirstLevelStatement,
bool afterExtractCall)
{
pt_scope_offsets *off = pt_scope_offsets_for(Z_OBJCE_P(scope));
if (UNEXPECTED(off->expression_types < 0 || off->native_expression_types < 0
|| off->conditional_expressions < 0 || off->currently_assigned < 0
|| off->currently_allowed_undefined < 0 || off->in_function_calls_stack < 0
|| off->in_first_level_statement < 0 || off->after_extract_call < 0)) {
zend_throw_error(NULL, "phpstan_turbo: scope property layout mismatch");
return zv::Val();
}
zend_object *clone = zend_objects_clone_obj(Z_OBJ_P(scope));
if (UNEXPECTED(EG(exception))) {
return zv::Val();
}
zv::ObjRef cloneObj(clone);
setTableProp(cloneObj, off->expression_types, expressionTypes);
setTableProp(cloneObj, off->native_expression_types, nativeExpressionTypes);
setTableProp(cloneObj, off->conditional_expressions, conditionalExpressions);
setTableProp(cloneObj, off->currently_assigned, currentlyAssignedExpressions);
setTableProp(cloneObj, off->currently_allowed_undefined, currentlyAllowedUndefinedExpressions);
setTableProp(cloneObj, off->in_function_calls_stack, inFunctionCallsStack);
cloneObj.propAtOffset((uint32_t) off->in_first_level_statement).assign(zv::Val::boolean(inFirstLevelStatement));
cloneObj.propAtOffset((uint32_t) off->after_extract_call).assign(zv::Val::boolean(afterExtractCall));
/* fresh-constructor defaults for per-instance memos */
resetToEmptyArray(cloneObj, off->resolved_types);
resetToEmptyArray(cloneObj, off->truthy_scopes);
resetToEmptyArray(cloneObj, off->falsey_scopes);
resetToNull(cloneObj, off->node_callback_scope);
resetToNull(cloneObj, off->scope_out_of_first_level);
resetToNull(cloneObj, off->scope_with_promoted_native);
resetToNull(cloneObj, off->walk_scope);
resetToNull(cloneObj, off->seeded_walk_scope);
resetToEmptyArray(cloneObj, off->truthy_value_exprs);
resetToEmptyArray(cloneObj, off->falsey_value_exprs);
zval out;
ZVAL_OBJ(&out, clone);
return zv::Val::adopt(out);
}
/*
* Mirrors ScopeOps::mergeVariableHolders(). differing (nullable) receives
* a true marker for every key that is not one shared holder on both sides
* — the twin's &$differingKeys out-parameter.
*/
static zv::Val mergeVariableHolders(zv::TableRef ours, zv::TableRef theirs, HashTable *differing)
{
zv::Arr merged = zv::Arr::create(ours.size());
if (UNEXPECTED(!mergeVariableHoldersInto(merged, ours, theirs, differing))) {
return zv::Val();
}
return zv::Val(std::move(merged));
}
/* Mirrors ScopeOps::finishMerge(). Returns [filteredMerged, mergedNative]. */
static zv::Val finishMerge(zv::TableRef merged, zv::TableRef oursExpr, zv::TableRef theirsExpr, zv::TableRef oursNative, zv::TableRef theirsNative)
{
zv::Arr filteredMerged;
if (UNEXPECTED(!filterHolders(merged, filteredMerged))) {
return zv::Val();
}
zv::Arr oursNativeRemaining = zv::Arr::adoptTable(zend_array_dup(oursNative.table()));
zv::Arr theirsNativeRemaining = zv::Arr::adoptTable(zend_array_dup(theirsNative.table()));
zv::Arr mergedNative = zv::Arr::create(0);
for (auto entry : oursNative) {
zend_string *key = entry.stringKeyOrNull();
zend_ulong idx = entry.indexKey();
zv::Ref holder = entry.value().deref();
if (UNEXPECTED(!pt_check_holder(holder.raw()))) {
return zv::Val();
}
zval *theirNativeSlot = pt_ht_find(theirsNative.table(), key, idx);
if (theirNativeSlot == NULL) {
continue;
}
zval *ourExprSlot = pt_ht_find(oursExpr.table(), key, idx);
if (ourExprSlot == NULL) {
continue;
}
zval *theirExprSlot = pt_ht_find(theirsExpr.table(), key, idx);
if (theirExprSlot == NULL) {
continue;
}
bool equal;
{
zv::Ref ourExprHolder = zv::Ref(ourExprSlot).deref();
if (UNEXPECTED(!pt_check_holder(ourExprHolder.raw()))) {
return zv::Val();
}
if (UNEXPECTED(!pt_holder_equals(holder.raw(), ourExprHolder.raw(), &equal))) {
return zv::Val();
}
}
if (!equal) {
continue;
}
{
zv::Ref theirNativeHolder = zv::Ref(theirNativeSlot).deref();
zv::Ref theirExprHolder = zv::Ref(theirExprSlot).deref();
if (UNEXPECTED(!pt_check_holder(theirNativeHolder.raw())) || UNEXPECTED(!pt_check_holder(theirExprHolder.raw()))) {
return zv::Val();
}
if (UNEXPECTED(!pt_holder_equals(theirNativeHolder.raw(), theirExprHolder.raw(), &equal))) {
return zv::Val();
}
}
if (!equal) {
continue;
}
zval *mergedHolder = pt_ht_find(filteredMerged.table(), key, idx);
if (mergedHolder == NULL) {
continue;
}
tableUpdateCopy(mergedNative.table(), key, idx, zv::Ref(mergedHolder));
pt_ht_del(oursNativeRemaining.table(), key, idx);
pt_ht_del(theirsNativeRemaining.table(), key, idx);
}
/* mergedNative += filter(mergeVariableHolders(oursRemaining, theirsRemaining)) */
{
zv::Val remainingMerged = mergeVariableHolders(zv::TableRef(oursNativeRemaining.table()), zv::TableRef(theirsNativeRemaining.table()), NULL);
if (UNEXPECTED(remainingMerged.isUndef())) {
return zv::Val();
}
zv::Arr remainingFiltered;
if (UNEXPECTED(!filterHolders(zv::TableRef(Z_ARRVAL_P(remainingMerged.raw())), remainingFiltered))) {
return zv::Val();
}
for (auto entry : zv::ArrRef(remainingFiltered.raw())) {
tableUpdateCopy(mergedNative.table(), entry.stringKeyOrNull(), entry.indexKey(), entry.value());
}
}
zv::Arr result = zv::Arr::create(2);
result.push(std::move(filteredMerged));
result.push(std::move(mergedNative));
return zv::Val(std::move(result));
}
/* Mirrors ScopeOps::intersectConditionalExpressions(). */
static zv::Val intersectConditionalExpressions(zv::TableRef ours, zv::TableRef theirs)
{
zv::Arr result = zv::Arr::create(0);
for (auto entry : ours) {
zend_string *key = entry.stringKeyOrNull();
zend_ulong idx = entry.indexKey();
zval *otherHoldersSlot = pt_ht_find(theirs.table(), key, idx);
if (otherHoldersSlot == NULL) {
continue;
}
zv::Ref holders = entry.value().deref();
zv::Ref otherHolders = zv::Ref(otherHoldersSlot).deref();
if (!holders.isArray() || !otherHolders.isArray()) {
continue;
}
HashTable *otherTable = otherHolders.asArrayTable();
zv::Arr intersected; /* stays UNDEF until the first shared holder */
for (auto holderEntry : zv::TableRef(holders.asArrayTable())) {
zend_string *holderKey = holderEntry.stringKeyOrNull();
zend_ulong holderIdx = holderEntry.indexKey();
if (!pt_ht_exists(otherTable, holderKey, holderIdx)) {
continue;
}
if (intersected.isUndef()) {
intersected = zv::Arr::create(0);
}
tableAddNewCopy(intersected.table(), holderKey, holderIdx, holderEntry.value());
}
if (intersected.isUndef()) {
continue;
}
tableAddNew(result.table(), key, idx, std::move(intersected));
}
return zv::Val(std::move(result));
}
/*
* Mirrors ScopeOps::createConditionalExpressions(). The isSuperTypeOf /
* isConstantArray results are cached per guard, exactly like the twin's
* per-guard caches; the input array is only duplicated once the first
* conditional is actually appended.
*/
static zv::Val createConditionalExpressions(zv::TableRef conditional, zv::TableRef ours, zv::TableRef theirs, zv::TableRef merged, zv::TableRef differingKeys)
{
zend_class_entry *virtualNodeCe = pt_class(PT_CLASS_VIRTUAL_NODE);
zend_class_entry *neverTypeCe = pt_class(PT_CLASS_NEVER_TYPE);
if (UNEXPECTED(virtualNodeCe == NULL || neverTypeCe == NULL)) {
return zv::Val();
}
/* A guard is only ever consumed paired with a target: a *different* key
* in the first target loop below, any key in the second one. Deriving a
* guard costs a TypeCombinator::remove() of the two branch types - the
* most expensive step of the merge - so settle which keys can be targets
* with the cheap checks first, bail out when none can, and skip the
* subtraction for a guard no target can pair with. The first target loop
* reuses this set instead of repeating the checks. Mirrors the twin. */
zv::ScratchTable targets(8);
bool hasUndefinedTarget = false;
for (auto diffEntry : differingKeys) {
zend_string *key = diffEntry.stringKeyOrNull();
zend_ulong idx = diffEntry.indexKey();
zval *ourSlot = pt_ht_find(ours.table(), key, idx);
zval *mergedSlot = pt_ht_find(merged.table(), key, idx);
if (ourSlot == NULL) {
if (mergedSlot != NULL) {
zv::Ref mergedHolder = zv::Ref(mergedSlot).deref();
if (UNEXPECTED(!pt_check_holder(mergedHolder.raw()))) {
return zv::Val();
}
if (!instanceof_function(holderExpr(mergedHolder)->ce, virtualNodeCe)) {
hasUndefinedTarget = true;
}
}
continue;
}
zv::Ref holder = zv::Ref(ourSlot).deref();
if (UNEXPECTED(!pt_check_holder(holder.raw()))) {
return zv::Val();
}
if (instanceof_function(holderExpr(holder)->ce, virtualNodeCe)) {
continue;
}
if (mergedSlot != NULL) {
zv::Ref mergedHolder = zv::Ref(mergedSlot).deref();
bool equal;
if (UNEXPECTED(!pt_holder_equals(mergedHolder.raw(), holder.raw(), &equal))) {
return zv::Val();
}
if (equal) {
continue;
}
}
zval targetTrue;
ZVAL_TRUE(&targetTrue);
pt_ht_update(targets.table(), key, idx, &targetTrue);
}
if (!hasUndefinedTarget && targets.size() == 0) {
return zv::Arr::copyOfTable(conditional.table());
}
bool onlySelfIsTarget = !hasUndefinedTarget && targets.size() == 1;
zv::ScratchTable guardsToExclude(8);
zv::ScratchTable typeGuards(8);
/* owns the remainder-typed holders created below; the scratch table
* only borrows them */
zv::Arr createdGuardHolders;
/* guardsToExclude: subtype-absorbed their-branch variables cannot be
* guards (their branch set difference is empty) but stay valid
* conditional targets. Only the merge's differing keys can qualify —
* iterate those (in their insertion order, like the twin) instead of
* the whole holder maps. */
for (auto diffEntry : differingKeys) {
zend_string *key = diffEntry.stringKeyOrNull();
zend_ulong idx = diffEntry.indexKey();
zval *theirSlot = pt_ht_find(theirs.table(), key, idx);
if (theirSlot == NULL) {
continue;
}
zval *mergedSlot = pt_ht_find(merged.table(), key, idx);
if (mergedSlot == NULL) {
continue;
}
zv::Ref holder = zv::Ref(theirSlot).deref();
if (UNEXPECTED(!pt_check_holder(holder.raw()))) {
return zv::Val();
}
bool equalTypes;
{
zv::Ref mergedHolder = zv::Ref(mergedSlot).deref();
if (UNEXPECTED(!pt_check_holder(mergedHolder.raw()))) {
return zv::Val();
}
if (UNEXPECTED(!pt_holder_equal_types(mergedHolder.raw(), holder.raw(), &equalTypes))) {
return zv::Val();
}
}
if (!equalTypes) {
continue;
}
zval *ourSlot = pt_ht_find(ours.table(), key, idx);
if (ourSlot != NULL) {
zv::Ref ourHolder = zv::Ref(ourSlot).deref();
if (UNEXPECTED(!pt_check_holder(ourHolder.raw()))) {
return zv::Val();
}
if (pt_holder_certainty_value(ourHolder.asObject()) != pt_holder_certainty_value(holder.asObject())) {
bool ourEqualTypes;
if (UNEXPECTED(!pt_holder_equal_types(ourHolder.raw(), holder.raw(), &ourEqualTypes))) {
return zv::Val();
}
if (ourEqualTypes) {
continue;
}
}
}
zval trueZv;
ZVAL_TRUE(&trueZv);
pt_ht_update(guardsToExclude.table(), key, idx, &trueZv);
}
/* typeGuards */
for (auto diffEntry : differingKeys) {
zend_string *key = diffEntry.stringKeyOrNull();
zend_ulong idx = diffEntry.indexKey();
zval *ourSlot = pt_ht_find(ours.table(), key, idx);
if (ourSlot == NULL) {
continue;
}
zv::Ref holder = zv::Ref(ourSlot).deref();
if (UNEXPECTED(!pt_check_holder(holder.raw()))) {
return zv::Val();
}
if (instanceof_function(holderExpr(holder)->ce, virtualNodeCe)) {
continue;
}
zval *mergedSlot = pt_ht_find(merged.table(), key, idx);
if (mergedSlot == NULL) {
continue;
}
if (pt_holder_certainty_value(holder.asObject()) != PT_TRI_YES) {
continue;
}
if (pt_ht_exists(guardsToExclude.table(), key, idx)) {
continue;
}
zval *theirSlot = pt_ht_find(theirs.table(), key, idx);
if (theirSlot == NULL) {
/* with no their-branch entry the merged holder keeps our type
* with lowered certainty, so no later type assertion can tell
* the branches apart */
continue;
}
zv::Ref theirHolder = zv::Ref(theirSlot).deref();
if (UNEXPECTED(!pt_check_holder(theirHolder.raw()))) {
return zv::Val();
}
if (pt_holder_certainty_value(theirHolder.asObject()) != PT_TRI_YES) {
continue;
}
bool equalTypes;
if (UNEXPECTED(!pt_holder_equal_types(holder.raw(), theirHolder.raw(), &equalTypes))) {
return zv::Val();
}
if (equalTypes) {
continue;
}
if (onlySelfIsTarget && pt_ht_exists(targets.table(), key, idx)) {
/* the sole target is this very key, which the target loop unsets
* from its own guard set - no pairing can use this guard */
continue;
}
/* the branch set difference — see the twin for why an unchanged
* remainder falls back to the merged-type comparison */
zv::Val remainder = typeCombinatorRemove(holderType(holder), holderType(theirHolder));
if (UNEXPECTED(remainder.isUndef())) {
return zv::Val();
}
if (remainder.ref().instanceOf(neverTypeCe)) {
continue;
}
{
zv::Ref mergedHolder = zv::Ref(mergedSlot).deref();
if (UNEXPECTED(!pt_check_holder(mergedHolder.raw()))) {
return zv::Val();
}
bool mergedEqualsRemainder = pt_types_identical_or_equal(holderType(mergedHolder), remainder.raw());
if (UNEXPECTED(EG(exception))) {
return zv::Val();
}
if (mergedEqualsRemainder) {
continue;
}
}
if (Z_OBJ_P(remainder.raw()) == Z_OBJ_P(holderType(holder))) {
/* borrowed entry — the scratch table has no destructor */
zval borrowed;
ZVAL_COPY_VALUE(&borrowed, holder.raw());
pt_ht_update(typeGuards.table(), key, idx, &borrowed);
} else {
/* ExpressionTypeHolder::createYes($holder->expr, $remainder) —
* owned by createdGuardHolders, borrowed by the scratch table */
zval created;
pt_holder_create(&created, zv::ObjRef(holder.asObject()).propAt(PT_ETH_PROP_EXPR).raw(), remainder.raw(), PT_TRI_YES);
zval borrowed;
ZVAL_COPY_VALUE(&borrowed, &created);
if (createdGuardHolders.isUndef()) {
createdGuardHolders = zv::Arr::create(4);
}
createdGuardHolders.push(zv::Val::adopt(created));
pt_ht_update(typeGuards.table(), key, idx, &borrowed);
}
}
if (typeGuards.size() == 0) {
return zv::Arr::copyOfTable(conditional.table());
}
/* Both isSuperTypeOf() results depend only on the guard, not on the
* target expression — cache them per guard across the target loop. */
zv::ScratchTable guardIsSuperTypeOfTheirExprCache(8);
zv::ScratchTable theirExprIsSuperTypeOfGuardCache(8);
zv::ScratchTable guardIsConstantArrayCache(8);
zv::Arr result; /* stays UNDEF until the first append duplicates the input */
/* main loop: pair non-merged expressions with guards - the settled
* target set already carries the cheap checks */
for (auto targetEntry : zv::TableRef(targets.table())) {
zend_string *key = targetEntry.stringKeyOrNull();
zend_ulong idx = targetEntry.indexKey();
zval *ourSlot = pt_ht_find(ours.table(), key, idx);
if (UNEXPECTED(ourSlot == NULL)) {
continue;
}
zv::Ref holder = zv::Ref(ourSlot).deref();
bool hasSelfGuard = pt_ht_exists(typeGuards.table(), key, idx);
if (typeGuards.size() - (hasSelfGuard ? 1 : 0) == 0) {
continue;
}
bool exprIsGuardExcluded = pt_ht_exists(guardsToExclude.table(), key, idx);
for (auto guardEntry : zv::TableRef(typeGuards.table())) {
zend_string *guardKey = guardEntry.stringKeyOrNull();
zend_ulong guardIdx = guardEntry.indexKey();
zv::Ref guardHolder = guardEntry.value();
if (sameDualKey(guardKey, guardIdx, key, idx)) {
continue;
}
if (exprIsGuardExcluded) {
/* a subtype-absorbed target paired with a constant-array
* guard never helps — skip before pricing supertype checks */
zval *cached = pt_ht_find(guardIsConstantArrayCache.table(), guardKey, guardIdx);
bool isConstantArray;
if (cached != NULL) {
isConstantArray = Z_TYPE_P(cached) == IS_TRUE;
} else {
if (UNEXPECTED(!isConstantArrayYes(holderType(guardHolder), &isConstantArray))) {
return zv::Val();
}
zval cacheVal;
ZVAL_BOOL(&cacheVal, isConstantArray);
pt_ht_update(guardIsConstantArrayCache.table(), guardKey, guardIdx, &cacheVal);
}
if (isConstantArray) {
continue;
}
}
zval *theirGuardSlot = pt_ht_find(theirs.table(), guardKey, guardIdx);
if (theirGuardSlot != NULL) {
zv::Ref theirGuard = zv::Ref(theirGuardSlot).deref();
if (pt_holder_certainty_value(theirGuard.asObject()) == PT_TRI_YES) {
zend_long guardIsSuperTypeOfTheirExpr;
zval *cached = pt_ht_find(guardIsSuperTypeOfTheirExprCache.table(), guardKey, guardIdx);
if (cached != NULL) {
guardIsSuperTypeOfTheirExpr = Z_LVAL_P(cached);
} else {
if (UNEXPECTED(!isSuperTypeOfValue(holderType(guardHolder), holderType(theirGuard), &guardIsSuperTypeOfTheirExpr))) {
return zv::Val();
}
zval cacheVal;
ZVAL_LONG(&cacheVal, guardIsSuperTypeOfTheirExpr);
pt_ht_update(guardIsSuperTypeOfTheirExprCache.table(), guardKey, guardIdx, &cacheVal);
}
if (guardIsSuperTypeOfTheirExpr == PT_TRI_YES) {
continue;
}
bool skip = false;
zval *theirExprSlot = pt_ht_find(theirs.table(), key, idx);
if (theirExprSlot != NULL) {
zv::Ref theirExprHolder = zv::Ref(theirExprSlot).deref();
if (pt_holder_certainty_value(theirExprHolder.asObject()) == PT_TRI_YES && guardIsSuperTypeOfTheirExpr != PT_TRI_NO) {
skip = true;
}
} else if (guardIsSuperTypeOfTheirExpr != PT_TRI_NO) {
bool typesEqual = pt_types_identical_or_equal(holderType(holder), holderType(guardHolder));
if (UNEXPECTED(EG(exception))) {
return zv::Val();
}
if (typesEqual) {
skip = true;
}
}
/* the reverse isSuperTypeOf() is priced last, only
* when the cheaper conditions did not already decide */
if (!skip) {
zend_long theirExprIsSuperTypeOfGuard;
zval *cachedReverse = pt_ht_find(theirExprIsSuperTypeOfGuardCache.table(), guardKey, guardIdx);
if (cachedReverse != NULL) {
theirExprIsSuperTypeOfGuard = Z_LVAL_P(cachedReverse);
} else {
if (UNEXPECTED(!isSuperTypeOfValue(holderType(theirGuard), holderType(guardHolder), &theirExprIsSuperTypeOfGuard))) {
return zv::Val();
}
zval cacheVal;
ZVAL_LONG(&cacheVal, theirExprIsSuperTypeOfGuard);
pt_ht_update(theirExprIsSuperTypeOfGuardCache.table(), guardKey, guardIdx, &cacheVal);
}
if (theirExprIsSuperTypeOfGuard == PT_TRI_YES) {
skip = true;
}
}
if (skip) {
continue;
}
}
}
if (UNEXPECTED(!appendConditional(result, conditional, key, idx, guardKey, guardIdx, guardHolder, holder))) {
return zv::Val();
}
}
}
/* their-only expressions: record certainty-No conditionals per guard */
for (auto diffEntry : differingKeys) {
zend_string *key = diffEntry.stringKeyOrNull();
zend_ulong idx = diffEntry.indexKey();
zval *mergedSlot = pt_ht_find(merged.table(), key, idx);
if (mergedSlot == NULL) {
continue;
}
if (pt_ht_exists(ours.table(), key, idx)) {
continue;
}
zv::Ref mergedHolder = zv::Ref(mergedSlot).deref();
if (UNEXPECTED(!pt_check_holder(mergedHolder.raw()))) {
return zv::Val();
}
if (instanceof_function(holderExpr(mergedHolder)->ce, virtualNodeCe)) {
continue;
}
for (auto guardEntry : zv::TableRef(typeGuards.table())) {
zv::Val noHolder = createNoErrorHolder(zv::ObjRef(mergedHolder.asObject()).propAt(PT_ETH_PROP_EXPR).raw());
if (UNEXPECTED(noHolder.isUndef())) {
return zv::Val();
}
if (UNEXPECTED(!appendConditional(result, conditional, key, idx, guardEntry.stringKeyOrNull(), guardEntry.indexKey(), guardEntry.value(), noHolder.ref()))) {
return zv::Val();
}
}
}
if (!result.isUndef()) {
return zv::Val(std::move(result));
}
return zv::Arr::copyOfTable(conditional.table());
}
/*
* Mirrors ScopeOps::invalidateMethodsOnExpression(): drops tracked
* MethodCall expressions whose var matches the invalidated key. Returns
* null when nothing changed.
*/
static zv::Val invalidateMethodsOnExpression(zval *exprPrinter, zend_string *exprStringToInvalidate, zv::TableRef expressionTypes, zv::TableRef nativeExpressionTypes)
{
zend_class_entry *methodCallCe = pt_class(PT_CLASS_METHOD_CALL);
if (UNEXPECTED(methodCallCe == NULL)) {
return zv::Val();
}
bool invalidated = false;
zv::Arr resultExpr, resultNative; /* stay UNDEF until the first hit */
/* Same compositional-key shortcut as in invalidateExpressionEntries(): a
* method call's key embeds its receiver's key verbatim, so when the
* invalidated key does not occur in the entry's key, the receiver cannot
* match and the entry can be kept without re-printing the receiver. */
const bool canUseKeyPrefilter = !keyMayHideSubExpressions(exprStringToInvalidate)
&& !strContains(exprStringToInvalidate, "/*", 2);
for (auto entry : expressionTypes) {
zend_string *entryKey = entry.stringKeyOrNull();
if (canUseKeyPrefilter && entryKey != NULL
&& !strContainsStr(entryKey, exprStringToInvalidate)
&& !keyMayHideSubExpressions(entryKey)) {
continue;
}
zv::Ref holder = entry.value().deref();
if (UNEXPECTED(!pt_check_holder(holder.raw()))) {
return zv::Val();
}
zend_object *expr = holderExpr(holder);
if (!instanceof_function(expr->ce, methodCallCe)) {
continue;
}
int32_t varOffset = pt_instance_prop_offset(expr->ce, "var", sizeof("var") - 1);
if (varOffset < 0) {
continue;
}
zv::Ref var = zv::ObjRef(expr).propAtOffset((uint32_t) varOffset).deref();
if (!var.isObject()) {
continue;
}
zv::Str varKey = zv::Str::adopt(pt_node_key(var.asObject(), exprPrinter));
if (UNEXPECTED(varKey.isNull())) {
return zv::Val();
}
if (!zend_string_equals(varKey.get(), exprStringToInvalidate)) {
continue;
}
if (resultExpr.isUndef()) {
resultExpr = zv::Arr::adoptTable(zend_array_dup(expressionTypes.table()));
resultNative = zv::Arr::adoptTable(zend_array_dup(nativeExpressionTypes.table()));
}
pt_ht_del(resultExpr.table(), entry.stringKeyOrNull(), entry.indexKey());
pt_ht_del(resultNative.table(), entry.stringKeyOrNull(), entry.indexKey());
invalidated = true;
}
if (!invalidated) {
return zv::Val::null();
}
zv::Arr result = zv::Arr::create(2);
result.push(std::move(resultExpr));
result.push(std::move(resultNative));
return zv::Val(std::move(result));
}
/*
* Mirrors ScopeOps::invalidateExpressionEntries(). Returns
* [expressionTypes, nativeExpressionTypes, conditionalExpressions] with
* the invalidated entries removed, or null when nothing changed; the
* expression tables are only duplicated once an entry is invalidated.
*/
static zv::Val invalidateExpressionEntries(
zval *scope,
zval *exprPrinter,
zend_string *exprStringToInvalidate,
zval *expressionToInvalidate,
bool requireMoreCharacters,
zval *invalidatingClass,
zv::TableRef expressionTypes,
zv::TableRef nativeExpressionTypes,
zv::TableRef conditionalExpressions,
bool keepPropertyFetches)
{
InvalidationQuery query = {
scope,
exprPrinter,
exprStringToInvalidate,
expressionToInvalidate,
invalidatingClass,
zend_string_equals_literal(exprStringToInvalidate, "$this"),
keepPropertyFetches,
};
/* Mirrors the twin's $canUseKeyPrefilter: outside shouldInvalidate()'s
* compositional-key carve-outs, a key that does not contain the
* invalidated key as a substring cannot belong to an expression
* containing the invalidated one, so the much more expensive
* per-expression check can be skipped without being called. */
const bool canUseKeyPrefilter = !query.isThis
&& !keyMayHideSubExpressions(exprStringToInvalidate)
&& !strContains(exprStringToInvalidate, "/*", 2);
bool invalidated = false;
zv::Arr resultExpr, resultNative; /* stay UNDEF until the first hit */
for (auto entry : expressionTypes) {
zend_string *key = entry.stringKeyOrNull();
zend_ulong idx = entry.indexKey();
if (canUseKeyPrefilter && key != NULL
&& !strContainsStr(key, exprStringToInvalidate)
&& !keyMayHideSubExpressions(key)) {
continue;
}
zv::Ref holder = entry.value().deref();
if (UNEXPECTED(!pt_check_holder(holder.raw()))) {
return zv::Val();
}
zend_object *expr = holderExpr(holder);
zend_string *entryKey = key != NULL ? key : zend_long_to_str((zend_long) idx);
bool failed = false;
bool should = shouldInvalidate(query, entryKey, expr, requireMoreCharacters, &failed);
if (key == NULL) {
zend_string_release(entryKey);
}
if (!should) {
if (UNEXPECTED(failed)) {
return zv::Val();
}
continue;
}
if (resultExpr.isUndef()) {
resultExpr = zv::Arr::adoptTable(zend_array_dup(expressionTypes.table()));
resultNative = zv::Arr::adoptTable(zend_array_dup(nativeExpressionTypes.table()));
}