Repository navigation
Expand file tree
/
Copy pathNewHandler.php
More file actions
860 lines (769 loc) · 35.8 KB
/
Copy pathNewHandler.php
File metadata and controls
860 lines (769 loc) · 35.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
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
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\ExprHandler;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt;
use PHPStan\Analyser\ArgsResult;
use PHPStan\Analyser\ArgumentsHandler;
use PHPStan\Analyser\ArgumentsNormalizer;
use PHPStan\Analyser\ConditionalTypeResolver;
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\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\Scope;
use PHPStan\Analyser\SpecifiedTypes;
use PHPStan\Analyser\StatementContext;
use PHPStan\Analyser\ThrowPoint;
use PHPStan\Analyser\Traverser\GenericTypeTemplateTraverser;
use PHPStan\Analyser\TypeSpecifierContext;
use PHPStan\Analyser\VariableFlow;
use PHPStan\Analyser\VariableFlowBuilder;
use PHPStan\Dependency\Dependencies;
use PHPStan\Dependency\DependencyTypes;
use PHPStan\DependencyInjection\AutowiredExtensions;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\DependencyInjection\Container;
use PHPStan\DependencyInjection\ExtensionsCollection;
use PHPStan\Node\MethodReturnStatementsNode;
use PHPStan\Parser\NewAssignedToPropertyVisitor;
use PHPStan\Reflection\Callables\SimpleImpurePoint;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\Dummy\DummyConstructorReflection;
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\Rules\Properties\PropertyReflectionFinder;
use PHPStan\ShouldNotHappenException;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\DynamicReturnTypeExtensionRegistry;
use PHPStan\Type\DynamicStaticMethodThrowTypeExtension;
use PHPStan\Type\ErrorType;
use PHPStan\Type\Generic\GenericObjectType;
use PHPStan\Type\Generic\GenericStaticType;
use PHPStan\Type\Generic\TemplateType;
use PHPStan\Type\Generic\TemplateTypeHelper;
use PHPStan\Type\Generic\TemplateTypeMap;
use PHPStan\Type\Generic\TemplateTypeVariance;
use PHPStan\Type\Generic\TemplateTypeVarianceMap;
use PHPStan\Type\Generic\UnresolvedTemplateArgumentType;
use PHPStan\Type\NeverType;
use PHPStan\Type\NonexistentParentClassType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\StaticType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeTraverser;
use Throwable;
use function array_key_exists;
use function array_keys;
use function array_map;
use function array_merge;
use function count;
use function sprintf;
/**
* @implements ExprHandler<New_>
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/NewHandler.cpp')]
final class NewHandler implements ExprHandler
{
/**
* @param ExtensionsCollection<DynamicStaticMethodThrowTypeExtension> $dynamicStaticMethodThrowTypeExtensions
*/
public function __construct(
private ReflectionProvider $reflectionProvider,
#[AutowiredExtensions(of: DynamicStaticMethodThrowTypeExtension::class)]
private ExtensionsCollection $dynamicStaticMethodThrowTypeExtensions,
private DynamicReturnTypeExtensionRegistry $dynamicReturnTypeExtensionRegistry,
private PropertyReflectionFinder $propertyReflectionFinder,
#[AutowiredParameter(ref: '%exceptions.implicitThrows%')]
private bool $implicitThrows,
private ExpressionResultFactory $expressionResultFactory,
private DefaultNarrowingHelper $defaultNarrowingHelper,
private DynamicReturnTypeStoragePrimer $storagePrimer,
private Container $container,
private ArgumentsHandler $argumentsHandler,
)
{
}
public function supports(Expr $expr): bool
{
return $expr instanceof New_ && !$expr->isFirstClassCallable();
}
public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Expr $expr, MutatingScope $scope, ExpressionResultStorage $storage, callable $nodeCallback, ExpressionContext $context): ExpressionResult
{
$beforeScope = $scope;
$parametersAcceptor = null;
$constructorReflection = null;
$classReflection = null;
$isDynamic = false;
$hasYield = false;
$throwPoints = [];
$impurePoints = [];
$isAlwaysTerminating = false;
$normalizedExpr = $expr;
$className = null;
$classResult = null;
$deferredConstructorImpureIsDynamic = null;
$anonymousClassDependencies = null;
if ($expr->class instanceof Name) {
$className = $scope->resolveName($expr->class);
[$constructorReflection, $classReflection, $parametersAcceptor] = $this->processConstructorReflection($className, $expr);
$deferredConstructorImpureIsDynamic = false;
if ($parametersAcceptor !== null) {
$normalizedExpr = ArgumentsNormalizer::reorderNewArguments($parametersAcceptor, $expr) ?? $expr;
}
} elseif ($expr->class instanceof Node\Stmt\Class_) {
$classReflection = $this->reflectionProvider->getAnonymousClassReflection($expr->class, $scope); // populates $expr->class->name
if ($classReflection->hasConstructor()) {
$constructorReflection = $classReflection->getConstructor();
// A structural acceptor (names/positions/variadic) drives argument
// normalization and the throw point - generics are resolved
// type-driven by processArgs() into $resolvedParametersAcceptor.
$parametersAcceptor = ParametersAcceptorSelector::combineVariantsForNormalization($expr->getArgs(), $constructorReflection->getVariants(), $constructorReflection->getNamedArgumentsVariants());
if ($constructorReflection->getDeclaringClass()->getName() === $classReflection->getName()) {
$constructorResult = null;
$nodeScopeResolver->pushNodeGatherer(static function (Node $node, Scope $scope) use ($classReflection, &$constructorResult): void {
if (!$node instanceof MethodReturnStatementsNode) {
return;
}
if ($constructorResult !== null) {
return;
}
$currentClassReflection = $node->getClassReflection();
if ($currentClassReflection->getName() !== $classReflection->getName()) {
return;
}
if (!$currentClassReflection->hasConstructor()) {
return;
}
if ($currentClassReflection->getConstructor()->getName() !== $node->getMethodReflection()->getName()) {
return;
}
$constructorResult = $node;
});
try {
$anonymousClassDependencies = $nodeScopeResolver->processStmtNode($expr->class, $scope, $storage, $nodeCallback, StatementContext::createTopLevel($context->shouldResolveTemplateArguments()))->getDependencies();
} finally {
$nodeScopeResolver->popNodeGatherer();
}
if ($constructorResult !== null) {
$throwPoints = array_map(static fn (ThrowPoint $point): InternalThrowPoint => InternalThrowPoint::createFromPublic($point, $scope), $constructorResult->getStatementResult()->getThrowPoints());
$impurePoints = $constructorResult->getImpurePoints();
}
} else {
$anonymousClassDependencies = $nodeScopeResolver->processStmtNode($expr->class, $scope, $storage, $nodeCallback, StatementContext::createTopLevel($context->shouldResolveTemplateArguments()))->getDependencies();
if (!$constructorReflection->hasSideEffects()->no()) {
$certain = $constructorReflection->isPure()->no();
$impurePoints[] = new ImpurePoint(
$scope,
$expr,
'new',
sprintf('instantiation of class %s', $constructorReflection->getDeclaringClass()->getDisplayName()),
$certain,
);
}
}
} else {
$anonymousClassDependencies = $nodeScopeResolver->processStmtNode($expr->class, $scope, $storage, $nodeCallback, StatementContext::createTopLevel($context->shouldResolveTemplateArguments()))->getDependencies();
}
if ($parametersAcceptor !== null) {
$normalizedExpr = ArgumentsNormalizer::reorderNewArguments($parametersAcceptor, $expr) ?? $expr;
}
} else {
$isDynamic = true;
$classResult = $nodeScopeResolver->processExprNode($stmt, $expr->class, $scope, $storage, $nodeCallback, $context->enterDeep());
$scope = $classResult->getScope();
$hasYield = $classResult->hasYield();
$throwPoints = $classResult->getThrowPoints();
$impurePoints = $classResult->getImpurePoints();
$isAlwaysTerminating = $classResult->isAlwaysTerminating();
// The instantiated object type derives from the class expression - read
// its already-processed result rather than asking Scope::getType() for
// the not-yet-stored New_ node, which would re-enter this handler.
$objectClasses = $classResult->getType()->getObjectTypeOrClassStringObjectType()->getObjectClassNames();
if (count($objectClasses) === 1) {
$objectExprResult = $nodeScopeResolver->processExprNode($stmt, new New_(new Name($objectClasses[0]), attributes: [TemplateArgumentFrame::SYNTHETIC_SITE_ATTRIBUTE => true]), $scope, $storage, new NoopNodeCallback(), $context->enterDeep()->withoutTemplateArgumentResolution());
$className = $objectClasses[0];
$additionalThrowPoints = $objectExprResult->getThrowPoints();
} else {
$additionalThrowPoints = [InternalThrowPoint::createImplicit($scope, $expr)];
}
$throwPoints = array_merge($throwPoints, $additionalThrowPoints);
if ($className !== null) {
[$constructorReflection, $classReflection, $parametersAcceptor] = $this->processConstructorReflection($className, $expr);
$deferredConstructorImpureIsDynamic = true;
} else {
$impurePoints[] = new ImpurePoint(
$scope,
$expr,
'new',
'instantiation of unknown class',
false,
);
}
if ($parametersAcceptor !== null) {
$normalizedExpr = ArgumentsNormalizer::reorderNewArguments($parametersAcceptor, $expr) ?? $expr;
}
}
$variants = $constructorReflection !== null ? $constructorReflection->getVariants() : [];
$namedArgumentsVariants = $constructorReflection !== null ? $constructorReflection->getNamedArgumentsVariants() : null;
$scopeBeforeArgs = $scope;
$argsResult = $this->argumentsHandler->processArgs($nodeScopeResolver, $stmt, $constructorReflection, null, $variants, $namedArgumentsVariants, $normalizedExpr, $scope, $storage, $nodeCallback, $context);
$resolvedParametersAcceptor = $argsResult->getResolvedParametersAcceptor();
$scope = $argsResult->getScope();
$this->argumentsHandler->processDroppedArgs($nodeScopeResolver, $stmt, $expr, $normalizedExpr, $scope, $storage, $context);
$hasYield = $hasYield || $argsResult->hasYield();
$throwPoints = array_merge($throwPoints, $argsResult->getThrowPoints());
$impurePoints = array_merge($impurePoints, $argsResult->getImpurePoints());
if ($deferredConstructorImpureIsDynamic !== 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
$impurePoints = array_merge($impurePoints, $this->getConstructorImpurePoints($constructorReflection, $classReflection, $parametersAcceptor, $expr, $scope, $scopeBeforeArgs, $deferredConstructorImpureIsDynamic));
}
$isAlwaysTerminating = $isAlwaysTerminating || $argsResult->isAlwaysTerminating();
// The new-expression type is derived from $resolvedParametersAcceptor - the
// constructor acceptor processArgs() selected from the arg types gathered on
// the arg-to-arg evolving scope (type-driven, resolves the class's @template
// parameters from constructor args). When null (native-types-promoted, or
// on-demand / synthetic pricing), resolveReturnType() re-selects a structural
// acceptor from the args on the asking scope.
$typeCallback = fn (bool $nativeTypesPromoted): Type => $this->resolveReturnType(
$nativeTypesPromoted ? $beforeScope->doNotTreatPhpDocTypesAsCertain() : $beforeScope,
$expr,
$nativeTypesPromoted ? null : $resolvedParametersAcceptor,
$classResult !== null ? ($nativeTypesPromoted ? $classResult->getNativeType() : $classResult->getType()) : null,
$argsResult,
!$nativeTypesPromoted,
);
$specifyTypesCallback = fn (TypeSpecifierContext $specifyContext, bool $nativeTypesPromoted): SpecifiedTypes => $this->specifyTypes(
$nativeTypesPromoted ? $beforeScope->doNotTreatPhpDocTypesAsCertain() : $beforeScope,
$expr,
$resolvedParametersAcceptor,
$specifyContext,
);
// Store a preliminary result carrying the type/specify callbacks before the
// throw-point return type is computed: getConstructorThrowPoint() and the
// exact-instantiation return type resolution can re-enter on demand (e.g. a
// dynamic static-method return type extension narrowing this very
// instantiation). Without a stored result that narrowing would re-process
// this New_ on demand and recurse. The callbacks are scope-independent, so
// the preliminary result answers those asks correctly; the final result
// finalize() 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: [],
typeCallback: $typeCallback,
specifyTypesCallback: $specifyTypesCallback,
);
$nodeScopeResolver->storeExpressionResult($storage, $expr, $preliminaryResult);
if ($constructorReflection !== null && $parametersAcceptor !== null) {
$className ??= $constructorReflection->getDeclaringClass()->getName();
$constructorThrowPoint = $this->getConstructorThrowPoint($constructorReflection, $parametersAcceptor, $expr, new Name\FullyQualified($className), $expr->getArgs(), $scope, $context);
if ($constructorThrowPoint !== null) {
$throwPoints[] = $constructorThrowPoint;
}
} elseif ($classReflection === null || ($isDynamic && $constructorReflection === null && !$classReflection->isFinal())) {
$throwPoints[] = InternalThrowPoint::createImplicit($scope, $expr);
}
$calleeKnown = $classReflection !== null && !($isDynamic && !$classReflection->isFinal());
if (
($constructorReflection !== null && !$constructorReflection->getDeclaringClass()->isBuiltin() && !$constructorReflection->hasSideEffects()->no())
|| ($constructorReflection === null && !$calleeKnown)
) {
$scope = $scope->invalidateVolatileExpressions();
}
$variableFlow = VariableFlow::sequence(
$classResult !== null ? $classResult->getVariableFlow() : null,
VariableFlowBuilder::arguments($expr, $argsResult, $storage),
VariableFlowBuilder::throws($expr, $throwPoints),
$isAlwaysTerminating ? VariableFlow::exit(VariableFlow::STOP) : null,
);
// the instantiated class - named, or named by a string the type system resolved
if ($expr->class instanceof Name) {
$ownDependencies = Dependencies::create($beforeScope->getFile(), classNames: [$beforeScope->resolveName($expr->class)]);
} elseif ($classResult !== null) {
$ownDependencies = Dependencies::create($beforeScope->getFile(), [$preliminaryResult->getType()], DependencyTypes::classNamesOfClassString($classResult->getType()));
} else {
$ownDependencies = null;
}
$dependencies = Dependencies::merge(
$classResult !== null ? $classResult->getDependencies() : null,
$anonymousClassDependencies,
$argsResult->getDependencies(),
$ownDependencies,
);
return $preliminaryResult->finalize($scope, $hasYield, $isAlwaysTerminating, $throwPoints, $impurePoints, $variableFlow, $dependencies);
}
/**
* @return array{?ExtendedMethodReflection, ?ClassReflection, ?ParametersAcceptor}
*/
private function processConstructorReflection(string $className, New_ $expr): array
{
$constructorReflection = null;
$parametersAcceptor = null;
$classReflection = null;
if ($this->reflectionProvider->hasClass($className)) {
$classReflection = $this->reflectionProvider->getClass($className);
if ($classReflection->hasConstructor()) {
$constructorReflection = $classReflection->getConstructor();
// A structural acceptor (names/positions/variadic) drives argument
// normalization and the throw point - generics are resolved
// type-driven by processArgs() into $resolvedParametersAcceptor.
$parametersAcceptor = ParametersAcceptorSelector::combineVariantsForNormalization($expr->getArgs(), $constructorReflection->getVariants(), $constructorReflection->getNamedArgumentsVariants());
}
}
return [$constructorReflection, $classReflection, $parametersAcceptor];
}
/**
* @return ImpurePoint[]
*/
private function getConstructorImpurePoints(?ExtendedMethodReflection $constructorReflection, ?ClassReflection $classReflection, ?ParametersAcceptor $parametersAcceptor, New_ $expr, MutatingScope $scope, MutatingScope $scopeBeforeArgs, bool $isDynamic): array
{
if ($constructorReflection !== null) {
if ($parametersAcceptor === null) {
throw new ShouldNotHappenException();
}
if ($constructorReflection->hasSideEffects()->no()) {
return [];
}
$certain = $constructorReflection->isPure()->no();
// A constructor can carry both flags at once, so combine the verdicts
// the same way SimpleImpurePoint::createFromVariant() does for calls:
// Yes = pure, No = impure, Maybe = possibly impure.
$verdict = SimpleImpurePoint::resolvePureUnlessCallableIsImpureVerdict($parametersAcceptor, $scope, $expr->getArgs());
$passedVerdict = SimpleImpurePoint::resolvePureUnlessParameterPassedVerdict($parametersAcceptor, $expr->getArgs());
if ($passedVerdict !== null) {
$verdict = $verdict === null ? $passedVerdict : $verdict->and($passedVerdict);
}
if ($verdict !== null && $verdict->yes()) {
return [];
}
if ($verdict !== null && $verdict->no()) {
$certain = true;
}
return [
new ImpurePoint(
$scopeBeforeArgs,
$expr,
'new',
sprintf('instantiation of class %s', $constructorReflection->getDeclaringClass()->getDisplayName()),
$certain,
),
];
}
if ($classReflection === null) {
return [
new ImpurePoint(
$scopeBeforeArgs,
$expr,
'new',
'instantiation of unknown class',
false,
),
];
}
if ($isDynamic && !$classReflection->isFinal()) {
return [
new ImpurePoint(
$scopeBeforeArgs,
$expr,
'new',
sprintf('instantiation of class %s', $classReflection->getDisplayName()),
false,
),
];
}
return [];
}
/**
* @param list<Node\Arg> $args
*/
private function getConstructorThrowPoint(MethodReflection $constructorReflection, ParametersAcceptor $parametersAcceptor, New_ $new, Name $className, array $args, MutatingScope $scope, ExpressionContext $context): ?InternalThrowPoint
{
$methodCall = new StaticCall($className, $constructorReflection->getName(), $args);
$normalizedMethodCall = ArgumentsNormalizer::reorderStaticCallArguments($parametersAcceptor, $methodCall);
if ($normalizedMethodCall !== null) {
foreach ($this->dynamicStaticMethodThrowTypeExtensions->getAll() as $extension) {
if (!$extension->isStaticMethodSupported($constructorReflection)) {
continue;
}
$throwType = $extension->getThrowTypeFromStaticMethodCall($constructorReflection, $normalizedMethodCall, $scope);
if ($throwType === null || $throwType->isVoid()->yes()) {
return null;
}
return InternalThrowPoint::createExplicit($scope, $throwType, $new, false);
}
}
if ($constructorReflection->getThrowType() !== null) {
$throwType = ConditionalTypeResolver::resolveForCall($constructorReflection->getThrowType(), $parametersAcceptor, $args, $scope);
if (!$throwType->isVoid()->yes()) {
return InternalThrowPoint::createExplicit($scope, $throwType, $new, true);
}
} elseif ($this->implicitThrows) {
if (!$context->isInThrow() || !$constructorReflection->getDeclaringClass()->is(Throwable::class)) {
return InternalThrowPoint::createImplicit($scope, $new);
}
}
return null;
}
/**
* The stored new-expression type is derived from $preResolvedAcceptor - the
* constructor acceptor processArgs() selected from the arg types gathered on
* the arg-to-arg evolving scope (resolves the class's @template parameters
* from constructor args). Null falls back to re-selecting a structural acceptor
* from the args on the asking scope (on-demand / synthetic pricing).
*
* @param New_ $expr
*/
private function resolveReturnType(MutatingScope $scope, Expr $expr, ?ParametersAcceptor $preResolvedAcceptor, ?Type $classExprType, ?ArgsResult $argsResult = null, bool $allowUnresolved = true): Type
{
if ($expr->class instanceof Name) {
return $this->exactInstantiation($scope, $expr, $expr->class, $preResolvedAcceptor, $argsResult, $allowUnresolved);
}
if ($expr->class instanceof Node\Stmt\Class_) {
$anonymousClassReflection = $this->reflectionProvider->getAnonymousClassReflection($expr->class, $scope);
return new ObjectType($anonymousClassReflection->getName());
}
// the class expression was walked by processExpr; its result's type of
// the asked flavour is passed in by the typeCallback
if ($classExprType === null) {
throw new ShouldNotHappenException();
}
return $classExprType->getObjectTypeOrClassStringObjectType();
}
/**
* @param bool $allowUnresolved false for the native flavour, which never carries UnresolvedTemplateArgumentType
*/
private function exactInstantiation(MutatingScope $scope, New_ $node, Name $className, ?ParametersAcceptor $preResolvedAcceptor, ?ArgsResult $argsResult = null, bool $allowUnresolved = true): Type
{
$resolvedClassName = $scope->resolveName($className);
$isStatic = false;
$lowercasedClassName = $className->toLowerString();
if ($lowercasedClassName === 'static') {
$isStatic = true;
}
if (!$this->reflectionProvider->hasClass($resolvedClassName)) {
if ($lowercasedClassName === 'static') {
if (!$scope->isInClass()) {
return new ErrorType();
}
return new StaticType($scope->getClassReflection());
}
if ($lowercasedClassName === 'parent') {
return new NonexistentParentClassType();
}
return new ObjectType($resolvedClassName);
}
$classReflection = $this->reflectionProvider->getClass($resolvedClassName);
$nonFinalClassReflection = $classReflection;
if (!$isStatic) {
$classReflection = $classReflection->asFinal();
}
if ($classReflection->hasConstructor()) {
$constructorMethod = $classReflection->getConstructor();
} else {
$constructorMethod = new DummyConstructorReflection($classReflection);
}
if ($constructorMethod->getName() === '') {
throw new ShouldNotHappenException();
}
$resolvedTypes = [];
$methodCall = new Expr\StaticCall(
new Name($resolvedClassName),
new Node\Identifier($constructorMethod->getName()),
$node->getArgs(),
);
$parametersAcceptor = $preResolvedAcceptor ?? ParametersAcceptorSelector::combineVariantsForNormalization(
$methodCall->getArgs(),
$constructorMethod->getVariants(),
$constructorMethod->getNamedArgumentsVariants(),
);
$normalizedMethodCall = ArgumentsNormalizer::reorderStaticCallArguments($parametersAcceptor, $methodCall);
if ($normalizedMethodCall !== null) {
// runs lazily in the typeCallback - prime the storage with the argument
// results so the extensions' Scope::getType() asks about the arguments
// answer from them instead of re-walking on demand
$popPrimedStorage = $this->storagePrimer->pushPrimedStorage($scope, $argsResult);
try {
foreach ($this->dynamicReturnTypeExtensionRegistry->getDynamicStaticMethodReturnTypeExtensionsForClass($classReflection->getName()) as $dynamicStaticMethodReturnTypeExtension) {
if (!$dynamicStaticMethodReturnTypeExtension->isStaticMethodSupported($constructorMethod)) {
continue;
}
$resolvedType = $dynamicStaticMethodReturnTypeExtension->getTypeFromStaticMethodCall(
$constructorMethod,
$normalizedMethodCall,
$scope,
);
if ($resolvedType === null) {
continue;
}
$resolvedTypes[] = $resolvedType;
}
} finally {
$popPrimedStorage();
}
}
if (count($resolvedTypes) > 0) {
return TypeCombinator::union(...$resolvedTypes);
}
// A constructor makes `new` never-returning only when its own return type
// is (or can resolve to) explicit never; the dynamic static-method return
// type extensions already ran above, so only the base return type is left
// to check. Pricing the synthetic StaticCall on demand for this is
// expensive and pointless for the overwhelmingly common plain
// void/object constructor - skip it unless the return type could be never.
$constructorReturnType = $parametersAcceptor->getReturnType();
if ($constructorReturnType instanceof NeverType || $constructorReturnType->hasTemplateOrLateResolvableType()) {
// $methodCall is a synthetic StaticCall the handler built; price it
// through the sanctioned on-demand walk (the constructor's own
// never-returning conditional return type).
$methodResult = $this->container->getByType(NodeScopeResolver::class)->processSyntheticOnDemand($methodCall, $scope)->getTypeOnScope($scope, false);
if ($methodResult instanceof NeverType && $methodResult->isExplicit()) {
return $methodResult;
}
}
$objectType = $isStatic ? new StaticType($classReflection) : new ObjectType($resolvedClassName, classReflection: $classReflection);
if (!$classReflection->isGeneric()) {
return $objectType;
}
$frame = $allowUnresolved ? $scope->getCurrentTemplateArgumentFrame() : null;
// the class's arguments when the constructor says nothing about them
$unresolvedArguments = function () use ($classReflection, $node, $frame, $allowUnresolved, $isStatic, $resolvedClassName): Type {
$types = $this->unresolvedArgumentList($classReflection, $node, $frame, $allowUnresolved);
if ($isStatic) {
return new GenericStaticType($classReflection, $types, null, []);
}
return new GenericObjectType($resolvedClassName, $types, classReflection: $classReflection->withTypes($types)->asFinal());
};
if (!$allowUnresolved) {
// Native types use the bounds or defaults, without PHPDoc inference.
return $unresolvedArguments();
}
$assignedToProperty = $node->getAttribute(NewAssignedToPropertyVisitor::ATTRIBUTE_NAME);
if ($assignedToProperty !== null) {
$constructorVariants = $constructorMethod->getVariants();
if (count($constructorVariants) === 1) {
// When the arguments resolve none of the class template types,
// the declared type of the assigned property is the only source
// of the type arguments - whether the constructor never mentions
// them or the passed arguments (T|null receiving null) say nothing.
$resolvedTemplateTypeMap = $parametersAcceptor->getResolvedTemplateTypeMap();
$hasResolvedClassTemplateType = false;
foreach (array_keys($classReflection->getTemplateTypeMap()->getTypes()) as $classTemplateTypeName) {
$resolvedType = $resolvedTemplateTypeMap->getType($classTemplateTypeName);
if ($resolvedType === null || $resolvedType instanceof ErrorType) {
continue;
}
$hasResolvedClassTemplateType = true;
break;
}
if (!$hasResolvedClassTemplateType) {
$foundProperty = $this->propertyReflectionFinder->findPropertyReflectionFromNode($assignedToProperty, $scope);
if ($foundProperty !== null) {
$nonFinalObjectType = $isStatic ? new StaticType($nonFinalClassReflection) : new ObjectType($resolvedClassName, classReflection: $nonFinalClassReflection);
$propertyType = TypeCombinator::intersect($foundProperty->getWritableType(), $nonFinalObjectType);
if (!$propertyType instanceof NeverType) {
return $propertyType;
}
}
}
}
}
if ($constructorMethod instanceof DummyConstructorReflection) {
return $unresolvedArguments();
}
if ($constructorMethod->getDeclaringClass()->getName() !== $classReflection->getName()) {
if (!$constructorMethod->getDeclaringClass()->isGeneric()) {
return $unresolvedArguments();
}
$newType = new GenericObjectType($resolvedClassName, $classReflection->typeMapToList($classReflection->getTemplateTypeMap()));
$ancestorType = $newType->getAncestorWithClassName($constructorMethod->getDeclaringClass()->getName());
if ($ancestorType === null) {
return $unresolvedArguments();
}
$ancestorClassReflections = $ancestorType->getObjectClassReflections();
if (count($ancestorClassReflections) !== 1) {
return $unresolvedArguments();
}
$newParentNode = new New_(new Name($constructorMethod->getDeclaringClass()->getName()), $node->args, [TemplateArgumentFrame::SYNTHETIC_SITE_ATTRIBUTE => true]);
// the synthetic walk is load-bearing: it re-resolves the parent
// constructor's template types from the arguments (processArgs against
// the parent's signature), which a direct exactInstantiation() recursion
// with the child's acceptor cannot do
$newParentType = $this->container->getByType(NodeScopeResolver::class)->processSyntheticOnDemand($newParentNode, $scope)->getTypeOnScope($scope, false);
$newParentTypeClassReflections = $newParentType->getObjectClassReflections();
if (count($newParentTypeClassReflections) !== 1) {
return $unresolvedArguments();
}
$newParentTypeClassReflection = $newParentTypeClassReflections[0];
$ancestorClassReflection = $ancestorClassReflections[0];
$ancestorMapping = [];
foreach ($ancestorClassReflection->getActiveTemplateTypeMap()->getTypes() as $typeName => $templateType) {
if (!$templateType instanceof TemplateType) {
continue;
}
$ancestorMapping[$typeName] = $templateType;
}
$resolvedTypeMap = [];
foreach ($newParentTypeClassReflection->getActiveTemplateTypeMap()->getTypes() as $typeName => $type) {
if (!array_key_exists($typeName, $ancestorMapping)) {
continue;
}
$ancestorType = $ancestorMapping[$typeName];
if ($type instanceof UnresolvedTemplateArgumentType) {
// inferred by the parent constructor under the synthetic node:
// this node is the site, the child's template the argument
$type = $this->rekeyParentTemplateArgument($type, $node, $ancestorType, $frame, $allowUnresolved);
}
if (!$ancestorType->getBound()->isSuperTypeOf($type)->yes()) {
continue;
}
if (!array_key_exists($ancestorType->getName(), $resolvedTypeMap)) {
$resolvedTypeMap[$ancestorType->getName()] = $type;
continue;
}
$resolvedTypeMap[$ancestorType->getName()] = TypeCombinator::union($resolvedTypeMap[$ancestorType->getName()], $type);
}
if ($isStatic) {
return new GenericStaticType(
$classReflection,
$classReflection->typeMapToList(new TemplateTypeMap($resolvedTypeMap)),
null,
[],
);
}
$types = $classReflection->typeMapToList(new TemplateTypeMap($resolvedTypeMap));
return new GenericObjectType(
$resolvedClassName,
$types,
classReflection: $classReflection->withTypes($types)->asFinal(),
);
}
$resolvedTemplateTypeMap = $parametersAcceptor->getResolvedTemplateTypeMap();
$types = $classReflection->typeMapToList($classReflection->getTemplateTypeMap());
$newGenericType = new GenericObjectType(
$resolvedClassName,
$types,
classReflection: $classReflection->withTypes($types)->asFinal(),
);
if ($isStatic) {
$newGenericType = new GenericStaticType(
$classReflection,
$types,
null,
[],
);
}
if (!$newGenericType->hasTemplateOrLateResolvableType()) {
return $newGenericType;
}
return TypeTraverser::map($newGenericType, new GenericTypeTemplateTraverser($resolvedTemplateTypeMap, $node, $frame, $allowUnresolved));
}
/**
* The class's template arguments when the constructor says nothing about
* them: unresolved markers during a body's observation pass, the frame's
* resolutions (the defaults or bounds when unconstrained) during its second
* pass, the bounds outside any frame.
*
* @return list<Type>
*/
private function unresolvedArgumentList(ClassReflection $classReflection, New_ $site, ?TemplateArgumentFrame $frame, bool $allowUnresolved): array
{
if ($frame === null) {
return $classReflection->typeMapToList($classReflection->getTemplateTypeMap()->resolveToBounds());
}
// a synthetic site (the parent constructor's `new`) always hands out
// markers - the real site re-keys and resolves them
$synthetic = $site->getAttribute(TemplateArgumentFrame::SYNTHETIC_SITE_ATTRIBUTE) === true;
return $classReflection->typeMapToList($classReflection->getTemplateTypeMap()->map(static function (string $name, Type $type) use ($site, $frame, $allowUnresolved, $synthetic): Type {
if (!$type instanceof TemplateType) {
return $type;
}
if ($synthetic) {
return new UnresolvedTemplateArgumentType($site, $type, null);
}
if ($allowUnresolved && $frame->isObserving()) {
// a send in a body enclosing this one decided the site
return $frame->resolveSentFromEnclosingBody($site, $type->getName()) ?? new UnresolvedTemplateArgumentType($site, $type, null);
}
return $frame->resolveOrUnconstrained($site, $type);
}));
}
private function rekeyParentTemplateArgument(UnresolvedTemplateArgumentType $type, New_ $site, TemplateType $template, ?TemplateArgumentFrame $frame, bool $allowUnresolved): Type
{
if ($frame === null) {
return $type->getInitialType() ?? $template->getDefault() ?? $template->getBound();
}
if ($allowUnresolved && $frame->isObserving()) {
// a send in a body enclosing this one decided the site
return $frame->resolveSentFromEnclosingBody($site, $template->getName()) ?? $type->withSite($site, $template);
}
return $frame->resolve($site, $template->getName()) ?? $type->getInitialType() ?? $frame->resolveOrUnconstrained($site, $template);
}
/**
* Ported inside-out from the old TypeResolvingExprHandler::specifyTypes(): the
* constructor's @phpstan-assert narrowing is 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::specifyDefaultTypes(), which
* would re-enter this expression through TypeSpecifier::create().
*
* @param New_ $expr
*/
private function specifyTypes(MutatingScope $scope, Expr $expr, ?ParametersAcceptor $resolvedParametersAcceptor, TypeSpecifierContext $context): SpecifiedTypes
{
if (
!$expr->class instanceof Name
|| !$this->reflectionProvider->hasClass($expr->class->toString())
) {
return $this->defaultNarrowingHelper->specifyDefaultTypes($expr, $context);
}
$classReflection = $this->reflectionProvider->getClass($expr->class->toString());
if ($classReflection->hasConstructor()) {
$methodReflection = $classReflection->getConstructor();
$asserts = $methodReflection->getAsserts();
if ($asserts->getAll() !== [] && $resolvedParametersAcceptor !== null) {
$asserts = $asserts->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) {
return $specifiedTypes;
}
}
}
// A known class without (applicable) constructor asserts contributes no
// narrowing entry, mirroring the old handler's empty return for this path
// (a `new X()` is always a truthy object, so the default truthy/falsey
// removal that path 1 emits would be a no-op here anyway).
return (new SpecifiedTypes([], []))->setRootExpr($expr);
}
}