forked from sebastianbergmann/php-code-coverage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExecutableLinesFindingVisitor.php
More file actions
682 lines (557 loc) · 19.9 KB
/
ExecutableLinesFindingVisitor.php
File metadata and controls
682 lines (557 loc) · 19.9 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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
<?php declare(strict_types=1);
/*
* This file is part of phpunit/php-code-coverage.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\CodeCoverage\StaticAnalysis;
use function array_any;
use function array_diff_key;
use function array_intersect_key;
use function array_key_last;
use function assert;
use function count;
use function ctype_space;
use function explode;
use function is_array;
use function max;
use function str_replace;
use function strtolower;
use function trim;
use PhpParser\Node;
use PhpParser\NodeVisitorAbstract;
/**
* Identifies lines of a parsed PHP source file that should appear in the code
* coverage report and groups them by execution branch.
*
* Two related sets are produced and exposed via accessors:
*
* - {@see executableLinesGroupedByBranch()}:
* An over-approximating envelope. Every line that may potentially carry
* an opcode reachable by the runtime is included, mapped to a branch
* identifier. The filter pipeline keeps driver hits for any of these
* lines and lets sibling lines in the same branch inherit each other's
* execution status.
*
* - {@see branchOperatorLines()}:
* A precise subset. Only lines added by handlers for AST nodes whose
* execution is guaranteed to emit an opcode (match arm bodies, ternary
* branches, coalesce right-hand side, conditional and loop conditions,
* function-call sites, arrow-function bodies, …) are included. Lines
* contributed only by the generic statement default ("anything else")
* are excluded. The filter pipeline force-marks lines from this set as
* not-executed when the driver did not report them, so reachable but
* un-hit branches still surface in the report; structural default-only
* lines are spared this treatment.
*
* After traversal, two cleanup passes run in {@see afterTraverse()}:
*
* - Blank lines and lines whose only content matches a tracked comment are
* removed from the executable map.
* - The {@see $unsets} map is applied destructively to the executable map,
* and {@see $branchOperatorLines} is intersected with the result so it
* cannot reference lines no longer in the executable map.
*
* IMPORTANT: Behaviour changes here must be accompanied by a {@see Version::id()}
* bump. Otherwise stale entries in {@see CachingSourceAnalyser}'s
* on-disk cache will serve incorrect analysis results.
*
* @internal This class is not covered by the backward compatibility promise for phpunit/php-code-coverage
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for phpunit/php-code-coverage
*
* @phpstan-import-type LinesType from AnalysisResult
*/
final class ExecutableLinesFindingVisitor extends NodeVisitorAbstract
{
/**
* @var list<class-string<Node>>
*/
private const array ALWAYS_IGNORED = [
Node\Stmt\Declare_::class,
Node\DeclareItem::class,
Node\Stmt\Else_::class,
Node\Stmt\EnumCase::class,
Node\Stmt\Finally_::class,
Node\Stmt\GroupUse::class,
Node\Stmt\Label::class,
Node\Stmt\Namespace_::class,
Node\Stmt\Nop::class,
Node\Stmt\Switch_::class,
Node\Stmt\TryCatch::class,
Node\Stmt\Use_::class,
Node\UseItem::class,
Node\Expr\ConstFetch::class,
Node\Expr\Variable::class,
Node\Expr\Throw_::class,
Node\ComplexType::class,
Node\Const_::class,
Node\Identifier::class,
Node\Name::class,
Node\Param::class,
Node\Scalar::class,
];
private int $nextBranch = 0;
private readonly string $source;
/**
* @var LinesType
*/
private array $executableLinesGroupedByBranch = [];
/**
* @var array<int, true>
*/
private array $branchOperatorLines = [];
/**
* @var array<int, bool>
*/
private array $unsets = [];
/**
* @var array<int, string>
*/
private array $commentsToCheckForUnset = [];
public function __construct(string $source)
{
$this->source = str_replace("\r\n", "\n", $source);
}
public function enterNode(Node $node): null
{
$this->collectMatchingComments($node);
if ($node instanceof Node\Scalar\String_ ||
$node instanceof Node\InterpolatedStringPart) {
$this->stripMultilineStringInterior($node);
return null;
}
if ($node instanceof Node\Stmt\Interface_ ||
$node instanceof Node\Attribute) {
$this->markRangeForUnset($node->getStartLine(), $node->getEndLine());
return null;
}
if ($this->isAlwaysIgnored($node)) {
return null;
}
if ($node instanceof Node\Expr\Match_) {
$this->enterMatch($node);
return null;
}
if ($node instanceof Node\Stmt\Expression &&
$node->expr instanceof Node\Expr\Throw_) {
$line = $node->expr->expr->getEndLine();
$this->setLineBranch($line, $line, ++$this->nextBranch);
return null;
}
if ($node instanceof Node\Stmt\Expression &&
(
$node->expr instanceof Node\Scalar ||
$node->expr instanceof Node\Expr\ConstFetch
)
) {
return null;
}
if ($node instanceof Node\Stmt\Enum_ ||
$node instanceof Node\Stmt\Function_ ||
$node instanceof Node\Stmt\Class_ ||
$node instanceof Node\Stmt\ClassMethod ||
$node instanceof Node\Expr\Closure ||
$node instanceof Node\Stmt\Trait_) {
$this->enterCallableOrClassLike($node);
return null;
}
if ($node instanceof Node\PropertyHook) {
$this->enterPropertyHook($node);
return null;
}
if ($node instanceof Node\Expr\ArrowFunction) {
$this->enterArrowFunction($node);
return null;
}
if ($node instanceof Node\Expr\Ternary) {
$this->enterTernary($node);
return null;
}
if ($node instanceof Node\Expr\BinaryOp\Coalesce) {
$this->enterCoalesce($node);
return null;
}
if ($node instanceof Node\Stmt\If_ ||
$node instanceof Node\Stmt\ElseIf_) {
$this->enterConditional($node);
return null;
}
if ($node instanceof Node\Stmt\Case_) {
$this->enterCase($node);
return null;
}
if ($node instanceof Node\Stmt\For_) {
$this->enterFor($node);
return null;
}
if ($node instanceof Node\Stmt\Foreach_) {
$this->setLineBranch(
$node->expr->getStartLine(),
$node->valueVar->getEndLine(),
++$this->nextBranch,
);
return null;
}
if ($node instanceof Node\Stmt\While_ ||
$node instanceof Node\Stmt\Do_) {
$this->setLineBranch(
$node->cond->getStartLine(),
$node->cond->getEndLine(),
++$this->nextBranch,
);
return null;
}
if ($node instanceof Node\Stmt\Catch_) {
$this->enterCatch($node);
return null;
}
if ($node instanceof Node\Expr\CallLike) {
$branch = $this->executableLinesGroupedByBranch[$node->getStartLine()] ?? ++$this->nextBranch;
$this->setLineBranch($node->getStartLine(), $node->getEndLine(), $branch);
return null;
}
$this->enterDefault($node);
return null;
}
public function afterTraverse(array $nodes): null
{
$this->stripBlankAndCommentOnlyLines();
$this->executableLinesGroupedByBranch = array_diff_key(
$this->executableLinesGroupedByBranch,
$this->unsets,
);
$this->branchOperatorLines = array_intersect_key(
$this->branchOperatorLines,
$this->executableLinesGroupedByBranch,
);
return null;
}
/**
* @return LinesType
*/
public function executableLinesGroupedByBranch(): array
{
return $this->executableLinesGroupedByBranch;
}
/**
* @return array<int, true>
*/
public function branchOperatorLines(): array
{
return $this->branchOperatorLines;
}
private function collectMatchingComments(Node $node): void
{
foreach ($node->getComments() as $comment) {
$commentLine = $comment->getStartLine();
if (!isset($this->executableLinesGroupedByBranch[$commentLine])) {
continue;
}
foreach (explode("\n", $comment->getText()) as $text) {
$this->commentsToCheckForUnset[$commentLine] = $text;
$commentLine++;
}
}
}
private function stripMultilineStringInterior(Node $node): void
{
$startLine = $node->getStartLine() + 1;
$endLine = $node->getEndLine() - 1;
for ($line = $startLine; $line <= $endLine; $line++) {
unset($this->executableLinesGroupedByBranch[$line]);
}
}
private function isAlwaysIgnored(Node $node): bool
{
return array_any(
self::ALWAYS_IGNORED,
/** class-string<Node> $class */
static fn (string $class) => $node instanceof $class,
);
}
private function enterMatch(Node\Expr\Match_ $node): void
{
foreach ($node->arms as $arm) {
$this->setLineBranch(
$arm->body->getStartLine(),
$arm->body->getEndLine(),
++$this->nextBranch,
);
}
if ([] === $node->arms) {
return;
}
$firstArmLine = $node->arms[0]->getStartLine();
$lastArmLine = $node->arms[count($node->arms) - 1]->getEndLine();
if ($node->getStartLine() < $firstArmLine && $this->matchConditionHasNoOpcode($node->cond)) {
$this->markRangeForUnset($node->getStartLine(), $firstArmLine - 1);
}
if ($node->getEndLine() > $lastArmLine) {
$this->markRangeForUnset($lastArmLine + 1, $node->getEndLine());
}
}
/**
* @param Node\Expr\Closure|Node\Stmt\Class_|Node\Stmt\ClassMethod|Node\Stmt\Enum_|Node\Stmt\Function_|Node\Stmt\Trait_ $node
*/
private function enterCallableOrClassLike(Node $node): void
{
if ($node instanceof Node\Stmt\ClassMethod && $node->isAbstract()) {
return;
}
if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod) {
$this->markParameterLinesForUnset($node);
}
$isConcreteClassLike = $node instanceof Node\Stmt\Enum_ ||
$node instanceof Node\Stmt\Class_ ||
$node instanceof Node\Stmt\Trait_;
if (null !== $node->stmts) {
foreach ($node->stmts as $stmt) {
if ($stmt instanceof Node\Stmt\Nop) {
continue;
}
$protectedLines = $this->linesProtectedFromClassBodyUnset($stmt);
for ($line = $stmt->getStartLine(); $line <= $stmt->getEndLine(); $line++) {
if (isset($protectedLines[$line])) {
continue;
}
unset($this->executableLinesGroupedByBranch[$line]);
if ($isConcreteClassLike && !$stmt instanceof Node\Stmt\ClassMethod) {
$this->unsets[$line] = true;
}
}
}
}
if ($isConcreteClassLike) {
return;
}
$hasEmptyBody = [] === $node->stmts ||
null === $node->stmts ||
(
1 === count($node->stmts) &&
$node->stmts[0] instanceof Node\Stmt\Nop
);
if (!$hasEmptyBody) {
return;
}
if ($node->getEndLine() === $node->getStartLine() &&
isset($this->executableLinesGroupedByBranch[$node->getStartLine()])) {
return;
}
$this->setLineBranch($node->getEndLine(), $node->getEndLine(), ++$this->nextBranch);
}
/**
* Lines belonging to property-hook bodies must not be unset by the
* enclosing class iteration; the {@see enterPropertyHook()} handler will
* mark them, and traversal of inner statements will populate them via
* normal handlers.
*
* @return array<int, true>
*/
private function linesProtectedFromClassBodyUnset(Node\Stmt $stmt): array
{
if (!$stmt instanceof Node\Stmt\Property) {
return [];
}
$protected = [];
foreach ($stmt->hooks as $hook) {
if ($hook->body === null) {
continue;
}
if ($hook->body instanceof Node\Expr) {
for ($line = $hook->body->getStartLine(); $line <= $hook->body->getEndLine(); $line++) {
$protected[$line] = true;
}
continue;
}
if (is_array($hook->body)) {
foreach ($hook->body as $bodyStmt) {
if ($bodyStmt instanceof Node\Stmt\Nop) {
continue;
}
for ($line = $bodyStmt->getStartLine(); $line <= $bodyStmt->getEndLine(); $line++) {
$protected[$line] = true;
}
}
}
}
return $protected;
}
private function enterPropertyHook(Node\PropertyHook $node): void
{
$this->markParameterLinesForUnset($node);
if ($node->body === null) {
return;
}
if ($node->body instanceof Node\Expr) {
$this->setLineBranch(
$node->body->getStartLine(),
$node->body->getEndLine(),
++$this->nextBranch,
);
}
}
private function enterArrowFunction(Node\Expr\ArrowFunction $node): void
{
$startLine = max(
$node->getStartLine() + 1,
$node->expr->getStartLine(),
);
$endLine = $node->expr->getEndLine();
if ($endLine < $startLine) {
return;
}
$this->setLineBranch($startLine, $endLine, ++$this->nextBranch);
}
private function enterTernary(Node\Expr\Ternary $node): void
{
if (null !== $node->if &&
$node->getStartLine() !== $node->if->getEndLine()) {
$this->setLineBranch(
$node->if->getStartLine(),
$node->if->getEndLine(),
++$this->nextBranch,
);
}
if ($node->getStartLine() !== $node->else->getEndLine()) {
$this->setLineBranch(
$node->else->getStartLine(),
$node->else->getEndLine(),
++$this->nextBranch,
);
}
}
private function enterCoalesce(Node\Expr\BinaryOp\Coalesce $node): void
{
if ($node->getStartLine() === $node->getEndLine()) {
return;
}
$this->setLineBranch(
$node->getEndLine(),
$node->getEndLine(),
++$this->nextBranch,
);
}
/**
* @param Node\Stmt\ElseIf_|Node\Stmt\If_ $node
*/
private function enterConditional(Node $node): void
{
if (null === $node->cond) {
return;
}
$this->setLineBranch(
$node->cond->getStartLine(),
$node->cond->getStartLine(),
++$this->nextBranch,
);
}
private function enterCase(Node\Stmt\Case_ $node): void
{
if (null === $node->cond) {
return;
}
$line = $node->cond->getStartLine();
$this->executableLinesGroupedByBranch[$line] = ++$this->nextBranch;
}
private function enterFor(Node\Stmt\For_ $node): void
{
$startLine = null;
$endLine = null;
if ([] !== $node->init) {
$startLine = $node->init[0]->getStartLine();
$endLine = $node->init[array_key_last($node->init)]->getEndLine();
}
if ([] !== $node->cond) {
$startLine ??= $node->cond[0]->getStartLine();
$endLine = $node->cond[array_key_last($node->cond)]->getEndLine();
}
if ([] !== $node->loop) {
$startLine ??= $node->loop[0]->getStartLine();
$endLine = $node->loop[array_key_last($node->loop)]->getEndLine();
}
if (null === $startLine || null === $endLine) {
return;
}
$this->setLineBranch($startLine, $endLine, ++$this->nextBranch);
}
private function enterCatch(Node\Stmt\Catch_ $node): void
{
assert([] !== $node->types);
$startLine = $node->types[0]->getStartLine();
$endLine = $node->types[array_key_last($node->types)]->getEndLine();
$this->setLineBranch($startLine, $endLine, ++$this->nextBranch);
}
private function enterDefault(Node $node): void
{
if (isset($this->executableLinesGroupedByBranch[$node->getStartLine()])) {
return;
}
$branch = ++$this->nextBranch;
for ($line = $node->getStartLine(); $line <= $node->getEndLine(); $line++) {
$this->executableLinesGroupedByBranch[$line] = $branch;
}
}
/**
* @param Node\PropertyHook|Node\Stmt\ClassMethod|Node\Stmt\Function_ $node
*/
private function markParameterLinesForUnset(Node $node): void
{
$unsets = [];
foreach ($node->getParams() as $param) {
for ($line = $param->getStartLine(); $line <= $param->getEndLine(); $line++) {
$unsets[$line] = true;
}
}
unset($unsets[$node->getEndLine()]);
$this->unsets += $unsets;
}
private function markRangeForUnset(int $start, int $end): void
{
for ($line = $start; $line <= $end; $line++) {
$this->unsets[$line] = true;
}
}
/**
* Marks every line in `[$start, $end]` as executable in branch `$branch`
* AND records each line as branch-operator-derived (i.e. the line was
* added by a specific node handler, not by the generic default).
*
* Use this for any line that the analyser believes is guaranteed to carry
* an opcode the driver can hit. Anything that should NOT enter the
* branch-operator set (for example, the generic statement default) must
* write to {@see $executableLinesGroupedByBranch} directly.
*/
private function setLineBranch(int $start, int $end, int $branch): void
{
for ($line = $start; $line <= $end; $line++) {
$this->executableLinesGroupedByBranch[$line] = $branch;
$this->branchOperatorLines[$line] = true;
}
}
private function matchConditionHasNoOpcode(Node\Expr $cond): bool
{
if (!$cond instanceof Node\Expr\ConstFetch) {
return false;
}
$name = strtolower($cond->name->toString());
return $name === 'true' || $name === 'false' || $name === 'null';
}
private function stripBlankAndCommentOnlyLines(): void
{
foreach (explode("\n", $this->source) as $i => $line) {
$lineNumber = $i + 1;
if ($line === '' || ctype_space($line)) {
unset($this->executableLinesGroupedByBranch[$lineNumber]);
continue;
}
if (isset($this->commentsToCheckForUnset[$lineNumber]) &&
trim($line) === trim($this->commentsToCheckForUnset[$lineNumber])) {
unset($this->executableLinesGroupedByBranch[$lineNumber]);
}
}
}
}