Skip to content

Commit da09694

Browse files
committed
Walk the methods of a class before their callers and apply their walks at calls on $this
ClassLikeHandler walks the constructor and the methods it calls first, then the other instance methods, each after the methods of the class it calls on $this (PreservedPropertiesVisitor ranks them from its call graph; mutually recursive methods keep their order). A call on $this that runs exactly one method of the class - a private or final one, one of a final class, or one called through self:: - takes from the scope that method's walk ended with the properties it initialized and the types of the properties the class's own code it runs writes. This applies in every method, not only in the constructor. This replaces CalledMethodProcessor's second walk of the methods a constructor calls, which was limited to one level and to 50 lines. CalledMethodProcessor now only keeps the walks until the class's walk ends, and is no longer shadowed by the Turbo extension. ClassPropertiesNode reads the uninitialized properties from the constructors alone: a method a subclass can override no longer initializes properties, since an override does not have to. Reads in the methods the constructor calls before it initializes a property are reported, because those methods are no longer walked from the scope the constructor ends with. Amp-Thread-ID: https://ampcode.com/threads/T-01a1ffd7-32dc-7043-b3ac-2d8cf42d2441
1 parent 3240c15 commit da09694

31 files changed

Lines changed: 1095 additions & 1106 deletions

‎src/Analyser/CalledMethodProcessor.php‎

Lines changed: 100 additions & 132 deletions
Original file line numberDiff line numberDiff line change
@@ -2,179 +2,147 @@
22

33
namespace PHPStan\Analyser;
44

5-
use PhpParser\Node;
6-
use PHPStan\DependencyInjection\AutowiredParameter;
5+
use PhpParser\Node\Expr\PropertyFetch;
6+
use PhpParser\Node\Identifier;
77
use PHPStan\DependencyInjection\AutowiredService;
8-
use PHPStan\File\FileHelper;
98
use PHPStan\Node\MethodReturnStatementsNode;
10-
use PHPStan\Parser\Parser;
11-
use PHPStan\Reflection\MethodReflection;
12-
use PHPStan\Turbo\ShadowedByTurboExtension;
9+
use PHPStan\Node\PropertyAssignNode;
10+
use PHPStan\Reflection\ClassReflection;
1311
use PHPStan\Type\NeverType;
12+
use PHPStan\Type\Type;
13+
use PHPStan\Type\TypeCombinator;
14+
use PHPStan\Type\TypeUtils;
1415
use function array_key_exists;
15-
use function count;
16-
use function is_array;
17-
use function sprintf;
16+
use function strtolower;
1817

