Repository navigation
Expand file tree
/
Copy pathStaticCallHandler.php
More file actions
768 lines (709 loc) · 33.8 KB
/
Copy pathStaticCallHandler.php
File metadata and controls
768 lines (709 loc) · 33.8 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
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\ExprHandler;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt;
use PHPStan\Analyser\ArgsResult;
use PHPStan\Analyser\ArgumentsHandler;
use PHPStan\Analyser\ArgumentsNormalizer;
use PHPStan\Analyser\ExpressionContext;
use PHPStan\Analyser\ExpressionResult;
use PHPStan\Analyser\ExpressionResultFactory;
use PHPStan\Analyser\ExpressionResultStorage;
use PHPStan\Analyser\ExprHandler;
use PHPStan\Analyser\ExprHandler\Helper\DefaultNarrowingHelper;
use PHPStan\Analyser\ExprHandler\Helper\DynamicReturnTypeStoragePrimer;
use PHPStan\Analyser\ExprHandler\Helper\EarlyTerminatingCallHelper;
use PHPStan\Analyser\ExprHandler\Helper\MethodCallReturnTypeHelper;
use PHPStan\Analyser\ExprHandler\Helper\MethodThrowPointHelper;
use PHPStan\Analyser\Generics\TemplateArgumentFrame;
use PHPStan\Analyser\ImpurePoint;
use PHPStan\Analyser\InternalThrowPoint;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\Analyser\NoopNodeCallback;
use PHPStan\Analyser\SpecifiedTypes;
use PHPStan\Analyser\TypeSpecifier;
use PHPStan\Analyser\TypeSpecifierContext;
use PHPStan\Analyser\VariableFlow;
use PHPStan\Analyser\VariableFlowBuilder;
use PHPStan\Dependency\Dependencies;
use PHPStan\Dependency\DependencyTypes;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Node\Expr\PossiblyImpureCallExpr;
use PHPStan\Reflection\Callables\SimpleImpurePoint;
use PHPStan\Reflection\ExtendedMethodReflection;
use PHPStan\Reflection\ExtendedParametersAcceptor;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Reflection\ParametersAcceptor;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\ShouldNotHappenException;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\ErrorType;
use PHPStan\Type\Generic\TemplateTypeHelper;
use PHPStan\Type\Generic\TemplateTypeVariance;
use PHPStan\Type\Generic\TemplateTypeVarianceMap;
use PHPStan\Type\MixedType;
use PHPStan\Type\NeverType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\StaticType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeWithClassName;
use PHPStan\Type\UnionType;
use ReflectionProperty;
use function array_map;
use function array_merge;
use function count;
use function in_array;
use function sprintf;
use function strtolower;
/**
* @implements ExprHandler<StaticCall>
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/StaticCallHandler.cpp')]
final class StaticCallHandler implements ExprHandler
{
public function __construct(
private MethodCallReturnTypeHelper $methodCallReturnTypeHelper,
private MethodThrowPointHelper $methodThrowPointHelper,
private ReflectionProvider $reflectionProvider,
#[AutowiredParameter]
private bool $rememberPossiblyImpureFunctionValues,
private ExpressionResultFactory $expressionResultFactory,
private TypeSpecifier $typeSpecifier,
private DefaultNarrowingHelper $defaultNarrowingHelper,
private DynamicReturnTypeStoragePrimer $storagePrimer,
private EarlyTerminatingCallHelper $earlyTerminatingHelper,
private ArgumentsHandler $argumentsHandler,
)
{
}
public function supports(Expr $expr): bool
{
return $expr instanceof StaticCall && !$expr->isFirstClassCallable();
}
public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Expr $expr, MutatingScope $scope, ExpressionResultStorage $storage, callable $nodeCallback, ExpressionContext $context): ExpressionResult
{
$beforeScope = $scope;
$hasYield = false;
$throwPoints = [];
$impurePoints = [];
$isAlwaysTerminating = false;
$containsNullsafe = false;
$classResult = null;
$nameResult = null;
if ($expr->class instanceof Expr) {
$classResult = $nodeScopeResolver->processExprNode($stmt, $expr->class, $scope, $storage, $nodeCallback, $context->enterDeep());
$hasYield = $classResult->hasYield();
$throwPoints = array_merge($throwPoints, $classResult->getThrowPoints());
$impurePoints = array_merge($impurePoints, $classResult->getImpurePoints());
$isAlwaysTerminating = $classResult->isAlwaysTerminating();
$scope = $classResult->getScope();
$containsNullsafe = $classResult->containsNullsafe();
}
// `$a?->b::c()` is a link in a nullsafe chain and may never run: the chain
// short-circuits to null before the arguments are evaluated and before any
// of the call's effects happen. See MethodCallHandler::processExpr().
$mayShortCircuit = $classResult !== null
&& $containsNullsafe
&& TypeCombinator::containsNull($classResult->getType());
// A static call configured as early-terminating never returns: give it an
// explicit never so the statement's exit point follows from the result type,
// instead of NodeScopeResolver re-deriving it via Scope::getType().
$isEarlyTerminating = false;
if ($expr->name instanceof Identifier && !$mayShortCircuit) {
$earlyTerminatingClassType = $expr->class instanceof Name
? $scope->resolveTypeByName($expr->class)
: $classResult->getType();
$isEarlyTerminating = $this->earlyTerminatingHelper->isEarlyTerminatingMethodCall($expr->name->name, $earlyTerminatingClassType);
}
$isAlwaysTerminating = $isAlwaysTerminating || $isEarlyTerminating;
$parametersAcceptor = null;
$variants = [];
$namedArgumentsVariants = null;
$methodReflection = null;
$closureBindScopeFactory = null;
if ($expr->name instanceof Identifier) {
if ($expr->class instanceof Name) {
// the acceptor selected here feeds the call's return type - a
// STATIC method called through an explicit class name binds
// `static` to that class, so select from the demoted type
$classType = $this->resolveTypeByNameWithLateStaticBinding($scope, $expr->class, $expr->name->name);
$methodName = $expr->name->name;
if ($classType->hasMethod($methodName)->yes()) {
$methodReflection = $classType->getMethod($methodName, $scope);
$variants = $methodReflection->getVariants();
$namedArgumentsVariants = $methodReflection->getNamedArgumentsVariants();
// A structural acceptor (names/positions/variadic) drives argument
// normalization, the impure point and the throw point - generics are
// resolved type-driven by processArgs() into $resolvedParametersAcceptor.
$parametersAcceptor = ParametersAcceptorSelector::combineVariantsForNormalization($expr->getArgs(), $variants, $namedArgumentsVariants);
$declaringClass = $methodReflection->getDeclaringClass();
if (
$declaringClass->getName() === 'Closure'
&& strtolower($methodName) === 'bind'
) {
$closureBindScopeFactory = static function (MutatingScope $boundScope) use ($expr, $storage): MutatingScope {
// invoked while the closure argument is walked; the other
// arguments were processed before it (processArgs orders
// closures last), so their results are already stored. A
// missing result means degenerate code (a closure passed
// where the bound $this/scope belongs) - price it as mixed
// instead of walking on demand.
$readArgType = static function (Expr $argValue, bool $useNativeTypes) use ($boundScope, $storage): Type {
$argResult = $storage->findExpressionResult($argValue);
return $argResult !== null
? $argResult->getTypeOnScope($boundScope, $useNativeTypes)
: new MixedType();
};
$thisType = null;
$nativeThisType = null;
if (isset($expr->getArgs()[1])) {
$argType = $readArgType($expr->getArgs()[1]->value, false);
if (!$argType->isNull()->yes()) {
$thisType = $argType;
}
$nativeArgType = $readArgType($expr->getArgs()[1]->value, true);
if (!$nativeArgType->isNull()->yes()) {
$nativeThisType = $nativeArgType;
}
}
$scopeClasses = ['static'];
if (isset($expr->getArgs()[2])) {
$argValue = $expr->getArgs()[2]->value;
$argValueType = $readArgType($argValue, false);
$directClassNames = $argValueType->getObjectClassNames();
if (count($directClassNames) > 0) {
$scopeClasses = $directClassNames;
$scopeTypes = [];
foreach ($directClassNames as $directClassName) {
$scopeTypes[] = new ObjectType($directClassName);
}
$scopeType = TypeCombinator::union(...$scopeTypes);
} else {
$scopeType = $argValueType->getClassStringObjectType();
$scopeClasses = $scopeType->getObjectClassNames();
}
// $this is the bound object, not an instance of the scope
// class: the scope only refines the members of the bound
// object's type that may be an instance of it (the
// hydrator idiom binding an `object` into the class whose
// members it reads), a member that cannot be one stays
if ($thisType !== null && count($scopeClasses) > 0) {
$thisMembers = $thisType instanceof UnionType ? $thisType->getTypes() : [$thisType];
$refinedThisMembers = [];
foreach ($thisMembers as $thisMember) {
if ($scopeType->isSuperTypeOf($thisMember)->no()) {
$refinedThisMembers[] = $thisMember;
continue;
}
$refinedThisMembers[] = TypeCombinator::intersect($thisMember, $scopeType);
}
$thisType = TypeCombinator::union(...$refinedThisMembers);
}
}
return $boundScope->enterClosureBind($thisType, $nativeThisType, $scopeClasses);
};
}
} else {
$throwPoints[] = InternalThrowPoint::createImplicit($scope, $expr);
}
} elseif ($expr->class instanceof Expr) {
// the class expr was processed above as the receiver; read its
// already-computed result instead of re-walking via Scope::getType().
// A nullsafe receiver's null is the chain short-circuit, not a
// callee - strip it before the reflection lookup, like the
// return-type resolution does.
$classType = TypeCombinator::removeNull($classResult->getType())->getObjectTypeOrClassStringObjectType();
$methodName = $expr->name->name;
$methodReflection = $scope->getMethodReflection($classType, $methodName);
if ($methodReflection !== null) {
$variants = $methodReflection->getVariants();
$namedArgumentsVariants = $methodReflection->getNamedArgumentsVariants();
$parametersAcceptor = ParametersAcceptorSelector::combineVariantsForNormalization($expr->getArgs(), $variants, $namedArgumentsVariants);
}
}
} else {
$nameResult = $nodeScopeResolver->processExprNode($stmt, $expr->name, $scope, $storage, $nodeCallback, $context->enterDeep());
$hasYield = $hasYield || $nameResult->hasYield();
$throwPoints = array_merge($throwPoints, $nameResult->getThrowPoints());
$impurePoints = array_merge($impurePoints, $nameResult->getImpurePoints());
$isAlwaysTerminating = $isAlwaysTerminating || $nameResult->isAlwaysTerminating();
$scope = $nameResult->getScope();
}
if ($expr->class instanceof Expr) {
// the class expr was processed above as the receiver; read its
// already-computed result instead of re-walking via Scope::getType().
$objectClasses = $classResult->getType()->getObjectClassNames();
if (count($objectClasses) !== 1) {
// the receiver may be a class-string instead of an object - the
// instantiated type is what `new` would produce, read from the
// same result instead of walking a synthetic New_ node
$objectClasses = $classResult->getType()->getObjectTypeOrClassStringObjectType()->getObjectClassNames();
}
if (count($objectClasses) === 1) {
$objectExprResult = $nodeScopeResolver->processExprNode($stmt, new StaticCall(new Name($objectClasses[0]), $expr->name, []), $scope, $storage, new NoopNodeCallback(), $context->enterDeep()->withoutTemplateArgumentResolution());
$additionalThrowPoints = $objectExprResult->getThrowPoints();
} else {
$additionalThrowPoints = [InternalThrowPoint::createImplicit($scope, $expr)];
}
foreach ($additionalThrowPoints as $throwPoint) {
$throwPoints[] = $throwPoint;
}
}
$normalizedExpr = $expr;
if ($parametersAcceptor !== null) {
$normalizedExpr = ArgumentsNormalizer::reorderStaticCallArguments($parametersAcceptor, $expr) ?? $expr;
$returnType = $parametersAcceptor->getReturnType();
$isAlwaysTerminating = $isAlwaysTerminating || (!$mayShortCircuit && $returnType instanceof NeverType && $returnType->isExplicit());
}
$scopeBeforeArgs = $scope;
if ($parametersAcceptor !== null && $context->getInAssignRightSideExpr() === $expr) {
$context = $context->enterAssignRightSideCallArgs($parametersAcceptor);
}
$argsResult = $this->argumentsHandler->processArgs($nodeScopeResolver, $stmt, $methodReflection, null, $variants, $namedArgumentsVariants, $normalizedExpr, $scope, $storage, $nodeCallback, $context, $closureBindScopeFactory);
$resolvedParametersAcceptor = $argsResult->getResolvedParametersAcceptor();
$scope = $argsResult->getScope();
$this->argumentsHandler->processDroppedArgs($nodeScopeResolver, $stmt, $expr, $normalizedExpr, $scope, $storage, $context);
if ($methodReflection !== null) {
// created after the args were processed - the pure-unless-callable-
// is-impure parameters read an argument's type, which is only
// available once its result is stored
$impurePoint = SimpleImpurePoint::createFromVariant($methodReflection, $parametersAcceptor, $scope, $expr->getArgs());
if ($impurePoint !== null) {
$impurePoints[] = new ImpurePoint($scopeBeforeArgs, $expr, $impurePoint->getIdentifier(), $impurePoint->getDescription(), $impurePoint->isCertain());
}
} else {
$impurePoints[] = new ImpurePoint(
$scopeBeforeArgs,
$expr,
'methodCall',
'call to unknown method',
false,
);
}
$scopeFunction = $scope->getFunction();
// The early structural check above only sees the unresolved acceptor return
// type; a conditional-return never (e.g. `($x is Foo ? never : string)`)
// only resolves to never once the actual argument types are folded in by the
// type-driven resolved acceptor.
if ($resolvedParametersAcceptor !== null && !$mayShortCircuit) {
$resolvedReturnType = $resolvedParametersAcceptor->getReturnType();
$isAlwaysTerminating = $isAlwaysTerminating || ($resolvedReturnType instanceof NeverType && $resolvedReturnType->isExplicit());
}
// The return type is derived from $resolvedParametersAcceptor - the acceptor
// processArgs() selected from the arg types gathered on the arg-to-arg
// evolving scope (type-driven, generics resolved). When null
// (native-types-promoted, or on-demand / synthetic pricing) the acceptor is
// re-derived from the already-processed argument results on the asking scope.
$typeCallback = $isEarlyTerminating
? static fn (bool $nativeTypesPromoted): Type => new NeverType(true)
: fn (bool $nativeTypesPromoted): Type => $this->resolveReturnType(
$beforeScope,
$nativeTypesPromoted,
$expr,
$classResult,
$nameResult,
$nativeTypesPromoted ? null : $resolvedParametersAcceptor,
$argsResult,
);
$walkMethodReflection = $methodReflection;
$specifyTypesCallback = fn (TypeSpecifierContext $specifyContext, bool $nativeTypesPromoted): SpecifiedTypes => $this->specifyTypes(
$nativeTypesPromoted ? $beforeScope->doNotTreatPhpDocTypesAsCertain() : $beforeScope,
$expr,
$normalizedExpr,
$classResult,
$resolvedParametersAcceptor,
$walkMethodReflection,
$specifyContext,
$argsResult,
);
// A type constraint on a (narrowable, i.e. non-side-effecting) static call
// narrows the call itself - the inside-out equivalent of createForExpr's
// StaticCall purity gate + tail entry. An impure call narrows to nothing.
$createTypesCallback = function (Type $type, TypeSpecifierContext $createContext, bool $nativeTypesPromoted) use ($expr, $classResult, $beforeScope): SpecifiedTypes {
$s = $nativeTypesPromoted ? $beforeScope->doNotTreatPhpDocTypesAsCertain() : $beforeScope;
return $this->isStaticCallNarrowable($s, $expr, $classResult)
? $this->defaultNarrowingHelper->createSubjectTypes($s, $expr, null, $type, $createContext)
: new SpecifiedTypes([], []);
};
// Store a preliminary result carrying the type/specify callbacks before the
// throw point is computed: the method throw point resolves the return type
// (resolveReturnType below) through dynamic static-method return type
// extensions, which can narrow this very call on demand. Without a stored
// result that narrowing would re-process this StaticCall on demand and
// recurse. The callbacks are scope-independent, so the preliminary result
// answers those asks correctly; finalize() below completes it with the
// resolved scope and throw/impure points.
$preliminaryResult = $this->expressionResultFactory->create(
$scope,
beforeScope: $beforeScope,
expr: $expr,
hasYield: $hasYield,
isAlwaysTerminating: $isAlwaysTerminating,
throwPoints: [],
impurePoints: [],
containsNullsafe: $containsNullsafe,
typeCallback: $typeCallback,
specifyTypesCallback: $specifyTypesCallback,
createTypesCallback: $createTypesCallback,
argsResult: $argsResult,
);
$nodeScopeResolver->storeExpressionResult($storage, $expr, $preliminaryResult);
if ($methodReflection !== null) {
// The call's return type, computed from the already-processed argument
// results (resolveReturnType reads them via the class/name results,
// never re-running processArgs) - asking
// Scope::getType() for the StaticCall here would re-enter this handler on
// demand, as its final result is not stored yet.
// Resolve it through the stored preliminary result so the memoized
// value seeds the final result below - the first later type read
// would otherwise run resolveReturnType() again.
$staticCallReturnType = $preliminaryResult->getKeepVoidType(false);
$methodThrowPoint = $this->methodThrowPointHelper->getThrowPoint($methodReflection, $parametersAcceptor, $normalizedExpr, $scope, $context, $staticCallReturnType);
if ($methodThrowPoint !== null) {
$throwPoints[] = $methodThrowPoint;
}
}
if (
$expr->class instanceof Name
&& $methodReflection !== null
&& (
(
!$methodReflection->isStatic()
&& $methodReflection->getName() === '__construct'
)
|| $methodReflection->hasSideEffects()->yes()
)
&& $scope->isInClass()
&& $scope->getClassReflection()->is($methodReflection->getDeclaringClass()->getName())
) {
// a static method never receives $this, so property fetches on it survive
$scope = $scope->invalidateExpression(new Variable('this'), true, $methodReflection->getDeclaringClass(), $methodReflection->isStatic());
} elseif (
$expr->class instanceof Name
&& $methodReflection !== null
&& $this->rememberPossiblyImpureFunctionValues
&& $scope->isInClass()
&& $scope->getClassReflection()->is($methodReflection->getDeclaringClass()->getName())
&& $methodReflection->hasSideEffects()->maybe()
&& !$methodReflection->getDeclaringClass()->isBuiltin()
) {
// the remembered call value is generic-sensitive: resolve it from the
// type-driven acceptor processArgs() selected (generics resolved against
// the actual arg types), falling back to the structural acceptor.
$acceptorForGenerics = $resolvedParametersAcceptor ?? $parametersAcceptor;
$scope = $scope->assignExpression(
new PossiblyImpureCallExpr($normalizedExpr, new Variable('this'), sprintf('%s::%s()', $methodReflection->getDeclaringClass()->getDisplayName(), $methodReflection->getName())),
TemplateArgumentFrame::returnTypeOfCall($acceptorForGenerics, $scope, $expr),
new MixedType(),
);
}
if (
$expr->class instanceof Name
&& $methodReflection !== null
&& !$methodReflection->isStatic()
&& $methodReflection->getName() === '__construct'
&& $scopeFunction instanceof MethodReflection
&& !$scopeFunction->isStatic()
&& $scope->isInClass()
&& $scope->getClassReflection()->isSubclassOfClass($methodReflection->getDeclaringClass())
) {
$thisType = $scope->getVariableType('this');
$methodClassReflection = $methodReflection->getDeclaringClass();
foreach ($methodClassReflection->getNativeReflection()->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED) as $property) {
if (!$property->isPromoted() || $property->getDeclaringClass()->getName() !== $methodClassReflection->getName()) {
continue;
}
$scope = $scope->assignInitializedProperty($thisType, $property->getName());
}
}
if (
$methodReflection === null
|| (!$methodReflection->getDeclaringClass()->isBuiltin() && !$methodReflection->hasSideEffects()->no())
) {
$scope = $scope->invalidateVolatileExpressions();
}
$hasYield = $hasYield || $argsResult->hasYield();
$throwPoints = array_merge($throwPoints, $argsResult->getThrowPoints());
$impurePoints = array_merge($impurePoints, $argsResult->getImpurePoints());
$isAlwaysTerminating = $isAlwaysTerminating || (!$mayShortCircuit && $argsResult->isAlwaysTerminating());
$argumentsFlow = VariableFlowBuilder::arguments($expr, $argsResult, $storage);
$variableFlow = VariableFlow::sequence(
$classResult !== null ? $classResult->getVariableFlow() : null,
$nameResult !== null ? $nameResult->getVariableFlow() : null,
// the short-circuited world evaluates none of the arguments
$mayShortCircuit ? VariableFlow::choice($argumentsFlow, null) : $argumentsFlow,
VariableFlowBuilder::throws($expr, $throwPoints),
$isAlwaysTerminating ? VariableFlow::exit(VariableFlow::STOP) : null,
);
// the call's scope effects (@param-out, invalidations) only happened in the
// world where the chain did not short-circuit
if ($mayShortCircuit) {
$scope = $scope->mergeWith($scopeBeforeArgs);
}
// the class, what the call returns, the class declaring the method and what it can make of
// its arguments
$calledOnTypes = [$preliminaryResult->getType()];
$calledOnClassNames = [];
if ($classResult !== null) {
$calledOnTypes[] = $classResult->getType();
} elseif ($expr->class instanceof Name) {
$calledOnClassNames[] = $beforeScope->resolveName($expr->class);
}
if ($walkMethodReflection !== null) {
$calledOnClassNames[] = $walkMethodReflection->getDeclaringClass()->getName();
$calledOnTypes = [...$calledOnTypes, ...DependencyTypes::ofCalledMethod($walkMethodReflection, false)];
}
$dependencies = Dependencies::merge(
$classResult !== null ? $classResult->getDependencies() : null,
$nameResult !== null ? $nameResult->getDependencies() : null,
$argsResult->getDependencies(),
Dependencies::create($beforeScope->getFile(), $calledOnTypes, $calledOnClassNames),
);
return $preliminaryResult->finalize($scope, $hasYield, $isAlwaysTerminating, $throwPoints, $impurePoints, $variableFlow, $dependencies);
}
/**
* The call-expression type is derived from $preResolvedAcceptor - the acceptor
* processArgs() selected from the arg types gathered on the arg-to-arg evolving
* scope (type-driven, generics resolved). When null (native-types-promoted, or
* on-demand / synthetic pricing) it falls back to re-selecting from the args via
* MethodCallReturnTypeHelper on the asking scope.
*
* The class/name were processed during processExpr; their already computed
* results are read instead of re-walking via Scope::getType(). The dynamic-name
* branch builds a synthetic StaticCall priced on demand by the resolver.
*
*/
private function resolveReturnType(MutatingScope $reflectionScope, bool $nativeTypesPromoted, StaticCall $expr, ?ExpressionResult $classResult, ?ExpressionResult $nameResult, ?ParametersAcceptor $preResolvedAcceptor, ?ArgsResult $argsResult): Type
{
$classType = $classResult !== null
? ($nativeTypesPromoted ? $classResult->getNativeType() : $classResult->getType())
: null;
// a call on a nullsafe chain whose class-receiver is currently nullable
// short-circuits to null - the class result carries whether the chain
// contains a ?-> (a plain nullable receiver does not propagate).
$shortCircuit = static fn (Type $type): Type => $expr->class instanceof Expr
&& $classResult !== null
&& $classResult->containsNullsafe()
&& $classType !== null
&& TypeCombinator::containsNull($classType)
? TypeCombinator::addNull($type)
: $type;
// the method reflection and dynamic-return-type extensions run on the
// reflection scope (the lexical context / beforeScope); the class-
// expression type is read from the operand result above.
$resolveStaticMethod = function (string $methodName, StaticCall $staticCall) use ($reflectionScope, $nativeTypesPromoted, $classType, $expr, $preResolvedAcceptor, $argsResult): Type {
if ($nativeTypesPromoted) {
if ($expr->class instanceof Name) {
$staticMethodCalledOnType = $this->resolveTypeByNameWithLateStaticBinding($reflectionScope, $expr->class, $methodName);
} else {
if ($classType === null) {
throw new ShouldNotHappenException();
}
$staticMethodCalledOnType = $classType;
}
$methodReflection = $reflectionScope->getMethodReflection($staticMethodCalledOnType, $methodName);
if ($methodReflection === null) {
return new ErrorType();
}
return ParametersAcceptorSelector::combineAcceptors($methodReflection->getVariants())->getNativeReturnType();
}
if ($expr->class instanceof Name) {
$staticMethodCalledOnType = $this->resolveTypeByNameWithLateStaticBinding($reflectionScope, $expr->class, $methodName);
} else {
if ($classType === null) {
throw new ShouldNotHappenException();
}
$staticMethodCalledOnType = TypeCombinator::removeNull($classType)->getObjectTypeOrClassStringObjectType();
}
return $this->methodCallReturnTypeHelper->methodCallReturnType(
$reflectionScope,
$staticMethodCalledOnType,
$methodName,
$staticCall,
$preResolvedAcceptor,
$argsResult,
) ?? new ErrorType();
};
if ($expr->name instanceof Identifier) {
return $shortCircuit($resolveStaticMethod($expr->name->toString(), $expr));
}
// dynamic static call Foo::{$name}(): resolve each possible name on the
// reflection scope. The asking scope is not narrowed per name, so such
// calls can be less precise.
if ($nameResult === null) {
throw new ShouldNotHappenException();
}
$nameType = $nativeTypesPromoted ? $nameResult->getNativeType() : $nameResult->getType();
if (count($nameType->getConstantStrings()) > 0) {
return TypeCombinator::union(
...array_map(static function ($constantString) use ($expr, $resolveStaticMethod): Type {
if ($constantString->getValue() === '') {
return new ErrorType();
}
return $resolveStaticMethod(
$constantString->getValue(),
new StaticCall($expr->class, new Identifier($constantString->getValue()), $expr->args),
);
}, $nameType->getConstantStrings()),
);
}
return new MixedType();
}
/**
* Ported inside-out from the old TypeResolvingExprHandler::specifyTypes(): the
* StaticMethodTypeSpecifyingExtensions, conditional-return-type and assert
* narrowing are invoked on the already-processed argument
* results. The acceptor is $resolvedParametersAcceptor (type-driven, generics
* resolved by processArgs) rather than re-selected from the args on the asking
* scope. The subject's own default narrowing comes from DefaultNarrowingHelper
* instead of TypeSpecifier::handleDefaultTruthyOrFalseyContext(), which would
* re-enter this expression through TypeSpecifier::create().
*
* @param StaticCall $expr
* @param StaticCall $normalizedExpr
*/
private function specifyTypes(MutatingScope $scope, Expr $expr, Expr $normalizedExpr, ?ExpressionResult $classResult, ?ParametersAcceptor $resolvedParametersAcceptor, ?ExtendedMethodReflection $walkMethodReflection, TypeSpecifierContext $context, ?ArgsResult $argsResult = null): SpecifiedTypes
{
if (!$expr->name instanceof Identifier) {
return $this->defaultNarrowingHelper->specifyDefaultTypes($expr, $context);
}
if ($expr->class instanceof Name) {
$calleeType = $scope->resolveTypeByName($expr->class);
} else {
// the class expr was processed during processExpr; its result is
// always captured for an expression class
if ($classResult === null) {
throw new ShouldNotHappenException();
}
$calleeType = $classResult->getTypeOnScope($scope, $scope->nativeTypesPromoted);
}
$staticMethodReflection = $scope->getMethodReflection($calleeType, $expr->name->name);
// see MethodCallHandler::specifyTypes() - `$a?->b::c()` short-circuits too,
// so the branches admitting its null get no callee-derived narrowing
$mayHaveBeenSkipped = $this->defaultNarrowingHelper->callMayHaveBeenSkipped($classResult, $calleeType, $context);
if ($staticMethodReflection !== null && !$mayHaveBeenSkipped) {
$args = $expr->getArgs();
$referencedClasses = $calleeType->getObjectClassNames();
if (
count($referencedClasses) === 1
&& $this->reflectionProvider->hasClass($referencedClasses[0])
) {
$staticMethodClassReflection = $this->reflectionProvider->getClass($referencedClasses[0]);
// runs lazily at narrowing-apply time - prime the storage with the
// argument results, see MethodCallHandler::specifyTypes()
$popPrimedStorage = $this->storagePrimer->pushPrimedStorage($scope, $argsResult);
try {
foreach ($this->typeSpecifier->getStaticMethodTypeSpecifyingExtensionsForClass($staticMethodClassReflection->getName()) as $extension) {
if (!$extension->isStaticMethodSupported($staticMethodReflection, $normalizedExpr, $context)) {
continue;
}
return $extension->specifyTypes($staticMethodReflection, $normalizedExpr, $scope, $context);
}
} finally {
$popPrimedStorage();
}
}
if (count($args) > 0 && $resolvedParametersAcceptor !== null) {
$specifiedTypes = $this->defaultNarrowingHelper->specifyTypesFromConditionalReturnType($context, $expr, $resolvedParametersAcceptor, $scope);
if ($specifiedTypes !== null) {
return $specifiedTypes;
}
}
// see MethodCallHandler::specifyTypes() - `$obj::m()` resolves its callee
// from the receiver type of the asking scope, so a native-types-promoted
// ask reads the assertions off the walk's reflection to keep them paired
// with the walk's acceptor
$assertions = ($scope->nativeTypesPromoted ? $walkMethodReflection ?? $staticMethodReflection : $staticMethodReflection)->getAsserts();
if ($assertions->getAll() !== [] && $resolvedParametersAcceptor !== null) {
$asserts = $assertions->mapTypes(static fn (Type $type) => TemplateTypeHelper::resolveTemplateTypes(
$type,
$resolvedParametersAcceptor->getResolvedTemplateTypeMap(),
$resolvedParametersAcceptor instanceof ExtendedParametersAcceptor ? $resolvedParametersAcceptor->getCallSiteVarianceMap() : TemplateTypeVarianceMap::createEmpty(),
TemplateTypeVariance::createInvariant(),
));
$specifiedTypes = $this->defaultNarrowingHelper->specifyTypesFromAsserts($context, $expr, $asserts, $resolvedParametersAcceptor, $scope);
if ($specifiedTypes !== null) {
// see MethodCallHandler::specifyTypes() - the call's own key gets
// the purity gate, the asserts narrow their subjects regardless
return $specifiedTypes
->unionWith($this->defaultStaticCallNarrowing($scope, $expr, $classResult, $context))
->setRootExpr($specifiedTypes->getRootExpr());
}
}
}
return $this->defaultStaticCallNarrowing($scope, $expr, $classResult, $context);
}
/**
* The default truthy/falsey narrowing of the call expression itself, gated by
* the same purity check TypeSpecifier::create() applies: a static method with
* side effects (or an unknown method whose result is not remembered) is not
* narrowable - calling it twice may yield different values - so it contributes
* no entry. Mirrors create()'s StaticCall handling inside-out, without
* re-entering this expression through create().
*
* @param StaticCall $expr
*/
private function defaultStaticCallNarrowing(MutatingScope $scope, Expr $expr, ?ExpressionResult $classResult, TypeSpecifierContext $context): SpecifiedTypes
{
if (!$this->isStaticCallNarrowable($scope, $expr, $classResult)) {
return (new SpecifiedTypes([], []))->setRootExpr($expr);
}
return $this->defaultNarrowingHelper->specifyDefaultTypes($expr, $context);
}
/** @param StaticCall $expr */
private function isStaticCallNarrowable(MutatingScope $scope, Expr $expr, ?ExpressionResult $classResult): bool
{
if (!$expr->name instanceof Identifier) {
return true;
}
if ($expr->class instanceof Name) {
$calleeType = $scope->resolveTypeByName($expr->class);
} else {
if ($classResult === null) {
throw new ShouldNotHappenException();
}
$calleeType = $classResult->getTypeOnScope($scope, $scope->nativeTypesPromoted);
}
$methodReflection = $scope->getMethodReflection($calleeType, $expr->name->toString());
if ($methodReflection === null) {
return false;
}
$hasSideEffects = $methodReflection->hasSideEffects();
if ($hasSideEffects->yes()) {
return false;
}
return $this->rememberPossiblyImpureFunctionValues || $hasSideEffects->no();
}
/**
* An explicit class name within the current hierarchy resolves to a
* StaticType, but calling a STATIC method through it binds `static` to the
* named class - demote to the plain object type so `A::retStatic()` is `A`,
* not `static(self)`. self/static/parent keep late static binding.
*/
private function resolveTypeByNameWithLateStaticBinding(MutatingScope $scope, Name $class, string $methodName): TypeWithClassName
{
$classType = $scope->resolveTypeByName($class);
if (
$classType instanceof StaticType
&& !in_array($class->toLowerString(), ['self', 'static', 'parent'], true)
) {
$methodReflectionCandidate = $scope->getMethodReflection(
$classType,
$methodName,
);
if ($methodReflectionCandidate !== null && $methodReflectionCandidate->isStatic()) {
$classType = $classType->getStaticObjectType();
}
}
return $classType;
}
}