-
-
Notifications
You must be signed in to change notification settings - Fork 336
/
PHPStanNodeScopeResolver.php
436 lines (372 loc) · 16.3 KB
/
PHPStanNodeScopeResolver.php
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
<?php
declare(strict_types=1);
namespace Rector\NodeTypeResolver\PHPStan\Scope;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\AssignOp;
use PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\Ternary;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Enum_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Finally_;
use PhpParser\Node\Stmt\Foreach_;
use PhpParser\Node\Stmt\Interface_;
use PhpParser\Node\Stmt\Property;
use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\Stmt\Switch_;
use PhpParser\Node\Stmt\Trait_;
use PhpParser\Node\Stmt\TryCatch;
use PhpParser\NodeTraverser;
use PHPStan\AnalysedCodeException;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\Analyser\ScopeContext;
use PHPStan\BetterReflection\Reflector\Reflector;
use PHPStan\BetterReflection\SourceLocator\Type\AggregateSourceLocator;
use PHPStan\BetterReflection\SourceLocator\Type\SourceLocator;
use PHPStan\Node\UnreachableStatementNode;
use PHPStan\Reflection\BetterReflection\Reflector\MemoizingReflector;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Type\ObjectType;
use PHPStan\Type\TypeCombinator;
use Rector\Caching\Detector\ChangedFilesDetector;
use Rector\Caching\FileSystem\DependencyResolver;
use Rector\Core\Exception\ShouldNotHappenException;
use Rector\Core\StaticReflection\SourceLocator\ParentAttributeSourceLocator;
use Rector\Core\StaticReflection\SourceLocator\RenamedClassesSourceLocator;
use Rector\Core\Util\StringUtils;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\NodeTypeResolver\PHPStan\Scope\NodeVisitor\RemoveDeepChainMethodCallNodeVisitor;
use Symplify\PackageBuilder\Reflection\PrivatesAccessor;
use Symplify\SmartFileSystem\SmartFileInfo;
use Webmozart\Assert\Assert;
/**
* @inspired by https://github.com/silverstripe/silverstripe-upgrader/blob/532182b23e854d02e0b27e68ebc394f436de0682/src/UpgradeRule/PHP/Visitor/PHPStanScopeVisitor.php
* - https://github.com/silverstripe/silverstripe-upgrader/pull/57/commits/e5c7cfa166ad940d9d4ff69537d9f7608e992359#diff-5e0807bb3dc03d6a8d8b6ad049abd774
*/
final class PHPStanNodeScopeResolver
{
/**
* @var string
* @see https://regex101.com/r/aXsCkK/1
*/
private const ANONYMOUS_CLASS_START_REGEX = '#^AnonymousClass(\w+)#';
/**
* @var string
*/
private const CONTEXT = 'context';
public function __construct(
private readonly ChangedFilesDetector $changedFilesDetector,
private readonly DependencyResolver $dependencyResolver,
private readonly NodeScopeResolver $nodeScopeResolver,
private readonly ReflectionProvider $reflectionProvider,
private readonly RemoveDeepChainMethodCallNodeVisitor $removeDeepChainMethodCallNodeVisitor,
private readonly ScopeFactory $scopeFactory,
private readonly PrivatesAccessor $privatesAccessor,
private readonly RenamedClassesSourceLocator $renamedClassesSourceLocator,
private readonly ParentAttributeSourceLocator $parentAttributeSourceLocator,
private readonly NodeNameResolver $nodeNameResolver
) {
}
/**
* @param Stmt[] $stmts
* @return Stmt[]
*/
public function processNodes(
array $stmts,
SmartFileInfo $smartFileInfo,
?MutatingScope $formerMutatingScope = null
): array {
$isScopeRefreshing = $formerMutatingScope instanceof MutatingScope;
/**
* The stmts must be array of Stmt, or it will be silently skipped by PHPStan
* @see vendor/phpstan/phpstan/phpstan.phar/src/Analyser/NodeScopeResolver.php:282
*/
Assert::allIsInstanceOf($stmts, Stmt::class);
$this->removeDeepChainMethodCallNodes($stmts);
$scope = $formerMutatingScope ?? $this->scopeFactory->createFromFile($smartFileInfo);
// skip chain method calls, performance issue: https://github.com/phpstan/phpstan/issues/254
$nodeCallback = function (Node $node, MutatingScope $mutatingScope) use (
&$nodeCallback,
$isScopeRefreshing,
$smartFileInfo
): void {
if (($node instanceof Expression || $node instanceof Return_) && $node->expr instanceof Expr) {
$node->expr->setAttribute(AttributeKey::SCOPE, $mutatingScope);
}
if ($node instanceof Ternary) {
$this->processTernary($node, $mutatingScope);
}
if ($node instanceof AssignOp) {
$node->expr->setAttribute(AttributeKey::SCOPE, $mutatingScope);
}
if ($node instanceof BinaryOp) {
$this->processBinaryOp($node, $mutatingScope);
}
if ($node instanceof Arg) {
$node->value->setAttribute(AttributeKey::SCOPE, $mutatingScope);
}
if ($node instanceof Foreach_) {
// decorate value as well
$node->valueVar->setAttribute(AttributeKey::SCOPE, $mutatingScope);
}
if ($node instanceof Property) {
$this->processProperty($node, $mutatingScope);
}
if ($node instanceof Switch_) {
$this->processSwitch($node, $mutatingScope);
}
if ($node instanceof TryCatch) {
$this->processTryCatch($node, $smartFileInfo, $mutatingScope);
}
if ($node instanceof Assign) {
// decorate value as well
$node->expr->setAttribute(AttributeKey::SCOPE, $mutatingScope);
$node->var->setAttribute(AttributeKey::SCOPE, $mutatingScope);
}
if ($node instanceof Trait_) {
$traitName = $this->resolveClassName($node);
$traitReflectionClass = $this->reflectionProvider->getClass($traitName);
$traitScope = clone $mutatingScope;
$scopeContext = $this->privatesAccessor->getPrivatePropertyOfClass(
$traitScope,
self::CONTEXT,
ScopeContext::class
);
$traitContext = clone $scopeContext;
// before entering the class/trait again, we have to tell scope no class was set, otherwise it crashes
$this->privatesAccessor->setPrivatePropertyOfClass(
$traitContext,
'classReflection',
$traitReflectionClass,
ClassReflection::class
);
$this->privatesAccessor->setPrivatePropertyOfClass(
$traitScope,
self::CONTEXT,
$traitContext,
ScopeContext::class
);
$node->setAttribute(AttributeKey::SCOPE, $traitScope);
$this->nodeScopeResolver->processNodes($node->stmts, $traitScope, $nodeCallback);
$this->decorateTraitAttrGroups($node, $traitScope);
return;
}
// the class reflection is resolved AFTER entering to class node
// so we need to get it from the first after this one
if ($node instanceof Class_ || $node instanceof Interface_ || $node instanceof Enum_) {
/** @var MutatingScope $mutatingScope */
$mutatingScope = $this->resolveClassOrInterfaceScope($node, $mutatingScope, $isScopeRefreshing);
}
// special case for unreachable nodes
if ($node instanceof UnreachableStatementNode) {
$this->processUnreachableStatementNode($node, $smartFileInfo, $mutatingScope);
} else {
$node->setAttribute(AttributeKey::SCOPE, $mutatingScope);
}
};
$this->decoratePHPStanNodeScopeResolverWithRenamedClassSourceLocator($this->nodeScopeResolver);
return $this->processNodesWithDependentFiles($smartFileInfo, $stmts, $scope, $nodeCallback);
}
private function decorateTraitAttrGroups(Trait_ $trait, MutatingScope $mutatingScope): void
{
foreach ($trait->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attr) {
foreach ($attr->args as $arg) {
$arg->value->setAttribute(AttributeKey::SCOPE, $mutatingScope);
}
}
}
}
private function processSwitch(Switch_ $switch, MutatingScope $mutatingScope): void
{
// decorate value as well
foreach ($switch->cases as $case) {
$case->setAttribute(AttributeKey::SCOPE, $mutatingScope);
}
}
private function processTryCatch(
TryCatch $tryCatch,
SmartFileInfo $smartFileInfo,
MutatingScope $mutatingScope
): void {
foreach ($tryCatch->catches as $catch) {
$varName = $catch->var instanceof Variable
? $this->nodeNameResolver->getName($catch->var)
: null;
$type = TypeCombinator::union(
...array_map(static fn (Name $class): ObjectType => new ObjectType((string) $class), $catch->types)
);
$catchMutatingScope = $mutatingScope->enterCatchType($type, $varName);
$this->processNodes($catch->stmts, $smartFileInfo, $catchMutatingScope);
}
if ($tryCatch->finally instanceof Finally_) {
$tryCatch->finally->setAttribute(AttributeKey::SCOPE, $mutatingScope);
}
}
private function processUnreachableStatementNode(
UnreachableStatementNode $unreachableStatementNode,
SmartFileInfo $smartFileInfo,
MutatingScope $mutatingScope
): void {
$originalStmt = $unreachableStatementNode->getOriginalStatement();
$originalStmt->setAttribute(AttributeKey::IS_UNREACHABLE, true);
$originalStmt->setAttribute(AttributeKey::SCOPE, $mutatingScope);
$this->processNodes([$originalStmt], $smartFileInfo, $mutatingScope);
$next = $originalStmt->getAttribute(AttributeKey::NEXT_NODE);
while ($next instanceof Stmt) {
$next->setAttribute(AttributeKey::IS_UNREACHABLE, true);
$this->processNodes([$next], $smartFileInfo, $mutatingScope);
$next = $next->getAttribute(AttributeKey::NEXT_NODE);
}
}
private function processProperty(Property $property, MutatingScope $mutatingScope): void
{
foreach ($property->props as $propertyProperty) {
$propertyProperty->setAttribute(AttributeKey::SCOPE, $mutatingScope);
if ($propertyProperty->default instanceof Expr) {
$propertyProperty->default->setAttribute(AttributeKey::SCOPE, $mutatingScope);
}
}
foreach ($property->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attribute) {
$attribute->setAttribute(AttributeKey::SCOPE, $mutatingScope);
}
}
}
private function processBinaryOp(BinaryOp $binaryOp, MutatingScope $mutatingScope): void
{
$binaryOp->left->setAttribute(AttributeKey::SCOPE, $mutatingScope);
$binaryOp->right->setAttribute(AttributeKey::SCOPE, $mutatingScope);
}
private function processTernary(Ternary $ternary, MutatingScope $mutatingScope): void
{
if ($ternary->if instanceof Expr) {
$ternary->if->setAttribute(AttributeKey::SCOPE, $mutatingScope);
}
$ternary->else->setAttribute(AttributeKey::SCOPE, $mutatingScope);
}
/**
* @param Stmt[] $stmts
* @param callable(Node $node, MutatingScope $scope): void $nodeCallback
* @return Stmt[]
*/
private function processNodesWithDependentFiles(
SmartFileInfo $smartFileInfo,
array $stmts,
MutatingScope $mutatingScope,
callable $nodeCallback
): array {
$this->nodeScopeResolver->processNodes($stmts, $mutatingScope, $nodeCallback);
$this->resolveAndSaveDependentFiles($stmts, $mutatingScope, $smartFileInfo);
return $stmts;
}
/**
* @param Node[] $nodes
*/
private function removeDeepChainMethodCallNodes(array $nodes): void
{
$nodeTraverser = new NodeTraverser();
$nodeTraverser->addVisitor($this->removeDeepChainMethodCallNodeVisitor);
$nodeTraverser->traverse($nodes);
}
private function resolveClassOrInterfaceScope(
Class_ | Interface_ | Enum_ $classLike,
MutatingScope $mutatingScope,
bool $isScopeRefreshing
): MutatingScope {
$className = $this->resolveClassName($classLike);
// is anonymous class? - not possible to enter it since PHPStan 0.12.33, see https://github.com/phpstan/phpstan-src/commit/e87fb0ec26f9c8552bbeef26a868b1e5d8185e91
if ($classLike instanceof Class_ && StringUtils::isMatch($className, self::ANONYMOUS_CLASS_START_REGEX)) {
$classReflection = $this->reflectionProvider->getAnonymousClassReflection($classLike, $mutatingScope);
} elseif (! $this->reflectionProvider->hasClass($className)) {
return $mutatingScope;
} else {
$classReflection = $this->reflectionProvider->getClass($className);
}
// on refresh, remove entered class avoid entering the class again
if ($isScopeRefreshing && $mutatingScope->isInClass() && ! $classReflection->isAnonymous()) {
$context = $this->privatesAccessor->getPrivateProperty($mutatingScope, 'context');
$this->privatesAccessor->setPrivateProperty($context, 'classReflection', null);
}
return $mutatingScope->enterClass($classReflection);
}
private function resolveClassName(Class_ | Interface_ | Trait_| Enum_ $classLike): string
{
if ($classLike->namespacedName instanceof Name) {
return (string) $classLike->namespacedName;
}
if ($classLike->name === null) {
throw new ShouldNotHappenException();
}
return $classLike->name->toString();
}
/**
* @param Stmt[] $stmts
*/
private function resolveAndSaveDependentFiles(
array $stmts,
MutatingScope $mutatingScope,
SmartFileInfo $smartFileInfo
): void {
$dependentFiles = [];
foreach ($stmts as $stmt) {
try {
$nodeDependentFiles = $this->dependencyResolver->resolveDependencies($stmt, $mutatingScope);
$dependentFiles = array_merge($dependentFiles, $nodeDependentFiles);
} catch (AnalysedCodeException) {
// @ignoreException
}
}
$this->changedFilesDetector->addFileWithDependencies($smartFileInfo, $dependentFiles);
}
/**
* In case PHPStan tried to parse a file with missing class, it fails.
* But sometimes we want to rename old class that is missing with Rector..
*
* That's why we have to skip fatal errors of PHPStan caused by missing class,
* so Rector can fix it first. Then run Rector again to refactor code with new classes.
*/
private function decoratePHPStanNodeScopeResolverWithRenamedClassSourceLocator(
NodeScopeResolver $nodeScopeResolver
): void {
// 1. get PHPStan locator
/** @var MemoizingReflector $classReflector */
$classReflector = $this->privatesAccessor->getPrivatePropertyOfClass(
$nodeScopeResolver,
'reflector',
Reflector::class
);
$reflector = $this->privatesAccessor->getPrivatePropertyOfClass(
$classReflector,
'reflector',
Reflector::class
);
/** @var SourceLocator $sourceLocator */
$sourceLocator = $this->privatesAccessor->getPrivatePropertyOfClass(
$reflector,
'sourceLocator',
SourceLocator::class
);
// 2. get Rector locator
$aggregateSourceLocator = new AggregateSourceLocator([
$sourceLocator,
$this->renamedClassesSourceLocator,
$this->parentAttributeSourceLocator,
]);
$this->privatesAccessor->setPrivatePropertyOfClass(
$reflector,
'sourceLocator',
$aggregateSourceLocator,
AggregateSourceLocator::class
);
}
}