Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/Analyser/VariableLivenessResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,17 @@ public static function resolve(Node\FunctionLike $function, ?VariableFlow $flow)
$self->resolveCoverage();
}

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 = [];
foreach ($self->accesses as $name => $accesses) {
foreach ($accesses as $access) {
if (!in_array($access->kind, [VariableFlow::READ, VariableFlow::ESCAPE], true)) {
continue;
}
$observingAccessCounts[$name] = ($observingAccessCounts[$name] ?? 0) + 1;
}
}

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);
}

private function collect(?VariableFlow $flow): void
Expand Down
80 changes: 80 additions & 0 deletions src/Node/ClassStatementsGatherer.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,11 @@
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\TypeUtils;
use ReflectionProperty;
use function array_key_exists;
use function count;
use function in_array;
use function is_string;
use function spl_object_id;
use function strtolower;

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

/** @var array<string, array<int, array{string, PropertyWrite}>> lowercase method name => AssignRef object id => bound variable name and by-reference write */
private array $referenceBindings = [];

/**
* @param callable(Node $node, Scope $scope): void $nodeCallback
*/
Expand Down Expand Up @@ -220,6 +225,10 @@ private function gatherNodes(Node $node, Scope $scope): void
$this->propertyAssigns[] = new PropertyAssign($node, $scope);
return;
}
if ($node instanceof VariableWritesNode) {
$this->resolveReferenceBindings($node, $scope);
return;
}
if (!$node instanceof Expr) {
return;
}
Expand All @@ -228,6 +237,25 @@ private function gatherNodes(Node $node, Scope $scope): void
return;
}
if ($node instanceof Expr\AssignRef) {
$boundVar = $node->var;
while ($boundVar instanceof ArrayDimFetch) {
$boundVar = $boundVar->var;
}
if ($boundVar instanceof PropertyFetch || $boundVar instanceof StaticPropertyFetch) {
$write = new PropertyWrite($boundVar, $scope, false, $node);
$function = $scope->getFunction();
if (
$node->expr instanceof Expr\Variable
&& is_string($node->expr->name)
&& $function !== null
&& !$scope->isInAnonymousFunction()
) {
// whether the local is read through elsewhere is known once the method's VariableWritesNode arrives
$this->referenceBindings[strtolower($function->getName())][spl_object_id($node)] = [$node->expr->name, $write];
} else {
$this->propertyUsages[] = $write;
}
}
if (!$node->expr instanceof PropertyFetch && !$node->expr instanceof StaticPropertyFetch) {
$this->gatherNodes($node->expr, $scope);
return;
Expand Down Expand Up @@ -262,6 +290,58 @@ private function gatherNodes(Node $node, Scope $scope): void
$this->propertyUsages[] = new PropertyRead($node, $scope);
}

/**
* A property bound by reference to a local variable ($this->prop = &$local) is read
* through that variable only when the method uses the variable apart from the binding:
* reads it, passes it on, or shares it as a by-ref parameter, global or static.
*/
private function resolveReferenceBindings(VariableWritesNode $node, Scope $scope): void
{
if ($this->referenceBindings === [] || $scope->isInAnonymousFunction()) {
return;
}
$function = $scope->getFunction();
if ($function === null) {
return;
}
$methodKey = strtolower($function->getName());
if (!array_key_exists($methodKey, $this->referenceBindings)) {
return;
}
$bindings = $this->referenceBindings[$methodKey];
unset($this->referenceBindings[$methodKey]);

$sharedVariableNames = [];
foreach ($node->getFunctionLike()->getParams() as $param) {
if (!$param->byRef && $param->flags === 0) {
continue;
}
if (!$param->var instanceof Expr\Variable || !is_string($param->var->name)) {
continue;
}
$sharedVariableNames[$param->var->name] = true;
}

$bindingCounts = [];
foreach ($bindings as [$variableName]) {
$bindingCounts[$variableName] = ($bindingCounts[$variableName] ?? 0) + 1;
}

foreach ($bindings as [$variableName, $write]) {
if (
!array_key_exists($variableName, $sharedVariableNames)
&& !$node->areAllVariableNamesReferenced()
&& !$node->isOpaque()
// each binding itself reads the variable and lets it escape once
&& $node->getObservingAccessCount($variableName) <= 2 * $bindingCounts[$variableName]
) {
continue;
}

$this->propertyUsages[] = $write;
}
}

private function tryToApplyPropertyReads(Expr\FuncCall $node, Scope $scope): void
{
$args = $node->getArgs();
Expand Down
21 changes: 21 additions & 0 deletions src/Node/Property/PropertyWrite.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use PhpParser\Node\Expr\AssignRef;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\StaticPropertyFetch;
use PhpParser\Node\Param;
use PHPStan\Analyser\Scope;
use PHPStan\Node\ClassPropertyNode;
use PHPStan\Node\PropertyAssignNode;
Expand Down Expand Up @@ -44,6 +45,26 @@ public function isPromotedPropertyWrite(): bool
return $this->promotedPropertyWrite;
}

/**
* Whether the write binds the property to a reference ($this->prop = &$var,
* $var = &$this->prop, a by-ref promoted parameter), so what is later
* written to the property can be read through the other side.
*/
public function isByReference(): bool
{
if ($this->originalNode instanceof AssignRef) {
return true;
}

if (!$this->originalNode instanceof ClassPropertyNode) {
return false;
}

$propertyNode = $this->originalNode->getOriginalNode();

return $propertyNode instanceof Param && $propertyNode->byRef;
}

/**
* Whether the write happens through offset access ($this->prop[...] = ...)
* on an ArrayAccess object, which goes through offsetSet() rather than
Expand Down
12 changes: 12 additions & 0 deletions src/Node/VariableWritesNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ final class VariableWritesNode extends NodeAbstract implements VirtualNode
* @param array<string, true> $referencedVariableNames
* @param array<string, true> $untrackedVariableNames
* @param array<int, Foreach_|For_> $variableOverwritingLoops
* @param array<string, int> $observingAccessCounts
*/
public function __construct(
private Node\FunctionLike $functionLike,
Expand All @@ -52,6 +53,7 @@ public function __construct(
private array $variableOverwritingLoops,
private bool $opaque,
private bool $allVariableNamesReferenced,
private array $observingAccessCounts = [],
)
{
parent::__construct($functionLike->getAttributes());
Expand Down Expand Up @@ -134,6 +136,16 @@ public function isVariableEverRead(string $variableName): bool
return isset($this->readVariableNames[$variableName]);
}

/**
* How many sites in the body read the variable or let it escape (pass it
* by reference, bind a reference to it, capture it by reference, declare
* it global or static).
*/
public function getObservingAccessCount(string $variableName): int
{
return $this->observingAccessCounts[$variableName] ?? 0;
}

/**
* The type of the assigned value when the write assigns the value the
* variable provably already has, null otherwise.
Expand Down
4 changes: 4 additions & 0 deletions src/Rules/DeadCode/UnusedPrivatePropertyRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,10 @@ public function processNode(Node $node, Scope $scope): array
}
} else {
$properties[$propertyName]['written'] = true;
if ($usage->isByReference()) {
$properties[$propertyName]['read'] = true;
$properties[$propertyName]['hasTrueRead'] = true;
}
}
}
}
Expand Down
109 changes: 109 additions & 0 deletions tests/PHPStan/Rules/DeadCode/UnusedPrivatePropertyRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -516,4 +516,113 @@ public function testBug12201(): void
]);
}

public function testBug15886(): void
{
$this->alwaysWrittenTags = [];
$this->alwaysReadTags = [];

$this->analyse([__DIR__ . '/data/bug-15886.php'], [
[
'Property Bug15886\OnlyWritten::$log is never read, only written.',
54,
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
],
]);
}

#[RequiresPhp('>= 8.0.0')]
public function testBug15886Promoted(): void
{
$this->alwaysWrittenTags = [];
$this->alwaysReadTags = [];

$this->analyse([__DIR__ . '/data/bug-15886-promoted.php'], []);
}

public function testBug15886Static(): void
{
$this->alwaysWrittenTags = [];
$this->alwaysReadTags = [];

$this->analyse([__DIR__ . '/data/bug-15886-static.php'], []);
}

public function testBug15886Local(): void
{
$this->alwaysWrittenTags = [];
$this->alwaysReadTags = [];

$this->analyse([__DIR__ . '/data/bug-15886-local.php'], [
[
'Property Bug15886Local\ThrowawayLocal::$cache is never read, only written.',
9,
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
],
[
'Property Bug15886Local\ByValueParameter::$cache is never read, only written.',
28,
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
],
[
'Static property Bug15886Local\StaticPropertyThrowawayLocal::$cache is never read, only written.',
173,
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
],
]);
}

public function testBug15886ArrayOffset(): void
{
$this->alwaysWrittenTags = [];
$this->alwaysReadTags = [];

$this->analyse([__DIR__ . '/data/bug-15886-array-offset.php'], [
[
'Property Bug15886ArrayOffset\ArrayOffsetThrowawayLocal::$counters is never read, only written.',
56,
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
],
]);
}

#[RequiresPhp('>= 8.0.0')]
public function testBug15886Review(): void
{
$this->alwaysWrittenTags = [];
$this->alwaysReadTags = [];

$this->analyse([__DIR__ . '/data/bug-15886-review.php'], [
[
'Property Bug15886Review\TwoBindingsOfThrowawayLocal::$first is never read, only written.',
77,
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
],
[
'Property Bug15886Review\TwoBindingsOfThrowawayLocal::$second is never read, only written.',
80,
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
],
[
'Property Bug15886Review\PromotedByValueNeverRead::$spy is never read, only written.',
101,
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
],
]);
}

#[RequiresPhp('>= 8.0.0')]
public function testBug10068(): void
{
$this->alwaysWrittenTags = [];
$this->alwaysReadTags = [];

$this->analyse([__DIR__ . '/data/bug-10068.php'], [
[
'Property Bug10068\Bar::$spy is never read, only written.',
23,
'See: https://phpstan.org/developing-extensions/always-read-written-properties',
],
]);
}

}
38 changes: 38 additions & 0 deletions tests/PHPStan/Rules/DeadCode/data/bug-10068.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php // lint >= 8.0

declare(strict_types = 1);

namespace Bug10068;

class Foo
{
/** @param array<string, bool> $spy */
public function __construct(private array &$spy)
{
}

public function doSomething(): void
{
$this->spy['doSomething'] = true;
}
}

class Bar
{
/** @param array<string, bool> $spy */
public function __construct(private array $spy)
{
}

public function doSomething(): void
{
$this->spy['doSomething'] = true;
}
}

function (): void {
$spy = [];
$foo = new Foo($spy);
$foo->doSomething();
print_r($spy);
};
Loading
Loading