18+
/**
19+
* The walks of the methods of the classes being walked: the scope a method's walk ends
20+
* with is what calling the method does to $this. ClassLikeHandler walks the methods
21+
* called on $this before their callers.
22+
*/
1923
#[AutowiredService]
20-
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/CalledMethodProcessor.cpp')]
2124
final class CalledMethodProcessor
2225
{
2326

24-
/** @var array<string, true> */
25-
private array $calledMethodStack = [];
27+
/** @var array<string, array<string, MethodReturnStatementsNode>> by class name and lowercase method name */
28+
private array $walkedMethods = [];
2629

27-
/** @var array<string, MutatingScope|null> */
28-
private array $calledMethodResults = [];
30+
/** @var array<string, array<string, MutatingScope|null>> by class name and lowercase method name */
31+
private array $exitScopes = [];
2932

30-
public function __construct(
31-
private FileHelper $fileHelper,
32-
#[AutowiredParameter(ref: '@defaultAnalysisParser')]
33-
private Parser $parser,
34-
private ScopeFactory $scopeFactory,
35-
)
33+
/** @var array<string, array<string, array<string, array{Type, Type}|null>>> by class name and lowercase method name */
34+
private array $assignedTypes = [];
35+
36+
public function rememberWalkedMethod(MethodReturnStatementsNode $node): void
3637
{
38+
$className = $node->getClassReflection()->getName();
39+
$methodName = strtolower($node->getMethodName());
40+
$this->walkedMethods[$className][$methodName] = $node;
41+
unset($this->exitScopes[$className][$methodName], $this->assignedTypes[$className][$methodName]);
3742
}
3843

39-
public function processCalledMethod(NodeScopeResolver $nodeScopeResolver, MethodReflection $methodReflection): ?MutatingScope
44+
/**
45+
* The merged scope at the ends of the method's walk, null when it was not walked
46+
* yet or never returns.
47+
*/
48+
public function getWalkedMethodExitScope(ClassReflection $classReflection, string $methodName): ?MutatingScope
4049
{
41-
$declaringClass = $methodReflection->getDeclaringClass();
42-
if ($declaringClass->isAnonymous()) {
43-
return null;
44-
}
45-
if ($declaringClass->getFileName() === null) {
50+
$className = $classReflection->getName();
51+
$methodName = strtolower($methodName);
52+
if (!isset($this->walkedMethods[$className][$methodName])) {
4653
return null;
4754
}
48-
49-
$stackName = sprintf('%s::%s', $declaringClass->getName(), $methodReflection->getName());
50-
if (array_key_exists($stackName, $this->calledMethodResults)) {
51-
return $this->calledMethodResults[$stackName];
55+
if (!array_key_exists($methodName, $this->exitScopes[$className] ?? [])) {
56+
$this->exitScopes[$className][$methodName] = $this->getExitScope($this->walkedMethods[$className][$methodName]);
5257
}
5358

54-
if (array_key_exists($stackName, $this->calledMethodStack)) {
55-
return null;
56-
}
59+
return $this->exitScopes[$className][$methodName];
60+
}
5761

58-
if (count($this->calledMethodStack) > 0) {
62+
/**
63+
* The types the method's walk saw assigned to the property of any object with that name,
64+
* with their native types, by property name; a property with an assigned type that names
65+
* the method's template types is null. Null when the method was not walked yet.
66+
*
67+
* @return array<string, array{Type, Type}|null>|null
68+
*/
69+
public function getWalkedMethodAssignedTypes(ClassReflection $classReflection, string $methodName): ?array
70+
{
71+
$className = $classReflection->getName();
72+
$methodName = strtolower($methodName);
73+
if (!isset($this->walkedMethods[$className][$methodName])) {
5974
return null;
6075
}
61-
62-
$this->calledMethodStack[$stackName] = true;
63-
64-
$fileName = $this->fileHelper->normalizePath($declaringClass->getFileName());
65-
if (!$nodeScopeResolver->isAnalysedFile($fileName)) {
66-
unset($this->calledMethodStack[$stackName]);
67-
return null;
76+
if (isset($this->assignedTypes[$className][$methodName])) {
77+
return $this->assignedTypes[$className][$methodName];
6878
}
69-
$parserNodes = $this->parser->parseFile($fileName);
7079

71-
$returnStatement = null;
72-
$this->processNodesForCalledMethod($nodeScopeResolver, $parserNodes, new ExpressionResultStorage(), $fileName, $methodReflection, static function (Node $node, Scope $scope) use ($methodReflection, &$returnStatement): void {
73-
if (!$node instanceof MethodReturnStatementsNode) {
74-
return;
80+
$assignedTypes = [];
81+
foreach ($this->walkedMethods[$className][$methodName]->getImpurePoints() as $impurePoint) {
82+
$node = $impurePoint->getNode();
83+
if (!$node instanceof PropertyAssignNode) {
84+
continue;
7585
}
76-
77-
if ($node->getClassReflection()->getName() !== $methodReflection->getDeclaringClass()->getName()) {
78-
return;
86+
$propertyFetch = $node->getPropertyFetch();
87+
if (!$propertyFetch instanceof PropertyFetch || !$propertyFetch->name instanceof Identifier) {
88+
continue;
7989
}
80-
81-
if ($returnStatement !== null) {
82-
return;
90+
$propertyName = $propertyFetch->name->toString();
91+
if (array_key_exists($propertyName, $assignedTypes) && $assignedTypes[$propertyName] === null) {
92+
continue;
8393
}
84-
85-
$returnStatement = $node;
86-
});
87-
88-
$calledMethodEndScope = null;
89-
if ($returnStatement instanceof MethodReturnStatementsNode) {
90-
foreach ($returnStatement->getExecutionEnds() as $executionEnd) {
91-
$statementResult = $executionEnd->getStatementResult();
92-
$endExprResult = $executionEnd->getExprResult();
93-
if ($endExprResult !== null) {
94-
$walkScope = $statementResult->getScope()->toWalkScope();
95-
$exprType = $endExprResult->getTypeOnScope($walkScope, $walkScope->nativeTypesPromoted);
96-
if ($exprType instanceof NeverType && $exprType->isExplicit()) {
97-
continue;
98-
}
99-
}
100-
if ($calledMethodEndScope === null) {
101-
$calledMethodEndScope = $statementResult->getScope()->toWalkScope();
102-
continue;
103-
}
104-
105-
$calledMethodEndScope = $calledMethodEndScope->mergeWith($statementResult->getScope()->toWalkScope());
106-
}
107-
foreach ($returnStatement->getReturnStatements() as $statement) {
108-
if ($calledMethodEndScope === null) {
109-
$calledMethodEndScope = $statement->getScope()->toWalkScope();
110-
continue;
111-
}
112-
113-
$calledMethodEndScope = $calledMethodEndScope->mergeWith($statement->getScope()->toWalkScope());
94+
$scope = $impurePoint->getScope();
95+
$type = $scope->getType($node->getAssignedExpr());
96+
if (TypeUtils::containsTemplateType($type)) {
97+
// the method's own template types mean nothing after the call
98+
$assignedTypes[$propertyName] = null;
99+
continue;
114100
}
101+
$nativeType = $scope->getNativeType($node->getAssignedExpr());
102+
$assignedTypes[$propertyName] = isset($assignedTypes[$propertyName])
103+
? [TypeCombinator::union($assignedTypes[$propertyName][0], $type), TypeCombinator::union($assignedTypes[$propertyName][1], $nativeType)]
104+
: [$type, $nativeType];
115105
}
116106

117-
unset($this->calledMethodStack[$stackName]);
118-
119-
$this->calledMethodResults[$stackName] = $calledMethodEndScope;
120-
121-
return $calledMethodEndScope;
107+
return $this->assignedTypes[$className][$methodName] = $assignedTypes;
122108
}
123109

124-
public function clearCalledMethodResults(): void
110+
public function clearCalledMethodResults(ClassReflection $classReflection): void
125111
{
126-
$this->calledMethodResults = [];
112+
$className = $classReflection->getName();
113+
unset($this->walkedMethods[$className], $this->exitScopes[$className], $this->assignedTypes[$className]);
127114
}
128115

129-
/**
130-
* @param Node[]|Node|scalar|null $node
131-
* @param callable(Node $node, Scope $scope): void $nodeCallback
132-
*/
133-
private function processNodesForCalledMethod(NodeScopeResolver $nodeScopeResolver, $node, ExpressionResultStorage $storage, string $fileName, MethodReflection $methodReflection, callable $nodeCallback): void
116+
private function getExitScope(MethodReturnStatementsNode $returnStatement): ?MutatingScope
134117
{
135-
if ($node instanceof Node) {
136-
$declaringClass = $methodReflection->getDeclaringClass();
137-
if (
138-
$node instanceof Node\Stmt\Class_
139-
&& isset($node->namespacedName)
140-
&& $declaringClass->getName() === (string) $node->namespacedName
141-
&& $declaringClass->getNativeReflection()->getStartLine() === $node->getStartLine()
142-
) {
143-
144-
$stmts = $node->stmts;
145-
foreach ($stmts as $stmt) {
146-
if (!$stmt instanceof Node\Stmt\ClassMethod) {
147-
continue;
148-
}
149-
150-
if ($stmt->name->toString() !== $methodReflection->getName()) {
151-
continue;
152-
}
153-
154-
if ($stmt->getEndLine() - $stmt->getStartLine() > 50) {
155-
continue;
156-
}
157-
158-
$scope = $this->scopeFactory->create(ScopeContext::create($fileName))->enterClass($declaringClass);
159-
$nodeScopeResolver->processStmtNode($stmt, $scope, $storage, $nodeCallback, StatementContext::createTopLevel());
118+
$exitScope = null;
119+
foreach ($returnStatement->getExecutionEnds() as $executionEnd) {
120+
$statementResult = $executionEnd->getStatementResult();
121+
$endExprResult = $executionEnd->getExprResult();
122+
if ($endExprResult !== null) {
123+
$walkScope = $statementResult->getScope()->toWalkScope();
124+
$exprType = $endExprResult->getTypeOnScope($walkScope, $walkScope->nativeTypesPromoted);
125+
if ($exprType instanceof NeverType && $exprType->isExplicit()) {
126+
continue;
160127
}
161-
return;
162-
}
163-
if ($node instanceof Node\Stmt\ClassLike) {
164-
return;
165-
}
166-
if ($node instanceof Node\FunctionLike) {
167-
return;
168128
}
169-
foreach ($node->getSubNodeNames() as $subNodeName) {
170-
$subNode = $node->{$subNodeName};
171-
$this->processNodesForCalledMethod($nodeScopeResolver, $subNode, $storage, $fileName, $methodReflection, $nodeCallback);
129+
if ($exitScope === null) {
130+
$exitScope = $statementResult->getScope()->toWalkScope();
131+
continue;
172132
}
173-
} elseif (is_array($node)) {
174-
foreach ($node as $subNode) {
175-
$this->processNodesForCalledMethod($nodeScopeResolver, $subNode, $storage, $fileName, $methodReflection, $nodeCallback);
133+
134+
$exitScope = $exitScope->mergeWith($statementResult->getScope()->toWalkScope());
135+
}
136+
foreach ($returnStatement->getReturnStatements() as $statement) {
137+
if ($exitScope === null) {
138+
$exitScope = $statement->getScope()->toWalkScope();
139+
continue;
176140
}
141+
142+
$exitScope = $exitScope->mergeWith($statement->getScope()->toWalkScope());
177143
}
144+
145+
return $exitScope;
178146
}
179147

180148
}

‎src/Analyser/ExprHandler/MethodCallHandler.php‎

Lines changed: 2 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
use PHPStan\Analyser\ArgsResult;
1010
use PHPStan\Analyser\ArgumentsHandler;
1111
use PHPStan\Analyser\ArgumentsNormalizer;
12-
use PHPStan\Analyser\CalledMethodProcessor;
1312
use PHPStan\Analyser\ConditionalTypeResolver;
1413
use PHPStan\Analyser\ExpressionContext;
1514
use PHPStan\Analyser\ExpressionResult;
@@ -55,7 +54,6 @@
5554
use PHPStan\Type\StaticTypeFactory;
5655
use PHPStan\Type\Type;
5756
use PHPStan\Type\TypeCombinator;
58-
use PHPStan\Type\TypeUtils;
5957
use function array_map;
6058
use function array_merge;
6159
use function count;
@@ -70,7 +68,6 @@ final class MethodCallHandler implements ExprHandler
7068
{
7169

7270
public function __construct(
73-
private CalledMethodProcessor $calledMethodProcessor,
7471
private MethodCallReturnTypeHelper $methodCallReturnTypeHelper,
7572
private MethodThrowPointHelper $methodThrowPointHelper,
7673
private ReflectionProvider $reflectionProvider,
@@ -340,6 +337,7 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
340337
} elseif (!$hasSideEffects->no()) {
341338
$scope = $this->preservedPropertiesResolver->forgetWrittenProperties($scope, $expr);
342339
}
340+
$scope = $this->preservedPropertiesResolver->applyCalledMethodExitScope($scope, $expr, $methodReflection);
343341
if (!$methodReflection->isStatic()) {
344342
$selfOutType = $methodReflection->getSelfOutType();
345343
if ($selfOutType !== null) {
@@ -397,33 +395,7 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
397395
$walkMethodReflection !== null ? [$walkMethodReflection->getDeclaringClass()->getName()] : [],
398396
),
399397
);
400-
$result = $preliminaryResult->finalize($scope, $hasYield, $isAlwaysTerminating, $throwPoints, $impurePoints, $variableFlow, $dependencies);
401-
402-
// the var was processed above as the receiver; read its already-computed
403-
// result on the original scope instead of re-walking via Scope::getType().
404-
$calledOnType = $varResult->getType();
405-
if (!$expr->name instanceof Identifier) {
406-
return $result;
407-
}
408-
$methodName = $expr->name->name;
409-
$methodReflection = $originalScope->getMethodReflection($calledOnType, $methodName);
410-
if ($methodReflection === null) {
411-
return $result;
412-
}
413-
if (
414-
$scope->isInClass()
415-
&& $scope->getClassReflection()->getName() === $methodReflection->getDeclaringClass()->getName()
416-
&& ($scope->getFunctionName() !== null && strtolower($scope->getFunctionName()) === '__construct')
417-
&& TypeUtils::findThisType($calledOnType) !== null
418-
) {
419-
$calledMethodScope = $this->calledMethodProcessor->processCalledMethod($nodeScopeResolver, $methodReflection);
420-
if ($calledMethodScope !== null) {
421-
$scope = $scope->mergeInitializedProperties($calledMethodScope);
422-
return $result->withScope($scope);
423-
}
424-
}
425-
426-
return $result;
398+
return $preliminaryResult->finalize($scope, $hasYield, $isAlwaysTerminating, $throwPoints, $impurePoints, $variableFlow, $dependencies);
427399
}
428400

429401
/**

‎src/Analyser/ExprHandler/StaticCallHandler.php‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,9 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
404404
) {
405405
$scope = $this->preservedPropertiesResolver->forgetWrittenProperties($scope, $expr);
406406
}
407+
if ($methodReflection !== null) {
408+
$scope = $this->preservedPropertiesResolver->applyCalledMethodExitScope($scope, $expr, $methodReflection);
409+
}
407410

408411
if (
409412
$expr->class instanceof Name

0 commit comments

Comments
 (0)