Skip to content

Commit bdf33d3

Browse files
ondrejmirtesclaude
andcommitted
UnusedVariableRule: report values replaced before being read as overwritten
"Value assigned to variable $x is never read before being overwritten." (assign.overwritten, preInc/postInc/preDec/postDec.overwritten, foreach.valueOverwritten, foreach.keyOverwritten) when some path from the write reaches another write replacing the variable, or the written offset, and "is never read" when the value just goes out of scope. VariableLivenessResolver leaves a marker in the live set for each replacing write; the previous replacing write of the same slot kills it, and a write that finds another write's marker after it is overwritten. The same write running again in a loop does not count, and markers of writes inside arrow functions do not leave them. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Bm4YbtwnyY5UMgp64hK1ff
1 parent e7925a2 commit bdf33d3

8 files changed

Lines changed: 492 additions & 62 deletions

File tree

‎src/Analyser/VariableLivenessResolver.php‎

Lines changed: 102 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,15 @@ final class VariableLivenessResolver
8383
/** @var array<int, true> */
8484
private array $coveredIds = [];
8585

86+
/** @var array<int, string> */
87+
private array $overwriteMarkers = [];
88+
89+
/** @var array<int, array<string, true>> */
90+
private array $overwriteKeys = [];
91+
92+
/** @var array<int, true> */
93+
private array $overwrittenIds = [];
94+
8695
/** @var array<string, true> */
8796
private array $allReadKeys = [];
8897

@@ -143,7 +152,7 @@ public static function resolve(Node\FunctionLike $function, ?VariableFlow $flow)
143152
$self->resolveCoverage();
144153
}
145154

146-
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);
155+
return new VariableWritesNode($function, array_values($self->writes), $self->observedIds + $self->readIds, $self->readIds, $self->coveredIds, $self->overwrittenIds, $self->readNames, $self->redundantTypes, $self->mentionedNames, $self->escapedNames, $self->variableOverwritingLoops, $self->opaque, $self->allNamesMentioned);
147156
}
148157

149158
private function collect(?VariableFlow $flow, bool $dead = false): void
@@ -255,10 +264,20 @@ private function liveBefore(?VariableFlow $flow, array $next, VariableFlowContex
255264
foreach ($this->literalItems[$id] ?? [] as $item) {
256265
$this->observeWrite($item->getId(), $next);
257266
}
267+
foreach (array_keys($this->overwriteKeys[$id] ?? []) as $key) {
268+
if (!isset($next[$key])) {
269+
continue;
270+
}
271+
$this->overwrittenIds[$id] = true;
272+
break;
273+
}
258274
}
259275
foreach (array_keys($this->killedKeys[$id] ?? []) as $key) {
260276
unset($next[$key]);
261277
}
278+
if (isset($this->overwriteMarkers[$id])) {
279+
$next[$this->overwriteMarkers[$id]] = true;
280+
}
262281
return $next;
263282
}
264283
if ($flow instanceof VariableSequenceFlow) {
@@ -316,6 +335,13 @@ private function liveBefore(?VariableFlow $flow, array $next, VariableFlowContex
316335
unset($names[$key]);
317336
}
318337
}
338+
// the arrow function's own writes replace nothing outside of it
339+
foreach (array_keys($names) as $key) {
340+
if (!str_starts_with($key, "\1")) {
341+
continue;
342+
}
343+
unset($names[$key]);
344+
}
319345
return $next + $names;
320346
}
321347
if ($flow->kind === VariableFlow::LOOP) {
@@ -541,9 +567,84 @@ private function compileAccesses(): void
541567
}
542568
}
543569
}
570+
$this->compileOverwrites($name, $accesses);
544571
}
545572
}
546573

