Skip to content

Commit 9414cd8

Browse files
committed
Read the code of traits in analysed files like the using class's own
PreservedPropertiesVisitor scans traits like classes and stores the scan on the trait node. A class using traits attaches its own scan to its calls instead of what they keep. At the first such call, PreservedPropertiesResolver parses the traits' files, merges their methods (unless the class declares them itself), properties, closures and what they hand out into the class's scan, and annotates the class's calls with the result. A trait used with adaptations, one that uses other traits, one that cannot be parsed, and one that is not in an analysed file leave the class unsupported, as before. Amp-Thread-ID: https://ampcode.com/threads/T-01a1ffd7-32dc-7043-b3ac-2d8cf42d2441
1 parent 45928f4 commit 9414cd8

4 files changed

Lines changed: 307 additions & 24 deletions

File tree

‎src/Analyser/PreservedProperties/PreservedPropertiesResolver.php‎

Lines changed: 87 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace PHPStan\Analyser\PreservedProperties;
44

5+
use PhpParser\Node;
56
use PhpParser\Node\Expr;
67
use PhpParser\Node\Expr\MethodCall;
78
use PhpParser\Node\Expr\PropertyFetch;
@@ -10,7 +11,10 @@
1011
use PhpParser\Node\Name;
1112
use PHPStan\Analyser\CalledMethodProcessor;
1213
use PHPStan\Analyser\MutatingScope;
14+
use PHPStan\DependencyInjection\AutowiredParameter;
1315
use PHPStan\DependencyInjection\AutowiredService;
16+
use PHPStan\Parser\Parser;
17+
use PHPStan\Parser\PreservedPropertiesClassScan;
1418
use PHPStan\Parser\PreservedPropertiesVisitor;
1519
use PHPStan\Reflection\ClassReflection;
1620
use PHPStan\Reflection\MethodReflection;
@@ -25,6 +29,7 @@
2529
use function explode;
2630
use function implode;
2731
use function str_contains;
32+
use function strtolower;
2833

