Skip to content

Commit 10de21d

Browse files
ondrejmirtesclaude
andcommitted
Report array literal items replaced before being read as overwritten
"Offset 'x' of array assigned to variable $a is never read before being overwritten." (array.offsetOverwritten) when an offset write, or a write of the whole variable, replaces the item on some path before it is read. Re-assigning the same literal in a loop does not count. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Bm4YbtwnyY5UMgp64hK1ff
1 parent de2756d commit 10de21d

7 files changed

Lines changed: 116 additions & 34 deletions

File tree

‎src/Analyser/VariableLivenessResolver.php‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -258,15 +258,10 @@ private function liveBefore(?VariableFlow $flow, array $next, VariableFlowContex
258258
$id = $flow->write->getId();
259259
if ($flow->kind !== VariableFlow::DISCARD) {
260260
$this->observeWrite($id, $next);
261+
$this->observeOverwrite($id, $next);
261262
foreach ($this->literalItems[$id] ?? [] as $item) {
262263
$this->observeWrite($item->getId(), $next);
263-
}
264-
foreach (array_keys($this->overwriteKeys[$id] ?? []) as $key) {
265-
if (!isset($next[$key])) {
266-
continue;
267-
}
268-
$this->overwrittenIds[$id] = true;
269-
break;
264+
$this->observeOverwrite($item->getId(), $next);
270265
}
271266
}
272267
foreach (array_keys($this->killedKeys[$id] ?? []) as $key) {
@@ -607,8 +602,9 @@ private function compileOverwrites(string $name, array $accesses): void
607602
$observed += $markersBySlot[self::offsetKey($offset)] ?? [];
608603
}
609604
foreach ($observed as $marker => $writerId) {
610-
// a loop running the same write again replaces nothing it wrote
611-
if ($writerId === $id) {
605+
// a loop running the same write again replaces nothing it
606+
// wrote - nor the items of the array literal it assigns
607+
if ($writerId === $id || $writerId === $write->getParentId()) {
612608
continue;
613609
}
614610
$this->overwriteKeys[$id][$marker] = true;
@@ -658,6 +654,18 @@ private function observeWrite(int $id, array $next): void
658654
}
659655
}
660656

657+
/** @param array<string, true> $next */
658+
private function observeOverwrite(int $id, array $next): void
659+
{
660+
foreach (array_keys($this->overwriteKeys[$id] ?? []) as $key) {
661+
if (!isset($next[$key])) {
662+
continue;
663+
}
664+
$this->overwrittenIds[$id] = true;
665+
return;
666+
}
667+
}
668+
661669
private function resolveDependencies(): void
662670
{
663671
$stack = [];

‎src/Rules/DeadCode/UnusedVariableRule.php‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,13 +110,22 @@ public function processNode(Node $node, Scope $scope): array
110110
}
111111
$offset = $write->getOffset();
112112
$offsetType = is_int($offset) ? new ConstantIntegerType($offset) : new ConstantStringType($offset);
113+
if ($node->isRead($write)) {
114+
$outcome = 'only flows into values that are never used';
115+
$identifier = 'array.unusedOffsetFlow';
116+
} elseif ($node->isOverwritten($write)) {
117+
$outcome = 'is never read before being overwritten';
118+
$identifier = 'array.offsetOverwritten';
119+
} else {
120+
$outcome = 'is never read';
121+
$identifier = 'array.unusedOffset';
122+
}
113123
$message = sprintf(
114124
'Offset %s of array assigned to variable $%s %s.',
115125
$offsetType->describe(VerbosityLevel::value()),
116126
$name,
117-
$node->isRead($write) ? 'only flows into values that are never used' : 'is never read',
127+
$outcome,
118128
);
119-
$identifier = $node->isRead($write) ? 'array.unusedOffsetFlow' : 'array.unusedOffset';
120129
} elseif ($write->isOffsetWrite()) {
121130
$target = $write->getNode();
122131
if (!$target instanceof Node\Expr) {

‎tests/PHPStan/Rules/DeadCode/UnusedVariableRuleTest.php‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,7 @@ public function testOffsets(): void
335335
['Offset 1 of array assigned to variable $a is never read.', 50],
336336
['Offset 2 of array assigned to variable $a is never read.', 50],
337337
['Offset \'y\' of array assigned to variable $a is never read.', 58],
338-
['Offset \'x\' of array assigned to variable $a is never read.', 67],
338+
['Offset \'x\' of array assigned to variable $a is never read before being overwritten.', 67],
339339
['Offset \'y\' of array assigned to variable $a is never read.', 95],
340340
['Offset \'y\' of array assigned to variable $a is never read.', 103],
341341
['Offset \'z\' of array assigned to variable $a is never read.', 117],
@@ -353,7 +353,7 @@ public function testOffsets(): void
353353
['Value assigned to $a[$i] is never read.', 234],
354354
['Value assigned to $a[] is never read.', 247],
355355
['Value assigned to $a[\'x\'][\'y\'] is never read.', 260],
356-
['Offset \'x\' of array assigned to variable $a is never read.', 280],
356+
['Offset \'x\' of array assigned to variable $a is never read before being overwritten.', 280],
357357
['Value assigned to $a[\'x\'] is never read.', 295],
358358
['Value of $a[\'n\'] after ++ is never read.', 315],
359359
['Value assigned to $s[0] is never read.', 328],
@@ -437,6 +437,14 @@ public function testScopePollution(): void
437437
$this->analyse([__DIR__ . '/data/unused-variable-scope-pollution.php'], []);
438438
}
439439

440+
#[RequiresPhp('>= 8.0.0')]
441+
public function testBug15262(): void
442+
{
443+
$this->analyse([__DIR__ . '/data/bug-15262.php'], [
444+
['Offset \'success\' of array assigned to variable $result is never read before being overwritten.', 22],
445+
]);
446+
}
447+
440448
public function testUnsetCallsDestructor(): void
441449
{
442450
$this->analyse([__DIR__ . '/data/unused-variable-destructor.php'], [
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php // lint >= 8.0
2+
3+
declare(strict_types = 1);
4+
5+
namespace Bug15262;
6+
7+
use function PHPStan\dumpType;
8+
use function PHPStan\Testing\assertType;
9+
10+
class JsonResult {
11+
/** @param array<mixed> $arr */
12+
public function __construct(
13+
protected array $arr
14+
) {}
15+
}
16+
17+
class CoffeeBreak
18+
{
19+
public function foo(): JsonResult
20+
{
21+
$result = [
22+
'success' => false,
23+
];
24+
25+
$result['success'] = doBar();
26+
$result['worldid'] = 1;
27+
28+
return new JsonResult($result);
29+
}
30+
}
31+
32+
function doBar():mixed {
33+
return false;
34+
}

‎turbo-ext/src/VariableLivenessResolver.cpp‎

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -816,21 +816,14 @@ class VariableLivenessResolver
816816
zend_long id = view.id;
817817
if (kind != PT_VLR_DISCARD) {
818818
observeWrite(id, next);
819+
observeOverwrite(id, next);
819820
HashTable *items = innerTable(literalItems, id);
820821
if (items != NULL) {
821822
for (auto entry : zv::TableRef(items)) {
822823
zend_long itemId;
823824
if (UNEXPECTED(!writeId(entry.value().deref().raw(), itemId))) return zv::Val();
824825
observeWrite(itemId, next);
825-
}
826-
}
827-
HashTable *overwrites = innerTable(overwriteKeys, id);
828-
if (overwrites != NULL) {
829-
for (auto entry : zv::TableRef(overwrites)) {
830-
zend_string *key = entry.stringKeyOrNull();
831-
if (key == NULL || !isTrueAt(next, key)) continue;
832-
setTrueIndex(overwrittenIds, id);
833-
break;
826+
observeOverwrite(itemId, next);
834827
}
835828
}
836829
}
@@ -1462,10 +1455,10 @@ class VariableLivenessResolver
14621455
WriteView view;
14631456
if (UNEXPECTED(!view.load(write))) return false;
14641457
zend_long id = view.id;
1465-
observeOverwrites(id, innerTableByKey(markersBySlot, ZSTR_EMPTY_ALLOC()));
1458+
observeOverwrites(view, innerTableByKey(markersBySlot, ZSTR_EMPTY_ALLOC()));
14661459
if (view.offsetWrite && !view.offsetIsNull) {
14671460
zv::Str offsetSlot = offsetKey(view.offset.raw());
1468-
observeOverwrites(id, innerTableByKey(markersBySlot, offsetSlot.get()));
1461+
observeOverwrites(view, innerTableByKey(markersBySlot, offsetSlot.get()));
14691462
}
14701463
zv::Str slotName;
14711464
if (!replacedSlot(view, slotName)) continue;
@@ -1489,14 +1482,19 @@ class VariableLivenessResolver
14891482
return true;
14901483
}
14911484

1492-
/* The markers of $markers written by another write than $id. */
1493-
void observeOverwrites(zend_long id, HashTable *markers)
1485+
/* The markers of $markers written by another write than $write and the
1486+
* array literal it is an item of. */
1487+
void observeOverwrites(const WriteView &write, HashTable *markers)
14941488
{
14951489
if (markers == NULL) return;
1490+
zend_long id = write.id;
14961491
for (auto entry : zv::TableRef(markers)) {
14971492
zend_string *marker = entry.stringKeyOrNull();
1498-
// a loop running the same write again replaces nothing it wrote
1499-
if (marker == NULL || entry.value().deref().toLong() == id) continue;
1493+
if (marker == NULL) continue;
1494+
// a loop running the same write again replaces nothing it
1495+
// wrote - nor the items of the array literal it assigns
1496+
zend_long writerId = entry.value().deref().toLong();
1497+
if (writerId == id || (!write.parentIdIsNull && writerId == write.parentId)) continue;
15001498
zval *observed = innerSlot(overwriteKeys, id);
15011499
zval trueValue;
15021500
ZVAL_TRUE(&trueValue);
@@ -1516,6 +1514,19 @@ class VariableLivenessResolver
15161514
return true;
15171515
}
15181516

1517+
/* Mirrors observeOverwrite(). */
1518+
void observeOverwrite(zend_long id, const zv::Val &next)
1519+
{
1520+
HashTable *overwrites = innerTable(overwriteKeys, id);
1521+
if (overwrites == NULL) return;
1522+
for (auto entry : zv::TableRef(overwrites)) {
1523+
zend_string *key = entry.stringKeyOrNull();
1524+
if (key == NULL || !isTrueAt(next, key)) continue;
1525+
setTrueIndex(overwrittenIds, id);
1526+
return;
1527+
}
1528+
}
1529+
15191530
/* Mirrors observeWrite(). */
15201531
void observeWrite(zend_long id, const zv::Val &next)
15211532
{

‎turbo-ext/src/generated/VariableLivenessResolver.h‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,8 +111,9 @@ inline constexpr char strings[] =
111111
"replacedSlot\0" /* 360 */
112112
"id\0" /* 373 */
113113
"observeWrite\0" /* 376 */
114-
"resolveDependencies\0" /* 389 */
115-
"resolveCoverage"; /* 409 */
114+
"observeOverwrite\0" /* 389 */
115+
"resolveDependencies\0" /* 406 */
116+
"resolveCoverage"; /* 426 */
116117
inline constexpr reg::PackedArg args[] = {
117118
reg::packed(12, 0, 21), /* resolve $function */
118119
reg::packed(49, MAY_BE_NULL, 54), /* resolve $flow */
@@ -142,6 +143,9 @@ inline constexpr reg::PackedArg args[] = {
142143
reg::packed(373, MAY_BE_LONG), /* observeWrite $id */
143144
reg::packed(133, MAY_BE_ARRAY), /* observeWrite $next */
144145
reg::packed(84, MAY_BE_VOID), /* observeWrite return */
146+
reg::packed(373, MAY_BE_LONG), /* observeOverwrite $id */
147+
reg::packed(133, MAY_BE_ARRAY), /* observeOverwrite $next */
148+
reg::packed(84, MAY_BE_VOID), /* observeOverwrite return */
145149
reg::packed(84, MAY_BE_VOID), /* resolveDependencies return */
146150
reg::packed(84, MAY_BE_VOID), /* resolveCoverage return */
147151
};
@@ -161,8 +165,9 @@ inline constexpr sigtab::Sig compileAccesses = { { 317 /* compileAccesses */, 0,
161165
inline constexpr sigtab::Sig compileOverwrites = { { 342 /* compileOverwrites */, 2, 20, 2, 22, ZEND_ACC_PRIVATE } };
162166
inline constexpr sigtab::Sig replacedSlot = { { 360 /* replacedSlot */, 1, 23, 1, 24, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } };
163167
inline constexpr sigtab::Sig observeWrite = { { 376 /* observeWrite */, 2, 25, 2, 27, ZEND_ACC_PRIVATE } };
164-
inline constexpr sigtab::Sig resolveDependencies = { { 389 /* resolveDependencies */, 0, 28, 0, 28, ZEND_ACC_PRIVATE } };
165-
inline constexpr sigtab::Sig resolveCoverage = { { 409 /* resolveCoverage */, 0, 29, 0, 29, ZEND_ACC_PRIVATE } };
168+
inline constexpr sigtab::Sig observeOverwrite = { { 389 /* observeOverwrite */, 2, 28, 2, 30, ZEND_ACC_PRIVATE } };
169+
inline constexpr sigtab::Sig resolveDependencies = { { 406 /* resolveDependencies */, 0, 31, 0, 31, ZEND_ACC_PRIVATE } };
170+
inline constexpr sigtab::Sig resolveCoverage = { { 426 /* resolveCoverage */, 0, 32, 0, 32, ZEND_ACC_PRIVATE } };
166171
} // namespace sig
167172

168173
} // namespace ptdecl::VariableLivenessResolver

‎turbo-ext/tests/smoke.php‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3196,6 +3196,12 @@ public function isFirstClassCallable(): bool
31963196
$vlrF::read('c'),
31973197
$vlrF::write($vlrWrite('r', 14)),
31983198
$vlrF::arrow($vlrArrow, $vlrF::write($vlrWrite('r', 15)), null),
3199+
$vlrF::write($vlrWrite('lit', 17)),
3200+
$vlrF::write($vlrWrite('lit', 18, \PHPStan\Node\Variable\VariableWrite::KIND_ARRAY_LITERAL_ITEM, true, 'k', 17)),
3201+
$vlrF::write($vlrWrite('lit', 19, \PHPStan\Node\Variable\VariableWrite::KIND_ARRAY_DIM_WRITE, true, 'k')),
3202+
$vlrF::read('lit'),
3203+
$vlrF::loop(null, $vlrF::sequence($vlrF::write($vlrWrite('lp', 20)), $vlrF::write($vlrWrite('lp', 21, \PHPStan\Node\Variable\VariableWrite::KIND_ARRAY_LITERAL_ITEM, true, 'k', 20))), null, false, true),
3204+
$vlrF::read('lp', null, false, 'j'),
31993205
),
32003206
'read all' => $vlrF::sequence($vlrF::write($vlrWrite('a', 1)), $vlrF::write($vlrWrite('o', 2, \PHPStan\Node\Variable\VariableWrite::KIND_ARRAY_DIM_WRITE, true, 'k')), $vlrF::all($vlrF::READ_ALL), $vlrF::write($vlrWrite('b', 3)), $vlrF::mention('c')),
32013207
'mention all' => $vlrF::sequence($vlrF::write($vlrWrite('a', 1)), $vlrF::all($vlrF::MENTION_ALL)),
@@ -3250,10 +3256,11 @@ public function isFirstClassCallable(): bool
32503256
}
32513257
// the fixture's own writes (ids below 100): whole, same-offset, dynamic and
32523258
// nested offsets and one-path overwrites; not across unset(), not by the
3253-
// same write in a loop, not by an arrow function's write
3259+
// same write in a loop, not by an arrow function's write; an array literal's
3260+
// item replaced by an offset write, but not by its own literal in a loop
32543261
$vlrOverwritten = array_values(array_filter(array_keys($vlrResults['php']['function / overwrites']['overwrittenWriteIds']), static fn (int $id): bool => $id < 100));
32553262
sort($vlrOverwritten);
3256-
check($vlrOverwritten === [1, 3, 4, 5, 6, 7, 13], 'VariableLivenessResolver: overwrite markers ' . json_encode($vlrOverwritten));
3263+
check($vlrOverwritten === [1, 3, 4, 5, 6, 7, 13, 18], 'VariableLivenessResolver: overwrite markers ' . json_encode($vlrOverwritten));
32573264
check(count($vlrResults['php']['function / loops']['variableOverwritingLoops']) === 2 && $vlrResults['php']['function / read all']['readVariableNames'] !== [], 'VariableLivenessResolver: the fixture exercises binding probes and READ_ALL');
32583265

32593266
// ---- MutatingScope ----

0 commit comments

Comments
 (0)