-
Notifications
You must be signed in to change notification settings - Fork 369
Expand file tree
/
Copy pathDuplicateExpressionPlugin.php
More file actions
553 lines (527 loc) · 20 KB
/
DuplicateExpressionPlugin.php
File metadata and controls
553 lines (527 loc) · 20 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
<?php
declare(strict_types=1);
use ast\flags;
use ast\Node;
use Phan\Analysis\PostOrderAnalysisVisitor;
use Phan\AST\ASTHasher;
use Phan\AST\ASTReverter;
use Phan\AST\InferValue;
use Phan\PluginV3;
use Phan\PluginV3\PluginAwarePostAnalysisVisitor;
use Phan\PluginV3\PluginAwarePreAnalysisVisitor;
use Phan\PluginV3\PostAnalyzeNodeCapability;
use Phan\PluginV3\PreAnalyzeNodeCapability;
/**
* This plugin checks for duplicate expressions in a statement
* that are likely to be a bug.
*
* - E.g. `expr1 == expr1`
*
* This file demonstrates plugins for Phan. Plugins hook into various events.
* DuplicateExpressionPlugin hooks into two events:
*
* - getPostAnalyzeNodeVisitorClassName
* This method returns a visitor that is called on every AST node from every
* file being analyzed in post-order
* - getPreAnalyzeNodeVisitorClassName
* This method returns a visitor that is called on every AST node from every
* file being analyzed in pre-order
*
* 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
*/
class DuplicateExpressionPlugin extends PluginV3 implements
PostAnalyzeNodeCapability,
PreAnalyzeNodeCapability
{
/**
* @return class-string - name of PluginAwarePostAnalysisVisitor subclass
*/
public static function getPostAnalyzeNodeVisitorClassName(): string
{
return RedundantNodePostAnalysisVisitor::class;
}
/**
* @return class-string - name of PluginAwarePreAnalysisVisitor subclass
*/
public static function getPreAnalyzeNodeVisitorClassName(): string
{
return RedundantNodePreAnalysisVisitor::class;
}
}
/**
* This visitor analyzes node kinds that can be the root of expressions
* containing duplicate expressions, and is called on nodes in post-order.
*/
class RedundantNodePostAnalysisVisitor extends PluginAwarePostAnalysisVisitor
{
/**
* These are types of binary operations for which it is
* likely to be a typo if both the left and right-hand sides
* of the operation are the same.
*/
private const REDUNDANT_BINARY_OP_SET = [
flags\BINARY_BOOL_AND => true,
flags\BINARY_BOOL_OR => true,
flags\BINARY_BOOL_XOR => true,
flags\BINARY_BITWISE_OR => true,
flags\BINARY_BITWISE_AND => true,
flags\BINARY_BITWISE_XOR => true,
flags\BINARY_SUB => true,
flags\BINARY_DIV => true,
flags\BINARY_MOD => true,
flags\BINARY_IS_IDENTICAL => true,
flags\BINARY_IS_NOT_IDENTICAL => true,
flags\BINARY_IS_EQUAL => true,
flags\BINARY_IS_NOT_EQUAL => true,
flags\BINARY_IS_SMALLER => true,
flags\BINARY_IS_SMALLER_OR_EQUAL => true,
flags\BINARY_IS_GREATER => true,
flags\BINARY_IS_GREATER_OR_EQUAL => true,
flags\BINARY_SPACESHIP => true,
flags\BINARY_COALESCE => true,
];
/**
* A subset of REDUNDANT_BINARY_OP_SET.
*
* These binary operations will make this plugin warn if both sides are literals.
*/
private const BINARY_OP_BOTH_LITERAL_WARN_SET = [
flags\BINARY_BOOL_AND => true,
flags\BINARY_BOOL_OR => true,
flags\BINARY_BOOL_XOR => true,
flags\BINARY_IS_IDENTICAL => true,
flags\BINARY_IS_NOT_IDENTICAL => true,
flags\BINARY_IS_EQUAL => true,
flags\BINARY_IS_NOT_EQUAL => true,
flags\BINARY_IS_SMALLER => true,
flags\BINARY_IS_SMALLER_OR_EQUAL => true,
flags\BINARY_IS_GREATER => true,
flags\BINARY_IS_GREATER_OR_EQUAL => true,
flags\BINARY_SPACESHIP => true,
flags\BINARY_COALESCE => true,
];
/**
* @param Node $node
* A binary operation node to analyze
* @override
* @suppress PhanAccessClassConstantInternal
*/
public function visitBinaryOp(Node $node): void
{
$flags = $node->flags;
if (!\array_key_exists($flags, self::REDUNDANT_BINARY_OP_SET)) {
// Nothing to warn about
return;
}
$left = $node->children['left'];
$right = $node->children['right'];
if (ASTHasher::hash($left) === ASTHasher::hash($right)) {
$this->emitPluginIssue(
$this->code_base,
$this->context,
'PhanPluginDuplicateExpressionBinaryOp',
'Both sides of the binary operator {OPERATOR} are the same: {CODE}',
[
PostOrderAnalysisVisitor::NAME_FOR_BINARY_OP[$node->flags],
ASTReverter::toShortString($left),
]
);
return;
}
if (!\array_key_exists($flags, self::BINARY_OP_BOTH_LITERAL_WARN_SET)) {
return;
}
if ($left instanceof Node) {
$left = self::resolveLiteralValue($left);
if ($left instanceof Node) {
return;
}
}
if ($right instanceof Node) {
$right = self::resolveLiteralValue($right);
if ($right instanceof Node) {
return;
}
}
try {
$result_representation = ASTReverter::toShortString(InferValue::computeBinaryOpResult($left, $right, $flags));
} catch (Error) {
$result_representation = '(unknown)';
}
$this->emitPluginIssue(
$this->code_base,
$this->context,
'PhanPluginBothLiteralsBinaryOp',
'Suspicious usage of a binary operator where both operands are literals. Expression: {CODE} {OPERATOR} {CODE} (result is {CODE})',
[
ASTReverter::toShortString($left),
PostOrderAnalysisVisitor::NAME_FOR_BINARY_OP[$flags],
ASTReverter::toShortString($right),
$result_representation,
]
);
}
/**
* @param Node $node
* An assignment operation node to analyze
* @override
*/
public function visitAssignRef(Node $node): void
{
$this->visitAssign($node);
}
private const ASSIGN_OP_FLAGS = [
flags\BINARY_BITWISE_OR => '|',
flags\BINARY_BITWISE_AND => '&',
flags\BINARY_BITWISE_XOR => '^',
flags\BINARY_CONCAT => '.',
flags\BINARY_ADD => '+',
flags\BINARY_SUB => '-',
flags\BINARY_MUL => '*',
flags\BINARY_DIV => '/',
flags\BINARY_MOD => '%',
flags\BINARY_POW => '**',
flags\BINARY_SHIFT_LEFT => '<<',
flags\BINARY_SHIFT_RIGHT => '>>',
flags\BINARY_COALESCE => '??',
];
/**
* @param Node $node
* An assignment operation node to analyze
* @override
*/
public function visitAssign(Node $node): void
{
$expr = $node->children['expr'];
if (!$expr instanceof Node) {
// Guaranteed not to contain duplicate expressions in valid php assignments.
return;
}
$var = $node->children['var'];
if ($expr->kind === ast\AST_BINARY_OP) {
$op_str = self::ASSIGN_OP_FLAGS[$expr->flags] ?? null;
if (is_string($op_str) && ASTHasher::hash($var) === ASTHasher::hash($expr->children['left'])) {
$message = 'Can simplify this assignment to {CODE} {OPERATOR} {CODE}';
$this->emitPluginIssue(
$this->code_base,
$this->context,
'PhanPluginDuplicateExpressionAssignmentOperation',
$message,
[
ASTReverter::toShortString($var),
$op_str . '=',
ASTReverter::toShortString($expr->children['right']),
]
);
}
return;
}
if (ASTHasher::hash($var) === ASTHasher::hash($expr)) {
$this->emitPluginIssue(
$this->code_base,
$this->context,
'PhanPluginDuplicateExpressionAssignment',
'Both sides of the assignment {OPERATOR} are the same: {CODE}',
[
$node->kind === ast\AST_ASSIGN_REF ? '=&' : '=',
ASTReverter::toShortString($var),
]
);
return;
}
}
/**
* @return bool|null|Node the resolved value of $node, or $node if it could not be resolved
* This could be more permissive about what constants are allowed (e.g. user-defined constants, real constants like PI, etc.),
* but that may cause more false positives.
*/
private static function resolveLiteralValue(Node $node): Node|bool|null
{
if ($node->kind !== ast\AST_CONST) {
return $node;
}
// @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal
switch (\strtolower($node->children['name']->children['name'] ?? null)) {
case 'false':
return false;
case 'true':
return true;
case 'null':
return null;
default:
return $node;
}
}
/**
* @param Node $node
* A binary operation node to analyze
* @override
*/
public function visitConditional(Node $node): void
{
$cond_node = $node->children['cond'];
$true_node_hash = ASTHasher::hash($node->children['true']);
if (ASTHasher::hash($cond_node) === $true_node_hash) {
$this->emitPluginIssue(
$this->code_base,
$this->context,
'PhanPluginDuplicateConditionalTernaryDuplication',
'"X ? X : Y" can usually be simplified to "X ?: Y". The duplicated expression X was {CODE}',
[ASTReverter::toShortString($cond_node)]
);
return;
}
$false_node_hash = ASTHasher::hash($node->children['false']);
if ($true_node_hash === $false_node_hash) {
$this->emitPluginIssue(
$this->code_base,
$this->context,
'PhanPluginDuplicateConditionalUnnecessary',
'"X ? Y : Y" results in the same expression Y no matter what X evaluates to. Y was {CODE}',
[ASTReverter::toShortString($cond_node)]
);
return;
}
if (!$cond_node instanceof Node) {
return;
}
switch ($cond_node->kind) {
case ast\AST_ISSET:
if (ASTHasher::hash($cond_node->children['var']) === $true_node_hash) {
$this->warnDuplicateConditionalNullCoalescing('isset(X) ? X : Y', $node->children['true']);
}
break;
case ast\AST_BINARY_OP:
$this->checkBinaryOpOfConditional($cond_node, $true_node_hash);
break;
case ast\AST_UNARY_OP:
$this->checkUnaryOpOfConditional($cond_node, $true_node_hash);
break;
}
}
/**
* @param Node $node
* A statement list of kind ast\AST_STMT_LIST to analyze.
* @override
*/
public function visitStmtList(Node $node): void
{
$children = $node->children;
if (count($children) < 2) {
return;
}
$prev_hash = null;
foreach ($children as $child) {
$hash = ASTHasher::hash($child);
if ($hash === $prev_hash) {
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($child->lineno ?? $node->lineno),
'PhanPluginDuplicateAdjacentStatement',
"Statement {CODE} is a duplicate of the statement on the above line. Suppress this issue instance if there's a good reason for this.",
[ASTReverter::toShortString($child)]
);
}
$prev_hash = $hash;
}
}
private function checkBinaryOpOfConditional(Node $cond_node, int|string $true_node_hash): void
{
if ($cond_node->flags !== ast\flags\BINARY_IS_NOT_IDENTICAL) {
return;
}
$left_node = $cond_node->children['left'];
$right_node = $cond_node->children['right'];
if (self::isNullConstantNode($left_node)) {
if (ASTHasher::hash($right_node) === $true_node_hash) {
$this->warnDuplicateConditionalNullCoalescing('null !== X ? X : Y', $right_node);
}
} elseif (self::isNullConstantNode($right_node)) {
if (ASTHasher::hash($left_node) === $true_node_hash) {
$this->warnDuplicateConditionalNullCoalescing('X !== null ? X : Y', $left_node);
}
}
}
private function checkUnaryOpOfConditional(Node $cond_node, int|string $true_node_hash): void
{
if ($cond_node->flags !== ast\flags\UNARY_BOOL_NOT) {
return;
}
$expr = $cond_node->children['expr'];
if (!$expr instanceof Node) {
return;
}
if ($expr->kind === ast\AST_CALL) {
$function = $expr->children['expr'];
if (!$function instanceof Node ||
$function->kind !== ast\AST_NAME ||
strcasecmp((string)($function->children['name'] ?? ''), 'is_null') !== 0
) {
return;
}
$args = $expr->children['args']->children;
if (count($args) !== 1) {
return;
}
if (ASTHasher::hash($args[0]) === $true_node_hash) {
$this->warnDuplicateConditionalNullCoalescing('!is_null(X) ? X : Y', $args[0]);
}
}
}
/**
* @param Node|mixed $node
*/
private static function isNullConstantNode(mixed $node): bool
{
if (!$node instanceof Node) {
return false;
}
return $node->kind === ast\AST_CONST && strcasecmp((string)($node->children['name']->children['name'] ?? ''), 'null') === 0;
}
private function warnDuplicateConditionalNullCoalescing(string $expr, Node|float|int|null|string $x_node): void
{
$this->emitPluginIssue(
$this->code_base,
$this->context,
'PhanPluginDuplicateConditionalNullCoalescing',
'"' . $expr . '" can usually be simplified to "X ?? Y". The duplicated expression X was {CODE}',
[ASTReverter::toShortString($x_node)]
);
}
}
/**
* This visitor analyzes node kinds that can be the root of expressions
* containing duplicate expressions, and is called on nodes in pre-order.
*/
class RedundantNodePreAnalysisVisitor extends PluginAwarePreAnalysisVisitor
{
/**
* @override
*/
public function visitIf(Node $node): void
{
if (count($node->children) <= 1) {
// There can't be any duplicates.
return;
}
if (isset($node->is_inside_else)) {
return;
}
$children = self::extractIfElseifChain($node);
// The checks of visitIf are done in pre-order (parent nodes analyzed before child nodes)
// so that checked_duplicate_if can be set, to avoid redundant work.
if (isset($node->checked_duplicate_if)) {
return;
}
// @phan-suppress-next-line PhanUndeclaredProperty
$node->checked_duplicate_if = true;
['cond' => $prev_cond /*, 'stmts' => $prev_stmts */] = $children[0]->children;
// $prev_stmts_hash = ASTHasher::hash($prev_cond);
$condition_set = [ASTHasher::hash($prev_cond) => true];
$N = count($children);
for ($i = 1; $i < $N; $i++) {
['cond' => $cond /*, 'stmts' => $stmts */] = $children[$i]->children;
$cond_hash = ASTHasher::hash($cond);
if (isset($condition_set[$cond_hash])) {
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($cond->lineno ?? $children[$i]->lineno),
'PhanPluginDuplicateIfCondition',
'Saw the same condition {CODE} in an earlier if/elseif statement',
[ASTReverter::toShortString($cond)]
);
} else {
$condition_set[$cond_hash] = true;
}
}
if (!isset($cond)) {
$stmts = $children[$N - 1]->children['stmts'];
if (($stmts->children ?? null) && ASTHasher::hash($stmts) === ASTHasher::hash($children[$N - 2]->children['stmts'])) {
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($children[$N - 1]->lineno),
'PhanPluginDuplicateIfStatements',
'The statements of the else duplicate the statements of the previous if/elseif statement with condition {CODE}',
[ASTReverter::toShortString($children[$N - 2]->children['cond'])]
);
}
}
}
/**
* Visit a node of kind ast\AST_TRY, to check for adjacent catch blocks
*
* @override
* @suppress PhanPossiblyUndeclaredProperty
*/
public function visitTry(Node $node): void
{
$catches = $node->children['catches']->children ?? [];
$n = count($catches);
if ($n <= 1) {
// There can't be any duplicates.
return;
}
$prev_hash = ASTHasher::hash($catches[0]->children['stmts']) . ASTHasher::hash($catches[0]->children['var']);
for ($i = 1; $i < $n; $prev_hash = $cur_hash, $i++) {
$cur_hash = ASTHasher::hash($catches[$i]->children['stmts']) . ASTHasher::hash($catches[$i]->children['var']);
if ($prev_hash === $cur_hash) {
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($catches[$i]->lineno),
'PhanPluginDuplicateCatchStatementBody',
'The implementation of catch({CODE}) and catch({CODE}) are identical and can be combined',
[
ASTReverter::toShortString($catches[$i - 1]->children['class']),
ASTReverter::toShortString($catches[$i]->children['class']),
]
);
}
}
}
/**
* @param Node $node a node of kind ast\AST_IF
* @return list<Node> the list of AST_IF_ELEM nodes making up the chain of if/elseif/else if conditions.
* @suppress PhanPartialTypeMismatchReturn
*/
private static function extractIfElseifChain(Node $node): array
{
$children = $node->children;
if (count($children) <= 1) {
return $children;
}
$last_child = \end($children);
// Loop over the `} else {` blocks.
// @phan-suppress-next-line PhanPossiblyUndeclaredProperty
while ($last_child->children['cond'] === null) {
$first_stmt = $last_child->children['stmts']->children[0] ?? null;
if (!($first_stmt instanceof Node)) {
break;
}
if ($first_stmt->kind !== ast\AST_IF) {
break;
}
// @phan-suppress-next-line PhanUndeclaredProperty
$first_stmt->is_inside_else = true;
\array_pop($children);
$if_elems = $first_stmt->children;
foreach ($if_elems as $elem) {
$children[] = $elem;
}
$last_child = \end($children);
}
return $children;
}
}
// Every plugin needs to return an instance of itself at the
// end of the file in which it's defined.
return new DuplicateExpressionPlugin();