forked from rectorphp/rector-src
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNodeTypeResolver.php
More file actions
654 lines (534 loc) · 20.5 KB
/
NodeTypeResolver.php
File metadata and controls
654 lines (534 loc) · 20.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
<?php
declare(strict_types=1);
namespace Rector\NodeTypeResolver;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\BinaryOp\Coalesce;
use PhpParser\Node\Expr\ClassConstFetch;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\NullsafeMethodCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Expr\Ternary;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\NullableType;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\ClassConst;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\UnionType as NodeUnionType;
use PHPStan\Analyser\Scope;
use PHPStan\Broker\ClassNotFoundException;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\Native\NativeFunctionReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Type\ArrayType;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\ErrorType;
use PHPStan\Type\MixedType;
use PHPStan\Type\NeverType;
use PHPStan\Type\NullType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\ObjectWithoutClassType;
use PHPStan\Type\ThisType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeWithClassName;
use PHPStan\Type\UnionType;
use Rector\Configuration\RenamedClassesDataCollector;
use Rector\Exception\ShouldNotHappenException;
use Rector\NodeAnalyzer\ClassAnalyzer;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\NodeTypeResolver\Contract\NodeTypeResolverAwareInterface;
use Rector\NodeTypeResolver\Contract\NodeTypeResolverInterface;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\NodeTypeResolver\NodeTypeCorrector\AccessoryNonEmptyArrayTypeCorrector;
use Rector\NodeTypeResolver\NodeTypeCorrector\AccessoryNonEmptyStringTypeCorrector;
use Rector\NodeTypeResolver\NodeTypeCorrector\GenericClassStringTypeCorrector;
use Rector\NodeTypeResolver\PHPStan\ObjectWithoutClassTypeWithParentTypes;
use Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType;
use Rector\StaticTypeMapper\ValueObject\Type\ShortenedObjectType;
use Rector\TypeDeclaration\PHPStan\ObjectTypeSpecifier;
final class NodeTypeResolver
{
/**
* @var string
*/
private const ERROR_MESSAGE = '%s itself does not have any type. Check the %s node instead';
/**
* @var array<class-string<Node>, NodeTypeResolverInterface>
*/
private array $nodeTypeResolvers = [];
/**
* @param NodeTypeResolverInterface[] $nodeTypeResolvers
*/
public function __construct(
private readonly ObjectTypeSpecifier $objectTypeSpecifier,
private readonly ClassAnalyzer $classAnalyzer,
private readonly GenericClassStringTypeCorrector $genericClassStringTypeCorrector,
private readonly ReflectionProvider $reflectionProvider,
private readonly AccessoryNonEmptyStringTypeCorrector $accessoryNonEmptyStringTypeCorrector,
private readonly AccessoryNonEmptyArrayTypeCorrector $accessoryNonEmptyArrayTypeCorrector,
private readonly RenamedClassesDataCollector $renamedClassesDataCollector,
private readonly NodeNameResolver $nodeNameResolver,
iterable $nodeTypeResolvers
) {
foreach ($nodeTypeResolvers as $nodeTypeResolver) {
if ($nodeTypeResolver instanceof NodeTypeResolverAwareInterface) {
$nodeTypeResolver->autowire($this);
}
foreach ($nodeTypeResolver->getNodeClasses() as $nodeClass) {
$this->nodeTypeResolvers[$nodeClass] = $nodeTypeResolver;
}
}
}
/**
* @api doctrine symfony
* @param ObjectType[] $requiredTypes
*/
public function isObjectTypes(Node $node, array $requiredTypes): bool
{
foreach ($requiredTypes as $requiredType) {
if ($this->isObjectType($node, $requiredType)) {
return true;
}
}
return false;
}
public function isObjectType(Node $node, ObjectType $requiredObjectType): bool
{
if ($node instanceof ClassConstFetch) {
return false;
}
// warn about invalid use of this method
if ($node instanceof ClassMethod || $node instanceof ClassConst) {
throw new ShouldNotHappenException(sprintf(self::ERROR_MESSAGE, $node::class, ClassLike::class));
}
$resolvedType = $this->getType($node);
// cover call $this on trait
if ($resolvedType instanceof ErrorType && ($node instanceof Variable && $this->nodeNameResolver->isName(
$node,
'this'
))) {
$scope = $node->getAttribute(AttributeKey::SCOPE);
if (! $scope instanceof Scope) {
return false;
}
$classReflection = $scope->getClassReflection();
if (! $classReflection instanceof ClassReflection) {
return false;
}
if ($classReflection->isTrait()) {
$resolvedType = new ObjectType($classReflection->getName());
}
}
if ($resolvedType instanceof MixedType) {
return false;
}
if ($resolvedType instanceof ThisType) {
$resolvedType = $resolvedType->getStaticObjectType();
}
if ($resolvedType instanceof ObjectType) {
try {
return $this->resolveObjectType($resolvedType, $requiredObjectType);
} catch (ClassNotFoundException) {
// in some type checks, the provided type in rector.php configuration does not have to exists
return false;
}
}
if ($resolvedType instanceof ObjectWithoutClassType) {
return $this->isMatchObjectWithoutClassType($resolvedType, $requiredObjectType);
}
return $this->isMatchingUnionType($resolvedType, $requiredObjectType);
}
public function getType(Node $node): Type
{
if ($node instanceof NullableType) {
$type = $this->getType($node->type);
if (! $type instanceof MixedType) {
return new UnionType([$type, new NullType()]);
}
}
if ($node instanceof Ternary) {
$ternaryType = $this->resolveTernaryType($node);
if (! $ternaryType instanceof MixedType) {
return $ternaryType;
}
}
if ($node instanceof Coalesce) {
$first = $this->getType($node->left);
$second = $this->getType($node->right);
if ($this->isUnionTypeable($first, $second)) {
return new UnionType([$first, $second]);
}
}
$type = $this->resolveByNodeTypeResolvers($node);
if ($type instanceof Type) {
$type = $this->correctType($type);
if ($type instanceof ObjectType) {
$scope = $node->getAttribute(AttributeKey::SCOPE);
$type = $this->objectTypeSpecifier->narrowToFullyQualifiedOrAliasedObjectType(
$node,
$type,
$scope,
true
);
}
return $type;
}
$scope = $node->getAttribute(AttributeKey::SCOPE);
if (! $scope instanceof Scope) {
return new MixedType();
}
if ($node instanceof NodeUnionType) {
$types = [];
foreach ($node->types as $type) {
$types[] = $this->getType($type);
}
return new UnionType($types);
}
if (! $node instanceof Expr) {
return new MixedType();
}
$type = $this->correctType($scope->getType($node));
// hot fix for phpstan not resolving chain method calls
if (! $node instanceof MethodCall) {
return $type;
}
if (! $type instanceof MixedType) {
return $type;
}
return $this->getType($node->var);
}
/**
* e.g. string|null, ObjectNull|null
*/
public function isNullableType(Node $node): bool
{
$nodeType = $this->getType($node);
return TypeCombinator::containsNull($nodeType);
}
public function getNativeType(Expr $expr): Type
{
$scope = $expr->getAttribute(AttributeKey::SCOPE);
if (! $scope instanceof Scope) {
return new MixedType();
}
// cover direct New_ class
if ($this->classAnalyzer->isAnonymousClass($expr)) {
$type = $this->nodeTypeResolvers[New_::class]->resolve($expr);
if ($type instanceof ObjectWithoutClassType) {
return $type;
}
}
$type = $this->resolveNativeTypeWithBuiltinMethodCallFallback($expr, $scope);
if ($expr instanceof ArrayDimFetch) {
$type = $this->resolveArrayDimFetchType($expr, $scope, $type);
}
if (! $type instanceof UnionType) {
if ($this->isAnonymousObjectType($type)) {
return new ObjectWithoutClassType();
}
return $this->correctType($type);
}
return $this->resolveNativeUnionType($type);
}
public function isNumberType(Expr $expr): bool
{
$nodeType = $this->getNativeType($expr);
if ($nodeType->isInteger()->yes()) {
return true;
}
return $nodeType->isFloat()
->yes();
}
/**
* @template TType as Type
*
* @param class-string<TType> $desiredType
* @return TType|null
*/
public function matchNullableTypeOfSpecificType(Expr $expr, string $desiredType): ?Type
{
$nodeType = $this->getType($expr);
if (! $nodeType instanceof UnionType) {
return null;
}
$bareType = TypeCombinator::removeNull($nodeType);
if (! $bareType instanceof $desiredType) {
return null;
}
return $bareType;
}
public function getFullyQualifiedClassName(TypeWithClassName $typeWithClassName): string
{
if ($typeWithClassName instanceof ShortenedObjectType) {
return $typeWithClassName->getFullyQualifiedName();
}
if ($typeWithClassName instanceof AliasedObjectType) {
return $typeWithClassName->getFullyQualifiedName();
}
return $typeWithClassName->getClassName();
}
public function isMethodStaticCallOrClassMethodObjectType(Node $node, ObjectType $objectType): bool
{
if ($node instanceof MethodCall || $node instanceof NullsafeMethodCall) {
if ($this->isEnumTypeMatch($node, $objectType)) {
return true;
}
// method call is variable return
return $this->isObjectType($node->var, $objectType);
}
if ($node instanceof StaticCall) {
return $this->isObjectType($node->class, $objectType);
}
$scope = $node->getAttribute(AttributeKey::SCOPE);
if (! $scope instanceof Scope) {
return false;
}
$classReflection = $scope->getClassReflection();
if (! $classReflection instanceof ClassReflection) {
return false;
}
if ($classReflection->getName() === $objectType->getClassName()) {
return true;
}
if ($classReflection->is($objectType->getClassName())) {
return true;
}
return $classReflection->hasTraitUse($objectType->getClassName());
}
private function correctType(Type $type): Type
{
$type = $this->accessoryNonEmptyStringTypeCorrector->correct($type);
$type = $this->genericClassStringTypeCorrector->correct($type);
return $this->accessoryNonEmptyArrayTypeCorrector->correct($type);
}
/**
* Allow pull type from
*
* - native function
* - always defined by assignment
*
* eg:
*
* $parts = parse_url($url);
* if (!empty($parts['host'])) { }
*
* or
*
* $parts = ['host' => 'foo'];
* if (!empty($parts['host'])) { }
*/
private function resolveArrayDimFetchType(
ArrayDimFetch $arrayDimFetch,
Scope $scope,
Type $originalNativeType
): Type {
$nativeVariableType = $scope->getNativeType($arrayDimFetch->var);
if ($nativeVariableType instanceof MixedType || ($nativeVariableType instanceof ArrayType && $nativeVariableType->getIterableValueType() instanceof MixedType)) {
return $originalNativeType;
}
$type = $scope->getType($arrayDimFetch);
if (! $arrayDimFetch->dim instanceof String_) {
return $type;
}
$variableType = $scope->getType($arrayDimFetch->var);
if (! $variableType instanceof ConstantArrayType) {
return $type;
}
$optionalKeys = $variableType->getOptionalKeys();
foreach ($variableType->getKeyTypes() as $key => $keyType) {
if (! $keyType instanceof ConstantStringType) {
continue;
}
if ($keyType->getValue() !== $arrayDimFetch->dim->value) {
continue;
}
if (! in_array($key, $optionalKeys, true)) {
continue;
}
return $originalNativeType;
}
return $type;
}
private function resolveNativeUnionType(UnionType $unionType): Type
{
$hasChanged = false;
$types = $unionType->getTypes();
foreach ($types as $key => $childType) {
if ($this->isAnonymousObjectType($childType)) {
$types[$key] = new ObjectWithoutClassType();
$hasChanged = true;
}
}
if ($hasChanged) {
return new UnionType($types);
}
return $unionType;
}
private function isMatchObjectWithoutClassType(
ObjectWithoutClassType $objectWithoutClassType,
ObjectType $requiredObjectType
): bool {
if ($objectWithoutClassType instanceof ObjectWithoutClassTypeWithParentTypes) {
foreach ($objectWithoutClassType->getParentTypes() as $typeWithClassName) {
if ($requiredObjectType->isSuperTypeOf($typeWithClassName)->yes()) {
return true;
}
}
}
return false;
}
private function isAnonymousObjectType(Type $type): bool
{
if (! $type instanceof ObjectType) {
return false;
}
$classReflection = $type->getClassReflection();
if (! $classReflection instanceof ClassReflection) {
return false;
}
return $classReflection->isAnonymous();
}
private function isUnionTypeable(Type $first, Type $second): bool
{
return ! $first instanceof UnionType && ! $second instanceof UnionType && ! $second->isNull()
->yes();
}
private function isMatchingUnionType(Type $resolvedType, ObjectType $requiredObjectType): bool
{
$type = TypeCombinator::removeNull($resolvedType);
if ($type instanceof NeverType) {
return false;
}
// for falsy nullables
$type = TypeCombinator::remove($type, new ConstantBooleanType(false));
if ($type instanceof ObjectWithoutClassType) {
return $this->isMatchObjectWithoutClassType($type, $requiredObjectType);
}
return $requiredObjectType->isSuperTypeOf($type)
->yes();
}
private function resolveByNodeTypeResolvers(Node $node): ?Type
{
foreach ($this->nodeTypeResolvers as $nodeClass => $nodeTypeResolver) {
if (! $node instanceof $nodeClass) {
continue;
}
return $nodeTypeResolver->resolve($node);
}
return null;
}
private function isObjectTypeOfObjectType(ObjectType $resolvedObjectType, ObjectType $requiredObjectType): bool
{
$requiredClassName = $requiredObjectType->getClassName();
$resolvedClassName = $resolvedObjectType->getClassName();
if ($resolvedClassName === $requiredClassName) {
return true;
}
if ($resolvedObjectType->isInstanceOf($requiredClassName)->yes()) {
return true;
}
if (! $this->reflectionProvider->hasClass($requiredClassName)) {
return false;
}
$requiredClassReflection = $this->reflectionProvider->getClass($requiredClassName);
if ($requiredClassReflection->isTrait()) {
if (! $this->reflectionProvider->hasClass($resolvedClassName)) {
return false;
}
$resolvedClassReflection = $this->reflectionProvider->getClass($resolvedClassName);
foreach ($resolvedClassReflection->getAncestors() as $ancestorClassReflection) {
if ($ancestorClassReflection->hasTraitUse($requiredClassName)) {
return true;
}
}
}
return false;
}
private function resolveObjectType(ObjectType $resolvedObjectType, ObjectType $requiredObjectType): bool
{
$renamedObjectType = $this->renamedClassesDataCollector->matchClassName($resolvedObjectType);
if (! $renamedObjectType instanceof ObjectType) {
return $this->isObjectTypeOfObjectType($resolvedObjectType, $requiredObjectType);
}
if (! $this->isObjectTypeOfObjectType($renamedObjectType, $requiredObjectType)) {
return $this->isObjectTypeOfObjectType($resolvedObjectType, $requiredObjectType);
}
return true;
}
private function resolveTernaryType(Ternary $ternary): MixedType|UnionType
{
if ($ternary->if instanceof Expr) {
$first = $this->getType($ternary->if);
$second = $this->getType($ternary->else);
if ($this->isUnionTypeable($first, $second)) {
return new UnionType([$first, $second]);
}
}
$condType = $this->getType($ternary->cond);
if ($this->isNullableType($ternary->cond) && $condType instanceof UnionType) {
$first = $condType->getTypes()[0];
$second = $this->getType($ternary->else);
if ($this->isUnionTypeable($first, $second)) {
return new UnionType([$first, $second]);
}
}
return new MixedType();
}
/**
* Method calls on native PHP classes report mixed,
* even on strict known type; this fallbacks to getType() that provides correct type
*/
private function resolveNativeTypeWithBuiltinMethodCallFallback(Expr $expr, Scope $scope): Type
{
if ($expr instanceof MethodCall) {
$callerType = $scope->getType($expr->var);
if ($callerType instanceof ObjectType && $callerType->getClassReflection() instanceof ClassReflection && $callerType->getClassReflection()->isBuiltin()) {
return $scope->getType($expr);
}
}
if ($expr instanceof FuncCall) {
if (! $expr->name instanceof Name) {
return $scope->getNativeType($expr);
}
$functionName = new Name((string) $this->nodeNameResolver->getName($expr));
if (! $this->reflectionProvider->hasFunction($functionName, null)) {
return $scope->getNativeType($expr);
}
$functionReflection = $this->reflectionProvider->getFunction($functionName, null);
if (! $functionReflection instanceof NativeFunctionReflection) {
return $scope->getNativeType($expr);
}
return $scope->getType($expr);
}
return $scope->getNativeType($expr);
}
private function isEnumTypeMatch(MethodCall|NullsafeMethodCall $call, ObjectType $objectType): bool
{
if (! $call->var instanceof ClassConstFetch) {
return false;
}
// possibly enum
$classConstFetch = $call->var;
if (! $classConstFetch->class instanceof FullyQualified) {
return false;
}
$className = $classConstFetch->class->toString();
if (! $this->reflectionProvider->hasClass($className)) {
return false;
}
$classReflection = $this->reflectionProvider->getClass($className);
if (! $classReflection->isEnum()) {
return false;
}
return $classReflection->getName() === $objectType->getClassName();
}
}