Skip to content

Fix "Property is never read, only written" false positive, when initialized by ref - #7253

Open
staabm wants to merge 5 commits into
phpstan:2.3.xfrom
staabm:ref-read-prop
Open

staabm wants to merge 5 commits into
phpstan:2.3.xfrom
staabm:ref-read-prop

Conversation

@staabm

@staabm staabm commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

when a property is assigned from a reference passed in from a caller via parameter, the caller might read the results which the current scope writes. so it should not be consdered a "never read" property.

closes phpstan/phpstan#15886
closes phpstan/phpstan#10068

@Amoifr

Amoifr commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Thanks for picking this up! 🙌 One case that still slips through: binding an array offset of the property by reference.

class ArrayOffset
{
    /** @var array<string, int> */
    private array $counters = [];

    public function bind(int &$counter): void
    {
        $this->counters['requests'] = &$counter;
    }

    public function reset(): void
    {
        $this->counters['requests'] = 0;
    }
}

On 9734c86 this still reports Property ArrayOffset::$counters is never read, only written. The AssignRef branch checks $node->var instanceof PropertyFetch, so the ArrayDimFetch is never unwrapped. Walking down while ($var instanceof ArrayDimFetch) { $var = $var->var; } before the check (plus the same in the turbo mirror) fixes it on my side. Happy to leave it to you, of course!

@staabm
staabm marked this pull request as ready for review November 29, 2026 15:30
@staabm

staabm commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

//cc @SanderMuller

/**
* @param array<ClassMethod> $methods methods gathered so far in the class
*/
public static function isReadThroughReference(Expr $referencedExpr, Scope $scope, array $methods): bool

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really like this AST based node-finder deep seek, but since it only happens for by-ref parameters/promoted-properties, I think it is fine

@staabm

staabm commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

@janedbal could you have a look whether the failling phpstan check with

[0](https://github.com/phpstan/phpstan-src/actions/runs/46382850119/job/141725858541?pr=7253#step:10:21)
PHP Fatal error:  Allowed memory size of 536870912 bytes exhausted (tried to allocate 4194304 bytes) in D:\a\phpstan-src\phpstan-src\vendor\shipmonk\dead-code-detector\src\Rule\DeadCodeRule.php on line 740
Stack trace:
#0 D:\a\phpstan-src\phpstan-src\vendor\shipmonk\dead-code-detector\src\Rule\DeadCodeRule.php(374): ShipMonk\PHPStan\DeadCode\Rule\DeadCodeRule->markReachableAsWhite(Array, Array, true)
#1 {main}
Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 4194304 bytes) in D:\a\phpstan-src\phpstan-src\vendor\shipmonk\dead-code-detector\src\Rule\DeadCodeRule.php on line 740
Stack trace:
#0 D:\a\phpstan-src\phpstan-src\vendor\shipmonk\dead-code-detector\src\Rule\DeadCodeRule.php(374): ShipMonk\PHPStan\DeadCode\Rule\DeadCodeRule->markReachableAsWhite(Array, Array, true)
#1 {main}

is a bug in dead-code detector?

*
* Called from the native ClassStatementsGatherer in turbo-ext as well.
*/
final class PropertyReferenceBinding

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dunno if there is a better name/place for this service...

@SanderMuller SanderMuller left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked 845e12c against 2.3.x (6dc37db) on PHP 8.6, with and without Turbo. Both issue samples no longer report property.onlyWritten. I found one regression and two smaller points.

  1. With checkUninitializedProperties: true, the binding now reports an uninitialized access. The sample from phpstan/phpstan#15886 gives this on line 22, which is $this->forwarded = &$forwarded;:

    Access to an uninitialized property class@anonymous/issue15886.php:10::$forwarded.
    

    2.3.x does not report it. The new PropertyRead carries the scope from before the assignment. ClassPropertiesNode::getUninitializedProperties() then sees a read in the constructor before the property has a value. Across the PR's fixtures and my probes I get 11 of these new errors, with and without Turbo. A @readonly PHPDoc property gets property.uninitializedReadonlyByPhpDoc even without the option:

    /**
     * @readonly
     * @var list<string>
     */
    private array $cache;
    
    /** @param list<string> $c */
    public function __construct(array &$c)
    {
    	$this->cache = &$c;
    }

    I tried a flag on PropertyRead, isThroughReference(), set for the two new reads. The premature access check then skips the reads that have it. All 11 errors go away, the onlyWritten results stay the same, and the DeadCode and Properties rule tests pass. I did not port it to the C++ side, where pushNodeScope() would need to pass the flag too.

  2. A by-value parameter that is read after the binding is still reported:

    /** @param list<string> $tmp @return list<string> */
    public function run(array $tmp): array
    {
    	$this->cache = &$tmp;
    	$this->add();
    	return $tmp;
    }

    The parameter loop returns $param->byRef at once, so this case never gets the usage scan that local variables get. If a by-value parameter continues to that scan, this case is fixed, and ByValueParameter in the fixture is still reported.

  3. Each binding can walk the whole method body twice. I put 1000 bindings like $t1 = [1]; $this->p[1] = &$t1; in one method. Analysis took 3.09 to 3.28 s on 2.3.x and 11.6 to 12.9 s with this PR, in 3 rounds. With the walks skipped, the PR took 2.5 to 4.7 s. At 250 bindings the difference was within the noise, and real code rarely has this many bindings in one method.

    One walk per method, with the result kept per variable name, would avoid the repeated walks. The new code only runs for a reference assignment to a property and for a promoted by-ref parameter, so other code is not affected.

The other cases I checked are fine:

  • The new tests fail with the src change reverted.
  • A by-ref parameter of a closure, a nested offset ($this->c['a']['b'] = &$counter) and a foreach by-ref value are now not reported. They were false positives on 2.3.x.
  • A promoted by-value property that is never read is still reported.
  • Turbo: the smoke test and the signature parity check pass. The DeadCode tests pass with the extension loaded, and the probe output is the same with and without it.
  • The full test suite passes with and without Turbo. make phpstan and phpcs on the changed files are clean.

Two cases are now silent although nothing reads the property. One uses the same variable name in an unrelated closure, the other reads the local before the binding. The scan does not look at scope or position. Those cases only hide a report, so I would leave them.

The PHPStan (8.6, windows-latest) red is the same out-of-memory error in dead-code-detector that #7257 and #7258 have. The Benchmarks shards also fail on the 2.3.x push.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

"Property is never read, only written" false positive, when initialized by ref Constructor argument passed by reference is considered only written

4 participants