-
Notifications
You must be signed in to change notification settings - Fork 369
Expand file tree
/
Copy pathEmptyStatementListPlugin.php
More file actions
440 lines (415 loc) · 15 KB
/
EmptyStatementListPlugin.php
File metadata and controls
440 lines (415 loc) · 15 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
<?php
declare(strict_types=1);
use ast\Node;
use Phan\AST\InferPureAndNoThrowVisitor;
use Phan\Config;
use Phan\Library\FileCache;
use Phan\Parse\ParseVisitor;
use Phan\PluginV3;
use Phan\PluginV3\PluginAwarePostAnalysisVisitor;
use Phan\PluginV3\PostAnalyzeNodeCapability;
/**
* This file checks for empty statement lists in loops/branches.
* Due to Phan's AST rewriting for easier analysis, this may miss some edge cases.
*
* It hooks into one event:
*
* - getPostAnalyzeNodeVisitorClassName
* This method returns a class that is called on every AST node from every
* file being analyzed
*
* A plugin file must
*
* - Contain a class that inherits from \Phan\PluginV3
*
* - End by returning an instance of that class.
*
* It is assumed without being checked that plugins aren't
* mangling state within the passed code base or context.
*
* Note: When adding new plugins,
* add them to the corresponding section of README.md
*/
final class EmptyStatementListPlugin extends PluginV3 implements PostAnalyzeNodeCapability
{
/**
* If true, then never allow empty statement lists, even if there is a TODO/FIXME/"deliberately empty" comment.
* @var bool
* @internal
*/
public static $ignore_todos = false;
public function __construct()
{
self::$ignore_todos = (bool) (Config::getValue('plugin_config')['empty_statement_list_ignore_todos'] ?? false);
}
/**
* @return string - The name of the visitor that will be called.
*/
public static function getPostAnalyzeNodeVisitorClassName(): string
{
return EmptyStatementListVisitor::class;
}
}
/**
* When __invoke on this class is called with a node, a method
* will be dispatched based on the `kind` of the given node.
*
* Visitors such as this are useful for defining lots of different
* checks on a node based on its kind.
*/
final class EmptyStatementListVisitor extends PluginAwarePostAnalysisVisitor
{
/**
* @var list<Node> set by plugin framework
* @suppress PhanReadOnlyProtectedProperty
*/
protected $parent_node_list;
/**
* @param Node $node
* A node to analyze
* @override
*/
public function visitIf(Node $node): void
{
if (isset($node->is_simplified)) {
$first_child = end($node->children);
if (!$first_child instanceof Node || $first_child->children['cond'] === null) {
return;
}
$last_if_elem = reset($node->children);
} else {
$last_if_elem = end($node->children);
}
if (!$last_if_elem instanceof Node) {
// probably impossible
return;
}
$stmts_node = $last_if_elem->children['stmts'];
if (!$stmts_node instanceof Node) {
// probably impossible
return;
}
if ($stmts_node->children) {
// the last if element has statements
return;
}
if ($last_if_elem->children['cond'] === null) {
// Don't bother warning about else
return;
}
if ($this->hasTODOComment($stmts_node->lineno, $node)) {
// Don't warn if there is a FIXME/TODO comment in/around the empty statement list
return;
}
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($last_if_elem->children['stmts']->lineno ?? $last_if_elem->lineno),
'PhanPluginEmptyStatementIf',
'Empty statement list detected for the last if/elseif statement',
[]
);
}
private function hasTODOComment(int $lineno, Node $analyzed_node, ?int $end_lineno = null): bool
{
if (EmptyStatementListPlugin::$ignore_todos) {
return false;
}
$file = FileCache::getOrReadEntry($this->context->getFile());
$lines = $file->getLines();
$end_lineno = max($lineno, $end_lineno ?? $this->findEndLine($lineno, $analyzed_node));
for ($i = $lineno; $i <= $end_lineno; $i++) {
$line = $lines[$i] ?? null;
if (!is_string($line)) {
break;
}
if (preg_match('/todo|fixme|deliberately empty/i', $line) > 0) {
return true;
}
}
return false;
}
private function findEndLine(int $lineno, Node $search_node): int
{
for ($node_index = count($this->parent_node_list) - 1; $node_index >= 0; $node_index--) {
$node = $this->parent_node_list[$node_index] ?? null;
if (!$node) {
continue;
}
if (isset($node->endLineno)) {
// Return the end line of the function declaration.
return $node->endLineno;
}
if ($node->kind === ast\AST_STMT_LIST) {
foreach ($node->children as $i => $c) {
if ($c === $search_node) {
$next_node = $node->children[$i + 1] ?? null;
if ($next_node instanceof Node) {
return $next_node->lineno - 1;
}
break;
}
}
}
$search_node = $node;
}
// Give up and guess.
return $lineno + 5;
}
/**
* @param Node $node
* A node of kind ast\AST_FOR to analyze
* @override
*/
public function visitFor(Node $node): void
{
$stmts_node = $node->children['stmts'];
if (!$stmts_node instanceof Node) {
// impossible
return;
}
if ($stmts_node->children || ($node->children['loop']->children ?? null)) {
// the for loop has statements, in the body and/or in the loop condition.
return;
}
if ($this->hasTODOComment($stmts_node->lineno, $node)) {
// Don't warn if there is a FIXME/TODO comment in/around the empty statement list
return;
}
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($stmts_node->lineno ?? $node->lineno),
'PhanPluginEmptyStatementForLoop',
'Empty statement list detected for the for loop',
[]
);
}
/**
* @param Node $node
* A node to analyze
* @override
*/
public function visitWhile(Node $node): void
{
$stmts_node = $node->children['stmts'];
if (!$stmts_node instanceof Node) {
return; // impossible
}
if ($stmts_node->children) {
// the while loop has statements
return;
}
if ($this->hasTODOComment($stmts_node->lineno, $node)) {
// Don't warn if there is a FIXME/TODO comment in/around the empty statement list
return;
}
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($stmts_node->lineno ?? $node->lineno),
'PhanPluginEmptyStatementWhileLoop',
'Empty statement list detected for the while loop',
[]
);
}
/**
* @param Node $node
* A node to analyze
* @override
*/
public function visitDoWhile(Node $node): void
{
$stmts_node = $node->children['stmts'];
if (!$stmts_node instanceof Node) {
return; // impossible
}
if ($stmts_node->children ?? null) {
// the while loop has statements
return;
}
if ($this->hasTODOComment($stmts_node->lineno, $node)) {
// Don't warn if there is a FIXME/TODO comment in/around the empty statement list
return;
}
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($stmts_node->lineno),
'PhanPluginEmptyStatementDoWhileLoop',
'Empty statement list detected for the do-while loop',
[]
);
}
/**
* @param Node $node
* A node to analyze
* @override
*/
public function visitForeach(Node $node): void
{
$stmts_node = $node->children['stmts'];
if (!$stmts_node instanceof Node) {
// impossible
return;
}
if ($stmts_node->children) {
// the while loop has statements
return;
}
// Check if the 'as' clause has side effects (assignments to properties/array elements)
if (self::foreachHasSideEffectsInAsClause($node)) {
// Don't warn if foreach assigns to properties/array elements even with empty body
return;
}
if ($this->hasTODOComment($stmts_node->lineno, $node)) {
// Don't warn if there is a FIXME/TODO comment in/around the empty statement list
return;
}
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($stmts_node->lineno),
'PhanPluginEmptyStatementForeachLoop',
'Empty statement list detected for the foreach loop',
[]
);
}
/**
* Check if a foreach loop has side effects in its 'as' clause.
* Returns true if the value or key are assigned to properties, array elements, etc.
* Array destructuring like [$a, $b] is NOT considered a side effect (assigns to local vars).
*/
private static function foreachHasSideEffectsInAsClause(Node $node): bool
{
// Check the value assignment
$value = $node->children['value'];
if (self::assignmentTargetHasSideEffects($value)) {
return true;
}
// Check the key assignment (if present)
$key = $node->children['key'];
if (self::assignmentTargetHasSideEffects($key)) {
return true;
}
return false;
}
/**
* Check if an assignment target in a foreach has side effects.
* Returns true for property/array element assignments, false for simple variables.
* For array destructuring, recursively checks if any element has side effects.
*/
private static function assignmentTargetHasSideEffects(Node|string|int|float|null $target): bool
{
if (!$target instanceof Node) {
return false;
}
switch ($target->kind) {
case ast\AST_VAR:
case ast\AST_REF:
// Simple variable or reference - no external side effects
return false;
case ast\AST_ARRAY:
case ast\AST_LIST:
// Array destructuring - check if any element has side effects
foreach ($target->children as $elem) {
if (!$elem instanceof Node) {
continue;
}
// AST_ARRAY_ELEM has 'value' child with the actual assignment target
$elem_value = $elem->children['value'] ?? null;
if (self::assignmentTargetHasSideEffects($elem_value)) {
return true;
}
}
return false;
case ast\AST_PROP:
case ast\AST_STATIC_PROP:
case ast\AST_DIM:
// Property or array element assignment - has side effects
return true;
default:
// Other node types - conservatively assume side effects
return true;
}
}
/**
* @param Node $node
* A node to analyze
* @override
*/
public function visitTry(Node $node): void
{
['try' => $try_node, 'finally' => $finally_node] = $node->children;
if (!$try_node->children) {
if (!$this->hasTODOComment($try_node->lineno, $node, $node->children['catches']->children[0]->lineno ?? $finally_node->lineno ?? null)) {
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($try_node->lineno),
'PhanPluginEmptyStatementTryBody',
'Empty statement list detected for the try statement\'s body',
[]
);
}
} elseif (InferPureAndNoThrowVisitor::isUnlikelyToThrow($this->code_base, $this->context, $try_node)) {
if (!$this->hasTODOComment($try_node->lineno, $node, $node->children['catches']->children[0]->lineno ?? $finally_node->lineno ?? null)) {
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($try_node->lineno),
'PhanPluginEmptyStatementPossiblyNonThrowingTryBody',
'Found a try block that looks like it might not throw. Note that this check is a heuristic prone to false positives, especially because error handlers, signal handlers, destructors, and other things may all lead to throwing.'
);
}
}
if ($finally_node instanceof Node && !$finally_node->children) {
if (!$this->hasTODOComment($finally_node->lineno, $node)) {
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($finally_node->lineno),
'PhanPluginEmptyStatementTryFinally',
'Empty statement list detected for the try\'s finally body',
[]
);
}
}
}
/**
* @param Node $node
* A node of kind ast\AST_SWITCH to analyze
* @override
*/
public function visitSwitch(Node $node): void
{
// Check all case statements and return if something that isn't a no-op is seen.
foreach ($node->children['stmts']->children ?? [] as $c) {
if (!$c instanceof Node) {
// impossible
continue;
}
$children = $c->children['stmts']->children ?? null;
if ($children) {
if (count($children) > 1) {
return;
}
$only_node = $children[0];
if ($only_node instanceof Node) {
if (!in_array($only_node->kind, [ast\AST_CONTINUE, ast\AST_BREAK], true)) {
return;
}
if (($only_node->children['depth'] ?? 1) !== 1) {
// not a no-op
return;
}
}
}
if (!ParseVisitor::isConstExpr($c->children['cond'], ParseVisitor::CONSTANT_EXPRESSION_FORBID_NEW_EXPRESSION)) {
return;
}
}
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($node->lineno),
'PhanPluginEmptyStatementSwitch',
'No side effects seen for any cases of this switch statement',
[]
);
}
}
// Every plugin needs to return an instance of itself at the
// end of the file in which it's defined.
return new EmptyStatementListPlugin();