Skip to content

Commit 3126e8f

Browse files
committed
Count a property bound by reference as read when the other side can read it
A private property bound by reference - a by-ref promoted parameter, $this->prop = &$var, $this->prop['k'] = &$var, self::$prop = &$var - was only written, so it was reported as never read although whatever is written to it can be read through the variable it is bound to. PropertyWrite::isByReference() marks these writes, and UnusedPrivatePropertyRule counts them as reads. No PropertyRead is recorded, so the uninitialized-property checks see no read before the assignment. A binding to a local variable of a method waits for the method's VariableWritesNode and counts only when the method also reads the variable or lets it escape apart from the binding, or the variable is a by-ref or promoted parameter: a binding to a throwaway local is still reported. VariableWritesNode::getObservingAccessCount() gives the number of read and escape sites per variable for that. Closes phpstan/phpstan#15886 Closes phpstan/phpstan#10068 Amp-Thread-ID: https://ampcode.com/threads/T-01a22bbf-fbea-7343-93fe-fd2c23d22096
1 parent 217459a commit 3126e8f

20 files changed

Lines changed: 1073 additions & 19 deletions

‎src/Analyser/VariableLivenessResolver.php‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,17 @@ public static function resolve(Node\FunctionLike $function, ?VariableFlow $flow)
161161
$self->resolveCoverage();
162162
}
163163

164-
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);
164+
$observingAccessCounts = [];
165+
foreach ($self->accesses as $name => $accesses) {
166+
foreach ($accesses as $access) {
167+
if (!in_array($access->kind, [VariableFlow::READ, VariableFlow::ESCAPE], true)) {
168+
continue;
169+
}
170+
$observingAccessCounts[$name] = ($observingAccessCounts[$name] ?? 0) + 1;
171+
}
172+
}
173+
174+
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, $observingAccessCounts);
165175
}
166176

167177
private function collect(?VariableFlow $flow): void

‎src/Node/ClassStatementsGatherer.php‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,11 @@
2525
use PHPStan\Turbo\ShadowedByTurboExtension;
2626
use PHPStan\Type\TypeUtils;
2727
use ReflectionProperty;
28+
use function array_key_exists;
2829
use function count;
2930
use function in_array;
3031
use function is_string;
32+
use function spl_object_id;
3133
use function strtolower;
3234

3335
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/ClassStatementsGatherer.cpp')]
@@ -66,6 +68,9 @@ final class ClassStatementsGatherer
6668
/** @var list<PropertyAssign> */
6769
private array $propertyAssigns = [];
6870

