Repository navigation
Expand file tree
/
Copy pathClosureTypeResolver.cpp
More file actions
1667 lines (1543 loc) · 79.5 KB
/
Copy pathClosureTypeResolver.cpp
File metadata and controls
1667 lines (1543 loc) · 79.5 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\ClosureTypeResolver — native implementation of
* PHPStan\Analyser\ExprHandler\Helper\ClosureTypeResolver.
*
* A DI service (#[AutowiredService], PerFileAnalysisResettable): the
* constructor keeps the twin's arginfo so Nette autowires it, the per-file
* cache lives in the twin's $cachedTypes slot with the twin's shape
* (spl_object_id => ['expr' => ..., 'types' => [cacheKey => [...]]]) and is
* updated in place. The private static $resolveClosureTypeDepth guard and
* $cappedClosureTypeWalks are C++ counters (the declared statics stay for
* reflection parity).
*
* getClosureType(), buildClosureTypeForClosure(),
* buildClosureTypeForArrowFunction() and getDeclaredClosureType() are exported
* as pt_closure_type_resolver_*() (Engine.h conventions); MutatingScope,
* ArgumentsHandler and ClosureParameterResolver call them directly. The body
* walks of getClosureType() recurse through NodeScopeResolver's direct entries
* (which keep the fresh-stack guard on the path); their node callbacks are
* native closures capturing what the PHP closures capture (the entered scope
* by value, the gathered lists by reference). The array_map() callbacks and
* the ImpurePoints the twin builds only to map them to SimpleImpurePoints are
* spelled out inline.
*
* ContextualClosureParameterResolver, MutatingScope, NodeScopeResolver, the
* statement / expression results and throw / impure points, ClosureType,
* NativeParameterReflection, InitializerExprTypeResolver and the Type kernel
* are called through their direct entries; InitializerExprContext,
* SimpleThrowPoint and TemplateArgumentStats stay PHP (cached sites below).
*/
#include "support.h"
#include "generated/ClosureTypeResolver.h"
namespace slots = ptdecl::ClosureTypeResolver::slot;
namespace sigs = ptdecl::ClosureTypeResolver::sig;
#include "ClosureSupport.h"
#include "zend_smart_str.h"
zend_class_entry *pt_ce_closure_type_resolver = nullptr;
namespace {
/* the literals, permanent interned strings (module startup) */
zend_string *pt_ctr_free_variable_roots = nullptr;
zend_string *pt_ctr_this_root = nullptr;
zend_string *pt_ctr_function_call = nullptr;
zend_string *pt_ctr_by_ref_use = nullptr;
zend_string *pt_ctr_by_ref_parameter = nullptr;
zend_string *pt_ctr_generator = nullptr;
zend_string *pt_ctr_expr = nullptr;
zend_string *pt_ctr_types = nullptr;
zend_string *pt_ctr_return_type = nullptr;
zend_string *pt_ctr_throw_points = nullptr;
zend_string *pt_ctr_impure_points = nullptr;
zend_string *pt_ctr_invalidate_expressions = nullptr;
zend_string *pt_ctr_used_variables = nullptr;
/* the private static $resolveClosureTypeDepth */
int pt_ctr_resolve_closure_type_depth = 0;
/* the private static $cappedClosureTypeWalks */
int pt_ctr_capped_closure_type_walks = 0;
/* {{{ the PHP collaborators (one site each; switch to their direct entries
* once they are ported) */
pt_method_site pt_ctr_simple_throw_point_explicit_site;
pt_method_site pt_ctr_simple_throw_point_implicit_site;
pt_method_site pt_ctr_stats_increment_site;
/* $this->initializerExprTypeResolver->getType($expr, InitializerExprContext::fromScope($scope)) */
zv::Val initializerExprType(zval *initializerExprTypeResolver, zval *expr, zval *scope)
{
zv::Val context = pt_initializer_expr_context_from_scope(scope);
if (UNEXPECTED(context.isUndef())) return zv::Val();
return pt_initializer_expr_type_resolver_get_type(initializerExprTypeResolver, expr, context.raw());
}
/* SimpleThrowPoint::createExplicit($type, $canContainAnyThrowable) / ::createImplicit() */
zv::Val simpleThrowPointExplicit(zval *type, bool canContainAnyThrowable)
{
zv::Args argv{type, canContainAnyThrowable};
return pt_call_static_cached(pt_ctr_simple_throw_point_explicit_site, PT_CLASS_SIMPLE_THROW_POINT, PT_LC("createexplicit"), 2, argv);
}
zv::Val simpleThrowPointImplicit()
{
return pt_call_static_cached(pt_ctr_simple_throw_point_implicit_site, PT_CLASS_SIMPLE_THROW_POINT, PT_LC("createimplicit"), 0, NULL);
}
/* TemplateArgumentStats::$enabled && TemplateArgumentStats::increment('closureTypeBodyWalks'); false = pending exception */
[[nodiscard]] bool countClosureTypeBodyWalk()
{
zend_class_entry *ce = pt_class(PT_CLASS_TEMPLATE_ARGUMENT_STATS);
if (UNEXPECTED(ce == NULL)) return false;
zval *enabled = zend_read_static_property(ce, PT_LC("enabled"), 0);
if (UNEXPECTED(enabled == NULL)) return false;
ZVAL_DEREF(enabled);
if (EXPECTED(Z_TYPE_P(enabled) != IS_TRUE)) return true;
zval counter;
ZVAL_STRINGL(&counter, "closureTypeBodyWalks", sizeof("closureTypeBodyWalks") - 1);
zv::Val result = pt_call_static_cached(pt_ctr_stats_increment_site, PT_CLASS_TEMPLATE_ARGUMENT_STATS, PT_LC("increment"), 1, &counter);
zval_ptr_dtor(&counter);
return !result.isUndef();
}
/* }}} */
/* {{{ node reads */
pt_property_site pt_ctr_return_expr_site;
pt_property_site pt_ctr_yield_key_site;
pt_property_site pt_ctr_yield_value_site;
pt_property_site pt_ctr_yield_from_expr_site;
pt_property_site pt_ctr_execution_end_statement_result_site;
pt_property_site pt_ctr_attrs_site;
pt_property_site pt_ctr_attr_name_site;
pt_property_site pt_ctr_name_name_site;
pt_property_site pt_ctr_func_call_name_site;
/* $name->toLowerString() === $lowercase of a php-parser Name */
[[nodiscard]] bool nameIsLowercase(zval *name, const char *lowercase, size_t len, bool &out)
{
zval *value = ptclosure::prop(pt_ctr_name_name_site, name, PT_LC("name"));
if (UNEXPECTED(value == NULL)) return false;
if (UNEXPECTED(Z_TYPE_P(value) != IS_STRING)) {
zend_type_error("strtolower(): Argument #1 ($string) must be of type string, %s given", zend_zval_value_name(value));
return false;
}
out = ZSTR_LEN(Z_STR_P(value)) == len && zend_binary_strcasecmp(ZSTR_VAL(Z_STR_P(value)), len, lowercase, len) == 0;
return true;
}
/* TrinaryLogic::createYes() when an attribute of $expr->attrGroups is named
* NoDiscard (case-insensitively), createNo() otherwise (borrowed) */
zval *mustUseReturnValueOf(zval *expr)
{
zval *attrGroups = ptclosure::prop(ptclosure::attrGroupsSite, expr, PT_LC("attrGroups"));
if (UNEXPECTED(attrGroups == NULL)) return NULL;
bool mustUse = false;
if (EXPECTED(Z_TYPE_P(attrGroups) == IS_ARRAY) && zend_hash_num_elements(Z_ARRVAL_P(attrGroups)) > 0) {
for (zv::ArrayEntry groupEntry : zv::ArrRef(attrGroups)) {
zval *attrs = ptclosure::prop(pt_ctr_attrs_site, groupEntry.value().deref().raw(), PT_LC("attrs"));
if (UNEXPECTED(attrs == NULL)) return NULL;
if (UNEXPECTED(Z_TYPE_P(attrs) != IS_ARRAY)) continue;
for (zv::ArrayEntry attrEntry : zv::ArrRef(attrs)) {
zval *name = ptclosure::prop(pt_ctr_attr_name_site, attrEntry.value().deref().raw(), PT_LC("name"));
if (UNEXPECTED(name == NULL)) return NULL;
bool isNoDiscard = false;
if (UNEXPECTED(!nameIsLowercase(name, "nodiscard", sizeof("nodiscard") - 1, isNoDiscard))) return NULL;
if (isNoDiscard) {
mustUse = true;
break;
}
}
}
}
return ptclosure::trinaryFromBool(mustUse);
}
/* }}} */
/* the throw point, impure point and statement result reads of value
* objects the walk produced */
/* array_map(static fn ($throwPoint) => $throwPoint->toPublic(), $throwPoints) */
zv::Val throwPointsToPublic(zval *throwPoints)
{
if (UNEXPECTED(Z_TYPE_P(throwPoints) != IS_ARRAY)) {
zend_type_error("array_map(): Argument #2 ($array) must be of type array, %s given", zend_zval_value_name(throwPoints));
return zv::Val();
}
HashTable *table = Z_ARRVAL_P(throwPoints);
uint32_t count = zend_hash_num_elements(table);
if (count == 0) return zv::Val(zv::Arr::empty());
zv::Arr mapped = zv::Arr::create(count);
for (zv::ArrayEntry entry : zv::TableRef(table)) {
zv::Val publicPoint = pt_internal_throw_point_to_public(entry.value().deref().raw());
if (UNEXPECTED(publicPoint.isUndef())) return zv::Val();
if (entry.hasStringKey()) {
mapped.set(entry.stringKey(), std::move(publicPoint));
} else {
zval value = publicPoint.take();
zend_hash_index_update(mapped.table(), entry.indexKey(), &value);
}
}
return zv::Val(std::move(mapped));
}
/* array_merge($a, $b) of two lists the walk built */
zv::Val mergeLists(zval *a, zval *b)
{
zv::Arr merged = zv::Arr::empty();
if (UNEXPECTED(!pt_callable_array_merge_into(merged, a) || !pt_callable_array_merge_into(merged, b))) return zv::Val();
return zv::Val(std::move(merged));
}
/* static function (Node $node, Scope $scope) use ($arrowScope,
* &$arrowFunctionImpurePoints, &$invalidateExpressions): void — captures in
* that order */
void arrowFunctionWalkCallbackBody(zval *captures, uint32_t argc, zval *argv, zval *return_value)
{
(void) return_value;
ptclosure::arrowFunctionGatherer(captures, argc, argv, "PHPStan\\Analyser\\ExprHandler\\Helper\\ClosureTypeResolver::{closure}");
}
/* static function (Node $node, Scope $scope) use ($closureScope,
* &$closureReturnStatements, &$closureYieldStatements, &$closureExecutionEnds,
* &$closureImpurePoints, &$invalidateExpressions): void — captures in that
* order */
void closureWalkCallbackBody(zval *captures, uint32_t argc, zval *argv, zval *return_value)
{
(void) return_value;
if (UNEXPECTED(!ptcall::requireArguments(argc, 2, "PHPStan\\Analyser\\ExprHandler\\Helper\\ClosureTypeResolver::{closure}"))) return;
zval *node = &argv[0];
zval *scope = &argv[1];
if (ptclosure::differentAnonymousFunction(scope, &captures[0]) != 0) return;
int is = ptclosure::instanceOf(node, PT_CLASS_INVALIDATE_EXPR_NODE);
if (UNEXPECTED(is < 0)) return;
if (is) {
ptsh::appendToReference(&captures[5], node);
return;
}
is = ptclosure::instanceOf(node, PT_CLASS_PROPERTY_ASSIGN_NODE);
if (UNEXPECTED(is < 0)) return;
if (is) {
(void) ptclosure::gatherPropertyAssign(node, scope, &captures[4], &captures[5]);
return;
}
is = ptclosure::instanceOf(node, PT_CLASS_EXECUTION_END_NODE);
if (UNEXPECTED(is < 0)) return;
if (is) {
ptsh::appendToReference(&captures[3], node);
return;
}
is = ptclosure::instanceOf(node, PT_CLASS_RETURN_STMT);
if (UNEXPECTED(is < 0)) return;
if (is) {
zv::Val pair = ptclosure::pairOf(node, scope);
ptsh::appendToReference(&captures[1], pair.raw());
}
is = ptclosure::instanceOf(node, PT_CLASS_YIELD);
if (UNEXPECTED(is < 0)) return;
if (!is) {
is = ptclosure::instanceOf(node, PT_CLASS_YIELD_FROM);
if (UNEXPECTED(is < 0) || !is) return;
}
zv::Val pair = ptclosure::pairOf(node, scope);
ptsh::appendToReference(&captures[2], pair.raw());
}
/* the collected state of freeVariableRoots()'s NodeFinder walks over an
* arrow function body */
struct FreeVariableFindCtx : pt_find_ctx
{
zend_class_entry *variableCe;
zend_class_entry *funcCallCe;
zend_class_entry *nameCe;
HashTable *paramNames;
zv::Arr *roots;
bool dynamic;
};
/* the Variable walk: roots in pre-order, stopping at a dynamic name */
bool freeVariableMatcher(zend_object *node, void *vctx)
{
FreeVariableFindCtx *ctx = static_cast<FreeVariableFindCtx *>(static_cast<pt_find_ctx *>(vctx));
if (!instanceof_function(node->ce, ctx->variableCe)) return false;
zval nodeZv;
ZVAL_OBJ(&nodeZv, node);
zval *name = pt_property_cached(ptclosure::variableNameSite, node, PT_LC("name"));
if (UNEXPECTED(name == NULL)) {
zend_throw_error(NULL, "Undefined property: %s::$name", ZSTR_VAL(node->ce->name));
ctx->failed = true;
return true;
}
ZVAL_DEREF(name);
if (Z_TYPE_P(name) != IS_STRING) {
ctx->dynamic = true;
return true;
}
zend_string *root = zend_string_concat2("$", 1, Z_STRVAL_P(name), Z_STRLEN_P(name));
if (zend_hash_find(ctx->paramNames, root) == NULL) {
zval flag;
ZVAL_TRUE(&flag);
ctx->roots->separate();
zend_symtable_update(ctx->roots->table(), root, &flag);
}
zend_string_release(root);
return false;
}
/* the FuncCall walk: compact() / extract() / get_defined_vars() */
bool scopeReadingCallMatcher(zend_object *node, void *vctx)
{
FreeVariableFindCtx *ctx = static_cast<FreeVariableFindCtx *>(static_cast<pt_find_ctx *>(vctx));
if (!instanceof_function(node->ce, ctx->funcCallCe)) return false;
zval *name = pt_property_cached(pt_ctr_func_call_name_site, node, PT_LC("name"));
if (UNEXPECTED(name == NULL)) return false;
ZVAL_DEREF(name);
if (Z_TYPE_P(name) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(name), ctx->nameCe)) return false;
bool matches = false;
for (const char *function : { "compact", "extract", "get_defined_vars" }) {
if (UNEXPECTED(!nameIsLowercase(name, function, strlen(function), matches))) {
ctx->failed = true;
return true;
}
if (matches) {
ctx->dynamic = true;
return true;
}
}
return false;
}
} // namespace
namespace phpstanturbo {
/* Mirrors PHPStan\Analyser\ExprHandler\Helper\ClosureTypeResolver; UNDEF /
* false = pending exception. */
class ClosureTypeResolver
{
public:
explicit ClosureTypeResolver(zend_object *self) : self(self) {}
/* the constructor body: the promoted properties */
void construct(zval *nodeScopeResolver, zval *initializerExprTypeResolver, zval *contextualClosureParameterResolver, zval *closureSignatureInference)
{
writeSlot(slots::nodeScopeResolver, zv::Val::copyOf(zv::Ref(nodeScopeResolver)));
writeSlot(slots::initializerExprTypeResolver, zv::Val::copyOf(zv::Ref(initializerExprTypeResolver)));
writeSlot(slots::contextualClosureParameterResolver, zv::Val::copyOf(zv::Ref(contextualClosureParameterResolver)));
writeSlot(slots::closureSignatureInference, zv::Val::copyOf(zv::Ref(closureSignatureInference)));
}
/* Mirrors resetFileAnalysisState() */
void resetFileAnalysisState()
{
writeSlot(slots::cachedTypes, zv::Val(zv::Arr::empty()));
}
/* Mirrors getClosureType() ($storage, $passedToType NULL for null) */
zv::Val getClosureType(zval *scope, zval *expr, bool shallow, zval *storage, zval *passedToType = NULL)
{
Parameters p;
if (UNEXPECTED(!buildParametersAndAcceptors(scope, expr, storage, passedToType, NULL, p))) return zv::Val();
// A shallow reflection is the closure/arrow function's signature without
// walking its body: parameters plus the DECLARED return type.
if (shallow) return signatureClosureType(scope, expr, p.parameters.raw(), p.isVariadic);
zv::Val cachedTypes = findCachedTypes(expr);
zv::Str cacheKey = closureContextCacheKey(scope, expr, p.callableParameters.isNull() ? NULL : p.callableParameters.raw(), p.parameters.raw());
if (UNEXPECTED(cacheKey.isNull())) return zv::Val();
zval *cached = zend_symtable_find(Z_ARRVAL_P(cachedTypes.raw()), cacheKey.get());
if (cached != NULL) {
ZVAL_DEREF(cached);
return createClosureTypeFromCache(scope, expr, p.parameters.raw(), p.isVariadic, cached, p.contextFree);
}
if (pt_ctr_resolve_closure_type_depth >= 2) {
pt_ctr_capped_closure_type_walks++;
return signatureClosureType(scope, expr, p.parameters.raw(), p.isVariadic);
}
if (UNEXPECTED(!countClosureTypeBodyWalk())) return zv::Val();
int isArrowFunction = ptclosure::instanceOf(expr, PT_CLASS_ARROW_FUNCTION);
if (UNEXPECTED(isArrowFunction < 0)) return zv::Val();
if (isArrowFunction) return walkArrowFunction(scope, expr, p, cacheKey.get());
return walkClosure(scope, expr, p, cacheKey.get());
}
/* Mirrors buildClosureTypeForClosure() (the nullable ones NULL for null) */
zv::Val buildClosureTypeForClosure(zval *scope, zval *expr, zval *returnStatements, zval *yieldStatements, zval *executionEnds, zval *throwPoints, zval *impurePoints, zval *invalidateExpressions, bool native, zval *storage, zval *passedToType, zval *nativePassedToType)
{
Parameters p;
if (UNEXPECTED(!buildParametersAndAcceptors(scope, expr, storage, passedToType, nativePassedToType, p))) return zv::Val();
zv::Val publicThrowPoints = throwPointsToPublic(throwPoints);
if (UNEXPECTED(publicThrowPoints.isUndef())) return zv::Val();
// the flavour-correct key both keeps the native build from clobbering
// the phpdoc cache slot and lets a later getClosureType() ask on the
// promoted scope answer from this build instead of re-walking
zv::Str cacheKey = flavourCacheKey(scope, expr, p, native);
if (UNEXPECTED(cacheKey.isNull())) return zv::Val();
return buildClosureTypeFromClosureWalk(scope, expr, p.parameters.raw(), p.isVariadic, returnStatements, yieldStatements, executionEnds, publicThrowPoints.raw(), impurePoints, invalidateExpressions, cacheKey.get(), native, storage, p.contextFree);
}
/* Mirrors buildClosureTypeForArrowFunction() (the nullable ones NULL for null) */
zv::Val buildClosureTypeForArrowFunction(zval *scope, zval *expr, zval *arrowScope, zval *throwPoints, zval *impurePoints, zval *invalidateExpressions, bool native, zval *storage, zval *passedToType, zval *nativePassedToType)
{
Parameters p;
if (UNEXPECTED(!buildParametersAndAcceptors(scope, expr, storage, passedToType, nativePassedToType, p))) return zv::Val();
zv::Val returnType = resolveArrowFunctionReturnType(scope, arrowScope, expr, native, storage);
if (UNEXPECTED(returnType.isUndef())) return zv::Val();
zv::Str cacheKey = flavourCacheKey(scope, expr, p, native);
if (UNEXPECTED(cacheKey.isNull())) return zv::Val();
zv::Arr usedVariables = zv::Arr::empty();
return assembleClosureType(scope, expr, p.parameters.raw(), p.isVariadic, returnType.raw(), throwPoints, impurePoints, false, invalidateExpressions, usedVariables.raw(), cacheKey.get(), p.contextFree);
}
/* Mirrors getDeclaredClosureType() */
zv::Val getDeclaredClosureType(zval *scope, zval *expr)
{
zv::Val parameters;
bool isVariadic = false;
if (UNEXPECTED(!buildDeclaredParameters(scope, expr, parameters, isVariadic))) return zv::Val();
return signatureClosureType(scope, expr, parameters.raw(), isVariadic);
}
private:
zend_object *self;
/* [$parameters, $isVariadic, $callableParameters, $nativeCallableParameters] */
struct Parameters
{
zv::Val parameters;
bool isVariadic = false;
zv::Val callableParameters; /* null for null */
zv::Val nativeCallableParameters;
/* nothing types the closure where it is written (ClosureSignatureInference) */
bool contextFree = false;
};
void writeSlot(uint32_t index, zv::Val value)
{
zv::ObjRef(self).propAtWrite(index, std::move(value));
Z_PROP_FLAG_P(OBJ_PROP_NUM(self, index)) = 0;
}
/* new ClosureType($parameters, $scope->getFunctionType($expr->returnType,
* false, false), $isVariadic, isStatic: TrinaryLogic::createFromBoolean($expr->static)) */
static zv::Val signatureClosureType(zval *scope, zval *expr, zval *parameters, bool isVariadic)
{
zval *returnTypeNode = ptclosure::prop(ptclosure::returnTypeSite, expr, PT_LC("returnType"));
if (UNEXPECTED(returnTypeNode == NULL)) return zv::Val();
zv::Val returnType = pt_mutating_scope_get_function_type(Z_OBJ_P(scope), returnTypeNode, false, false);
if (UNEXPECTED(returnType.isUndef())) return zv::Val();
zval *isStatic = ptclosure::prop(ptclosure::staticSite, expr, PT_LC("static"));
if (UNEXPECTED(isStatic == NULL)) return zv::Val();
zval out;
if (UNEXPECTED(!pt_closure_type_new(&out, parameters, returnType.raw(), isVariadic, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, ptclosure::trinaryFromBool(zend_is_true(isStatic))))) return zv::Val();
return zv::Val::adopt(out);
}
/* Mirrors findCachedTypes(): an owned copy of the types array ([] when
* none is cached for this very node) */
zv::Val findCachedTypes(zval *expr) const
{
zval *cachedTypes = OBJ_PROP_NUM(self, slots::cachedTypes);
if (EXPECTED(Z_TYPE_P(cachedTypes) == IS_ARRAY)) {
zval *entry = zend_hash_index_find(Z_ARRVAL_P(cachedTypes), Z_OBJ_HANDLE_P(expr));
if (entry != NULL && Z_TYPE_P(entry) == IS_ARRAY) {
zval *entryExpr = zend_hash_find(Z_ARRVAL_P(entry), pt_ctr_expr);
zval *types = zend_hash_find(Z_ARRVAL_P(entry), pt_ctr_types);
if (entryExpr != NULL && types != NULL && Z_TYPE_P(entryExpr) == IS_OBJECT && Z_OBJ_P(entryExpr) == Z_OBJ_P(expr) && Z_TYPE_P(types) == IS_ARRAY) {
return zv::Val::copyOf(zv::Ref(types));
}
}
}
return zv::Val(zv::Arr::empty());
}
/* the cache key of a flavour build: closureContextCacheKey($native ?
* $scope->doNotTreatPhpDocTypesAsCertain() : $scope, $expr, $native ?
* $nativeCallableParameters : $callableParameters, $parameters) */
zv::Str flavourCacheKey(zval *scope, zval *expr, Parameters &p, bool native)
{
zv::Val nativeScope;
zval *keyScope = scope;
if (native) {
nativeScope = pt_mutating_scope_do_not_treat_phpdoc_types_as_certain(Z_OBJ_P(scope));
if (UNEXPECTED(nativeScope.isUndef())) return zv::Str();
keyScope = nativeScope.raw();
}
zv::Val &callable = native ? p.nativeCallableParameters : p.callableParameters;
return closureContextCacheKey(keyScope, expr, callable.isNull() ? NULL : callable.raw(), p.parameters.raw());
}
/* Mirrors closureContextCacheKey() ($callableParameters NULL for null) */
zv::Str closureContextCacheKey(zval *scope, zval *expr, zval *callableParameters, zval *parameters)
{
zval *cacheLevel = pt_verbosity_level_singleton(PT_VERBOSITY_LEVEL_CACHE);
if (UNEXPECTED(cacheLevel == NULL)) return zv::Str();
smart_str parts = {};
zval *described = callableParameters != NULL ? callableParameters : parameters;
if (EXPECTED(Z_TYPE_P(described) == IS_ARRAY)) {
bool first = true;
for (zv::ArrayEntry entry : zv::ArrRef(described)) {
zval *parameter = entry.value().deref().raw();
zv::Val type = ptclosure::parameterGetType(parameter);
zv::Val description = type.isUndef() ? zv::Val() : describeType(type.raw(), cacheLevel);
if (UNEXPECTED(description.isUndef())) {
smart_str_free(&parts);
return zv::Str();
}
if (!first) {
smart_str_appendc(&parts, '|');
}
first = false;
smart_str_append(&parts, Z_STR_P(description.raw()));
}
}
// a closure whose body creates an unresolved template argument has the
// same key in both passes of the enclosing body; the resolutions installed
// for the second pass change its type
zv::Val frame = pt_mutating_scope_get_current_template_argument_frame(Z_OBJ_P(scope));
zv::Val roots = frame.isUndef() ? zv::Val() : freeVariableRoots(expr);
zv::Val scopeKey = roots.isUndef() ? zv::Val() : pt_mutating_scope_get_closure_scope_cache_key(Z_OBJ_P(scope), roots.isNull() ? NULL : roots.raw());
if (UNEXPECTED(scopeKey.isUndef())) {
smart_str_free(&parts);
return zv::Str();
}
if (UNEXPECTED(!scopeKey.ref().isString())) {
smart_str_free(&parts);
zend_type_error("PHPStan\\Analyser\\ExprHandler\\Helper\\ClosureTypeResolver::closureContextCacheKey(): Return value must be of type string, %s returned", zend_zval_value_name(scopeKey.raw()));
return zv::Str();
}
bool promoted = false;
if (UNEXPECTED(!pt_mutating_scope_native_types_promoted(Z_OBJ_P(scope), promoted))) {
smart_str_free(&parts);
return zv::Str();
}
zv::Val suffix;
if (!frame.isNull()) {
suffix = pt_template_argument_frame_resolution_cache_key_suffix(frame.raw());
if (UNEXPECTED(suffix.isUndef())) {
smart_str_free(&parts);
return zv::Str();
}
}
smart_str key = {};
smart_str_append(&key, Z_STR_P(scopeKey.raw()));
smart_str_appendc(&key, '/');
if (parts.s != NULL) {
smart_str_append(&key, parts.s);
}
smart_str_free(&parts);
if (promoted) {
smart_str_appendl(&key, "/native", sizeof("/native") - 1);
} else {
smart_str_appendl(&key, "/phpdoc", sizeof("/phpdoc") - 1);
}
if (!suffix.isUndef()) {
zend_string *suffixString = zval_get_string(suffix.raw());
smart_str_append(&key, suffixString);
zend_string_release(suffixString);
}
return zv::Str::adopt(smart_str_extract(&key));
}
/* $type->describe($level) as a string; UNDEF = pending exception */
static zv::Val describeType(zval *type, zval *level)
{
if (UNEXPECTED(Z_TYPE_P(type) != IS_OBJECT)) {
zend_throw_error(NULL, "Call to a member function describe() on %s", zend_zval_value_name(type));
return zv::Val();
}
zv::Val description = pt_type_op(Z_OBJ_P(type), PT_OP_DESCRIBE, 1, level);
if (UNEXPECTED(description.isUndef())) return zv::Val();
if (UNEXPECTED(!description.ref().isString())) {
zend_type_error("implode(): Argument #2 ($array) must contain strings only");
return zv::Val();
}
return description;
}
/* Mirrors freeVariableRoots(): the list, or null */
static zv::Val freeVariableRoots(zval *expr)
{
zval *cached = ptclosure::attribute(expr, pt_ctr_free_variable_roots);
if (cached != NULL) return zv::Val::copyOf(zv::Ref(cached));
zv::Arr roots = zv::Arr::empty();
zval *isStatic = ptclosure::prop(ptclosure::staticSite, expr, PT_LC("static"));
if (UNEXPECTED(isStatic == NULL)) return zv::Val();
zval flag;
ZVAL_TRUE(&flag);
if (!zend_is_true(isStatic)) {
roots.separate();
zend_hash_update(roots.table(), pt_ctr_this_root, &flag);
}
int isClosure = ptclosure::instanceOf(expr, PT_CLASS_CLOSURE_EXPR);
if (UNEXPECTED(isClosure < 0)) return zv::Val();
zval null;
ZVAL_NULL(&null);
if (isClosure) {
zval *uses = ptclosure::prop(ptclosure::usesSite, expr, PT_LC("uses"));
if (UNEXPECTED(uses == NULL)) return zv::Val();
if (EXPECTED(Z_TYPE_P(uses) == IS_ARRAY)) {
for (zv::ArrayEntry entry : zv::ArrRef(uses)) {
zval *var = ptclosure::prop(ptclosure::useVarSite, entry.value().deref().raw(), PT_LC("var"));
if (UNEXPECTED(var == NULL)) return zv::Val();
zval *name = ptclosure::prop(ptclosure::variableNameSite, var, PT_LC("name"));
if (UNEXPECTED(name == NULL)) return zv::Val();
if (Z_TYPE_P(name) != IS_STRING) {
if (UNEXPECTED(!pt_node_set_attribute(Z_OBJ_P(expr), pt_ctr_free_variable_roots, &null))) return zv::Val();
return zv::Val::null();
}
zend_string *root = zend_string_concat2("$", 1, Z_STRVAL_P(name), Z_STRLEN_P(name));
roots.separate();
zend_symtable_update(roots.table(), root, &flag);
zend_string_release(root);
}
}
} else {
zv::ScratchTable paramNames(8);
zval *params = ptclosure::prop(ptclosure::paramsSite, expr, PT_LC("params"));
if (UNEXPECTED(params == NULL)) return zv::Val();
zend_class_entry *variableCe = pt_class(PT_CLASS_VARIABLE);
zend_class_entry *funcCallCe = pt_class(PT_CLASS_FUNC_CALL);
zend_class_entry *nameCe = pt_class(PT_CLASS_NAME);
if (UNEXPECTED(variableCe == NULL || funcCallCe == NULL || nameCe == NULL)) return zv::Val();
if (EXPECTED(Z_TYPE_P(params) == IS_ARRAY)) {
for (zv::ArrayEntry entry : zv::ArrRef(params)) {
zval *var = ptclosure::prop(ptclosure::paramVarSite, entry.value().deref().raw(), PT_LC("var"));
if (UNEXPECTED(var == NULL)) return zv::Val();
if (Z_TYPE_P(var) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(var), variableCe)) continue;
zval *name = ptclosure::prop(ptclosure::variableNameSite, var, PT_LC("name"));
if (UNEXPECTED(name == NULL)) return zv::Val();
if (Z_TYPE_P(name) != IS_STRING) continue;
zend_string *paramName = zend_string_concat2("$", 1, Z_STRVAL_P(name), Z_STRLEN_P(name));
zend_hash_update(paramNames.table(), paramName, &flag);
zend_string_release(paramName);
}
}
zval *body = ptclosure::prop(ptclosure::arrowExprSite, expr, PT_LC("expr"));
if (UNEXPECTED(body == NULL)) return zv::Val();
if (EXPECTED(Z_TYPE_P(body) == IS_OBJECT)) {
FreeVariableFindCtx ctx{};
ctx.variableCe = variableCe;
ctx.funcCallCe = funcCallCe;
ctx.nameCe = nameCe;
ctx.paramNames = paramNames.table();
ctx.roots = &roots;
(void) pt_find_first_recursive(Z_OBJ_P(body), freeVariableMatcher, static_cast<pt_find_ctx *>(&ctx));
if (UNEXPECTED(ctx.failed || EG(exception))) return zv::Val();
if (!ctx.dynamic) {
(void) pt_find_first_recursive(Z_OBJ_P(body), scopeReadingCallMatcher, static_cast<pt_find_ctx *>(&ctx));
if (UNEXPECTED(ctx.failed || EG(exception))) return zv::Val();
}
if (ctx.dynamic) {
if (UNEXPECTED(!pt_node_set_attribute(Z_OBJ_P(expr), pt_ctr_free_variable_roots, &null))) return zv::Val();
return zv::Val::null();
}
}
}
/* array_keys($roots) */
HashTable *rootsTable = roots.table();
zv::Arr rootList = zend_hash_num_elements(rootsTable) > 0 ? zv::Arr::create(zend_hash_num_elements(rootsTable)) : zv::Arr::empty();
for (zv::ArrayEntry entry : zv::TableRef(rootsTable)) {
if (entry.hasStringKey()) {
rootList.push(zv::Val::string(entry.stringKey()));
} else {
rootList.push(zv::Val::integer((zend_long) entry.indexKey()));
}
}
if (UNEXPECTED(!pt_node_set_attribute(Z_OBJ_P(expr), pt_ctr_free_variable_roots, rootList.raw()))) return zv::Val();
return zv::Val(std::move(rootList));
}
/* Mirrors readExprType() ($storage NULL for null) */
static zv::Val readExprType(zval *storage, zval *expr, zval *readScope, bool native)
{
if (storage != NULL) {
zv::Val result = pt_expression_result_storage_find(storage, expr);
if (UNEXPECTED(result.isUndef())) return zv::Val();
if (!result.isNull()) {
return native ? pt_expression_result_get_native_type(result.raw()) : pt_expression_result_get_type(result.raw());
}
}
return pt_mutating_scope_get_type(Z_OBJ_P(readScope), expr);
}
/* $gatheredScope->toWalkScope(), promoted for the native flavour */
static zv::Val readScopeOf(zval *gatheredScope, bool native)
{
if (UNEXPECTED(Z_TYPE_P(gatheredScope) != IS_OBJECT)) {
zend_throw_error(NULL, "Call to a member function toWalkScope() on %s", zend_zval_value_name(gatheredScope));
return zv::Val();
}
zv::Val readScope = pt_mutating_scope_to_walk_scope(Z_OBJ_P(gatheredScope));
if (UNEXPECTED(readScope.isUndef()) || !native) return readScope;
return pt_mutating_scope_do_not_treat_phpdoc_types_as_certain(Z_OBJ_P(readScope.raw()));
}
/* [$node, $scope] = $pair (borrowed); false = pending exception */
[[nodiscard]] static bool unpackPair(zval *pair, zval *&node, zval *&scope)
{
ZVAL_DEREF(pair);
node = Z_TYPE_P(pair) == IS_ARRAY ? zend_hash_index_find(Z_ARRVAL_P(pair), 0) : NULL;
scope = Z_TYPE_P(pair) == IS_ARRAY ? zend_hash_index_find(Z_ARRVAL_P(pair), 1) : NULL;
if (UNEXPECTED(node == NULL || scope == NULL)) {
zend_throw_error(NULL, "Cannot destructure the gathered statement pair");
return false;
}
ZVAL_DEREF(node);
ZVAL_DEREF(scope);
return true;
}
/* Mirrors buildClosureTypeFromClosureWalk() ($cacheKey / $storage NULL for null) */
zv::Val buildClosureTypeFromClosureWalk(zval *scope, zval *expr, zval *parameters, bool isVariadic, zval *returnStatements, zval *yieldStatements, zval *executionEnds, zval *throwPoints, zval *impurePoints, zval *invalidateExpressions, zend_string *cacheKey, bool native, zval *storage, bool contextFree)
{
int onlyNeverExecutionEnds = deriveOnlyNeverExecutionEnds(executionEnds);
if (UNEXPECTED(onlyNeverExecutionEnds == -2)) return zv::Val();
// like resolveArrowFunctionReturnType(): the single walk stored both
// flavours on the gathered scopes, so the native flavour just reads the
// stored native types - no second body walk on the promoted scope
zv::Arr returnTypes = zv::Arr::empty();
bool hasNull = false;
if (EXPECTED(Z_TYPE_P(returnStatements) == IS_ARRAY)) {
for (zv::ArrayEntry entry : zv::ArrRef(returnStatements)) {
zval *returnNode, *returnScope;
if (UNEXPECTED(!unpackPair(entry.value().raw(), returnNode, returnScope))) return zv::Val();
zval *returnExpr = ptclosure::prop(pt_ctr_return_expr_site, returnNode, PT_LC("expr"));
if (UNEXPECTED(returnExpr == NULL)) return zv::Val();
if (Z_TYPE_P(returnExpr) == IS_NULL) {
hasNull = true;
continue;
}
zv::Val returnExprHold = zv::Val::copyOf(zv::Ref(returnExpr));
zv::Val readScope = readScopeOf(returnScope, native);
if (UNEXPECTED(readScope.isUndef())) return zv::Val();
zv::Val type = readExprType(storage, returnExprHold.raw(), readScope.raw(), native);
if (UNEXPECTED(type.isUndef())) return zv::Val();
returnTypes.push(std::move(type));
}
}
zv::Val returnType;
if (zend_hash_num_elements(returnTypes.table()) == 0) {
zval type;
bool created = onlyNeverExecutionEnds == 1 && !hasNull ? pt_non_accepting_never_type_new(&type) : pt_void_type_new(&type);
if (UNEXPECTED(!created)) return zv::Val();
returnType = zv::Val::adopt(type);
} else {
if (onlyNeverExecutionEnds == 1) {
zval neverType;
if (UNEXPECTED(!pt_non_accepting_never_type_new(&neverType))) return zv::Val();
returnTypes.push(zv::Val::adopt(neverType));
}
if (hasNull) {
zval nullType;
if (UNEXPECTED(!pt_null_type_new(&nullType))) return zv::Val();
returnTypes.push(zv::Val::adopt(nullType));
}
returnType = ptclosure::unionOf(returnTypes);
if (UNEXPECTED(returnType.isUndef())) return zv::Val();
}
if (Z_TYPE_P(yieldStatements) == IS_ARRAY && zend_hash_num_elements(Z_ARRVAL_P(yieldStatements)) > 0) {
zv::Arr keyTypes = zv::Arr::empty();
zv::Arr valueTypes = zv::Arr::empty();
for (zv::ArrayEntry entry : zv::ArrRef(yieldStatements)) {
zval *yieldNode, *yieldScope;
if (UNEXPECTED(!unpackPair(entry.value().raw(), yieldNode, yieldScope))) return zv::Val();
zv::Val readScope = readScopeOf(yieldScope, native);
if (UNEXPECTED(readScope.isUndef())) return zv::Val();
zv::Val keyType, valueType;
if (UNEXPECTED(!yieldTypes(storage, yieldNode, readScope.raw(), native, keyType, valueType))) return zv::Val();
keyTypes.push(std::move(keyType));
valueTypes.push(std::move(valueType));
}
zv::Val keyUnion = ptclosure::unionOf(keyTypes);
if (UNEXPECTED(keyUnion.isUndef())) return zv::Val();
zv::Val valueUnion = ptclosure::unionOf(valueTypes);
if (UNEXPECTED(valueUnion.isUndef())) return zv::Val();
returnType = generatorType(keyUnion.raw(), valueUnion.raw(), returnType.raw());
if (UNEXPECTED(returnType.isUndef())) return zv::Val();
} else {
zval *returnTypeNode = ptclosure::prop(ptclosure::returnTypeSite, expr, PT_LC("returnType"));
if (UNEXPECTED(returnTypeNode == NULL)) return zv::Val();
if (Z_TYPE_P(returnTypeNode) != IS_NULL) {
zv::Val nativeReturnType = pt_mutating_scope_get_function_type(Z_OBJ_P(scope), returnTypeNode, false, false);
if (UNEXPECTED(nativeReturnType.isUndef())) return zv::Val();
returnType = pt_mutating_scope_intersect_but_not_never(nativeReturnType.raw(), returnType.raw());
if (UNEXPECTED(returnType.isUndef())) return zv::Val();
}
}
zval *uses = ptclosure::prop(ptclosure::usesSite, expr, PT_LC("uses"));
if (UNEXPECTED(uses == NULL)) return zv::Val();
zv::Val usesHold = zv::Val::copyOf(zv::Ref(uses));
zv::Arr usedVariables = zv::Arr::empty();
bool hasByRefUse = false;
if (EXPECTED(Z_TYPE_P(usesHold.raw()) == IS_ARRAY)) {
for (zv::ArrayEntry entry : zv::ArrRef(usesHold.raw())) {
zval *var = ptclosure::prop(ptclosure::useVarSite, entry.value().deref().raw(), PT_LC("var"));
if (UNEXPECTED(var == NULL)) return zv::Val();
zval *name = ptclosure::prop(ptclosure::variableNameSite, var, PT_LC("name"));
if (UNEXPECTED(name == NULL)) return zv::Val();
if (Z_TYPE_P(name) != IS_STRING) continue;
usedVariables.push(zv::Ref(name));
}
for (zv::ArrayEntry entry : zv::ArrRef(usesHold.raw())) {
zval *byRef = ptclosure::prop(ptclosure::useByRefSite, entry.value().deref().raw(), PT_LC("byRef"));
if (UNEXPECTED(byRef == NULL)) return zv::Val();
if (!zend_is_true(byRef)) continue;
hasByRefUse = true;
break;
}
}
return assembleClosureType(scope, expr, parameters, isVariadic, returnType.raw(), throwPoints, impurePoints, hasByRefUse, invalidateExpressions, usedVariables.raw(), cacheKey, contextFree);
}
/* the key and value types of a Yield_ / YieldFrom node read on readScope;
* false = pending exception */
[[nodiscard]] static bool yieldTypes(zval *storage, zval *yieldNode, zval *readScope, bool native, zv::Val &keyType, zv::Val &valueType)
{
int isYield = ptclosure::instanceOf(yieldNode, PT_CLASS_YIELD);
if (UNEXPECTED(isYield < 0)) return false;
if (isYield) {
zval *key = ptclosure::prop(pt_ctr_yield_key_site, yieldNode, PT_LC("key"));
if (UNEXPECTED(key == NULL)) return false;
if (Z_TYPE_P(key) == IS_NULL) {
zval integerType;
if (UNEXPECTED(!pt_integer_type_new(&integerType))) return false;
keyType = zv::Val::adopt(integerType);
} else {
zv::Val keyHold = zv::Val::copyOf(zv::Ref(key));
keyType = readExprType(storage, keyHold.raw(), readScope, native);
if (UNEXPECTED(keyType.isUndef())) return false;
}
zval *value = ptclosure::prop(pt_ctr_yield_value_site, yieldNode, PT_LC("value"));
if (UNEXPECTED(value == NULL)) return false;
if (Z_TYPE_P(value) == IS_NULL) {
zval nullType;
if (UNEXPECTED(!pt_null_type_new(&nullType))) return false;
valueType = zv::Val::adopt(nullType);
} else {
zv::Val valueHold = zv::Val::copyOf(zv::Ref(value));
valueType = readExprType(storage, valueHold.raw(), readScope, native);
if (UNEXPECTED(valueType.isUndef())) return false;
}
return true;
}
zval *fromExpr = ptclosure::prop(pt_ctr_yield_from_expr_site, yieldNode, PT_LC("expr"));
if (UNEXPECTED(fromExpr == NULL)) return false;
zv::Val fromHold = zv::Val::copyOf(zv::Ref(fromExpr));
zv::Val yieldFromType = readExprType(storage, fromHold.raw(), readScope, native);
if (UNEXPECTED(yieldFromType.isUndef())) return false;
if (UNEXPECTED(!yieldFromType.ref().isObject())) {
zend_type_error("PHPStan\\Analyser\\MutatingScope::getIterableKeyType(): Argument #1 ($type) must be of type PHPStan\\Type\\Type, %s given", zend_zval_value_name(yieldFromType.raw()));
return false;
}
keyType = pt_mutating_scope_get_iterable_key_type(Z_OBJ_P(readScope), yieldFromType.raw());
if (UNEXPECTED(keyType.isUndef())) return false;
valueType = pt_mutating_scope_get_iterable_value_type(Z_OBJ_P(readScope), yieldFromType.raw());
return !valueType.isUndef();
}
/* new GenericObjectType(Generator::class, [$keyType, $valueType, new MixedType(), $returnType]) */
static zv::Val generatorType(zval *keyType, zval *valueType, zval *returnType)
{
zv::Val mixed = pt_type_new_mixed_type();
if (UNEXPECTED(mixed.isUndef())) return zv::Val();
zv::Arr types = zv::Arr::create(4);
types.push(zv::Ref(keyType));
types.push(zv::Ref(valueType));
types.push(std::move(mixed));
types.push(zv::Ref(returnType));
zval out;
if (UNEXPECTED(!pt_generic_object_type_new(&out, pt_ctr_generator, types.raw()))) return zv::Val();
return zv::Val::adopt(out);
}
/* Mirrors resolveArrowFunctionReturnType() ($storage NULL for null) */
static zv::Val resolveArrowFunctionReturnType(zval *scope, zval *arrowScope, zval *expr, bool native, zval *storage)
{
// Unlike a closure (whose native type equals its phpdoc type), an arrow
// function's native return type is the body expression's native type.
zv::Val nativeArrowScope;
zval *readScope = arrowScope;
if (native) {
nativeArrowScope = pt_mutating_scope_do_not_treat_phpdoc_types_as_certain(Z_OBJ_P(arrowScope));
if (UNEXPECTED(nativeArrowScope.isUndef())) return zv::Val();
readScope = nativeArrowScope.raw();
}
zval *body = ptclosure::prop(ptclosure::arrowExprSite, expr, PT_LC("expr"));
if (UNEXPECTED(body == NULL)) return zv::Val();
zv::Val bodyHold = zv::Val::copyOf(zv::Ref(body));
int isYield = ptclosure::instanceOf(bodyHold.raw(), PT_CLASS_YIELD);
if (UNEXPECTED(isYield < 0)) return zv::Val();
if (!isYield) {
isYield = ptclosure::instanceOf(bodyHold.raw(), PT_CLASS_YIELD_FROM);
if (UNEXPECTED(isYield < 0)) return zv::Val();
}
if (isYield) {
zv::Val keyType, valueType;
if (UNEXPECTED(!yieldTypes(storage, bodyHold.raw(), readScope, native, keyType, valueType))) return zv::Val();
zval voidType;
if (UNEXPECTED(!pt_void_type_new(&voidType))) return zv::Val();
zv::Val voidHold = zv::Val::adopt(voidType);
return generatorType(keyType.raw(), valueType.raw(), voidHold.raw());
}
// prefer the stored result of the single body walk - it carries the
// extension-resolved type (dynamic return type extensions)
zv::Val storedBodyResult = zv::Val::null();
if (storage != NULL) {
storedBodyResult = pt_expression_result_storage_find(storage, bodyHold.raw());
if (UNEXPECTED(storedBodyResult.isUndef())) return zv::Val();
}
zv::Val returnType;
if (!storedBodyResult.isNull()) {
bool promoted = false;
if (UNEXPECTED(!pt_mutating_scope_native_types_promoted(Z_OBJ_P(readScope), promoted))) return zv::Val();
returnType = pt_expression_result_get_keep_void_type(storedBodyResult.raw(), promoted);
} else {
returnType = pt_mutating_scope_get_keep_void_type(Z_OBJ_P(readScope), bodyHold.raw());
}
if (UNEXPECTED(returnType.isUndef())) return zv::Val();
zval *returnTypeNode = ptclosure::prop(ptclosure::returnTypeSite, expr, PT_LC("returnType"));
if (UNEXPECTED(returnTypeNode == NULL)) return zv::Val();
if (Z_TYPE_P(returnTypeNode) != IS_NULL) {
zv::Val nativeReturnType = pt_mutating_scope_get_function_type(Z_OBJ_P(scope), returnTypeNode, false, false);
if (UNEXPECTED(nativeReturnType.isUndef())) return zv::Val();
returnType = pt_mutating_scope_intersect_but_not_never(nativeReturnType.raw(), returnType.raw());
}
return returnType;
}
/* Mirrors deriveOnlyNeverExecutionEnds(): -1 null, 0 false, 1 true; -2 =
* pending exception */
static int deriveOnlyNeverExecutionEnds(zval *executionEnds)
{
int onlyNever = -1;
if (UNEXPECTED(Z_TYPE_P(executionEnds) != IS_ARRAY)) return onlyNever;
for (zv::ArrayEntry entry : zv::ArrRef(executionEnds)) {
zval *node = entry.value().deref().raw();
zval *statementResult = ptclosure::prop(pt_ctr_execution_end_statement_result_site, node, PT_LC("statementResult"));
if (UNEXPECTED(statementResult == NULL)) return -2;
bool alwaysTerminating = false;
if (UNEXPECTED(!pt_statement_result_is_always_terminating(statementResult, alwaysTerminating))) return -2;
if (!alwaysTerminating) {
onlyNever = 0;
continue;
}
zv::Val exitPointsHold;
zval *exitPoints = pt_statement_result_exit_points(statementResult, exitPointsHold);
if (UNEXPECTED(exitPoints == NULL)) return -2;
if (EXPECTED(Z_TYPE_P(exitPoints) == IS_ARRAY)) {
for (zv::ArrayEntry exitEntry : zv::ArrRef(exitPoints)) {
zv::Val statementHold;
zval *statement = pt_statement_exit_point_statement(exitEntry.value().deref().raw(), statementHold);
if (UNEXPECTED(statement == NULL)) return -2;
int isReturn = ptclosure::instanceOf(statement, PT_CLASS_RETURN_STMT);
if (UNEXPECTED(isReturn < 0)) return -2;
if (isReturn) {
onlyNever = 0;
continue;
}
if (onlyNever == -1) {
onlyNever = 1;
}
break;
}
}
zv::Val countHold;
zval *countedExitPoints = pt_statement_result_exit_points(statementResult, countHold);
if (UNEXPECTED(countedExitPoints == NULL)) return -2;
if (Z_TYPE_P(countedExitPoints) == IS_ARRAY && zend_hash_num_elements(Z_ARRVAL_P(countedExitPoints)) == 0 && onlyNever == -1) {
onlyNever = 1;
}
}
return onlyNever;
}
/* Mirrors buildDeclaredParameters(): the list and $isVariadic */
[[nodiscard]] bool buildDeclaredParameters(zval *scope, zval *expr, zv::Val ¶meters, bool &isVariadic)
{
isVariadic = false;
zval *params = ptclosure::prop(ptclosure::paramsSite, expr, PT_LC("params"));
if (UNEXPECTED(params == NULL)) return false;
zv::Val paramsHold = zv::Val::copyOf(zv::Ref(params));
if (UNEXPECTED(Z_TYPE_P(paramsHold.raw()) != IS_ARRAY) || zend_hash_num_elements(Z_ARRVAL_P(paramsHold.raw())) == 0) {
parameters = zv::Val(zv::Arr::empty());
return true;
}
/* the index from which every parameter is an optional candidate
* (-1: none); the keys of a parameter list are its positions */
zend_long firstOptionalParameterIndex = -1;
for (zv::ArrayEntry entry : zv::ArrRef(paramsHold.raw())) {
zval *param = entry.value().deref().raw();
zval *defaultValue = ptclosure::prop(ptclosure::paramDefaultSite, param, PT_LC("default"));
if (UNEXPECTED(defaultValue == NULL)) return false;
bool isOptionalCandidate = Z_TYPE_P(defaultValue) != IS_NULL;
if (!isOptionalCandidate) {
zval *variadic = ptclosure::prop(ptclosure::paramVariadicSite, param, PT_LC("variadic"));