2934
/**
3035
* Which properties of $this keep their remembered types across an impure call
@@ -41,10 +46,89 @@ final class PreservedPropertiesResolver
4146
public function __construct(
4247
private ReflectionProvider $reflectionProvider,
4348
private CalledMethodProcessor $calledMethodProcessor,
49+
#[AutowiredParameter(ref: '@defaultAnalysisParser')]
50+
private Parser $parser,
4451
)
4552
{
4653
}
4754

55+
/**
56+
* What PreservedPropertiesVisitor attached to the call. In a class using traits that is the
57+
* class's scan until its first call: the traits' scans, read from their files, are merged in
58+
* then. A trait outside the analysed files is parsed without them, so the class keeps nothing.
59+
*/
60+
private function getPreservedProperties(Expr $call): ?PreservedProperties
61+
{
62+
$attribute = $call->getAttribute(PreservedPropertiesVisitor::ATTRIBUTE_NAME);
63+
if ($attribute instanceof PreservedPropertiesClassScan) {
64+
$attribute->annotateCallsWithTraits($this->findTraitScans($attribute->traitUses));
65+
$attribute = $call->getAttribute(PreservedPropertiesVisitor::ATTRIBUTE_NAME);
66+
}
67+
68+
return $attribute instanceof PreservedProperties ? $attribute : null;
69+
}
70+
71+
/**
72+
* @param list<Node\Stmt\TraitUse> $traitUses
73+
* @return list<PreservedPropertiesClassScan>|null null when the code of some trait is not known
74+
*/
75+
private function findTraitScans(array $traitUses): ?array
76+
{
77+
$traitScans = [];
78+
foreach ($traitUses as $traitUse) {
79+
if ($traitUse->adaptations !== []) {
80+
// renamed, hidden or reordered methods are not followed
81+
return null;
82+
}
83+
foreach ($traitUse->traits as $traitName) {
84+
$traitName = $traitName->toString();
85+
if (!$this->reflectionProvider->hasClass($traitName)) {
86+
return null;
87+
}
88+
$traitReflection = $this->reflectionProvider->getClass($traitName);
89+
$fileName = $traitReflection->getFileName();
90+
if (!$traitReflection->isTrait() || $fileName === null) {
91+
return null;
92+
}
93+
$traitScan = $this->findTraitScan($this->parser->parseFile($fileName), $traitReflection->getName());
94+
if ($traitScan === null) {
95+
return null;
96+
}
97+
$traitScans[] = $traitScan;
98+
}
99+
}
100+
101+
return $traitScans;
102+
}
103+
104+
/**
105+
* @param Node\Stmt[] $stmts
106+
*/
107+
private function findTraitScan(array $stmts, string $traitName): ?PreservedPropertiesClassScan
108+
{
109+
foreach ($stmts as $stmt) {
110+
if ($stmt instanceof Node\Stmt\Namespace_) {
111+
$traitScan = $this->findTraitScan($stmt->stmts, $traitName);
112+
if ($traitScan !== null) {
113+
return $traitScan;
114+
}
115+
continue;
116+
}
117+
if (
118+
!$stmt instanceof Node\Stmt\Trait_
119+
|| $stmt->namespacedName === null
120+
|| strtolower($stmt->namespacedName->toString()) !== strtolower($traitName)
121+
) {
122+
continue;
123+
}
124+
$traitScan = $stmt->getAttribute(PreservedPropertiesVisitor::TRAIT_SCAN_ATTRIBUTE_NAME);
125+
126+
return $traitScan instanceof PreservedPropertiesClassScan ? $traitScan : null;
127+
}
128+
129+
return null;
130+
}
131+
48132
/**
49133
* After a call of a method of the class on $this that runs exactly that method - a private
50134
* or final one, or one called through self:: - the properties the walk of the method ended
@@ -62,7 +146,7 @@ public function applyCalledMethodExitScope(MutatingScope $scope, Expr $call, Met
62146
$exitScope = $walk[0];
63147
$scope = $scope->mergeInitializedProperties($exitScope);
64148

65-
$preservedProperties = $call->getAttribute(PreservedPropertiesVisitor::ATTRIBUTE_NAME);
149+
$preservedProperties = $this->getPreservedProperties($call);
66150
if (!$preservedProperties instanceof PreservedProperties) {
67151
return $scope;
68152
}
@@ -258,7 +342,7 @@ private function findExitType(MutatingScope $exitScope, PropertyFetch $propertyF
258342
*/
259343
public function resolve(Expr $call): ?array
260344
{
261-
$preservedProperties = $call->getAttribute(PreservedPropertiesVisitor::ATTRIBUTE_NAME);
345+
$preservedProperties = $this->getPreservedProperties($call);
262346
if (!$preservedProperties instanceof PreservedProperties) {
263347
return null;
264348
}
@@ -296,7 +380,7 @@ public function resolve(Expr $call): ?array
296380
*/
297381
public function forgetWrittenProperties(MutatingScope $scope, Expr $call, MethodReflection $methodReflection): MutatingScope
298382
{
299-
$preservedProperties = $call->getAttribute(PreservedPropertiesVisitor::ATTRIBUTE_NAME);
383+
$preservedProperties = $this->getPreservedProperties($call);
300384
if (!$preservedProperties instanceof PreservedProperties) {
301385
return $scope;
302386
}

‎src/Parser/PreservedPropertiesClassScan.php‎

Lines changed: 94 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,11 @@
2222
* Private properties are forgotten when the followed code writes them; code outside
2323
* calling a method of $this it cannot reach otherwise needs $this, so once the class
2424
* lets $this out anywhere, a call that runs code outside keeps no property. A call that reaches a __call
25-
* method, which can write private properties, keeps nothing either, and nothing is kept in a class
26-
* using a trait.
25+
* method, which can write private properties, keeps nothing either.
26+
*
27+
* The code of the traits a class uses is read like the class's own, when they are in analysed
28+
* files and used without adaptations: PreservedPropertiesResolver merges their scans into the
29+
* class's at its first call. Otherwise nothing is kept in a class using a trait.
2730
*
2831
* @internal
2932
* @phpstan-type Summary array{writes: array<string, true>, calls: list<array{self::CALL_*, string}>, functionArguments: list<array{list<non-empty-string>, int, string}>, escapes: bool, unknown: bool}
@@ -46,6 +49,12 @@ final class PreservedPropertiesClassScan
4649
/** @var array<string, bool> declared instance properties, each with whether only the class's own code can write it */
4750
public array $properties = [];
4851

52+
/** @var array<string, array{bool, bool}> declared instance properties, each with whether it is private and whether it is protected */
53+
private array $propertyVisibility = [];
54+
55+
/** @var list<Node\Stmt\TraitUse> the trait uses of the class, whose code is merged in before its calls are annotated */
56+
public array $traitUses = [];
57+
4958
/** @var array<string, true> protected properties of a final class with a parent, which only the class's own code writes unless the parent declares them too */
5059
private array $unlessParentDeclares = [];
5160

@@ -66,7 +75,7 @@ final class PreservedPropertiesClassScan
6675
public array $methodParameters = [];
6776

6877
/**
69-
* Magic __get/__set/__unset, a hooked property or a trait: code nothing summarises can write the
78+
* Magic __get/__set/__unset, a hooked property or a trait whose code is not known: code nothing summarises can write the
7079
* properties, so the calls keep and forget what they did before.
7180
*/
7281
public bool $unsupported = false;
@@ -108,6 +117,7 @@ public function __construct(
108117

109118
public function addProperty(string $propertyName, bool $isPrivate, bool $isProtected): void
110119
{
120+
$this->propertyVisibility[$propertyName] = [$isPrivate, $isProtected];
111121
// no subclass reaches a protected property of a final class, and the parent's code only one it declares too
112122
$this->properties[$propertyName] = $isPrivate || ($isProtected && $this->isFinal);
113123
if ($isPrivate || !$isProtected || !$this->isFinal || !$this->hasParent) {
@@ -127,25 +137,100 @@ public function handOut(int $kind, string $methodName): void
127137

128138
public function annotateCalls(): void
129139
{
130-
if ($this->unsupported) {
131-
return;
132-
}
133-
134-
$overrideWrites = $this->collectOverrideWrites();
140+
$overrideWrites = $this->unsupported ? [] : $this->collectOverrideWrites();
135141
$results = [];
136142
foreach ($this->calls as [$node, $kind, $methodName]) {
137143
$key = $kind . ':' . $methodName;
138144
if (!array_key_exists($key, $results)) {
139-
$results[$key] = $this->resolve($kind, $methodName, $overrideWrites);
145+
$results[$key] = $this->unsupported ? null : $this->resolve($kind, $methodName, $overrideWrites);
140146
}
141147
if ($results[$key] === null) {
148+
if ($node->hasAttribute(PreservedPropertiesVisitor::ATTRIBUTE_NAME)) {
149+
// the scan deferred until the traits were merged
150+
$node->setAttribute(PreservedPropertiesVisitor::ATTRIBUTE_NAME, null);
151+
}
142152
continue;
143153
}
144154

145155
$node->setAttribute(PreservedPropertiesVisitor::ATTRIBUTE_NAME, $results[$key]);
146156
}
147157
}
148158

159+
/**
160+
* Attaches this scan to the class's calls instead of what they keep, which the class's
161+
* traits decide too: their code is in other files.
162+
*/
163+
public function deferCalls(): void
164+
{
165+
foreach ($this->calls as [$node]) {
166+
$node->setAttribute(PreservedPropertiesVisitor::ATTRIBUTE_NAME, $this);
167+
}
168+
}
169+
170+
/**
171+
* Merges the scans of the traits the class uses into it and annotates its calls.
172+
*
173+
* @param list<self>|null $traitScans null when the code of some trait is not known
174+
*/
175+
public function annotateCallsWithTraits(?array $traitScans): void
176+
{
177+
if ($traitScans === null) {
178+
$this->unsupported = true;
179+
}
180+
foreach ($traitScans ?? [] as $traitScan) {
181+
$this->mergeTrait($traitScan);
182+
}
183+
$this->traitUses = [];
184+
185+
$this->annotateCalls();
186+
}
187+
188+
private function mergeTrait(self $trait): void
189+
{
190+
if ($trait->unsupported || $trait->traitUses !== []) {
191+
$this->unsupported = true;
192+
return;
193+
}
194+
195+
foreach ($trait->methods as $methodName => $method) {
196+
if (isset($this->methods[$methodName])) {
197+
// the class's own method replaces the trait's
198+
continue;
199+
}
200+
$this->methods[$methodName] = $method;
201+
if (isset($trait->methodParameters[$methodName])) {
202+
$this->methodParameters[$methodName] = $trait->methodParameters[$methodName];
203+
}
204+
if (!isset($trait->summaries[$methodName])) {
205+
continue;
206+
}
207+
$this->summaries[$methodName] = $trait->summaries[$methodName];
208+
}
209+
210+
foreach ($trait->propertyVisibility as $propertyName => [$isPrivate, $isProtected]) {
211+
if (isset($this->properties[$propertyName])) {
212+
continue;
213+
}
214+
$this->addProperty($propertyName, $isPrivate, $isProtected);
215+
}
216+
217+
$this->closures['writes'] += $trait->closures['writes'];
218+
foreach ($trait->closures['calls'] as $call) {
219+
$this->closures['calls'][] = $call;
220+
}
221+
foreach ($trait->closures['functionArguments'] as $functionArgument) {
222+
$this->closures['functionArguments'][] = $functionArgument;
223+
}
224+
$this->closures['escapes'] = $this->closures['escapes'] || $trait->closures['escapes'];
225+
$this->closures['unknown'] = $this->closures['unknown'] || $trait->closures['unknown'];
226+
$this->handedOut += $trait->handedOut;
227+
$this->nonPlainWrites += $trait->nonPlainWrites;
228+
foreach ($trait->assignments as $traitMethodName => $propertyNames) {
229+
$this->assignments[$traitMethodName] ??= $propertyNames;
230+
}
231+
$this->thisEscapes = $this->thisEscapes || $trait->thisEscapes;
232+
}
233+
149234
/**
150235
* Ranks the methods so that each comes after the methods of the class it calls - the
151236
* methods are walked by it, and a call can then use the walk of what it calls. The

‎src/Parser/PreservedPropertiesVisitor.php‎

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,10 @@
2121
* class's methods: the properties of $this no code the call can run writes,
2222
* read from the class's own code only (see PreservedPropertiesClassScan).
2323
*
24-
* Traits, interfaces and calls in closures (which can be bound to another
25-
* object) get nothing, so every property is forgotten there as before. Files
26-
* outside the analysed paths are not parsed by the rich parser at all.
24+
* Interfaces and calls in traits and closures (which can be bound to another
25+
* object) get nothing, so every property is forgotten there as before. A trait
26+
* gets its scan, which the classes using it merge in. Files outside the analysed
27+
* paths are not parsed by the rich parser at all, so a trait there has no scan.
2728
*/
2829
#[AutowiredService]
2930
final class PreservedPropertiesVisitor extends NodeVisitorAbstract
@@ -34,6 +35,9 @@ final class PreservedPropertiesVisitor extends NodeVisitorAbstract
3435
/** Attached to each method of a class: ClassLikeHandler walks the methods by it, callees before their callers. */
3536
public const RANK_ATTRIBUTE_NAME = 'calleesFirstRank';
3637

38+
/** Attached to each trait: its PreservedPropertiesClassScan, merged into the scans of the classes using it. */
39+
public const TRAIT_SCAN_ATTRIBUTE_NAME = 'preservedPropertiesTraitScan';
40+
3741
private ?PreservedPropertiesClassScan $scan = null;
3842

3943
/** @var list<PreservedPropertiesClassScan|null> scans of the classes enclosing an anonymous class */
@@ -106,8 +110,17 @@ public function enterNode(Node $node): ?Node
106110
public function leaveNode(Node $node): ?Node
107111
{
108112
if ($node instanceof Node\Stmt\ClassLike) {
109-
$this->scan?->annotateCalls();
110-
$this->scan?->rankMethods($node);
113+
$scan = $this->scan;
114+
if ($node instanceof Node\Stmt\Trait_) {
115+
$node->setAttribute(self::TRAIT_SCAN_ATTRIBUTE_NAME, $scan);
116+
} elseif ($scan !== null) {
117+
if ($scan->traitUses !== [] && !$scan->unsupported) {
118+
$scan->deferCalls();
119+
} else {
120+
$scan->annotateCalls();
121+
}
122+
$scan->rankMethods($node);
123+
}
111124
$this->scan = array_pop($this->outerScans);
112125
return null;
113126
}
@@ -154,15 +167,17 @@ private function createScan(Node\Stmt\ClassLike $node): ?PreservedPropertiesClas
154167
false,
155168
($node->namespacedName ?? null)?->toLowerString(),
156169
);
170+
} elseif ($node instanceof Node\Stmt\Trait_) {
171+
// its methods run in the classes that use it, which tell whether they are final or have a parent
172+
$scan = new PreservedPropertiesClassScan(false, false, null);
157173
} else {
158-
// a trait's methods run in the classes that use it, an interface has no code
174+
// an interface has no code
159175
return null;
160176
}
161177

162178
foreach ($node->stmts as $stmt) {
163179
if ($stmt instanceof Node\Stmt\TraitUse) {
164-
// the trait's code can write any property, so not all the class's writes are seen
165-
$scan->unsupported = true;
180+
$scan->traitUses[] = $stmt;
166181
} elseif ($stmt instanceof Node\Stmt\Property) {
167182
if ($stmt->isStatic()) {
168183
continue;

0 commit comments

Comments
 (0)