Repository navigation
Expand file tree
/
Copy pathVariableLivenessResolver.php
More file actions
640 lines (593 loc) · 20.2 KB
/
Copy pathVariableLivenessResolver.php
File metadata and controls
640 lines (593 loc) · 20.2 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
<?php declare(strict_types = 1);
namespace PHPStan\Analyser;
use PhpParser\Node;
use PhpParser\Node\Stmt\For_;
use PhpParser\Node\Stmt\Foreach_;
use PHPStan\Node\Variable\VariableWrite;
use PHPStan\Node\VariableWritesNode;
use PHPStan\ShouldNotHappenException;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use Throwable;
use function array_keys;
use function array_pop;
use function array_reverse;
use function array_values;
use function count;
use function in_array;
use function is_int;
use function is_string;
use function spl_object_id;
use function sprintf;
use function str_ends_with;
use function str_starts_with;
use function strlen;
use function substr;
/** Resolve liveness backwards over immutable body fragments. */
final class VariableLivenessResolver
{
/** @var array<int, VariableWrite> */
private array $writes = [];
/** @var array<int, true> */
private array $readIds = [];
/** @var array<int, true> */
private array $observedIds = [];
/** @var array<string, true> */
private array $readNames = [];
/** @var array<string, true> */
private array $mentionedNames = [];
/** @var array<string, true> */
private array $escapedNames = [];
/** @var array<int, Type> */
private array $redundantTypes = [];
/** @var array<string, list<VariableAccessFlow>> */
private array $accesses = [];
/** @var array<int, array<string, true>> */
private array $readKeys = [];
/** @var array<string, array<string, true>> */
private array $nameKeys = [];
/** @var array<int, array<string, int|null>> */
private array $observedKeys = [];
/** @var array<int, array<string, true>> */
private array $killedKeys = [];
/** @var array<int, array<int, true>> */
private array $dependencies = [];
/** @var array<int, array<int, true>> */
private array $inputCopies = [];
/** @var array<int, true> */
private array $inputSinks = [];
/** @var array<int, array<int, VariableWrite>> */
private array $literalItems = [];
/** @var array<int, true> */
private array $coveredIds = [];
/** @var array<string, true> */
private array $allReadKeys = [];
/** @var array<int, Foreach_|For_> */
private array $loopStatements = [];
/** @var array<int, array<int, true>> */
private array $ownWriteIds = [];
/** @var array<int, Foreach_|For_> */
private array $variableOverwritingLoops = [];
private bool $opaque = false;
private bool $readsAllVariables = false;
private bool $allNamesMentioned = false;
private bool $returnsByReference = false;
private function __construct()
{
}
public static function resolve(Node\FunctionLike $function, ?VariableFlow $flow): VariableWritesNode
{
$self = new self();
$self->returnsByReference = $function->returnsByRef();
$imports = [];
foreach ($function->getParams() as $param) {
if (!$param->var instanceof Node\Expr\Variable || !is_string($param->var->name)) {
continue;
}
if ($param->byRef || $param->flags !== 0) {
$self->escapedNames[$param->var->name] = true;
continue;
}
$imports[] = VariableFlow::write(new VariableWrite($param->var->name, $param->var, spl_object_id($param->var), VariableWrite::KIND_PARAMETER));
}
if ($function instanceof Node\Expr\Closure) {
foreach ($function->uses as $use) {
if (!is_string($use->var->name)) {
continue;
}
if ($use->byRef) {
$self->escapedNames[$use->var->name] = true;
continue;
}
$imports[] = VariableFlow::write(new VariableWrite($use->var->name, $use->var, spl_object_id($use->var), VariableWrite::KIND_CLOSURE_USE));
}
}
$body = VariableFlow::sequence(...[...$imports, $flow]);
$self->collect($body);
if ($self->writes !== [] && !$self->opaque) {
$self->compileAccesses();
$self->liveBefore($body, [], new VariableFlowContext([]));
$self->resolveDependencies();
$self->resolveCoverage();
}
return new VariableWritesNode($function, array_values($self->writes), $self->observedIds + $self->readIds, $self->readIds, $self->coveredIds, $self->readNames, $self->redundantTypes, $self->mentionedNames, $self->escapedNames, $self->variableOverwritingLoops, $self->opaque, $self->allNamesMentioned);
}
private function collect(?VariableFlow $flow, bool $dead = false): void
{
if ($flow === null || $flow instanceof VariableInputFlow) {
return;
}
if ($flow instanceof VariableAccessFlow && $flow->name !== 'this' && !in_array($flow->name, Scope::SUPERGLOBAL_VARIABLES, true)) {
$this->mentionedNames[$flow->name] = true;
$this->accesses[$flow->name][] = $flow;
if ($flow->kind === VariableFlow::READ) {
$this->readNames[$flow->name] = true;
} elseif ($flow->kind === VariableFlow::ESCAPE) {
$this->escapedNames[$flow->name] = true;
}
if ($flow->write !== null && $flow->kind !== VariableFlow::DISCARD) {
$id = $flow->write->getId();
$this->writes[$id] = $flow->write;
$parentId = $flow->write->getParentId();
if ($parentId !== null) {
$this->literalItems[$parentId][$id] = $flow->write;
}
if ($flow->type !== null) {
$this->redundantTypes[$id] = $flow->type;
}
if ($dead) {
$this->readIds[$id] = true;
}
}
}
if ($flow->kind === VariableFlow::READ_ALL) {
$this->readsAllVariables = true;
}
if ($flow->kind === VariableFlow::OPAQUE) {
$this->opaque = true;
}
if (in_array($flow->kind, [VariableFlow::READ_ALL, VariableFlow::MENTION_ALL], true)) {
$this->allNamesMentioned = true;
}
if ($flow instanceof VariableAccessFlow) {
return;
}
if (!$flow instanceof VariableSequenceFlow && !$flow instanceof VariableControlFlow) {
throw new ShouldNotHappenException();
}
foreach ($flow->children as $child) {
$this->collect($child, $dead || $flow->kind === VariableFlow::DEAD);
}
if (!$flow instanceof VariableControlFlow) {
return;
}
if ($flow->kind === VariableFlow::LOOP_STATEMENT && $flow->stmt !== null) {
$ownIds = [];
foreach ($flow->ownWrites as $write) {
$ownIds[$write->getId()] = true;
}
foreach ($flow->bindings as $binding) {
$this->loopStatements[$binding->getId()] = $flow->stmt;
$this->ownWriteIds[$binding->getId()] = $ownIds;
}
}
if ($flow->kind === VariableFlow::RETURN && $flow->name !== null && $this->returnsByReference) {
$this->escapedNames[$flow->name] = true;
}
foreach ($flow->cases as [$condition, $body]) {
$this->collect($condition, $dead);
$this->collect($body, $dead);
}
foreach ($flow->catches as [, $catch]) {
$this->collect($catch, $dead);
}
}
/**
* @param array<string, true> $next
* @return array<string, true>
*/
private function liveBefore(?VariableFlow $flow, array $next, VariableFlowContext $context): array
{
if ($flow === null || $flow->kind === VariableFlow::DEAD) {
return $next;
}
if ($flow instanceof VariableInputFlow) {
if ($flow->targetId === null) {
$this->inputSinks[$flow->writeId] = true;
} else {
$this->inputCopies[$flow->targetId][$flow->writeId] = true;
}
return $next;
}
if ($flow instanceof VariableAccessFlow) {
if (in_array($flow->kind, [VariableFlow::READ, VariableFlow::ESCAPE], true)) {
// a by-reference capture aliases the variable - the value it
// holds at that point is observable through the alias
if ($flow->kind === VariableFlow::ESCAPE && $this->loopStatements !== []) {
$next = $this->passBindingProbes($next, $flow->name, null);
}
return $next + ($this->readKeys[spl_object_id($flow)] ?? []);
}
if ($flow->write === null || $flow->kind === VariableFlow::DEFINE) {
return $next;
}
if ($this->loopStatements !== []) {
$next = $this->passBindingProbes($next, $flow->name, $flow->write, $flow->kind === VariableFlow::DISCARD);
}
$id = $flow->write->getId();
if ($flow->kind !== VariableFlow::DISCARD) {
$this->observeWrite($id, $next);
foreach ($this->literalItems[$id] ?? [] as $item) {
$this->observeWrite($item->getId(), $next);
}
}
foreach (array_keys($this->killedKeys[$id] ?? []) as $key) {
unset($next[$key]);
}
return $next;
}
if ($flow instanceof VariableSequenceFlow) {
if ($flow->kind === VariableFlow::SEQUENCE) {
foreach (array_reverse($flow->children) as $child) {
$next = $this->liveBefore($child, $next, $context);
}
return $next;
}
$names = [];
foreach ($flow->children as $child) {
$names += $this->liveBefore($child, $next, $context);
}
return $names;
}
if (!$flow instanceof VariableControlFlow) {
throw new ShouldNotHappenException();
}
if ($flow->kind === VariableFlow::LOOP_STATEMENT) {
// a binding reusing a variable that is read after the loop: the
// probe follows the variable backwards through the statement;
// surviving to its entry, it is armed to catch the assignment
// before the loop whose value the binding replaces
foreach ($flow->bindings as $binding) {
if (!isset($this->nameKeys[$binding->getVariableName()])) {
continue;
}
foreach (array_keys($this->nameKeys[$binding->getVariableName()]) as $key) {
if (!isset($next[$key])) {
continue;
}
$next[self::bindingProbe($binding, false)] = true;
break;
}
}
$names = $this->liveBefore($flow->children[0], $next, $context);
foreach ($flow->bindings as $binding) {
$probe = self::bindingProbe($binding, false);
if (!isset($names[$probe])) {
continue;
}
unset($names[$probe]);
$names[self::bindingProbe($binding, true)] = true;
}
return $names;
}
if ($flow->kind === VariableFlow::ARROW && $flow->arrow !== null) {
$outputs = $this->liveBefore($flow->children[1], [], new VariableFlowContext([]));
$names = $this->liveBefore($flow->children[0], $outputs, new VariableFlowContext($outputs, uncaught: $outputs));
foreach ($flow->arrow->params as $param) {
if (!$param->var instanceof Node\Expr\Variable || !is_string($param->var->name)) {
continue;
}
foreach (array_keys($this->nameKeys[$param->var->name] ?? []) as $key) {
unset($names[$key]);
}
}
return $next + $names;
}
if ($flow->kind === VariableFlow::LOOP) {
$head = [];
do {
$previousCount = count($head);
$update = $this->liveBefore($flow->children[2], $head, $context);
$loopContext = new VariableFlowContext($context->return, [$next, ...$context->breaks], [$update, ...$context->continues], $context->catches, $context->uncaught);
$body = $this->liveBefore($flow->children[1], $update, $loopContext);
$afterCondition = $flow->canRepeat ? ($flow->canExit ? $body + $next : $body) : $next;
$head = $this->liveBefore($flow->children[0], $afterCondition, $context);
} while (count($head) !== $previousCount);
return $flow->atLeastOnce ? $this->liveBefore($flow->children[0], $body, $context) : $head;
}
if ($flow->kind === VariableFlow::SWITCH) {
$switchContext = new VariableFlowContext($context->return, [$next, ...$context->breaks], [$next, ...$context->continues], $context->catches, $context->uncaught);
$entries = [];
$caseNext = $next;
$unmatched = $flow->canExit ? $next : [];
for ($i = count($flow->cases) - 1; $i >= 0; $i--) {
[, $body, $default] = $flow->cases[$i];
$caseNext = $this->liveBefore($body, $caseNext, $switchContext);
$entries[$i] = $caseNext;
if (!$default) {
continue;
}
$unmatched = $caseNext;
}
for ($i = count($flow->cases) - 1; $i >= 0; $i--) {
[$condition, , $default] = $flow->cases[$i];
if ($default) {
continue;
}
$unmatched = $this->liveBefore($condition, $entries[$i] + $unmatched, $context);
}
return $this->liveBefore($flow->children[0], $unmatched, $context);
}
if ($flow->kind === VariableFlow::RETURN) {
return $context->return;
}
if ($flow->kind === VariableFlow::BREAK) {
return $context->breaks[$flow->level - 1] ?? [];
}
if ($flow->kind === VariableFlow::CONTINUE) {
return $context->continues[$flow->level - 1] ?? [];
}
if ($flow->kind === VariableFlow::STOP) {
return [];
}
if ($flow->kind === VariableFlow::THROW) {
$names = $flow->canExit ? $next : [];
if ($context->catches === []) {
return $names + $context->uncaught;
}
if ($flow->type === null) {
throw new ShouldNotHappenException();
}
if ($flow->canContainAnyThrowable) {
foreach ($context->catches as [$catchType, $destination]) {
if (!$catchType->isSuperTypeOf(new ObjectType(Throwable::class))->yes()) {
continue;
}
$names += $destination;
break;
}
}
foreach ($context->catches as [$catchType, $destination]) {
$accepts = $catchType->isSuperTypeOf($flow->type);
if (!$accepts->no() || !$flow->type->isSuperTypeOf($catchType)->no()) {
$names += $destination;
}
if ($accepts->yes()) {
return $names;
}
}
return $names + $context->uncaught;
}
if ($flow->kind === VariableFlow::TRY_CATCH) {
$finally = $flow->children[1];
$normal = $this->liveBefore($finally, $next, $context);
$breaks = [];
foreach ($context->breaks as $destination) {
$breaks[] = $this->liveBefore($finally, $destination, $context);
}
$continues = [];
foreach ($context->continues as $destination) {
$continues[] = $this->liveBefore($finally, $destination, $context);
}
$outerCatches = [];
foreach ($context->catches as [$type, $destination]) {
$outerCatches[] = [$type, $this->liveBefore($finally, $destination, $context)];
}
$catchContext = new VariableFlowContext($this->liveBefore($finally, $context->return, $context), $breaks, $continues, $outerCatches, $this->liveBefore($finally, $context->uncaught, $context));
$catches = [];
foreach ($flow->catches as [$type, $catch]) {
$catches[] = [$type, $this->liveBefore($catch, $normal, $catchContext)];
}
return $this->liveBefore($flow->children[0], $normal, new VariableFlowContext($catchContext->return, $breaks, $continues, [...$catches, ...$outerCatches], $catchContext->uncaught));
}
if ($flow->kind === VariableFlow::READ_ALL) {
$this->readNames += $this->mentionedNames;
return $next + $this->allReadKeys;
}
return $next;
}
/**
* A probe travels in the live set under a key no read can produce. Armed
* once it has survived its loop statement, it records the assignment (or
* by-reference alias) before the loop whose variable the binding takes
* over; the loop's own writes let it through in either state.
*/
private static function bindingProbe(VariableWrite $binding, bool $armed): string
{
return sprintf("\0%s\0%d%s", $binding->getVariableName(), $binding->getId(), $armed ? "\0" : '');
}
/**
* @param array<string, true> $next
* @return array<string, true>
*/
private function passBindingProbes(array $next, string $name, ?VariableWrite $write, bool $discard = false): array
{
$prefix = sprintf("\0%s\0", $name);
foreach (array_keys($next) as $key) {
if (!str_starts_with($key, $prefix)) {
continue;
}
$id = substr($key, strlen($prefix));
$armed = str_ends_with($id, "\0");
$bindingId = (int) ($armed ? substr($id, 0, -1) : $id);
if ($write !== null && isset($this->ownWriteIds[$bindingId][$write->getId()])) {
continue;
}
if ($armed && !$discard) {
$this->variableOverwritingLoops[$bindingId] = $this->loopStatements[$bindingId];
}
if ($write === null || $write->isOffsetWrite()) {
// an alias or an offset write keeps the variable - the probe
// carries on to the assignment that created it
continue;
}
unset($next[$key]);
}
return $next;
}
/** @param int|string $offset */
private static function offsetKey($offset): string
{
return (is_int($offset) ? 'i:' : 's:') . $offset;
}
/** Compile each access once; loop iterations only union and remove its keys. */
private function compileAccesses(): void
{
foreach ($this->accesses as $name => $accesses) {
$slots = ['container' => true, 'unknown' => true];
foreach ($accesses as $access) {
$offset = $access->write !== null ? $access->write->getOffset() : $access->offset;
if ($offset === null) {
continue;
}
$slots[self::offsetKey($offset)] = true;
}
$keysBySlot = [];
foreach ($accesses as $access) {
if (!in_array($access->kind, [VariableFlow::READ, VariableFlow::ESCAPE], true)) {
continue;
}
if ($access->container) {
$selected = ['container' => true];
} elseif ($access->offset !== null) {
$selected = ['container' => true, self::offsetKey($access->offset) => true];
} else {
$selected = $slots;
}
foreach (array_keys($selected) as $slot) {
$key = $name . "\0" . $slot . "\0" . ($access->targetId ?? 0);
$keysBySlot[$slot][$key] = $access->targetId;
$this->readKeys[spl_object_id($access)][$key] = true;
$this->nameKeys[$name][$key] = true;
}
}
// A dynamic observation sees every offset, including ones never named by a read.
if ($this->readsAllVariables) {
foreach (array_keys($slots) as $slot) {
$key = $name . "\0" . $slot . "\0" . 0;
$keysBySlot[$slot][$key] = null;
$this->allReadKeys[$key] = true;
$this->nameKeys[$name][$key] = true;
}
}
foreach ($accesses as $access) {
$write = $access->write;
if ($write === null) {
continue;
}
$id = $write->getId();
$offset = $write->getOffset();
if ($write->isOffsetWrite() && $offset !== null) {
$slot = self::offsetKey($offset);
$selectedKeys = [$slot => $keysBySlot[$slot] ?? []];
} else {
$selectedKeys = $keysBySlot;
if ($write->isOffsetWrite()) {
unset($selectedKeys['container']);
}
}
$kills = !$write->isOffsetWrite() || ($offset !== null && $write->replacesOffset());
foreach ($selectedKeys as $keys) {
foreach ($keys as $key => $targetId) {
$this->observedKeys[$id][$key] = $targetId;
if (!$kills) {
continue;
}
$this->killedKeys[$id][$key] = true;
}
}
}
}
}
/** @param array<string, true> $next */
private function observeWrite(int $id, array $next): void
{
foreach ($this->observedKeys[$id] ?? [] as $key => $targetId) {
if (!isset($next[$key])) {
continue;
}
$this->observedIds[$id] = true;
if ($targetId === null) {
$this->readIds[$id] = true;
} else {
$this->dependencies[$targetId][$id] = true;
}
}
}
private function resolveDependencies(): void
{
$stack = [];
foreach (array_keys($this->readIds) as $id) {
$stack[] = [$id, false];
}
foreach (array_keys($this->inputSinks) as $id) {
$stack[] = [$id, true];
}
foreach ($this->writes as $id => $write) {
if (!isset($this->escapedNames[$write->getVariableName()])) {
continue;
}
// a write to an aliased variable is observable through the alias,
// so whatever flows into it is used; whether the write itself is
// read stays with the flow-sensitive capture read
$stack[] = [$id, false];
$stack[] = [$id, true];
}
$visited = [];
while ($stack !== []) {
[$id, $inputs] = array_pop($stack);
$key = $id . ($inputs ? ':inputs' : ':value');
if (isset($visited[$key])) {
continue;
}
$visited[$key] = true;
foreach (array_keys($this->dependencies[$id] ?? []) as $dependency) {
$this->readIds[$dependency] = true;
$stack[] = [$dependency, false];
}
foreach (array_keys($this->inputCopies[$id] ?? []) as $source) {
$stack[] = [$source, true];
}
if (!$inputs) {
continue;
}
foreach ($this->literalItems[$id] ?? [] as $item) {
$stack[] = [$item->getId(), true];
}
}
}
/**
* A write whose value flows only into unused writes is covered when one of
* them is never read at all: reporting that write already points at the
* dead chain. Walks the dependency edges backwards from every never-read
* write; a chain that only feeds itself (Psalm's `$b = $b + 1` loop) has
* no such write and stays uncovered.
*/
private function resolveCoverage(): void
{
$stack = [];
foreach (array_keys($this->writes) as $id) {
if (isset($this->observedIds[$id]) || isset($this->readIds[$id])) {
continue;
}
$stack[] = $id;
}
$visited = [];
while ($stack !== []) {
$id = array_pop($stack);
if (isset($visited[$id])) {
continue;
}
$visited[$id] = true;
$sources = array_keys($this->dependencies[$id] ?? []);
foreach (array_keys($this->inputCopies[$id] ?? []) as $copied) {
// the inputs of $copied flow into $id as well
$sources = [...$sources, ...array_keys($this->dependencies[$copied] ?? [])];
}
foreach ($sources as $source) {
$this->coveredIds[$source] = true;
$stack[] = $source;
}
}
}
}