Skip to content

Commit 428ff02

Browse files
committed
Join the type before an overridable call with the walked type of a private property it writes
A call on $this that may run an override forgot the private properties the class's own method writes, so a property narrowed before the call went back to its declared type - a lazily created `?Client $client = null` became nullable again after any public method that runs `$this->client ??= new Client()`. Only the class's own code writes a private property, so it now has the type it had before the call or the type the walk of the class's method ends with. Amp-Thread-ID: https://ampcode.com/threads/T-01a1ffd7-32dc-7043-b3ac-2d8cf42d2441
1 parent da09694 commit 428ff02

7 files changed

Lines changed: 166 additions & 55 deletions

File tree

‎src/Analyser/ExprHandler/MethodCallHandler.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,7 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
335335
$this->preservedPropertiesResolver->resolve($expr),
336336
);
337337
} elseif (!$hasSideEffects->no()) {
338-
$scope = $this->preservedPropertiesResolver->forgetWrittenProperties($scope, $expr);
338+
$scope = $this->preservedPropertiesResolver->forgetWrittenProperties($scope, $expr, $methodReflection);
339339
}
340340
$scope = $this->preservedPropertiesResolver->applyCalledMethodExitScope($scope, $expr, $methodReflection);
341341
if (!$methodReflection->isStatic()) {

‎src/Analyser/ExprHandler/StaticCallHandler.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,7 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
402402
&& $methodReflection !== null
403403
&& !$methodReflection->hasSideEffects()->no()
404404
) {
405-
$scope = $this->preservedPropertiesResolver->forgetWrittenProperties($scope, $expr);
405+
$scope = $this->preservedPropertiesResolver->forgetWrittenProperties($scope, $expr, $methodReflection);
406406
}
407407
if ($methodReflection !== null) {
408408
$scope = $this->preservedPropertiesResolver->applyCalledMethodExitScope($scope, $expr, $methodReflection);

‎src/Analyser/PreservedProperties/PreservedPropertiesResolver.php‎

Lines changed: 108 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -55,78 +55,44 @@ public function __construct(
5555
*/
5656
public function applyCalledMethodExitScope(MutatingScope $scope, Expr $call, MethodReflection $methodReflection): MutatingScope
5757
{
58-
if ($methodReflection->isStatic() || !$scope->isInClass()) {
59-
return $scope;
60-
}
61-
$classReflection = $scope->getClassReflection();
62-
if ($methodReflection->getDeclaringClass()->getName() !== $classReflection->getName()) {
63-
return $scope;
64-
}
65-
66-
if ($call instanceof MethodCall) {
67-
if (!$call->var instanceof Variable || $call->var->name !== 'this') {
68-
return $scope;
69-
}
70-
$runsExactly = false;
71-
} elseif ($call instanceof StaticCall) {
72-
if (!$call->class instanceof Name) {
73-
return $scope;
74-
}
75-
$className = $call->class->toLowerString();
76-
if ($className === 'parent') {
77-
return $scope;
78-
}
79-
$function = $scope->getFunction();
80-
if (!$function instanceof MethodReflection || $function->isStatic()) {
81-
return $scope;
82-
}
83-
$runsExactly = $className !== 'static';
84-
} else {
85-
return $scope;
86-
}
87-
if (!$runsExactly && !$methodReflection->isPrivate() && !$methodReflection->isFinal()->yes() && !$classReflection->isFinal()) {
88-
return $scope;
89-
}
90-
91-
$exitScope = $this->calledMethodProcessor->getWalkedMethodExitScope($classReflection, $methodReflection->getName());
92-
if ($exitScope === null) {
58+
$walk = $this->findWalk($scope, $call, $methodReflection);
59+
if ($walk === null || !$walk[1]) {
9360
return $scope;
9461
}
62+
$exitScope = $walk[0];
9563
$scope = $scope->mergeInitializedProperties($exitScope);
9664

9765
$preservedProperties = $call->getAttribute(PreservedPropertiesVisitor::ATTRIBUTE_NAME);
9866
if (!$preservedProperties instanceof PreservedProperties) {
9967
return $scope;
10068
}
101-
$writtenPropertyNames = $preservedProperties->getWrittenPropertyNames();
10269

10370
$closureWrittenPropertyNames = $preservedProperties->getClosureWrittenPropertyNames();
10471
$overrideAssignedTypes = null;
105-
foreach (array_keys($writtenPropertyNames) as $propertyName) {
72+
foreach (array_keys($preservedProperties->getWrittenPropertyNames()) as $propertyName) {
10673
$propertyFetch = new PropertyFetch(new Variable('this'), $propertyName);
10774
if (
10875
$scope->hasExpressionType($propertyFetch)->yes()
109-
|| !$exitScope->hasExpressionType($propertyFetch)->yes()
11076
|| isset($closureWrittenPropertyNames[$propertyName])
11177
) {
11278
continue;
11379
}
114-
$type = $exitScope->getType($propertyFetch);
115-
if (TypeUtils::containsTemplateType($type)) {
116-
// the method's own template types mean nothing after the call
80+
$exitType = $this->findExitType($exitScope, $propertyFetch);
81+
if ($exitType === null) {
11782
continue;
11883
}
119-
$nativeType = $exitScope->getNativeType($propertyFetch);
12084
$overrideAssignedTypes ??= $this->findOverrideAssignedTypes($scope, $preservedProperties);
12185
if (array_key_exists($propertyName, $overrideAssignedTypes)) {
12286
if ($overrideAssignedTypes[$propertyName] === null) {
12387
// not all the writes are seen
12488
continue;
12589
}
126-
$type = TypeCombinator::union($type, $overrideAssignedTypes[$propertyName][0]);
127-
$nativeType = TypeCombinator::union($nativeType, $overrideAssignedTypes[$propertyName][1]);
90+
$exitType = [
91+
TypeCombinator::union($exitType[0], $overrideAssignedTypes[$propertyName][0]),
92+
TypeCombinator::union($exitType[1], $overrideAssignedTypes[$propertyName][1]),
93+
];
12894
}
129-
$scope = $scope->assignExpression($propertyFetch, $type, $nativeType);
95+
$scope = $scope->assignExpression($propertyFetch, $exitType[0], $exitType[1]);
13096
}
13197

13298
return $scope;
@@ -223,6 +189,70 @@ private function findAssignedType(ClassReflection $classReflection, array $write
223189
return [TypeCombinator::union(...$types), TypeCombinator::union(...$nativeTypes)];
224190
}
225191

192+
/**
193+
* The walk of the method of the class the call on $this runs, and whether the call runs
194+
* exactly that method; null when the call runs no walked method of the class.
195+
*
196+
* @return array{MutatingScope, bool}|null
197+
*/
198+
private function findWalk(MutatingScope $scope, Expr $call, MethodReflection $methodReflection): ?array
199+
{
200+
if ($methodReflection->isStatic() || !$scope->isInClass()) {
201+
return null;
202+
}
203+
$classReflection = $scope->getClassReflection();
204+
if ($methodReflection->getDeclaringClass()->getName() !== $classReflection->getName()) {
205+
return null;
206+
}
207+
208+
if ($call instanceof MethodCall) {
209+
if (!$call->var instanceof Variable || $call->var->name !== 'this') {
210+
return null;
211+
}
212+
$runsExactly = false;
213+
} elseif ($call instanceof StaticCall) {
214+
if (!$call->class instanceof Name) {
215+
return null;
216+
}
217+
$className = $call->class->toLowerString();
218+
if ($className === 'parent') {
219+
return null;
220+
}
221+
$function = $scope->getFunction();
222+
if (!$function instanceof MethodReflection || $function->isStatic()) {
223+
return null;
224+
}
225+
$runsExactly = $className !== 'static';
226+
} else {
227+
return null;
228+
}
229+
$runsExactly = $runsExactly || $methodReflection->isPrivate() || $methodReflection->isFinal()->yes() || $classReflection->isFinal();
230+
231+
$exitScope = $this->calledMethodProcessor->getWalkedMethodExitScope($classReflection, $methodReflection->getName());
232+
if ($exitScope === null) {
233+
return null;
234+
}
235+
236+
return [$exitScope, $runsExactly];
237+
}
238+
239+
/**
240+
* @return array{Type, Type}|null the type and native type the walk ended with
241+
*/
242+
private function findExitType(MutatingScope $exitScope, PropertyFetch $propertyFetch): ?array
243+
{
244+
if (!$exitScope->hasExpressionType($propertyFetch)->yes()) {
245+
return null;
246+
}
247+
$type = $exitScope->getType($propertyFetch);
248+
if (TypeUtils::containsTemplateType($type)) {
249+
// the method's own template types mean nothing after the call
250+
return null;
251+
}
252+
253+
return [$type, $exitScope->getNativeType($propertyFetch)];
254+
}
255+
226256
/**
227257
* @return array<string, true>|null null when every property is forgotten
228258
*/
@@ -247,8 +277,11 @@ public function resolve(Expr $call): ?array
247277
/**
248278
* A call not known to have side effects keeps everything remembered, except the properties
249279
* of $this that PreservedPropertiesVisitor saw the class's own code run by the call write.
280+
* When the call may run an override instead of the walked method, a private property only
281+
* the class's own code writes can also have only the type it had before the call or the type
282+
* the walk ended with.
250283
*/
251-
public function forgetWrittenProperties(MutatingScope $scope, Expr $call): MutatingScope
284+
public function forgetWrittenProperties(MutatingScope $scope, Expr $call, MethodReflection $methodReflection): MutatingScope
252285
{
253286
$preservedProperties = $call->getAttribute(PreservedPropertiesVisitor::ATTRIBUTE_NAME);
254287
if (!$preservedProperties instanceof PreservedProperties) {
@@ -263,18 +296,46 @@ public function forgetWrittenProperties(MutatingScope $scope, Expr $call): Mutat
263296
$propertyNames[$propertyName] = true;
264297
}
265298

299+
$walk = $this->findWalk($scope, $call, $methodReflection);
300+
$overridableExitScope = $walk !== null && !$walk[1] ? $walk[0] : null;
301+
$closureWrittenPropertyNames = $preservedProperties->getClosureWrittenPropertyNames();
266302
foreach (array_keys($propertyNames) as $propertyName) {
267303
$propertyFetch = new PropertyFetch(new Variable('this'), $propertyName);
268304
if ($scope->hasExpressionType($propertyFetch)->yes() && $scope->isReadonlyPropertyFetch($propertyFetch, true)) {
269305
// remembered, so initialized, and a readonly property cannot change after that
270306
continue;
271307
}
272-
$scope = $scope->invalidateExpression($propertyFetch);
308+
$exitType = $overridableExitScope !== null && !isset($closureWrittenPropertyNames[$propertyName]) && $this->isPrivatelyWritten($scope, $propertyName)
309+
? $this->findExitType($overridableExitScope, $propertyFetch)
310+
: null;
311+
if ($exitType === null || !$scope->hasExpressionType($propertyFetch)->yes()) {
312+
$scope = $scope->invalidateExpression($propertyFetch);
313+
continue;
314+
}
315+
316+
$scope = $scope->assignExpression(
317+
$propertyFetch,
318+
TypeCombinator::union($scope->getType($propertyFetch), $exitType[0]),
319+
TypeCombinator::union($scope->getNativeType($propertyFetch), $exitType[1]),
320+
);
273321
}
274322

275323
return $scope;
276324
}
277325

326+
private function isPrivatelyWritten(MutatingScope $scope, string $propertyName): bool
327+
{
328+
$classReflection = $scope->getClassReflection();
329+
if ($classReflection === null || !$classReflection->hasNativeProperty($propertyName)) {
330+
return false;
331+
}
332+
$property = $classReflection->getNativeProperty($propertyName);
333+
334+
return !$property->isStatic()
335+
&& ($property->isPrivate() || $property->isPrivateSet())
336+
&& $property->getDeclaringClass()->getName() === $classReflection->getName();
337+
}
338+
278339
/**
279340
* @param list<non-empty-string> $functionNames
280341
*/

‎tests/PHPStan/Analyser/nsrt/method-call-preserved-properties.php‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,13 @@ public function test(): void
5252
$callback();
5353
}
5454

55+
public function overridable(): void
56+
{
57+
$this->history = [];
58+
$this->prepareOverridable();
59+
assertType('list<int>', $this->history);
60+
}
61+
5562
private function prepare(): \Closure
5663
{
5764
$this->history = [];
@@ -62,6 +69,13 @@ private function prepare(): \Closure
6269
};
6370
}
6471

72+
public function prepareOverridable(): bool
73+
{
74+
$this->history = [];
75+
76+
return true;
77+
}
78+
6579
}
6680

6781
/** Called private method calling an overridable one: an override can write public and protected properties, not private ones. */
@@ -1384,6 +1398,7 @@ public function update(): void
13841398
}
13851399

13861400
}
1401+
13871402
abstract class ArgumentOverridesParent
13881403
{
13891404

@@ -1436,6 +1451,41 @@ private function load(): void
14361451

14371452
}
14381453

1454+
/** An overridable callee: a private property only the class's own code writes has its old type or the type the walk of the class's method ends with. */
1455+
class OverridableCalleeWrites
1456+
{
1457+
1458+
private ?\stdClass $client = null;
1459+
1460+
public ?\stdClass $publicClient = null;
1461+
1462+
private ?int $sometimes = null;
1463+
1464+
public function run(): void
1465+
{
1466+
if ($this->client === null || $this->publicClient === null) {
1467+
return;
1468+
}
1469+
$this->sometimes = 1;
1470+
$this->connect();
1471+
assertType('stdClass', $this->client);
1472+
assertType('stdClass|null', $this->publicClient);
1473+
assertType('int|null', $this->sometimes); // the walk starts from the declared type
1474+
}
1475+
1476+
public function connect(): bool
1477+
{
1478+
$this->client ??= new \stdClass();
1479+
$this->publicClient ??= new \stdClass();
1480+
if (rand(0, 1) === 1) {
1481+
$this->sometimes = 2;
1482+
}
1483+
1484+
return true;
1485+
}
1486+
1487+
}
1488+
14391489

14401490
class EscapedThisSender
14411491
{

‎turbo-ext/src/CallHandlerSupport.h‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -156,15 +156,15 @@ inline zv::Val preservedPropertiesResolve(zval *resolver, zval *call)
156156
return pt_call_method_cached(preservedPropertiesResolveSite, Z_OBJ_P(resolver), PT_LC("resolve"), 1, argv);
157157
}
158158

159-
/* $preservedPropertiesResolver->forgetWrittenProperties($scope, $call)
159+
/* $preservedPropertiesResolver->forgetWrittenProperties($scope, $call, $methodReflection)
160160
* (a call without the PreservedPropertiesVisitor attribute keeps the scope) */
161-
inline zv::Val forgetWrittenProperties(zval *resolver, zval *scope, zval *call)
161+
inline zv::Val forgetWrittenProperties(zval *resolver, zval *scope, zval *call, zval *methodReflection)
162162
{
163163
static zend_string *attributeName = zend_string_init(PT_LC("preservedProperties"), 1);
164164
zval *attribute = pt_node_attribute(Z_OBJ_P(call), attributeName);
165165
if (attribute == NULL || Z_TYPE_P(attribute) != IS_OBJECT) return zv::Val::copyOf(zv::Ref(scope));
166-
zv::Args argv{scope, call};
167-
return pt_call_method_cached(forgetWrittenPropertiesSite, Z_OBJ_P(resolver), PT_LC("forgetwrittenproperties"), 2, argv);
166+
zv::Args argv{scope, call, methodReflection};
167+
return pt_call_method_cached(forgetWrittenPropertiesSite, Z_OBJ_P(resolver), PT_LC("forgetwrittenproperties"), 3, argv);
168168
}
169169

170170
/* $type->getConstantStrings() */

‎turbo-ext/src/MethodCallHandler.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -466,7 +466,7 @@ class MethodCallHandler
466466
currentScope = pt_mutating_scope_invalidate_expression(Z_OBJ_P(currentScope.raw()), normalizedVar, true, declaringClass.raw(), zend_is_true(isStatic.raw()), preservedPropertyNames.isNull() ? NULL : preservedPropertyNames.raw());
467467
if (UNEXPECTED(currentScope.isUndef())) return zv::Val();
468468
} else if (hasSideEffects != PT_TRI_NO) {
469-
currentScope = forgetWrittenProperties(OBJ_PROP_NUM(self, slots::preservedPropertiesResolver), currentScope.raw(), expr);
469+
currentScope = forgetWrittenProperties(OBJ_PROP_NUM(self, slots::preservedPropertiesResolver), currentScope.raw(), expr, methodReflection.raw());
470470
if (UNEXPECTED(currentScope.isUndef())) return zv::Val();
471471
}
472472
currentScope = applyCalledMethodExitScope(OBJ_PROP_NUM(self, slots::preservedPropertiesResolver), currentScope.raw(), expr, methodReflection.raw(), true);

‎turbo-ext/src/StaticCallHandler.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -696,7 +696,7 @@ class StaticCallHandler
696696
currentScope = pt_mutating_scope_invalidate_expression(Z_OBJ_P(currentScope.raw()), thisVariable.raw(), true, declaringClass.raw(), isStatic, preservedPropertyNames.isNull() ? NULL : preservedPropertyNames.raw());
697697
if (UNEXPECTED(currentScope.isUndef())) return zv::Val();
698698
} else if (hasSideEffects != PT_TRI_NO) {
699-
currentScope = forgetWrittenProperties(OBJ_PROP_NUM(self, slots::preservedPropertiesResolver), currentScope.raw(), expr);
699+
currentScope = forgetWrittenProperties(OBJ_PROP_NUM(self, slots::preservedPropertiesResolver), currentScope.raw(), expr, methodReflection.raw());
700700
if (UNEXPECTED(currentScope.isUndef())) return zv::Val();
701701
}
702702
}

0 commit comments

Comments
 (0)