-
-
Notifications
You must be signed in to change notification settings - Fork 445
Expand file tree
/
Copy pathCheaperGuardFirstRule.php
More file actions
274 lines (227 loc) · 7.89 KB
/
Copy pathCheaperGuardFirstRule.php
File metadata and controls
274 lines (227 loc) · 7.89 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
<?php
declare(strict_types=1);
namespace Rector\Utils\PHPStan\Rule;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\CallLike;
use PhpParser\Node\Expr\ConstFetch;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\NullsafeMethodCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Continue_;
use PhpParser\Node\Stmt\Else_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\Stmt\Return_;
use PhpParser\NodeFinder;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Rules\IdentifierRuleError;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
/**
* Inside a Rector rule, a cheap early-return guard (isName(), instanceof, isset(), arg count)
* that does not depend on an expensive analysis call (getType(), isObjectType(),
* createFromNodeOrEmpty(), ...) should run BEFORE that call, so non-matching nodes bail out
* before paying for the costly analysis.
*
* @implements Rule<ClassMethod>
* @see \Rector\Utils\PHPStan\Tests\Rule\CheaperGuardFirstRule\CheaperGuardFirstRuleTest
*/
final class CheaperGuardFirstRule implements Rule
{
private const string ERROR_MESSAGE = 'Cheap guard on line %d can run before the expensive call on line %d; move the early return up to bail before the costly analysis.';
/**
* Calls that trigger heavy analysis (type resolution, docblock parsing, file re-parsing).
*
* @var string[]
*/
private const array EXPENSIVE_CALLS = [
'getType',
'getNativeType',
'isObjectType',
'isObjectTypes',
'createFromNode',
'createFromNodeOrEmpty',
];
/**
* Calls cheap enough to evaluate as a pre-filter.
*
* @var string[]
*/
private const array CHEAP_CALLS = ['isName', 'isNames', 'isFirstClassCallable', 'in_array', 'count'];
private const string ABSTRACT_RECTOR_CLASS = 'Rector\Rector\AbstractRector';
public function getNodeType(): string
{
return ClassMethod::class;
}
/**
* @param ClassMethod $node
* @return list<IdentifierRuleError>
*/
public function processNode(Node $node, Scope $scope): array
{
if ($node->stmts === null) {
return [];
}
$classReflection = $scope->getClassReflection();
if (! $classReflection instanceof ClassReflection) {
return [];
}
if (! in_array(self::ABSTRACT_RECTOR_CLASS, $classReflection->getParentClassesNames(), true)) {
return [];
}
$stmts = $node->stmts;
$anchorIndex = $this->findExpensiveAnchorIndex($stmts);
if ($anchorIndex === null) {
return [];
}
$assignedVariableNames = $this->resolveAssignedVariableNames($stmts[$anchorIndex]);
$counter = count($stmts);
for ($index = $anchorIndex + 1; $index < $counter; ++$index) {
$stmt = $stmts[$index];
if ($this->isPureBailGuard($stmt)) {
/** @var If_ $stmt */
if ($this->isCheapCondition($stmt->cond) && $this->isIndependent($stmt->cond, $assignedVariableNames)) {
return [
RuleErrorBuilder::message(
sprintf(self::ERROR_MESSAGE, $stmt->getStartLine(), $stmts[$anchorIndex]->getStartLine())
)
->identifier('rector.cheaperGuardFirst')
->line($stmt->getStartLine())
->build(),
];
}
// a dependent or non-cheap bail guard is legitimately here; keep scanning
continue;
}
if ($stmt instanceof Expression && $stmt->expr instanceof Assign) {
$assignedVariableNames = [...$assignedVariableNames, ...$this->resolveAssignedVariableNames($stmt)];
continue;
}
// any other statement (value return, transformation, loop) makes hoisting unsafe
return [];
}
return [];
}
/**
* @param Stmt[] $stmts
*/
private function findExpensiveAnchorIndex(array $stmts): ?int
{
foreach ($stmts as $index => $stmt) {
if (! $stmt instanceof Expression && ! $stmt instanceof If_) {
continue;
}
if ($this->containsCall($stmt, self::EXPENSIVE_CALLS)) {
return $index;
}
}
return null;
}
private function isPureBailGuard(Stmt $stmt): bool
{
if (! $stmt instanceof If_) {
return false;
}
if ($stmt->elseifs !== [] || $stmt->else instanceof Else_) {
return false;
}
if (count($stmt->stmts) !== 1) {
return false;
}
$onlyStmt = $stmt->stmts[0];
if ($onlyStmt instanceof Continue_) {
return true;
}
if (! $onlyStmt instanceof Return_) {
return false;
}
// bare "return;" or "return null;"
if (! $onlyStmt->expr instanceof Node) {
return true;
}
return $onlyStmt->expr instanceof ConstFetch && $onlyStmt->expr->name->toLowerString() === 'null';
}
private function isCheapCondition(Expr $expr): bool
{
$nodeFinder = new NodeFinder();
$callLikes = $nodeFinder->findInstanceOf($expr, CallLike::class);
foreach ($callLikes as $callLike) {
$name = $this->resolveCallName($callLike);
if ($name === null) {
return false;
}
if (! in_array($name, self::CHEAP_CALLS, true)) {
return false;
}
}
return true;
}
/**
* @param string[] $assignedVariableNames
*/
private function isIndependent(Expr $expr, array $assignedVariableNames): bool
{
if ($assignedVariableNames === []) {
return true;
}
$nodeFinder = new NodeFinder();
$variables = $nodeFinder->findInstanceOf($expr, Variable::class);
foreach ($variables as $variable) {
if (! is_string($variable->name)) {
continue;
}
if (in_array($variable->name, $assignedVariableNames, true)) {
return false;
}
}
return true;
}
/**
* @param string[] $callNames
*/
private function containsCall(Node $node, array $callNames): bool
{
$nodeFinder = new NodeFinder();
$callLikes = $nodeFinder->findInstanceOf($node, CallLike::class);
foreach ($callLikes as $callLike) {
$name = $this->resolveCallName($callLike);
if ($name !== null && in_array($name, $callNames, true)) {
return true;
}
}
return false;
}
private function resolveCallName(CallLike $callLike): ?string
{
if ($callLike instanceof MethodCall || $callLike instanceof NullsafeMethodCall || $callLike instanceof StaticCall) {
return $callLike->name instanceof Identifier ? $callLike->name->toString() : null;
}
if ($callLike instanceof FuncCall) {
return $callLike->name instanceof Name ? $callLike->name->toString() : null;
}
return null;
}
/**
* @return string[]
*/
private function resolveAssignedVariableNames(Stmt $stmt): array
{
if (! $stmt instanceof Expression || ! $stmt->expr instanceof Assign) {
return [];
}
$assign = $stmt->expr;
if ($assign->var instanceof Variable && is_string($assign->var->name)) {
return [$assign->var->name];
}
return [];
}
}