574+
/**
575+
* A write replacing the variable, or one of its offsets, leaves a marker in
576+
* the live set that the previous replacing write of the same slot kills: a
577+
* write finding another write's marker after it reaches that replacement
578+
* on some path, with no replacement in between.
579+
*
580+
* @param list<VariableAccessFlow> $accesses
581+
*/
582+
private function compileOverwrites(string $name, array $accesses): void
583+
{
584+
$markersBySlot = [];
585+
foreach ($accesses as $markingAccess) {
586+
if ($markingAccess->write === null || $markingAccess->kind !== VariableFlow::WRITE) {
587+
continue;
588+
}
589+
$slot = self::replacedSlot($markingAccess->write);
590+
if ($slot === null) {
591+
continue;
592+
}
593+
$id = $markingAccess->write->getId();
594+
$marker = "\1" . $name . "\0" . $slot . "\0" . $id;
595+
$markersBySlot[$slot][$marker] = $id;
596+
$this->overwriteMarkers[$id] = $marker;
597+
}
598+
if ($markersBySlot === []) {
599+
return;
600+
}
601+
foreach ($accesses as $access) {
602+
$write = $access->write;
603+
if ($write === null) {
604+
continue;
605+
}
606+
$id = $write->getId();
607+
$offset = $write->getOffset();
608+
$observed = $markersBySlot[''] ?? [];
609+
if ($write->isOffsetWrite() && $offset !== null) {
610+
$observed += $markersBySlot[self::offsetKey($offset)] ?? [];
611+
}
612+
foreach ($observed as $marker => $writerId) {
613+
// a loop running the same write again replaces nothing it wrote
614+
if ($writerId === $id) {
615+
continue;
616+
}
617+
$this->overwriteKeys[$id][$marker] = true;
618+
}
619+
$slot = self::replacedSlot($write);
620+
if ($slot === null) {
621+
continue;
622+
}
623+
foreach ($markersBySlot as $markerSlot => $markers) {
624+
if ($slot !== '' && $markerSlot !== $slot) {
625+
continue;
626+
}
627+
foreach (array_keys($markers) as $marker) {
628+
$this->killedKeys[$id][$marker] = true;
629+
}
630+
}
631+
}
632+
}
633+
634+
/** The slot a write replaces: '' for the whole variable, null when it keeps the old value. */
635+
private static function replacedSlot(VariableWrite $write): ?string
636+
{
637+
if (!$write->isOffsetWrite()) {
638+
return '';
639+
}
640+
$offset = $write->getOffset();
641+
if ($offset === null || !$write->replacesOffset()) {
642+
return null;
643+
}
644+
645+
return self::offsetKey($offset);
646+
}
647+
547648
/** @param array<string, true> $next */
548649
private function observeWrite(int $id, array $next): void
549650
{

‎src/Node/VariableWritesNode.php‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ final class VariableWritesNode extends NodeAbstract implements VirtualNode
3131
* @param array<int, true> $readWriteIds
3232
* @param array<int, true> $usedWriteIds
3333
* @param array<int, true> $coveredWriteIds
34+
* @param array<int, true> $overwrittenWriteIds
3435
* @param array<string, true> $readVariableNames
3536
* @param array<int, Type> $redundantWriteTypes
3637
* @param array<string, true> $referencedVariableNames
@@ -43,6 +44,7 @@ public function __construct(
4344
private array $readWriteIds,
4445
private array $usedWriteIds,
4546
private array $coveredWriteIds,
47+
private array $overwrittenWriteIds,
4648
private array $readVariableNames,
4749
private array $redundantWriteTypes,
4850
private array $referencedVariableNames,
@@ -107,6 +109,16 @@ public function flowsIntoNeverReadWrite(VariableWrite $write): bool
107109
return isset($this->coveredWriteIds[$write->getId()]);
108110
}
109111

112+
/**
113+
* Whether some path from the write reaches another write replacing the
114+
* variable (or the written offset) - for a write that is never read, the
115+
* value is replaced before anything looks at it.
116+
*/
117+
public function isOverwritten(VariableWrite $write): bool
118+
{
119+
return isset($this->overwrittenWriteIds[$write->getId()]);
120+
}
121+
110122
/** Whether some path from the write reaches a read of the written value. */
111123
public function isRead(VariableWrite $write): bool
112124
{

‎src/Rules/DeadCode/UnusedVariableRule.php‎

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -122,11 +122,11 @@ public function processNode(Node $node, Scope $scope): array
122122
if (!$target instanceof Node\Expr) {
123123
throw new ShouldNotHappenException();
124124
}
125-
$message = $this->getMessage($write->getKind(), $this->exprPrinter->printExpr($target), false, $node->isRead($write));
126-
$identifier = $this->getIdentifier($write->getKind(), false, $node->isRead($write));
125+
$message = $this->getMessage($write->getKind(), $this->exprPrinter->printExpr($target), false, $node->isRead($write), $node->isOverwritten($write));
126+
$identifier = $this->getIdentifier($write->getKind(), false, $node->isRead($write), $node->isOverwritten($write));
127127
} else {
128-
$message = $this->getMessage($write->getKind(), 'variable $' . $name, $unusedVariable, $node->isRead($write));
129-
$identifier = $this->getIdentifier($write->getKind(), $unusedVariable, $node->isRead($write));
128+
$message = $this->getMessage($write->getKind(), 'variable $' . $name, $unusedVariable, $node->isRead($write), $node->isOverwritten($write));
129+
$identifier = $this->getIdentifier($write->getKind(), $unusedVariable, $node->isRead($write), $node->isOverwritten($write));
130130
}
131131
$errors[] = RuleErrorBuilder::message($message)
132132
->identifier($identifier)
@@ -140,12 +140,19 @@ public function processNode(Node $node, Scope $scope): array
140140
/**
141141
* @param VariableWrite::KIND_* $kind
142142
*/
143-
private function getMessage(int $kind, string $target, bool $unusedVariable, bool $read): string
143+
private function getMessage(int $kind, string $target, bool $unusedVariable, bool $read, bool $overwritten): string
144144
{
145-
// "never read": nothing looks at the written value; "only flows into
145+
// "never read": nothing looks at the written value; "before being
146+
// overwritten": another write replaces it first; "only flows into
146147
// values that are never used": something reads it, but only to compute
147148
// values that never reach a sink themselves
148-
$outcome = $read ? 'only flows into values that are never used' : 'is never read';
149+
if ($read) {
150+
$outcome = 'only flows into values that are never used';
151+
} elseif ($overwritten) {
152+
$outcome = 'is never read before being overwritten';
153+
} else {
154+
$outcome = 'is never read';
155+
}
149156
switch ($kind) {
150157
case VariableWrite::KIND_ASSIGN:
151158
case VariableWrite::KIND_READ_MODIFY_WRITE:
@@ -176,9 +183,9 @@ private function getMessage(int $kind, string $target, bool $unusedVariable, boo
176183

177184
/**
178185
* @param VariableWrite::KIND_* $kind
179-
* @return 'variable.unused'|'assign.unused'|'assign.unusedFlow'|'preInc.unused'|'preInc.unusedFlow'|'postInc.unused'|'postInc.unusedFlow'|'preDec.unused'|'preDec.unusedFlow'|'postDec.unused'|'postDec.unusedFlow'|'foreach.unusedValue'|'foreach.unusedValueFlow'|'foreach.unusedKey'|'foreach.unusedKeyFlow'|'catch.unusedVariableFlow'
186+
* @return 'variable.unused'|'assign.unused'|'assign.overwritten'|'assign.unusedFlow'|'preInc.unused'|'preInc.overwritten'|'preInc.unusedFlow'|'postInc.unused'|'postInc.overwritten'|'postInc.unusedFlow'|'preDec.unused'|'preDec.overwritten'|'preDec.unusedFlow'|'postDec.unused'|'postDec.overwritten'|'postDec.unusedFlow'|'foreach.unusedValue'|'foreach.valueOverwritten'|'foreach.unusedValueFlow'|'foreach.unusedKey'|'foreach.keyOverwritten'|'foreach.unusedKeyFlow'|'catch.unusedVariableFlow'
180187
*/
181-
private function getIdentifier(int $kind, bool $unusedVariable, bool $read): string
188+
private function getIdentifier(int $kind, bool $unusedVariable, bool $read, bool $overwritten): string
182189
{
183190
switch ($kind) {
184191
case VariableWrite::KIND_ASSIGN:
@@ -189,25 +196,25 @@ private function getIdentifier(int $kind, bool $unusedVariable, bool $read): str
189196
return 'variable.unused';
190197
}
191198

192-
return $read ? 'assign.unusedFlow' : 'assign.unused';
199+
return $read ? 'assign.unusedFlow' : ($overwritten ? 'assign.overwritten' : 'assign.unused');
193200
case VariableWrite::KIND_PRE_INC:
194-
return $read ? 'preInc.unusedFlow' : 'preInc.unused';
201+
return $read ? 'preInc.unusedFlow' : ($overwritten ? 'preInc.overwritten' : 'preInc.unused');
195202
case VariableWrite::KIND_POST_INC:
196-
return $read ? 'postInc.unusedFlow' : 'postInc.unused';
203+
return $read ? 'postInc.unusedFlow' : ($overwritten ? 'postInc.overwritten' : 'postInc.unused');
197204
case VariableWrite::KIND_PRE_DEC:
198-
return $read ? 'preDec.unusedFlow' : 'preDec.unused';
205+
return $read ? 'preDec.unusedFlow' : ($overwritten ? 'preDec.overwritten' : 'preDec.unused');
199206
case VariableWrite::KIND_POST_DEC:
200-
return $read ? 'postDec.unusedFlow' : 'postDec.unused';
207+
return $read ? 'postDec.unusedFlow' : ($overwritten ? 'postDec.overwritten' : 'postDec.unused');
201208
case VariableWrite::KIND_FOREACH_VALUE:
202-
return $read ? 'foreach.unusedValueFlow' : 'foreach.unusedValue';
209+
return $read ? 'foreach.unusedValueFlow' : ($overwritten ? 'foreach.valueOverwritten' : 'foreach.unusedValue');
203210
case VariableWrite::KIND_FOREACH_VALUE_WITH_KEY:
204211
if (!$read) {
205212
throw new ShouldNotHappenException();
206213
}
207214

208215
return 'foreach.unusedValueFlow';
209216
case VariableWrite::KIND_FOREACH_KEY:
210-
return $read ? 'foreach.unusedKeyFlow' : 'foreach.unusedKey';
217+
return $read ? 'foreach.unusedKeyFlow' : ($overwritten ? 'foreach.keyOverwritten' : 'foreach.unusedKey');
211218
case VariableWrite::KIND_CATCH:
212219
if (!$read) {
213220
throw new ShouldNotHappenException();

0 commit comments

Comments
 (0)