Repository navigation
Expand file tree
/
Copy pathForeachHandler.cpp
More file actions
2048 lines (1906 loc) · 100 KB
/
Copy pathForeachHandler.cpp
File metadata and controls
2048 lines (1906 loc) · 100 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\ForeachHandler — native implementation of
* PHPStan\Analyser\StmtHandler\ForeachHandler.
*
* A DI service (#[AutowiredService]): the constructor keeps the twin's
* arginfo (the Container / VarAnnotationProcessor / AssignHandler classes
* and the #[AutowiredParameter] bools by name) so Nette autowires it.
* processStmt() is registered as the class's statement-handler entry
* (Engine.h).
*
* The iteratee, the convergence passes over the body, the unrolled
* constant-array iterations and the final walk go through NodeScopeResolver's
* direct entries (the fresh-stack guard stays on the recursion);
* VarAnnotationProcessor, AssignHandler::processVirtualAssign(),
* IdenticalNarrowingHelper, ExpressionResult, MutatingScope,
* ExpressionResultStorage, the contexts, the holders, VariableFlow,
* VariableFlowBuilder, InternalThrowPoint and the statement results through
* theirs; the Type queries through the native type dispatch. The twin's
* closures (the `iteratee !== []` type callback, the mapValueType() /
* mapKeyType() replacements) are native closures; the private
* tryProcessUnrolledConstantArrayForeach()'s array shape is a C++ struct.
* $stmt->getDocComment() is read off the comments attribute when the node
* class inherits NodeAbstract's method.
*/
#include "support.h"
#include "generated/ForeachHandler.h"
namespace slots = ptdecl::ForeachHandler::slot;
namespace sigs = ptdecl::ForeachHandler::sig;
#include "zv.h"
#include "TypeTraits.h"
#include "TypeOps.h"
#include "Engine.h"
#include "AnalyserValues.h"
#include "StmtHandlerCalls.h"
#include "LoopHandlerCalls.h"
#include "zend_smart_str.h"
#include <vector>
zend_class_entry *pt_ce_foreach_handler = nullptr;
/* ForeachHandler::FOREACH_UNROLL_LIMIT / ::FOREACH_UNROLL_NESTED_LIMIT */
#define PT_FEH_FOREACH_UNROLL_LIMIT 16
#define PT_FEH_FOREACH_UNROLL_NESTED_LIMIT 8
namespace {
pt_property_site pt_feh_expr_site;
pt_property_site pt_feh_key_var_site;
pt_property_site pt_feh_value_var_site;
pt_property_site pt_feh_by_ref_site;
pt_property_site pt_feh_stmts_site;
pt_property_site pt_feh_variable_name_site;
pt_property_site pt_feh_call_name_site;
pt_property_site pt_feh_arg_value_site;
pt_property_site pt_feh_list_items_site;
pt_property_site pt_feh_item_value_site;
pt_property_site pt_feh_item_key_site;
pt_property_site pt_feh_scalar_value_site;
pt_method_site pt_feh_get_attributes_site;
pt_method_site pt_feh_set_attributes_site;
pt_method_site pt_feh_get_doc_comment_site;
/* the permanent interned strings of the twin's literals (module startup) */
zend_string *pt_feh_identical_narrowing_helper_class = nullptr;
zend_string *pt_feh_empty_or_object_narrowing_helper_class = nullptr;
zend_string *pt_feh_traversable_class = nullptr;
zend_string *pt_feh_iterator_aggregate_class = nullptr;
zend_string *pt_feh_get_iterator = nullptr;
/* $node->getAttributes() / ->setAttributes($attributes) */
zv::Val getAttributes(zval *node)
{
return pt_call_method_cached(pt_feh_get_attributes_site, Z_OBJ_P(node), PT_LC("getattributes"), 0, NULL);
}
[[nodiscard]] bool setAttributes(zval *node, zval *attributes)
{
return !pt_call_method_cached(pt_feh_set_attributes_site, Z_OBJ_P(node), PT_LC("setattributes"), 1, attributes).isUndef();
}
/* $type->getMethod($name, $scope) / $method->getThrowType() */
zv::Val getMethod(zval *type, zend_string *name, zval *scope)
{
zv::Args argv{name, scope};
return pt_type_op(Z_OBJ_P(type), PT_OP_GET_METHOD, 2, argv);
}
zv::Val getThrowType(zval *method)
{
if (UNEXPECTED(Z_TYPE_P(method) != IS_OBJECT)) {
zend_throw_error(NULL, "Call to a member function getThrowType() on %s", zend_zval_value_name(method));
return zv::Val();
}
return pt_extended_method_reflection_call(method, PT_MR_GET_THROW_TYPE);
}
/* $stmt->getDocComment() === null: NodeAbstract's loop over getComments()
* for a class inheriting both methods, the method otherwise; false =
* pending exception */
struct DocCommentMethodCache
{
zend_class_entry *ce;
uint32_t generation;
bool inherits;
zend_function *nodeAbstractMethod;
};
DocCommentMethodCache pt_feh_doc_comment_cache;
[[nodiscard]] bool hasNoDocComment(zval *stmt, bool &out)
{
zend_class_entry *ce = Z_OBJCE_P(stmt);
DocCommentMethodCache &cache = pt_feh_doc_comment_cache;
if (UNEXPECTED(cache.ce != ce || cache.generation != pt_engine_generation)) {
zend_class_entry *nodeAbstract = pt_class(PT_CLASS_NODE_ABSTRACT);
if (UNEXPECTED(nodeAbstract == NULL)) return false;
zend_function *base = (zend_function *) zend_hash_str_find_ptr(&PT_CE(nodeAbstract, function_table), PT_LC("getdoccomment"));
zend_function *own = (zend_function *) zend_hash_str_find_ptr(&PT_CE(ce, function_table), PT_LC("getdoccomment"));
cache = { ce, pt_engine_generation, base != NULL && own == base, base };
}
if (EXPECTED(cache.inherits)) {
zv::Val comments = pt_engine_node_get_comments(Z_OBJ_P(stmt));
if (UNEXPECTED(comments.isUndef())) return false;
out = true;
if (Z_TYPE_P(comments.raw()) != IS_ARRAY) return true;
HashTable *table = Z_ARRVAL_P(comments.raw());
uint32_t count = zend_hash_num_elements(table);
if (count == 0) return true;
zend_class_entry *docCe = pt_class_loaded(PT_CLASS_DOC_COMMENT);
if (docCe == NULL) return EG(exception) == NULL;
for (uint32_t i = count; i-- > 0;) {
zval *comment = zend_hash_index_find(table, i);
if (UNEXPECTED(comment == NULL)) {
zend_error(E_WARNING, "Undefined array key %u", i);
if (UNEXPECTED(EG(exception))) return false;
continue;
}
ZVAL_DEREF(comment);
if (Z_TYPE_P(comment) == IS_OBJECT && instanceof_function(Z_OBJCE_P(comment), docCe)) {
out = false;
return true;
}
}
return true;
}
zv::Val docComment = pt_call_method_cached(pt_feh_get_doc_comment_site, Z_OBJ_P(stmt), PT_LC("getdoccomment"), 0, NULL);
if (UNEXPECTED(docComment.isUndef())) return false;
out = docComment.isNull();
return true;
}
/* ExpressionTypeHolder::createYes($expr, $type) */
zv::Val expressionTypeHolderYes(zval *expr, zval *type)
{
zval holder;
pt_holder_create(&holder, expr, type, PT_TRI_YES);
return zv::Val::adopt(holder);
}
/* new ConditionalExpressionHolder($conditions, $typeHolder) */
zv::Val newConditionalExpressionHolder(zval *conditions, zval *typeHolder)
{
if (UNEXPECTED(Z_TYPE_P(conditions) != IS_ARRAY || zend_hash_num_elements(Z_ARRVAL_P(conditions)) == 0)) {
pt_throw_should_not_happen();
return zv::Val();
}
zval raw;
object_init_ex(&raw, pt_ce_cond_expr_holder);
zv::Val holder = zv::Val::adopt(raw);
zv::ObjRef object(holder.ref().asObject());
object.propAtWrite(PT_CEH_PROP_CONDS, zv::Val::copyOf(zv::Ref(conditions)));
object.propAtWrite(PT_CEH_PROP_TYPEHOLDER, zv::Val::copyOf(zv::Ref(typeHolder)));
return holder;
}
/* $holder->getKey() of a native ConditionalExpressionHolder (owned; NULL =
* pending exception) */
zend_string *conditionalHolderKey(zval *holder)
{
zv::ObjRef object(Z_OBJ_P(holder));
return pt_ceh_key_build(object.propAt(PT_CEH_PROP_CONDS).deref().asArrayTable(), object.propAt(PT_CEH_PROP_TYPEHOLDER).deref().raw());
}
/* new Variable($name) */
zv::Val newVariable(zend_string *name)
{
zval nameZv;
ZVAL_STR(&nameZv, name);
return pt_type_new(PT_CLASS_VARIABLE, 1, &nameZv);
}
/* new ArrayDimFetch($var, $dim) */
zv::Val newArrayDimFetch(zval *var, zval *dim)
{
zv::Args argv{var, dim};
return pt_type_new(PT_CLASS_ARRAY_DIM_FETCH, 2, argv);
}
/* new NativeTypeExpr($scope->getIterableKeyType($type), $scope->getIterableKeyType($nativeType))
* (or the value types), the PHPDoc flavour asked first */
zv::Val newIterableTypeExpr(zval *scope, zval *type, zval *nativeType, bool key)
{
zv::Val phpDocType = key ? pt_mutating_scope_get_iterable_key_type(Z_OBJ_P(scope), type) : pt_mutating_scope_get_iterable_value_type(Z_OBJ_P(scope), type);
if (UNEXPECTED(phpDocType.isUndef())) return zv::Val();
zv::Val nativeIterableType = key ? pt_mutating_scope_get_iterable_key_type(Z_OBJ_P(scope), nativeType) : pt_mutating_scope_get_iterable_value_type(Z_OBJ_P(scope), nativeType);
if (UNEXPECTED(nativeIterableType.isUndef())) return zv::Val();
zv::Args argv{phpDocType.raw(), nativeIterableType.raw()};
return pt_type_new(PT_CLASS_NATIVE_TYPE_EXPR, 2, argv);
}
/* new Array_([]) */
zv::Val newEmptyArrayExpr()
{
zval items;
ZVAL_EMPTY_ARRAY(&items);
return pt_type_new(PT_CLASS_ARRAY_EXPR, 1, &items);
}
/* $type->isSuperTypeOf($other) as a PT_TRI_* value; -1 = pending exception */
zend_long isSuperTypeOf(zval *type, zval *other)
{
if (UNEXPECTED(Z_TYPE_P(type) != IS_OBJECT)) {
zend_throw_error(NULL, "Call to a member function isSuperTypeOf() on %s", zend_zval_value_name(type));
return -1;
}
zv::Val result = pt_type_op(Z_OBJ_P(type), PT_OP_IS_SUPER_TYPE_OF, 1, other);
if (UNEXPECTED(result.isUndef())) return -1;
if (UNEXPECTED(Z_TYPE_P(result.raw()) != IS_OBJECT)) {
zend_throw_error(NULL, "Call to a member function yes() on %s", zend_zval_value_name(result.raw()));
return -1;
}
return pt_result_value(Z_OBJ_P(result.raw()));
}
/* a TrinaryLogic-returning op on a type value; -1 = pending exception */
zend_long typeTrinary(zval *type, pt_type_op_id op, const char *method)
{
if (UNEXPECTED(Z_TYPE_P(type) != IS_OBJECT)) {
zend_throw_error(NULL, "Call to a member function %s() on %s", method, zend_zval_value_name(type));
return -1;
}
return pt_type_op_trinary(Z_OBJ_P(type), op, 0, NULL);
}
/* a Type-returning op on a type value */
zv::Val typeOp(zval *type, pt_type_op_id op, const char *method, uint32_t argc = 0, zval *argv = NULL)
{
if (UNEXPECTED(Z_TYPE_P(type) != IS_OBJECT)) {
zend_throw_error(NULL, "Call to a member function %s() on %s", method, zend_zval_value_name(type));
return zv::Val();
}
return pt_type_op(Z_OBJ_P(type), op, argc, argv);
}
/* the element of a list at `index` (borrowed), NULL when missing */
inline zval *listAt(zval *list, zend_ulong index)
{
if (UNEXPECTED(Z_TYPE_P(list) != IS_ARRAY)) return NULL;
zval *found = zend_hash_index_find(Z_ARRVAL_P(list), index);
if (found != NULL) {
ZVAL_DEREF(found);
}
return found;
}
/* TypeCombinator::union(...$list) over a list built here */
zv::Val unionOfList(zv::Arr &list)
{
HashTable *table = list.table();
uint32_t count = zend_hash_num_elements(table);
if (count == 0) return pt_type_combinator_union(0, NULL);
if (HT_IS_PACKED(table) && table->nNumUsed == count) return pt_type_combinator_union(count, table->arPacked);
return pt_type_combinator_call_spread(PT_LC("union"), table);
}
} // namespace
/* the last convergence pass when it recorded its emissions (its
* [entries, recording] record), NULL otherwise */
static zval *lastRecordedPass(zv::Val &previousPass)
{
if (!previousPass.ref().isArray()) return NULL;
zval *recording = zend_hash_index_find(Z_ARRVAL_P(previousPass.raw()), 1);
return recording != NULL && Z_TYPE_P(recording) == IS_OBJECT ? previousPass.raw() : NULL;
}
namespace phpstanturbo {
/* Mirrors PHPStan\Analyser\StmtHandler\ForeachHandler; UNDEF = pending
* exception. */
class ForeachHandler
{
public:
explicit ForeachHandler(zend_object *self) : self(self) {}
/* the constructor body: the promoted properties */
void construct(zval *container, bool implicitThrows, zval *varAnnotationProcessor, zval *assignHandler, bool polluteScopeWithAlwaysIterableForeach)
{
zv::ObjRef object(self);
object.propAtWrite(slots::container, zv::Val::copyOf(zv::Ref(container)));
object.propAtWrite(slots::implicitThrows, zv::Val::boolean(implicitThrows));
object.propAtWrite(slots::varAnnotationProcessor, zv::Val::copyOf(zv::Ref(varAnnotationProcessor)));
object.propAtWrite(slots::assignHandler, zv::Val::copyOf(zv::Ref(assignHandler)));
object.propAtWrite(slots::polluteScopeWithAlwaysIterableForeach, zv::Val::boolean(polluteScopeWithAlwaysIterableForeach));
}
/* Mirrors supports(); false = pending exception */
[[nodiscard]] bool supports(zval *stmt, bool &out) const
{
bool error = false;
out = ptsh::isInstanceOf(stmt, PT_CLASS_FOREACH_STMT, error);
return !error;
}
/* Mirrors processStmt(). */
zv::Val processStmt(zval *nodeScopeResolver, zval *stmt, zval *entryScope, zval *originalStorage, zval *nodeCallback, zval *context) const
{
bool polluteScopeWithAlwaysIterableForeach = ptlh::boolSlot(self, slots::polluteScopeWithAlwaysIterableForeach);
StmtParts parts;
if (UNEXPECTED(!parts.read(stmt))) return zv::Val();
zval *iteratee = parts.expr.raw();
zv::Val scope = zv::Val::copyOf(zv::Ref(entryScope));
if (parts.exprName != NULL) {
scope = processVarAnnotation(scope.raw(), parts.exprName, stmt);
if (UNEXPECTED(scope.isUndef())) return zv::Val();
}
bool resolveTemplateArguments;
if (UNEXPECTED(!pt_statement_context_should_resolve_template_arguments(context, resolveTemplateArguments))) return zv::Val();
zv::Val condResult;
{
zv::Val expressionContext = pt_expression_context_create_deep(resolveTemplateArguments);
if (UNEXPECTED(expressionContext.isUndef())) return zv::Val();
condResult = pt_node_scope_resolver_process_expr_node(nodeScopeResolver, stmt, iteratee, scope.raw(), originalStorage, nodeCallback, expressionContext.raw());
if (UNEXPECTED(condResult.isUndef())) return zv::Val();
}
if (UNEXPECTED(!pt_node_scope_resolver_call_node_callback(nodeScopeResolver, nodeCallback, stmt, entryScope, originalStorage))) return zv::Val();
zv::Arr throwPoints, impurePoints;
{
zv::Val hold;
if (UNEXPECTED(!ptlh::arrayOf(pt_expression_result_throw_points(condResult.raw(), hold), throwPoints))) return zv::Val();
}
{
zv::Val hold;
if (UNEXPECTED(!ptlh::arrayOf(pt_expression_result_impure_points(condResult.raw(), hold), impurePoints))) return zv::Val();
}
{
zv::Val hold;
zval *resultScope = pt_expression_result_scope(condResult.raw(), hold);
if (UNEXPECTED(resultScope == NULL)) return zv::Val();
scope = zv::Val::copyOf(zv::Ref(resultScope));
}
/* $arrayComparisonExpr = new BinaryOp\NotIdentical($stmt->expr, new Array_([])) */
zv::Val comparisonRight = newEmptyArrayExpr();
if (UNEXPECTED(comparisonRight.isUndef())) return zv::Val();
zv::Val arrayComparisonExpr;
{
zv::Args argv{iteratee, comparisonRight.raw()};
arrayComparisonExpr = pt_type_new(PT_CLASS_BINARY_OP_NOT_IDENTICAL, 2, argv);
if (UNEXPECTED(arrayComparisonExpr.isUndef())) return zv::Val();
}
{
zv::Val inForeachNode = pt_type_new(PT_CLASS_IN_FOREACH_NODE, 1, stmt);
if (UNEXPECTED(inForeachNode.isUndef())) return zv::Val();
if (UNEXPECTED(!pt_node_scope_resolver_call_node_callback(nodeScopeResolver, nodeCallback, inForeachNode.raw(), scope.raw(), originalStorage))) return zv::Val();
}
zv::Val originalScope = zv::Val::copyOf(scope.ref());
zv::Val bodyScope = zv::Val::copyOf(scope.ref());
zv::Val foreachIterateeType = pt_expression_result_get_type(condResult.raw());
if (UNEXPECTED(foreachIterateeType.isUndef())) return zv::Val();
zv::Val foreachNativeIterateeType = pt_expression_result_get_native_type(condResult.raw());
if (UNEXPECTED(foreachNativeIterateeType.isUndef())) return zv::Val();
if (parts.keyVarIsVariable) {
zv::Val keyTypeExpr = newIterableTypeExpr(originalScope.raw(), foreachIterateeType.raw(), foreachNativeIterateeType.raw(), true);
if (UNEXPECTED(keyTypeExpr.isUndef())) return zv::Val();
zv::Args argv{parts.keyVar.raw(), keyTypeExpr.raw()};
zv::Val assignNode = pt_type_new(PT_CLASS_VARIABLE_ASSIGN_NODE, 2, argv);
if (UNEXPECTED(assignNode.isUndef())) return zv::Val();
if (UNEXPECTED(!pt_node_scope_resolver_call_node_callback(nodeScopeResolver, nodeCallback, assignNode.raw(), originalScope.raw(), originalStorage))) return zv::Val();
}
if (parts.valueVarIsVariable) {
zv::Val valueTypeExpr = newIterableTypeExpr(originalScope.raw(), foreachIterateeType.raw(), foreachNativeIterateeType.raw(), false);
if (UNEXPECTED(valueTypeExpr.isUndef())) return zv::Val();
zv::Args argv{parts.valueVar.raw(), valueTypeExpr.raw()};
zv::Val assignNode = pt_type_new(PT_CLASS_VARIABLE_ASSIGN_NODE, 2, argv);
if (UNEXPECTED(assignNode.isUndef())) return zv::Val();
if (UNEXPECTED(!pt_node_scope_resolver_call_node_callback(nodeScopeResolver, nodeCallback, assignNode.raw(), originalScope.raw(), originalStorage))) return zv::Val();
} else if (parts.valueVarIsList) {
zv::Val valueTypeExpr = newIterableTypeExpr(originalScope.raw(), foreachIterateeType.raw(), foreachNativeIterateeType.raw(), false);
if (UNEXPECTED(valueTypeExpr.isUndef())) return zv::Val();
zv::Args argv{parts.valueVar.raw(), valueTypeExpr.raw()};
zv::Val virtualAssign = pt_type_new(PT_CLASS_ASSIGN_EXPR, 2, argv);
if (UNEXPECTED(virtualAssign.isUndef())) return zv::Val();
zv::Val valueVarAttributes = getAttributes(parts.valueVar.raw());
if (UNEXPECTED(valueVarAttributes.isUndef())) return zv::Val();
zv::Val attributes = pt_attributes_without_expression_key(valueVarAttributes.raw());
if (UNEXPECTED(!setAttributes(virtualAssign.raw(), attributes.raw()))) return zv::Val();
if (UNEXPECTED(!pt_node_scope_resolver_call_node_callback(nodeScopeResolver, nodeCallback, virtualAssign.raw(), scope.raw(), originalStorage))) return zv::Val();
}
// the "iteratee !== []" narrowing every loop pass merges in - composed
// once from the iteratee's result (the same sentinel comparison the
// walked synthetic would delegate to); the walk is the composition's
// miss seam
zv::Val nonEmptyIterateeScope = zv::Val::copyOf(scope.ref());
if (polluteScopeWithAlwaysIterableForeach) {
zv::Val identicalNarrowingHelper = ptlh::containerGetByType(OBJ_PROP_NUM(self, slots::container), pt_feh_identical_narrowing_helper_class);
if (UNEXPECTED(identicalNarrowingHelper.isUndef())) return zv::Val();
if (UNEXPECTED(Z_TYPE_P(identicalNarrowingHelper.raw()) != IS_OBJECT)) {
zend_throw_error(NULL, "Call to a member function specifyIdenticalAgainstType() on %s", zend_zval_value_name(identicalNarrowingHelper.raw()));
return zv::Val();
}
zv::Val emptyArrayType;
{
zval keyTypes, valueTypes, out;
ZVAL_EMPTY_ARRAY(&keyTypes);
ZVAL_EMPTY_ARRAY(&valueTypes);
if (UNEXPECTED(!pt_constant_array_type_new(&out, &keyTypes, &valueTypes))) return zv::Val();
emptyArrayType = zv::Val::adopt(out);
}
zend_object *falseContextObject = pt_type_specifier_context_create_false();
if (UNEXPECTED(falseContextObject == NULL)) return zv::Val();
zval falseContext;
ZVAL_OBJ(&falseContext, falseContextObject);
zv::Val subjectArgResult = pt_identical_narrowing_helper_capture_first_arg_result(identicalNarrowingHelper.raw(), iteratee, originalStorage);
if (UNEXPECTED(subjectArgResult.isUndef())) return zv::Val();
zv::Val identicalTypeCallback = pt_native_closure(&nonEmptyIterateeTypeBody, condResult.raw(), emptyArrayType.raw());
zv::Val nonEmptyTypes = pt_identical_narrowing_helper_specify_identical_against_type(identicalNarrowingHelper.raw(), iteratee, condResult.raw(), comparisonRight.raw(), emptyArrayType.raw(), &falseContext, scope.raw(), subjectArgResult.raw(), identicalTypeCallback.raw());
if (UNEXPECTED(nonEmptyTypes.isUndef())) return zv::Val();
if (!nonEmptyTypes.isNull()) {
nonEmptyIterateeScope = pt_mutating_scope_apply_specified_types(Z_OBJ_P(scope.raw()), nonEmptyTypes.raw());
} else {
zend_object *truthy = pt_type_specifier_context_create_truthy();
if (UNEXPECTED(truthy == NULL)) return zv::Val();
zval truthyContext;
ZVAL_OBJ(&truthyContext, truthy);
nonEmptyIterateeScope = pt_node_scope_resolver_narrow_scope_with_condition(nodeScopeResolver, scope.raw(), arrayComparisonExpr.raw(), &truthyContext);
}
if (UNEXPECTED(nonEmptyIterateeScope.isUndef())) return zv::Val();
}
zv::Val replayBodyRecording, replayPassStorage, replayPassResult, replayEntryScope;
zv::Val previousPass = zv::Val::null();
zv::Val previousPassStorage = zv::Val::null();
zv::Val unrolledEndScope;
bool unrolled = false;
zend_long unrolledTotalKeys = 0;
bool isTopLevel;
if (UNEXPECTED(!pt_statement_context_is_top_level(context, isTopLevel))) return zv::Val();
if (isTopLevel) {
zv::Val storage = pt_expression_result_storage_duplicate(originalStorage);
if (UNEXPECTED(storage.isUndef())) return zv::Val();
originalScope = zv::Val::copyOf(nonEmptyIterateeScope.ref());
// $originalScope may narrow the iteratee to a non-empty array - a genuinely
// different scope than its own. The narrowing is tracked by the scope
// (getTypeOnScope's authoritative read), so the iteratee only needs
// reprocessing there when the scope neither owns nor matches its state.
bool answers;
if (UNEXPECTED(!pt_expression_result_answers_on_scope(condResult.raw(), originalScope.raw(), false, answers))) return zv::Val();
if (answers) {
if (UNEXPECTED(!pt_expression_result_answers_on_scope(condResult.raw(), originalScope.raw(), true, answers))) return zv::Val();
}
if (answers) {
foreachIterateeType = pt_expression_result_get_type_on_scope(condResult.raw(), originalScope.raw(), false);
if (UNEXPECTED(foreachIterateeType.isUndef())) return zv::Val();
foreachNativeIterateeType = pt_expression_result_get_type_on_scope(condResult.raw(), originalScope.raw(), true);
if (UNEXPECTED(foreachNativeIterateeType.isUndef())) return zv::Val();
} else {
// the duplicate lets subresults whose state matches answer from
// the already-processed iteratee instead of being re-priced
zv::Val duplicate = pt_expression_result_storage_duplicate(originalStorage);
if (UNEXPECTED(duplicate.isUndef())) return zv::Val();
zv::Val iterateeResult = pt_node_scope_resolver_process_expr_on_demand(nodeScopeResolver, iteratee, originalScope.raw(), duplicate.raw());
if (UNEXPECTED(iterateeResult.isUndef())) return zv::Val();
foreachIterateeType = pt_expression_result_get_type(iterateeResult.raw());
if (UNEXPECTED(foreachIterateeType.isUndef())) return zv::Val();
foreachNativeIterateeType = pt_expression_result_get_native_type(iterateeResult.raw());
if (UNEXPECTED(foreachNativeIterateeType.isUndef())) return zv::Val();
}
UnrolledResult unrolledResult;
if (UNEXPECTED(!tryProcessUnrolledConstantArrayForeach(nodeScopeResolver, stmt, parts, originalScope.raw(), originalStorage, context, foreachIterateeType.raw(), foreachNativeIterateeType.raw(), unrolledResult))) return zv::Val();
if (unrolledResult.found) {
bodyScope = std::move(unrolledResult.bodyScope);
unrolledEndScope = std::move(unrolledResult.endScope);
unrolled = true;
unrolledTotalKeys = unrolledResult.totalKeys;
} else {
if (UNEXPECTED(!pt_mutating_scope_push_expression_result_storage(Z_OBJ_P(scope.raw()), storage.raw()))) return zv::Val();
bodyScope = enterForeach(nodeScopeResolver, originalScope.raw(), storage.raw(), originalScope.raw(), stmt, parts, foreachIterateeType.raw(), foreachNativeIterateeType.raw(), nodeCallback);
pt_finally([&]() { (void) pt_mutating_scope_pop_expression_result_storage(Z_OBJ_P(scope.raw())); });
if (UNEXPECTED(EG(exception))) return zv::Val();
zend_long count = 0;
zv::Val prevEntryScope;
// each pass after the first re-walks only the statements whose
// entry state differs from the previous pass's (StatementsHandler::processLoopPassStmtNodes())
bool bodyIsReplayable;
if (UNEXPECTED(!pt_node_scope_resolver_is_replayable_convergence_body(nodeScopeResolver, stmt, parts.stmts.raw(), bodyIsReplayable))) return zv::Val();
do {
zv::Val prevScope = zv::Val::copyOf(bodyScope.ref());
bodyScope = pt_mutating_scope_merge_with(Z_OBJ_P(bodyScope.raw()), nonEmptyIterateeScope.raw());
if (UNEXPECTED(bodyScope.isUndef())) return zv::Val();
if (!prevEntryScope.isNull()) {
bool equal;
if (UNEXPECTED(!ptlh::scopesEqual(bodyScope.raw(), prevEntryScope.raw(), equal))) return zv::Val();
if (equal) {
// walking is deterministic in the entry scope - an unchanged entry
// reproduces the previous pass's exit, so the verification walk is skipped
bodyScope = std::move(prevScope);
break;
}
}
prevEntryScope = zv::Val::copyOf(bodyScope.ref());
storage = pt_expression_result_storage_duplicate(originalStorage);
if (UNEXPECTED(storage.isUndef())) return zv::Val();
// the statements this pass replays answer from the results the previous pass stored
if (!previousPassStorage.isNull() && UNEXPECTED(!pt_expression_result_storage_merge_results(storage.raw(), previousPassStorage.raw()))) return zv::Val();
zv::Val bodyRecording = ptlh::newPassNodeCallback(true);
if (UNEXPECTED(bodyRecording.isUndef())) return zv::Val();
if (UNEXPECTED(!pt_mutating_scope_push_expression_result_storage(Z_OBJ_P(scope.raw()), storage.raw()))) return zv::Val();
zv::Val bodyScopeResult;
bool brokeOut = false;
[&]() {
zv::Val entered = enterForeach(nodeScopeResolver, bodyScope.raw(), storage.raw(), originalScope.raw(), stmt, parts, foreachIterateeType.raw(), foreachNativeIterateeType.raw(), nodeCallback);
if (UNEXPECTED(entered.isUndef())) return;
bodyScope = std::move(entered);
zv::Val deepContext = pt_statement_context_enter_deep(context);
if (UNEXPECTED(deepContext.isUndef())) return;
zv::Val passContext = pt_statement_context_without_template_argument_resolution(deepContext.raw());
if (UNEXPECTED(passContext.isUndef())) return;
zv::Val passRecord = zv::Val::null();
zv::Val walked = pt_node_scope_resolver_process_loop_pass_stmt_nodes(nodeScopeResolver, stmt, parts.stmts.raw(), bodyScope.raw(), storage.raw(), bodyRecording.raw(), passContext.raw(), previousPass.raw(), passRecord);
if (UNEXPECTED(walked.isUndef())) return;
previousPass = std::move(passRecord);
previousPassStorage = zv::Val::copyOf(storage.ref());
bodyScopeResult = pt_internal_statement_result_filter_out_loop_exit_points(walked.raw());
if (UNEXPECTED(bodyScopeResult.isUndef())) return;
zv::Val backEdgeScope = pt_internal_statement_result_loop_back_edge_scope(bodyScopeResult.raw());
if (UNEXPECTED(backEdgeScope.isUndef())) return;
if (backEdgeScope.isNull()) {
bodyScope = std::move(prevScope);
brokeOut = true;
return;
}
bodyScope = std::move(backEdgeScope);
}();
pt_finally([&]() { (void) pt_mutating_scope_pop_expression_result_storage(Z_OBJ_P(scope.raw())); });
if (UNEXPECTED(EG(exception))) return zv::Val();
if (brokeOut) break;
// the candidate to replace the final walk when this pass's
// entry turns out to be the fixpoint
if (bodyIsReplayable) {
replayBodyRecording = std::move(bodyRecording);
replayPassStorage = zv::Val::copyOf(storage.ref());
replayPassResult = zv::Val::copyOf(bodyScopeResult.ref());
replayEntryScope = zv::Val::copyOf(prevEntryScope.ref());
}
bool equal;
if (UNEXPECTED(!ptlh::scopesEqual(bodyScope.raw(), prevScope.raw(), equal))) return zv::Val();
if (equal) break;
if (count >= PT_LH_GENERALIZE_AFTER_ITERATION_LIMIT) {
zv::Val flowHold;
zval *passFlow = pt_internal_statement_result_variable_flow(bodyScopeResult.raw(), flowHold);
if (UNEXPECTED(passFlow == NULL)) return zv::Val();
bodyScope = ptlh::generalizeWithWrittenNames(prevScope.raw(), bodyScope.raw(), stmt, passFlow);
if (UNEXPECTED(bodyScope.isUndef())) return zv::Val();
}
count++;
} while (count < PT_LH_LOOP_SCOPE_ITERATIONS_LIMIT);
}
}
bodyScope = pt_mutating_scope_merge_with(Z_OBJ_P(bodyScope.raw()), nonEmptyIterateeScope.raw());
if (UNEXPECTED(bodyScope.isUndef())) return zv::Val();
zv::Val finalEntryScope = zv::Val::copyOf(bodyScope.ref());
zval *lastPass = lastRecordedPass(previousPass);
zval *storage = originalStorage;
bodyScope = enterForeach(nodeScopeResolver, bodyScope.raw(), storage, originalScope.raw(), stmt, parts, foreachIterateeType.raw(), foreachNativeIterateeType.raw(), nodeCallback);
if (UNEXPECTED(bodyScope.isUndef())) return zv::Val();
bool replay = !replayBodyRecording.isNull() && !replayPassStorage.isNull() && !replayPassResult.isNull() && !replayEntryScope.isNull();
if (replay) {
if (UNEXPECTED(!ptlh::scopesEqual(finalEntryScope.raw(), replayEntryScope.raw(), replay))) return zv::Val();
}
zv::Val finalScopeResult;
if (replay) {
// the final walk would repeat the recorded fixpoint pass exactly
// (same entry scope, deterministic walk) - adopt the pass's results
// and replay its emissions through the real callback instead
if (UNEXPECTED(!pt_expression_result_storage_merge_results(originalStorage, replayPassStorage.raw()))) return zv::Val();
if (UNEXPECTED(!pt_node_scope_resolver_replay_recording(nodeScopeResolver, replayBodyRecording.raw(), nodeCallback, originalStorage, scope.raw()))) return zv::Val();
finalScopeResult = std::move(replayPassResult);
} else if (lastPass != NULL && !previousPassStorage.isNull()) {
// the last pass stands in for the statements whose state it walked
// with - they replay through the real callback
if (UNEXPECTED(!pt_expression_result_storage_merge_results(originalStorage, previousPassStorage.raw()))) return zv::Val();
zval *stmts = ptsh::readNodeProperty(pt_feh_stmts_site, stmt, PT_LC("stmts"));
if (UNEXPECTED(stmts == NULL)) return zv::Val();
zv::Val stmtsHold = zv::Val::copyOf(zv::Ref(stmts));
zv::Val walked = pt_node_scope_resolver_process_loop_final_stmt_nodes(nodeScopeResolver, stmt, stmtsHold.raw(), bodyScope.raw(), storage, nodeCallback, context, lastPass);
if (UNEXPECTED(walked.isUndef())) return zv::Val();
finalScopeResult = pt_internal_statement_result_filter_out_loop_exit_points(walked.raw());
if (UNEXPECTED(finalScopeResult.isUndef())) return zv::Val();
} else {
zv::Val finalPassContext;
if (unrolled) {
finalPassContext = pt_statement_context_enter_unrolled_foreach(context, unrolledTotalKeys);
if (UNEXPECTED(finalPassContext.isUndef())) return zv::Val();
} else {
finalPassContext = zv::Val::copyOf(zv::Ref(context));
}
zval *stmts = ptsh::readNodeProperty(pt_feh_stmts_site, stmt, PT_LC("stmts"));
if (UNEXPECTED(stmts == NULL)) return zv::Val();
zv::Val stmtsHold = zv::Val::copyOf(zv::Ref(stmts));
zv::Val walked = pt_node_scope_resolver_process_stmt_nodes_internal(nodeScopeResolver, stmt, stmtsHold.raw(), bodyScope.raw(), storage, nodeCallback, finalPassContext.raw());
if (UNEXPECTED(walked.isUndef())) return zv::Val();
finalScopeResult = pt_internal_statement_result_filter_out_loop_exit_points(walked.raw());
if (UNEXPECTED(finalScopeResult.isUndef())) return zv::Val();
}
zval *result = finalScopeResult.raw();
zv::Val finalScope = zv::Val::null();
{
bool endReachable;
if (UNEXPECTED(!pt_internal_statement_result_is_end_reachable(result, endReachable))) return zv::Val();
if (endReachable) {
zv::Val hold;
zval *resultScope = pt_internal_statement_result_scope(result, hold);
if (UNEXPECTED(resultScope == NULL)) return zv::Val();
finalScope = zv::Val::copyOf(zv::Ref(resultScope));
}
}
zv::Arr scopesWithIterableValueType = zv::Arr::empty();
/* re-read, like the twin's property reads after the walks */
if (UNEXPECTED(!parts.read(stmt))) return zv::Val();
iteratee = parts.expr.raw();
zval *keyVarExpr = NULL;
zv::Val originalKeyVarExpr;
if (parts.keyVarName != NULL) {
keyVarExpr = parts.keyVar.raw();
zval nameZv;
ZVAL_STR(&nameZv, parts.keyVarName);
originalKeyVarExpr = pt_type_new(PT_CLASS_ORIGINAL_FOREACH_KEY_EXPR, 1, &nameZv);
if (UNEXPECTED(originalKeyVarExpr.isUndef())) return zv::Val();
}
zv::Val originalValueExpr;
if (parts.valueVarName != NULL) {
zval nameZv;
ZVAL_STR(&nameZv, parts.valueVarName);
originalValueExpr = pt_type_new(PT_CLASS_ORIGINAL_FOREACH_VALUE_EXPR, 1, &nameZv);
if (UNEXPECTED(originalValueExpr.isUndef())) return zv::Val();
}
// With a key variable, each iteration is tracked through the original key
// expression and the narrowed element is projected onto the array dim fetch.
// Without one (`foreach ($a as $v)`) we instead track the original value
// expression and rewrite the array value type directly from the value var.
zval *trackingExpr = !originalKeyVarExpr.isNull() ? originalKeyVarExpr.raw() : (!originalValueExpr.isNull() ? originalValueExpr.raw() : NULL);
bool continueExitPointHasUnoriginalKeyType = false;
if (trackingExpr != NULL && !finalScope.isNull()) {
zend_long has = pt_mutating_scope_has_expression_type(Z_OBJ_P(finalScope.raw()), trackingExpr);
if (UNEXPECTED(has < 0)) return zv::Val();
if (has == PT_TRI_YES) {
scopesWithIterableValueType.push(zv::Ref(finalScope.raw()));
} else {
continueExitPointHasUnoriginalKeyType = true;
}
}
{
zv::Val continues = ptlh::continueExitPoints(result);
if (UNEXPECTED(continues.isUndef())) return zv::Val();
for (auto entry : zv::ArrRef(continues.raw())) {
zv::Val hold;
zval *continueScopeSlot = pt_internal_statement_exit_point_scope(entry.value().deref().raw(), hold);
if (UNEXPECTED(continueScopeSlot == NULL)) return zv::Val();
zv::Val continueScope = zv::Val::copyOf(zv::Ref(continueScopeSlot));
if (finalScope.isNull()) {
finalScope = zv::Val::copyOf(continueScope.ref());
} else if (UNEXPECTED(!ptlh::otherMergeWith(continueScope.raw(), finalScope))) {
return zv::Val();
}
bool tracked = false;
if (trackingExpr != NULL) {
zend_long has = pt_mutating_scope_has_expression_type(Z_OBJ_P(continueScope.raw()), trackingExpr);
if (UNEXPECTED(has < 0)) return zv::Val();
tracked = has == PT_TRI_YES;
}
if (!tracked) {
continueExitPointHasUnoriginalKeyType = true;
continue;
}
scopesWithIterableValueType.push(std::move(continueScope));
}
}
zv::Val breakExitPoints = ptlh::breakExitPoints(result);
if (UNEXPECTED(breakExitPoints.isUndef())) return zv::Val();
for (auto entry : zv::ArrRef(breakExitPoints.raw())) {
zv::Val hold;
zval *breakScope = pt_internal_statement_exit_point_scope(entry.value().deref().raw(), hold);
if (UNEXPECTED(breakScope == NULL)) return zv::Val();
if (finalScope.isNull()) {
finalScope = zv::Val::copyOf(zv::Ref(breakScope));
} else if (UNEXPECTED(!ptlh::otherMergeWith(breakScope, finalScope))) {
return zv::Val();
}
}
if (finalScope.isNull()) {
zv::Val hold;
zval *resultScope = pt_internal_statement_result_scope(result, hold);
if (UNEXPECTED(resultScope == NULL)) return zv::Val();
finalScope = zv::Val::copyOf(zv::Ref(resultScope));
}
if (!unrolledEndScope.isNull()) {
finalScope = zv::Val::copyOf(unrolledEndScope.ref());
}
// $scope is the post-loop scope; the body may have modified the iteratee
// (e.g. $arr[] = ...). A tracked iteratee reads the modified type off the
// scope (getTypeOnScope's authoritative read); only an untracked one whose
// inputs the body changed needs reprocessing there to observe it.
zv::Val exprType, exprNativeType;
{
bool answers;
if (UNEXPECTED(!pt_expression_result_answers_on_scope(condResult.raw(), scope.raw(), false, answers))) return zv::Val();
if (answers) {
if (UNEXPECTED(!pt_expression_result_answers_on_scope(condResult.raw(), scope.raw(), true, answers))) return zv::Val();
}
if (answers) {
exprType = pt_expression_result_get_type_on_scope(condResult.raw(), scope.raw(), false);
if (UNEXPECTED(exprType.isUndef())) return zv::Val();
exprNativeType = pt_expression_result_get_type_on_scope(condResult.raw(), scope.raw(), true);
if (UNEXPECTED(exprNativeType.isUndef())) return zv::Val();
} else {
zv::Val freshStorage = pt_expression_result_storage_new();
if (UNEXPECTED(freshStorage.isUndef())) return zv::Val();
zv::Val postLoopIterateeResult = pt_node_scope_resolver_process_expr_on_demand(nodeScopeResolver, iteratee, scope.raw(), freshStorage.raw());
if (UNEXPECTED(postLoopIterateeResult.isUndef())) return zv::Val();
exprType = pt_expression_result_get_type(postLoopIterateeResult.raw());
if (UNEXPECTED(exprType.isUndef())) return zv::Val();
exprNativeType = pt_expression_result_get_native_type(postLoopIterateeResult.raw());
if (UNEXPECTED(exprNativeType.isUndef())) return zv::Val();
}
}
zend_long hasExpr = pt_mutating_scope_has_expression_type(Z_OBJ_P(scope.raw()), iteratee);
if (UNEXPECTED(hasExpr < 0)) return zv::Val();
if (UNEXPECTED(!rewriteIterateeAfterLoop(nodeScopeResolver, parts, keyVarExpr, originalValueExpr, breakExitPoints.raw(), scopesWithIterableValueType, continueExitPointHasUnoriginalKeyType, hasExpr, exprType.raw(), exprNativeType.raw(), finalScope))) return zv::Val();
zend_long isIterableAtLeastOnce = typeTrinary(exprType.raw(), PT_OP_IS_ITERABLE_AT_LEAST_ONCE, "isIterableAtLeastOnce");
if (UNEXPECTED(isIterableAtLeastOnce < 0)) return zv::Val();
bool narrowToEmpty = isIterableAtLeastOnce == PT_TRI_MAYBE;
if (!narrowToEmpty) {
zend_long isIterable = pt_type_call_trinary(Z_OBJ_P(exprType.raw()), PT_LC("isiterable"), 0, NULL);
if (UNEXPECTED(isIterable < 0)) return zv::Val();
narrowToEmpty = isIterable == PT_TRI_NO;
}
bool resultAlwaysTerminating;
if (UNEXPECTED(!pt_internal_statement_result_is_always_terminating(result, resultAlwaysTerminating))) return zv::Val();
if (narrowToEmpty) {
zv::Val emptyScope = narrowToEmptyOrObject(nodeScopeResolver, scope.raw(), iteratee, condResult.raw(), originalStorage);
if (UNEXPECTED(emptyScope.isUndef())) return zv::Val();
zv::Val merged = pt_mutating_scope_merge_with(Z_OBJ_P(finalScope.raw()), emptyScope.raw());
if (UNEXPECTED(merged.isUndef())) return zv::Val();
finalScope = std::move(merged);
} else if (isIterableAtLeastOnce == PT_TRI_NO || resultAlwaysTerminating) {
finalScope = zv::Val::copyOf(scope.ref());
} else if (!polluteScopeWithAlwaysIterableForeach) {
zv::Val processed = pt_mutating_scope_process_always_iterable_foreach_scope_without_pollute(Z_OBJ_P(scope.raw()), Z_OBJ_P(finalScope.raw()));
if (UNEXPECTED(processed.isUndef())) return zv::Val();
finalScope = std::move(processed);
// get types from finalScope, but don't create new variables
}
if (isIterableAtLeastOnce != PT_TRI_NO) {
{
zv::Val hold;
zval *more = pt_internal_statement_result_throw_points(result, hold);
if (UNEXPECTED(more == NULL || !ptlh::mergeInto(throwPoints, more))) return zv::Val();
}
zv::Val hold;
zval *more = pt_internal_statement_result_impure_points(result, hold);
if (UNEXPECTED(more == NULL || !ptlh::mergeInto(impurePoints, more))) return zv::Val();
}
zv::Val traversableThrowPoint = getTraversableForeachThrowPoint(scope.raw(), iteratee, exprType.raw());
if (UNEXPECTED(traversableThrowPoint.isUndef())) return zv::Val();
if (!traversableThrowPoint.isNull()) {
throwPoints.push(zv::Ref(traversableThrowPoint.raw()));
}
if (isTopLevel && parts.byRef) {
zv::Val byRefExpr = pt_type_new(PT_CLASS_FOREACH_VALUE_BY_REF_EXPR, 1, parts.valueVar.raw());
if (UNEXPECTED(byRefExpr.isUndef())) return zv::Val();
zv::Val mixed = pt_type_new_mixed_type();
if (UNEXPECTED(mixed.isUndef())) return zv::Val();
zv::Val nativeMixed = pt_type_new_mixed_type();
if (UNEXPECTED(nativeMixed.isUndef())) return zv::Val();
zv::Val assigned = pt_mutating_scope_assign_expression(Z_OBJ_P(finalScope.raw()), Z_OBJ_P(byRefExpr.raw()), mixed.raw(), nativeMixed.raw());
if (UNEXPECTED(assigned.isUndef())) return zv::Val();
finalScope = std::move(assigned);
}
zv::Val bindingFlow;
{
zval flows[5];
for (int i = 0; i < 5; i++) {
ZVAL_NULL(&flows[i]);
}
zv::Val keyRead, keyWrite, valueRead, valueWrite, escape;
if (!parts.keyVar.isNull()) {
keyRead = pt_variable_flow_builder_target_read(parts.keyVar.raw(), storage, false, NULL);
if (UNEXPECTED(keyRead.isUndef())) return zv::Val();
ZVAL_COPY_VALUE(&flows[0], keyRead.raw());
keyWrite = pt_variable_flow_builder_target_write(parts.keyVar.raw(), ptlh::PT_LH_WRITE_KIND_FOREACH_KEY, finalScope.raw(), storage, NULL);
if (UNEXPECTED(keyWrite.isUndef())) return zv::Val();
ZVAL_COPY_VALUE(&flows[1], keyWrite.raw());
}
valueRead = pt_variable_flow_builder_target_read(parts.valueVar.raw(), storage, false, NULL);
if (UNEXPECTED(valueRead.isUndef())) return zv::Val();
ZVAL_COPY_VALUE(&flows[2], valueRead.raw());
valueWrite = pt_variable_flow_builder_target_write(parts.valueVar.raw(), parts.keyVar.isNull() ? ptlh::PT_LH_WRITE_KIND_FOREACH_VALUE : ptlh::PT_LH_WRITE_KIND_FOREACH_VALUE_WITH_KEY, finalScope.raw(), storage, NULL);
if (UNEXPECTED(valueWrite.isUndef())) return zv::Val();
ZVAL_COPY_VALUE(&flows[3], valueWrite.raw());
if (parts.byRef && parts.valueVarName != NULL) {
escape = pt_variable_flow_escape(parts.valueVarName);
if (UNEXPECTED(escape.isUndef())) return zv::Val();
ZVAL_COPY_VALUE(&flows[4], escape.raw());
}
bindingFlow = pt_variable_flow_sequence(5, flows);
if (UNEXPECTED(bindingFlow.isUndef())) return zv::Val();
}
zv::Val loopFlow;
{
zv::Val throwingFlow = zv::Val::null();
if (!traversableThrowPoint.isNull()) {
zv::Val hold;
zval *throwType = pt_internal_throw_point_type(traversableThrowPoint.raw(), hold);
if (UNEXPECTED(throwType == NULL)) return zv::Val();
throwingFlow = pt_variable_flow_throwing(throwType, true, false);
if (UNEXPECTED(throwingFlow.isUndef())) return zv::Val();
}
zv::Val bodyFlowHold;
zval *bodyFlow = pt_internal_statement_result_variable_flow(result, bodyFlowHold);
if (UNEXPECTED(bodyFlow == NULL)) return zv::Val();
zv::Args bodyFlows{bindingFlow.raw(), bodyFlow};
zv::Val body = pt_variable_flow_sequence(2, bodyFlows);
if (UNEXPECTED(body.isUndef())) return zv::Val();
// the body may run or not whatever the iterated type says: a write in it
// does not make an earlier write dead, and a read in it counts even
// when the iterated value is inferred empty
loopFlow = pt_variable_flow_loop(throwingFlow.raw(), body.raw(), NULL, false, true);
if (UNEXPECTED(loopFlow.isUndef())) return zv::Val();
}
zv::Val bindingWrites = pt_variable_flow_builder_writes(bindingFlow.raw());
if (UNEXPECTED(bindingWrites.isUndef())) return zv::Val();
zv::Arr bindings = zv::Arr::empty();
for (auto entry : zv::ArrRef(bindingWrites.raw())) {
zval *write = entry.value().deref().raw();
bool isOffsetWrite;
zend_long id;
if (UNEXPECTED(!ptlh::variableWriteInfo(write, isOffsetWrite, id))) return zv::Val();
if (isOffsetWrite) continue;
bindings.push(zv::Ref(write));
}
loopFlow = pt_variable_flow_loop_statement(stmt, loopFlow.raw(), bindings.raw(), bindingWrites.raw());
if (UNEXPECTED(loopFlow.isUndef())) return zv::Val();
zv::Val resultScope;
{
zv::Val hold;
zval *bodyScopeSlot = pt_internal_statement_result_scope(result, hold);
if (UNEXPECTED(bodyScopeSlot == NULL)) return zv::Val();
zv::Val constraints = pt_mutating_scope_get_template_argument_constraints(Z_OBJ_P(bodyScopeSlot));
if (UNEXPECTED(constraints.isUndef())) return zv::Val();
resultScope = pt_mutating_scope_add_template_argument_constraints(Z_OBJ_P(finalScope.raw()), constraints.raw());
if (UNEXPECTED(resultScope.isUndef())) return zv::Val();
}
bool hasYield;
if (UNEXPECTED(!pt_internal_statement_result_has_yield(result, hasYield))) return zv::Val();
if (!hasYield) {
if (UNEXPECTED(!pt_expression_result_has_yield(condResult.raw(), hasYield))) return zv::Val();
}
zv::Val exitPoints = pt_internal_statement_result_exit_points_for_outer_loop(result);
if (UNEXPECTED(exitPoints.isUndef())) return zv::Val();
zv::Val variableFlow;
{
zv::Val condFlow = pt_expression_result_variable_flow(condResult.raw());
if (UNEXPECTED(condFlow.isUndef())) return zv::Val();
zv::Args flows{condFlow.raw(), loopFlow.raw()};
variableFlow = pt_variable_flow_sequence(2, flows);
if (UNEXPECTED(variableFlow.isUndef())) return zv::Val();
}
zv::Val dependencies;
{
zv::Val condHold, bodyHold;
zval *condDependencies = pt_expression_result_dependencies(condResult.raw(), condHold);
if (UNEXPECTED(condDependencies == NULL)) return zv::Val();
zval *bodyDependencies = pt_internal_statement_result_dependencies(result, bodyHold);
if (UNEXPECTED(bodyDependencies == NULL)) return zv::Val();
// the classes in the types of the keys and the values iterated over
zval *keyVar = ptsh::readNodeProperty(pt_feh_key_var_site, stmt, PT_LC("keyVar"));
if (UNEXPECTED(keyVar == NULL)) return zv::Val();
zv::Val keyType = zv::Val::null();
if (Z_TYPE_P(keyVar) != IS_NULL) {
keyType = pt_mutating_scope_get_iterable_key_type(Z_OBJ_P(entryScope), foreachIterateeType.raw());
if (UNEXPECTED(keyType.isUndef())) return zv::Val();
}
zv::Val valueType = pt_mutating_scope_get_iterable_value_type(Z_OBJ_P(entryScope), foreachIterateeType.raw());
if (UNEXPECTED(valueType.isUndef())) return zv::Val();
zv::Arr iteratedTypes = zv::Arr::create(2);
iteratedTypes.push(std::move(keyType));
iteratedTypes.push(std::move(valueType));
zv::Val iterated = pt_dependencies_create_in(entryScope, iteratedTypes.raw());
if (UNEXPECTED(iterated.isUndef())) return zv::Val();
dependencies = pt_dependencies_merge({condDependencies, bodyDependencies, iterated.raw()});
if (UNEXPECTED(dependencies.isUndef())) return zv::Val();
}
return pt_internal_statement_result_new(resultScope.raw(), hasYield, isIterableAtLeastOnce == PT_TRI_YES && resultAlwaysTerminating, exitPoints.raw(), throwPoints.raw(), impurePoints.raw(), NULL, variableFlow.raw(), -1, dependencies.raw());
}
/* the statement-handler entry (Engine.h) */
static zv::Val processStmtEntry(zend_object *handler, zval *nodeScopeResolver, zval *stmt, zval *scope, zval *storage, zval *nodeCallback, zval *context)
{
return ForeachHandler(handler).processStmt(nodeScopeResolver, stmt, scope, storage, nodeCallback, context);
}
private:
zend_object *self;
/* the Foreach_ properties the handler reads, owned for the duration of
* a step, with the twin's `instanceof Variable && is_string(->name)`
* answers */
struct StmtParts
{
zv::Val expr;
zv::Val keyVar;
zv::Val valueVar;
zv::Val stmts;
bool byRef = false;
bool keyVarIsVariable = false;
bool valueVarIsVariable = false;
bool valueVarIsList = false;
/* the string names (borrowed from the held nodes), NULL otherwise */
zend_string *exprName = NULL;
zend_string *keyVarName = NULL;
zend_string *valueVarName = NULL;
/* false = pending exception */
[[nodiscard]] bool read(zval *stmt)
{
zval *slot = ptsh::readNodeProperty(pt_feh_expr_site, stmt, PT_LC("expr"));
if (UNEXPECTED(slot == NULL)) return false;
expr = zv::Val::copyOf(zv::Ref(slot));
slot = ptsh::readNodeProperty(pt_feh_key_var_site, stmt, PT_LC("keyVar"));
if (UNEXPECTED(slot == NULL)) return false;
keyVar = zv::Val::copyOf(zv::Ref(slot));
slot = ptsh::readNodeProperty(pt_feh_value_var_site, stmt, PT_LC("valueVar"));
if (UNEXPECTED(slot == NULL)) return false;
valueVar = zv::Val::copyOf(zv::Ref(slot));
slot = ptsh::readNodeProperty(pt_feh_by_ref_site, stmt, PT_LC("byRef"));
if (UNEXPECTED(slot == NULL)) return false;
byRef = zend_is_true(slot);
slot = ptsh::readNodeProperty(pt_feh_stmts_site, stmt, PT_LC("stmts"));
if (UNEXPECTED(slot == NULL)) return false;
stmts = zv::Val::copyOf(zv::Ref(slot));
bool error = false;
exprName = variableName(expr.raw(), NULL, error);
if (UNEXPECTED(error)) return false;
keyVarName = variableName(keyVar.raw(), &keyVarIsVariable, error);
if (UNEXPECTED(error)) return false;
valueVarName = variableName(valueVar.raw(), &valueVarIsVariable, error);
if (UNEXPECTED(error)) return false;
valueVarIsList = !valueVarIsVariable && ptsh::isInstanceOf(valueVar.raw(), PT_CLASS_LIST_EXPR, error);
return !error;
}
/* the string name of a Variable node, NULL otherwise */
static zend_string *variableName(zval *node, bool *isVariable, bool &error)
{
bool variable = ptsh::isInstanceOf(node, PT_CLASS_VARIABLE, error);
if (isVariable != NULL) *isVariable = variable;
if (!variable) return NULL;
zval *name = ptsh::readNodeProperty(pt_feh_variable_name_site, node, PT_LC("name"));
if (UNEXPECTED(name == NULL)) {
error = true;
return NULL;
}
return Z_TYPE_P(name) == IS_STRING ? Z_STR_P(name) : NULL;
}
};
/* $this->varAnnotationProcessor->processVarAnnotation($scope, [$name], $stmt) */
zv::Val processVarAnnotation(zval *scope, zend_string *name, zval *stmt) const