Skip to content

Commit 07d57b7

Browse files
committed
Allow initializing readonly properties in methods only the constructor calls
PreservedPropertiesVisitor now records which methods call each method on $this. A private method, or a protected one in a final class without a parent, that is only run from the constructors (directly or through other such methods) may initialize readonly and @readonly properties. A method the constructor calls twice now reports the second initialization as already assigned: the call sites are combined with extremeIdentity instead of and. Amp-Thread-ID: https://ampcode.com/threads/T-01a213ea-2998-7296-a072-5e436e1454ce
1 parent 9df712a commit 07d57b7

13 files changed

Lines changed: 751 additions & 1 deletion

‎src/Node/ClassPropertiesNode.php‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,13 @@ private function getMethodsCalledFromConstructor(
385385
$methodName = $methodCallNode->name->toString();
386386
if (array_key_exists($methodName, $initializedProperties)) {
387387
foreach ($this->getInitializedProperties($callScope, $initializedProperties[$inMethod->getName()] ?? $initialInitializedProperties) as $propertyName => $isInitialized) {
388-
$initializedProperties[$methodName][$propertyName] = $initializedProperties[$methodName][$propertyName]->and($isInitialized);
388+
if (in_array($methodName, $originalConstructors, true)) {
389+
// parent::__construct() is another method of the same name
390+
$initializedProperties[$methodName][$propertyName] = $initializedProperties[$methodName][$propertyName]->and($isInitialized);
391+
continue;
392+
}
393+
// maybe when initialized before some calls only: a read can come too early, and a write too late
394+
$initializedProperties[$methodName][$propertyName] = TrinaryLogic::extremeIdentity($initializedProperties[$methodName][$propertyName], $isInitialized);
389395
}
390396
continue;
391397
}

‎src/Parser/PreservedPropertiesClassScan.php‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@
77
use PHPStan\Analyser\PreservedProperties\PreservedProperties;
88
use function array_key_exists;
99
use function array_keys;
10+
use function array_map;
1011
use function array_pop;
1112
use function count;
13+
use function str_starts_with;
1214
use function usort;
1315

1416
/**
@@ -107,6 +109,15 @@ final class PreservedPropertiesClassScan
107109
/** @var list<array{Expr, self::CALL_*, string}> calls on $this outside closures, with their kind and lowercase method name */
108110
public array $calls = [];
109111

112+
/** @var array<string, array<string, true>> the methods calling each method of the class on $this by lowercase name, self::CLOSURES for calls in closures */
113+
public array $callers = [];
114+
115+
/** @var array<string, true> lowercase method names called other than on $this, handed out, or mentioned in a string, which can name a callable */
116+
public array $calledElsewhere = [];
117+
118+
/** Some code calls a method by a name that is not written in it, which can be any method of the class. */
119+
public bool $hasDynamicCalls = false;
120+
110121
public function __construct(
111122
public bool $isFinal,
112123
public bool $hasParent,
@@ -133,6 +144,81 @@ public function addProperty(string $propertyName, bool $isPrivate, bool $isProte
133144
public function handOut(int $kind, string $methodName): void
134145
{
135146
$this->handedOut[$kind . ':' . $methodName] = [$kind, $methodName];
147+
$this->calledElsewhere[$methodName] = true;
148+
}
149+
150+
/**
151+
* Attaches to each method only the class's own code can call - private, or protected
152+
* in a final class without a parent - the methods it is only ever run from: the
153+
* methods outside this set that call it on $this, directly or through other such
154+
* methods. A method also called in a closure, on another object, through a callable
155+
* or one the class never calls gets nothing.
156+
*/
157+
public function annotateOnlyCalledFrom(Node\Stmt\ClassLike $node): void
158+
{
159+
if ($this->unsupported || $this->traitUses !== [] || $this->hasDynamicCalls) {
160+
// code of a trait or a property hook, which the scan does not follow, can call the methods too
161+
return;
162+
}
163+
164+
$candidates = [];
165+
foreach ($node->stmts as $stmt) {
166+
if (!$stmt instanceof Node\Stmt\ClassMethod || $stmt->isStatic() || $stmt->stmts === null) {
167+
continue;
168+
}
169+
$methodName = $stmt->name->toLowerString();
170+
if (str_starts_with($methodName, '__')) {
171+
// magic methods are called by PHP
172+
continue;
173+
}
174+
if (!$stmt->isPrivate() && !($stmt->isProtected() && $this->isFinal && !$this->hasParent)) {
175+
continue;
176+
}
177+
if (
178+
!isset($this->callers[$methodName])
179+
|| isset($this->callers[$methodName][self::CLOSURES])
180+
|| isset($this->calledElsewhere[$methodName])
181+
) {
182+
continue;
183+
}
184+
$candidates[$methodName] = $stmt;
185+
}
186+
187+
$roots = [];
188+
foreach (array_keys($candidates) as $methodName) {
189+
$roots[$methodName] = [];
190+
foreach (array_keys($this->callers[$methodName]) as $callerName) {
191+
if (isset($candidates[$callerName])) {
192+
continue;
193+
}
194+
$roots[$methodName][$callerName] = true;
195+
}
196+
}
197+
198+
do {
199+
$changed = false;
200+
foreach (array_keys($candidates) as $methodName) {
201+
foreach (array_keys($this->callers[$methodName]) as $callerName) {
202+
if (!isset($candidates[$callerName])) {
203+
continue;
204+
}
205+
$count = count($roots[$methodName]);
206+
$roots[$methodName] += $roots[$callerName];
207+
if (count($roots[$methodName]) === $count) {
208+
continue;
209+
}
210+
$changed = true;
211+
}
212+
}
213+
} while ($changed);
214+
215+
foreach ($candidates as $methodName => $stmt) {
216+
if ($roots[$methodName] === []) {
217+
// only called by methods nothing else calls
218+
continue;
219+
}
220+
$stmt->setAttribute(PreservedPropertiesVisitor::ONLY_CALLED_FROM_ATTRIBUTE_NAME, array_map('strval', array_keys($roots[$methodName])));
221+
}
136222
}
137223

138224
public function annotateCalls(): void

‎src/Parser/PreservedPropertiesVisitor.php‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
use function count;
1616
use function in_array;
1717
use function is_string;
18+
use function strtolower;
1819

1920
/**
2021
* Attaches PreservedProperties to each method and static call on $this in a
@@ -38,6 +39,9 @@ final class PreservedPropertiesVisitor extends NodeVisitorAbstract
3839
/** Attached to each trait: its PreservedPropertiesClassScan, merged into the scans of the classes using it. */
3940
public const TRAIT_SCAN_ATTRIBUTE_NAME = 'preservedPropertiesTraitScan';
4041

42+
/** Attached to a method only the class's own code calls: the lowercase names of the methods it is only ever run from (see PreservedPropertiesClassScan::annotateOnlyCalledFrom()). */
43+
public const ONLY_CALLED_FROM_ATTRIBUTE_NAME = 'onlyCalledFrom';
44+
4145
private ?PreservedPropertiesClassScan $scan = null;
4246

4347
/** @var list<PreservedPropertiesClassScan|null> scans of the classes enclosing an anonymous class */
@@ -74,6 +78,12 @@ public function enterNode(Node $node): ?Node
7478
return null;
7579
}
7680

81+
if ($node instanceof Node\Scalar\String_) {
82+
// may name a method in a callable
83+
$scan->calledElsewhere[strtolower($node->value)] = true;
84+
return null;
85+
}
86+
7787
if ($scan->currentMethod === null) {
7888
if ($node instanceof Node\Stmt\ClassMethod && $node->stmts !== null) {
7989
$scan->currentMethod = $node->name->toLowerString();
@@ -120,6 +130,7 @@ public function leaveNode(Node $node): ?Node
120130
$scan->annotateCalls();
121131
}
122132
$scan->rankMethods($node);
133+
$scan->annotateOnlyCalledFrom($node);
123134
}
124135
$this->scan = array_pop($this->outerScans);
125136
return null;
@@ -233,6 +244,16 @@ private static function emptySummary(): array
233244

234245
private function enterBodyNode(PreservedPropertiesClassScan $scan, Node $node): void
235246
{
247+
if (
248+
$node instanceof Expr\Array_
249+
&& count($node->items) === 2
250+
&& !$node->items[1]->value instanceof Node\Scalar\String_
251+
&& $this->isThisOrSelf($node->items[0]->value)
252+
) {
253+
// a callable of a method whose name is not written here
254+
$scan->hasDynamicCalls = true;
255+
}
256+
236257
if ($node instanceof Expr\Variable && $node->name === 'this') {
237258
if (!$this->containedThis->offsetExists($node)) {
238259
// passed out, assigned or used as a callable: other code can call any method on it
@@ -277,7 +298,14 @@ private function enterBodyNode(PreservedPropertiesClassScan $scan, Node $node):
277298
} else {
278299
$this->writeArgs($scan, $node->args, true);
279300
}
301+
if (!$node->name instanceof Identifier) {
302+
$scan->hasDynamicCalls = true;
303+
}
280304
if (!$this->isThis($node->var)) {
305+
if ($node->name instanceof Identifier) {
306+
// another object of the class can call its private methods too
307+
$scan->calledElsewhere[$node->name->toLowerString()] = true;
308+
}
281309
// another object's method can do anything a call from outside the class can
282310
$this->escape($scan);
283311
return;
@@ -415,11 +443,17 @@ private function enterStaticCall(PreservedPropertiesClassScan $scan, Expr\Static
415443
$kind = PreservedPropertiesClassScan::CALL_THIS;
416444
} else {
417445
// '$class::m()' can name this class or an ancestor and run any of their methods with this $this
446+
if ($node->name instanceof Identifier) {
447+
$scan->calledElsewhere[$node->name->toLowerString()] = true;
448+
} else {
449+
$scan->hasDynamicCalls = true;
450+
}
418451
$this->markUnknown($scan);
419452
return;
420453
}
421454

422455
if (!$node->name instanceof Identifier) {
456+
$scan->hasDynamicCalls = true;
423457
$this->markUnknown($scan);
424458
return;
425459
}
@@ -444,10 +478,13 @@ private function addCall(PreservedPropertiesClassScan $scan, Expr $node, int $ki
444478
}
445479

446480
if ($kind === PreservedPropertiesClassScan::CALL_OUTSIDE) {
481+
$scan->calledElsewhere[$methodName] = true;
447482
$this->escape($scan);
448483
return;
449484
}
450485

486+
$scan->callers[$methodName][$scan->closureDepth > 0 ? PreservedPropertiesClassScan::CLOSURES : (string) $scan->currentMethod] = true;
487+
451488
$scan->summaries[(string) $scan->currentMethod]['calls'][] = [$kind, $methodName];
452489
if ($scan->closureDepth <= 0) {
453490
return;
@@ -688,6 +725,19 @@ private function isThis(Node $node): bool
688725
return $node instanceof Expr\Variable && $node->name === 'this';
689726
}
690727

728+
private function isThisOrSelf(Expr $expr): bool
729+
{
730+
if ($this->isThis($expr) || $expr instanceof Node\Scalar\MagicConst\Class_) {
731+
return true;
732+
}
733+
734+
return $expr instanceof Expr\ClassConstFetch
735+
&& $expr->class instanceof Name
736+
&& in_array($expr->class->toLowerString(), ['self', 'static'], true)
737+
&& $expr->name instanceof Identifier
738+
&& $expr->name->toLowerString() === 'class';
739+
}
740+
691741
private function containThis(Node $node): void
692742
{
693743
if (!$node instanceof Expr\Variable || !$this->isThis($node)) {

‎src/Reflection/ConstructorsHelper.php‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,12 @@
66
use PHPStan\DependencyInjection\AutowiredParameter;
77
use PHPStan\DependencyInjection\AutowiredService;
88
use PHPStan\DependencyInjection\ExtensionsCollection;
9+
use PHPStan\Reflection\Php\PhpMethodFromParserNodeReflection;
910
use ReflectionException;
1011
use function array_key_exists;
12+
use function array_map;
1113
use function explode;
14+
use function in_array;
1215

1316
#[AutowiredService]
1417
final class ConstructorsHelper
@@ -80,4 +83,28 @@ public function getConstructors(ClassReflection $classReflection): array
8083
return $constructors;
8184
}
8285

86+
/**
87+
* Whether only the class's own code calls the method, and only from its constructors,
88+
* directly or through other such methods.
89+
*/
90+
public function isOnlyCalledFromConstructors(ClassReflection $classReflection, MethodReflection $method): bool
91+
{
92+
if (!$method instanceof PhpMethodFromParserNodeReflection) {
93+
return false;
94+
}
95+
$callers = $method->getOnlyCalledFrom();
96+
if ($callers === null) {
97+
return false;
98+
}
99+
100+
$constructors = array_map('strtolower', $this->getConstructors($classReflection));
101+
foreach ($callers as $caller) {
102+
if (!in_array($caller, $constructors, true)) {
103+
return false;
104+
}
105+
}
106+
107+
return true;
108+
}
109+
83110
}

‎src/Reflection/Php/PhpMethodFromParserNodeReflection.php‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use PhpParser\Node;
66
use PhpParser\Node\Stmt\ClassMethod;
7+
use PHPStan\Parser\PreservedPropertiesVisitor;
78
use PHPStan\PhpDoc\ResolvedPhpDocBlock;
89
use PHPStan\Reflection\Assertions;
910
use PHPStan\Reflection\AttributeReflection;
@@ -289,6 +290,18 @@ public function isConstructor(): bool
289290
return $this->isConstructor;
290291
}
291292

293+
/**
294+
* Lowercase names of the methods of the class this method is only ever run from,
295+
* null when other code can call it too.
296+
*
297+
* @internal
298+
* @return non-empty-list<string>|null
299+
*/
300+
public function getOnlyCalledFrom(): ?array
301+
{
302+
return $this->getClassMethod()->getAttribute(PreservedPropertiesVisitor::ONLY_CALLED_FROM_ATTRIBUTE_NAME);
303+
}
304+
292305
public function hasSideEffects(): TrinaryLogic
293306
{
294307
// a void function that is pure unless its callable is impure has only the callable's effects

‎src/Rules/Properties/ReadOnlyByPhpDocPropertyAssignRule.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,14 @@ public function processNode(Node $node, Scope $scope): array
120120
continue;
121121
}
122122

123+
if (
124+
$this->constructorsHelper->isOnlyCalledFromConstructors($scopeClassReflection, $scopeMethod)
125+
&& TypeUtils::findThisType($scope->getType($propertyFetch->var)) !== null
126+
) {
127+
// a method the constructor calls initializes the property
128+
continue;
129+
}
130+
123131
$errors[] = RuleErrorBuilder::message(sprintf('@readonly property %s::$%s is assigned outside of the constructor.', $declaringClass->getDisplayName(), $propertyReflection->getName()))
124132
->line($propertyFetch->name->getStartLine())
125133
->identifier('property.readOnlyByPhpDocAssignNotInConstructor')

‎src/Rules/Properties/ReadOnlyPropertyAssignRule.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,14 @@ public function processNode(Node $node, Scope $scope): array
133133
continue;
134134
}
135135

136+
if (
137+
$this->constructorsHelper->isOnlyCalledFromConstructors($scopeClassReflection, $scopeMethod)
138+
&& TypeUtils::findThisType($scope->getType($propertyFetch->var)) !== null
139+
) {
140+
// a method the constructor calls initializes the property
141+
continue;
142+
}
143+
136144
$errors[] = RuleErrorBuilder::message(sprintf('Readonly property %s::$%s is assigned outside of the constructor.', $declaringClass->getDisplayName(), $propertyReflection->getName()))
137145
->line($propertyFetch->name->getStartLine())
138146
->identifier('property.readOnlyAssignNotInConstructor')

‎tests/PHPStan/Rules/Properties/MissingReadOnlyPropertyAssignRuleTest.php‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,4 +349,19 @@ public function testBug9789(): void
349349
$this->analyse([__DIR__ . '/data/bug-9789.php'], []);
350350
}
351351

352+
#[RequiresPhp('>= 8.1.0')]
353+
public function testBug9326(): void
354+
{
355+
$this->analyse([__DIR__ . '/data/bug-9326-already-assigned.php'], [
356+
[
357+
'Readonly property Bug9326AlreadyAssigned\\CalledTwice::$x is already assigned.',
358+
17,
359+
],
360+
[
361+
'Readonly property Bug9326AlreadyAssigned\\Promoted::$x is already assigned.',
362+
49,
363+
],
364+
]);
365+
}
366+
352367
}

‎tests/PHPStan/Rules/Properties/ReadOnlyByPhpDocPropertyAssignRuleTest.php‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,4 +192,14 @@ public function testCloneWith(): void
192192
$this->analyse([__DIR__ . '/data/readonly-phpdoc-property-assign-clone-with.php'], []);
193193
}
194194

195+
public function testBug9326(): void
196+
{
197+
$this->analyse([__DIR__ . '/data/bug-9326-phpdoc.php'], [
198+
[
199+
'@readonly property Bug9326PhpDoc\\AlsoCalledElsewhere::$foo is assigned outside of the constructor.',
200+
38,
201+
],
202+
]);
203+
}
204+
195205
}

0 commit comments

Comments
 (0)