71+
/** @var array<string, array<int, array{string, PropertyWrite}>> lowercase method name => AssignRef object id => bound variable name and by-reference write */
72+
private array $referenceBindings = [];
73+
6974
/**
7075
* @param callable(Node $node, Scope $scope): void $nodeCallback
7176
*/
@@ -220,6 +225,10 @@ private function gatherNodes(Node $node, Scope $scope): void
220225
$this->propertyAssigns[] = new PropertyAssign($node, $scope);
221226
return;
222227
}
228+
if ($node instanceof VariableWritesNode) {
229+
$this->resolveReferenceBindings($node, $scope);
230+
return;
231+
}
223232
if (!$node instanceof Expr) {
224233
return;
225234
}
@@ -228,6 +237,25 @@ private function gatherNodes(Node $node, Scope $scope): void
228237
return;
229238
}
230239
if ($node instanceof Expr\AssignRef) {
240+
$boundVar = $node->var;
241+
while ($boundVar instanceof ArrayDimFetch) {
242+
$boundVar = $boundVar->var;
243+
}
244+
if ($boundVar instanceof PropertyFetch || $boundVar instanceof StaticPropertyFetch) {
245+
$write = new PropertyWrite($boundVar, $scope, false, $node);
246+
$function = $scope->getFunction();
247+
if (
248+
$node->expr instanceof Expr\Variable
249+
&& is_string($node->expr->name)
250+
&& $function !== null
251+
&& !$scope->isInAnonymousFunction()
252+
) {
253+
// whether the local is read through elsewhere is known once the method's VariableWritesNode arrives
254+
$this->referenceBindings[strtolower($function->getName())][spl_object_id($node)] = [$node->expr->name, $write];
255+
} else {
256+
$this->propertyUsages[] = $write;
257+
}
258+
}
231259
if (!$node->expr instanceof PropertyFetch && !$node->expr instanceof StaticPropertyFetch) {
232260
$this->gatherNodes($node->expr, $scope);
233261
return;
@@ -262,6 +290,58 @@ private function gatherNodes(Node $node, Scope $scope): void
262290
$this->propertyUsages[] = new PropertyRead($node, $scope);
263291
}
264292

293+
/**
294+
* A property bound by reference to a local variable ($this->prop = &$local) is read
295+
* through that variable only when the method uses the variable apart from the binding:
296+
* reads it, passes it on, or shares it as a by-ref parameter, global or static.
297+
*/
298+
private function resolveReferenceBindings(VariableWritesNode $node, Scope $scope): void
299+
{
300+
if ($this->referenceBindings === [] || $scope->isInAnonymousFunction()) {
301+
return;
302+
}
303+
$function = $scope->getFunction();
304+
if ($function === null) {
305+
return;
306+
}
307+
$methodKey = strtolower($function->getName());
308+
if (!array_key_exists($methodKey, $this->referenceBindings)) {
309+
return;
310+
}
311+
$bindings = $this->referenceBindings[$methodKey];
312+
unset($this->referenceBindings[$methodKey]);
313+
314+
$sharedVariableNames = [];
315+
foreach ($node->getFunctionLike()->getParams() as $param) {
316+
if (!$param->byRef && $param->flags === 0) {
317+
continue;
318+
}
319+
if (!$param->var instanceof Expr\Variable || !is_string($param->var->name)) {
320+
continue;
321+
}
322+
$sharedVariableNames[$param->var->name] = true;
323+
}
324+
325+
$bindingCounts = [];
326+
foreach ($bindings as [$variableName]) {
327+
$bindingCounts[$variableName] = ($bindingCounts[$variableName] ?? 0) + 1;
328+
}
329+
330+
foreach ($bindings as [$variableName, $write]) {
331+
if (
332+
!array_key_exists($variableName, $sharedVariableNames)
333+
&& !$node->areAllVariableNamesReferenced()
334+
&& !$node->isOpaque()
335+
// each binding itself reads the variable and lets it escape once
336+
&& $node->getObservingAccessCount($variableName) <= 2 * $bindingCounts[$variableName]
337+
) {
338+
continue;
339+
}
340+
341+
$this->propertyUsages[] = $write;
342+
}
343+
}
344+
265345
private function tryToApplyPropertyReads(Expr\FuncCall $node, Scope $scope): void
266346
{
267347
$args = $node->getArgs();

‎src/Node/Property/PropertyWrite.php‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use PhpParser\Node\Expr\AssignRef;
66
use PhpParser\Node\Expr\PropertyFetch;
77
use PhpParser\Node\Expr\StaticPropertyFetch;
8+
use PhpParser\Node\Param;
89
use PHPStan\Analyser\Scope;
910
use PHPStan\Node\ClassPropertyNode;
1011
use PHPStan\Node\PropertyAssignNode;
@@ -44,6 +45,26 @@ public function isPromotedPropertyWrite(): bool
4445
return $this->promotedPropertyWrite;
4546
}
4647

48+
/**
49+
* Whether the write binds the property to a reference ($this->prop = &$var,
50+
* $var = &$this->prop, a by-ref promoted parameter), so what is later
51+
* written to the property can be read through the other side.
52+
*/
53+
public function isByReference(): bool
54+
{
55+
if ($this->originalNode instanceof AssignRef) {
56+
return true;
57+
}
58+
59+
if (!$this->originalNode instanceof ClassPropertyNode) {
60+
return false;
61+
}
62+
63+
$propertyNode = $this->originalNode->getOriginalNode();
64+
65+
return $propertyNode instanceof Param && $propertyNode->byRef;
66+
}
67+
4768
/**
4869
* Whether the write happens through offset access ($this->prop[...] = ...)
4970
* on an ArrayAccess object, which goes through offsetSet() rather than

‎src/Node/VariableWritesNode.php‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ final class VariableWritesNode extends NodeAbstract implements VirtualNode
3737
* @param array<string, true> $referencedVariableNames
3838
* @param array<string, true> $untrackedVariableNames
3939
* @param array<int, Foreach_|For_> $variableOverwritingLoops
40+
* @param array<string, int> $observingAccessCounts
4041
*/
4142
public function __construct(
4243
private Node\FunctionLike $functionLike,
@@ -52,6 +53,7 @@ public function __construct(
5253
private array $variableOverwritingLoops,
5354
private bool $opaque,
5455
private bool $allVariableNamesReferenced,
56+
private array $observingAccessCounts = [],
5557
)
5658
{
5759
parent::__construct($functionLike->getAttributes());
@@ -134,6 +136,16 @@ public function isVariableEverRead(string $variableName): bool
134136
return isset($this->readVariableNames[$variableName]);
135137
}
136138

139+
/**
140+
* How many sites in the body read the variable or let it escape (pass it
141+
* by reference, bind a reference to it, capture it by reference, declare
142+
* it global or static).
143+
*/
144+
public function getObservingAccessCount(string $variableName): int
145+
{
146+
return $this->observingAccessCounts[$variableName] ?? 0;
147+
}
148+
137149
/**
138150
* The type of the assigned value when the write assigns the value the
139151
* variable provably already has, null otherwise.

‎src/Rules/DeadCode/UnusedPrivatePropertyRule.php‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,10 @@ public function processNode(Node $node, Scope $scope): array
247247
}
248248
} else {
249249
$properties[$propertyName]['written'] = true;
250+
if ($usage->isByReference()) {
251+
$properties[$propertyName]['read'] = true;
252+
$properties[$propertyName]['hasTrueRead'] = true;
253+
}
250254
}
251255
}
252256
}

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

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -516,4 +516,112 @@ public function testBug12201(): void
516516
]);
517517
}
518518

519+
public function testBug15886(): void
520+
{
521+
$this->alwaysWrittenTags = [];
522+
$this->alwaysReadTags = [];
523+
524+
$this->analyse([__DIR__ . '/data/bug-15886.php'], [
525+
[
526+
'Property Bug15886\OnlyWritten::$log is never read, only written.',
527+
54,
528+
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
529+
],
530+
]);
531+
}
532+
533+
#[RequiresPhp('>= 8.0.0')]
534+
public function testBug15886Promoted(): void
535+
{
536+
$this->alwaysWrittenTags = [];
537+
$this->alwaysReadTags = [];
538+
539+
$this->analyse([__DIR__ . '/data/bug-15886-promoted.php'], []);
540+
}
541+
542+
public function testBug15886Static(): void
543+
{
544+
$this->alwaysWrittenTags = [];
545+
$this->alwaysReadTags = [];
546+
547+
$this->analyse([__DIR__ . '/data/bug-15886-static.php'], []);
548+
}
549+
550+
public function testBug15886Local(): void
551+
{
552+
$this->alwaysWrittenTags = [];
553+
$this->alwaysReadTags = [];
554+
555+
$this->analyse([__DIR__ . '/data/bug-15886-local.php'], [
556+
[
557+
'Property Bug15886Local\ThrowawayLocal::$cache is never read, only written.',
558+
9,
559+
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
560+
],
561+
[
562+
'Property Bug15886Local\ByValueParameter::$cache is never read, only written.',
563+
28,
564+
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
565+
],
566+
[
567+
'Static property Bug15886Local\StaticPropertyThrowawayLocal::$cache is never read, only written.',
568+
173,
569+
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
570+
],
571+
]);
572+
}
573+
574+
public function testBug15886ArrayOffset(): void
575+
{
576+
$this->alwaysWrittenTags = [];
577+
$this->alwaysReadTags = [];
578+
579+
$this->analyse([__DIR__ . '/data/bug-15886-array-offset.php'], [
580+
[
581+
'Property Bug15886ArrayOffset\ArrayOffsetThrowawayLocal::$counters is never read, only written.',
582+
56,
583+
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
584+
],
585+
]);
586+
}
587+
588+
#[RequiresPhp('>= 8.0.0')]
589+
public function testBug15886Review(): void
590+
{
591+
$this->alwaysWrittenTags = [];
592+
$this->alwaysReadTags = [];
593+
594+
$this->analyse([__DIR__ . '/data/bug-15886-review.php'], [
595+
[
596+
'Property Bug15886Review\TwoBindingsOfThrowawayLocal::$first is never read, only written.',
597+
75,
598+
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
599+
],
600+
[
601+
'Property Bug15886Review\TwoBindingsOfThrowawayLocal::$second is never read, only written.',
602+
78,
603+
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
604+
],
605+
[
606+
'Property Bug15886Review\PromotedByValueNeverRead::$spy is never read, only written.',
607+
99,
608+
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
609+
],
610+
]);
611+
}
612+
613+
public function testBug10068(): void
614+
{
615+
$this->alwaysWrittenTags = [];
616+
$this->alwaysReadTags = [];
617+
618+
$this->analyse([__DIR__ . '/data/bug-10068.php'], [
619+
[
620+
'Property Bug10068\Bar::$spy is never read, only written.',
621+
21,
622+
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
623+
],
624+
]);
625+
}
626+
519627
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug10068;
4+
5+
class Foo
6+
{
7+
/** @param array<string, bool> $spy */
8+
public function __construct(private array &$spy)
9+
{
10+
}
11+
12+
public function doSomething(): void
13+
{
14+
$this->spy['doSomething'] = true;
15+
}
16+
}
17+
18+
class Bar
19+
{
20+
/** @param array<string, bool> $spy */
21+
public function __construct(private array $spy)
22+
{
23+
}
24+
25+
public function doSomething(): void
26+
{
27+
$this->spy['doSomething'] = true;
28+
}
29+
}
30+
31+
function (): void {
32+
$spy = [];
33+
$foo = new Foo($spy);
34+
$foo->doSomething();
35+
print_r($spy);
36+
};

0 commit comments

Comments
 (0)