Skip to content

Commit 2f59b3c

Browse files
committed
Forget only the still-changing variables when a loop reaches the iteration limit
A loop that did not converge within LOOP_SCOPE_ITERATIONS passes turned every variable it writes into mixed. A single variable whose type never equals itself between passes - phpstan-doctrine's query builder types are keyed by uniqid() - so took every other variable of the loop with it: for ($i = 0; $i < 12; $i++) { $qb = $factory->where('a'); $to = $to->minusMonths(1); } // $to was mixed, $i NAN|float|int At the limit each further pass now calls MutatingScope::forgetChangedLoopVariables(), which makes only the variables whose type changed since the previous head mixed and lets the loop iterate on. A forgotten variable that is reassigned changes again and is forgotten again, so the head stops changing once every non-converging variable is mixed. When what still changes is not a variable, or the loop has not converged after LOOP_SCOPE_FORGETTING_ITERATIONS_LIMIT more passes, it forgets everything the loop writes as before. The native loop handlers and MutatingScope follow the same logic. Amp-Thread-ID: https://ampcode.com/threads/T-01a21efd-56f1-73e5-84f4-12131a86dbe9
1 parent 64f367f commit 2f59b3c

20 files changed

Lines changed: 638 additions & 238 deletions

‎src/Analyser/MutatingScope.php‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5029,6 +5029,58 @@ public function forgetLoopWrittenVariables(?array $writtenVariableNames): self
50295029
return $scope;
50305030
}
50315031

5032+
/**
5033+
* One pass of a loop that reached NodeScopeResolver::LOOP_SCOPE_ITERATIONS:
5034+
* only the variables whose type changed since $previousScope become mixed,
5035+
* so the variables that did converge keep their types while the loop
5036+
* iterates on. A variable reassigned after it was forgotten changes again
5037+
* and is forgotten again, so the head stops changing once every variable
5038+
* that does not converge is mixed.
5039+
*
5040+
* Returns null when what changed is not a variable - forgetting cannot
5041+
* make such a head converge.
5042+
*/
5043+
public function forgetChangedLoopVariables(self $previousScope): ?self
5044+
{
5045+
$changedVariableNames = $this->getChangedVariableNames($previousScope);
5046+
if ($changedVariableNames !== []) {
5047+
return $this->forgetLoopWrittenVariables($changedVariableNames);
5048+
}
5049+
5050+
// a head no variable changed in converges at the next pass's entry check
5051+
return $this->equals($previousScope) ? $this : null;
5052+
}
5053+
5054+
/**
5055+
* Variables whose type or certainty differs between this scope and
5056+
* $otherScope, in either flavour.
5057+
*
5058+
* @return array<string, true>
5059+
*/
5060+
private function getChangedVariableNames(self $otherScope): array
5061+
{
5062+
$names = [];
5063+
foreach ([
5064+
[$this->expressionTypes, $otherScope->expressionTypes],
5065+
[$this->nativeExpressionTypes, $otherScope->nativeExpressionTypes],
5066+
] as [$holders, $otherHolders]) {
5067+
foreach ([[$holders, $otherHolders], [$otherHolders, $holders]] as [$a, $b]) {
5068+
foreach ($a as $exprString => $holder) {
5069+
$expr = $holder->getExpr();
5070+
if (!$expr instanceof Variable || !is_string($expr->name)) {
5071+
continue;
5072+
}
5073+
if (isset($b[$exprString]) && $holder->equals($b[$exprString])) {
5074+
continue;
5075+
}
5076+
$names[$expr->name] = true;
5077+
}
5078+
}
5079+
}
5080+
5081+
return $names;
5082+
}
5083+
50325084
/**
50335085
* Generalizes a type that grew in a round of a fixed point the way a loop
50345086
* generalizes a variable it writes: the constant parts that changed

‎src/Analyser/NodeScopeResolver.php‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,9 @@ class NodeScopeResolver
6666
public const LOOP_SCOPE_ITERATIONS = 10;
6767
public const GENERALIZE_AFTER_ITERATION = 1;
6868

69+
/** Passes a loop that reached LOOP_SCOPE_ITERATIONS makes forgetting its still-changing variables before it forgets everything it writes. */
70+
public const LOOP_SCOPE_FORGETTING_ITERATIONS_LIMIT = 10;
71+
6972
/** @var array<string, true> filePath(string) => bool(true) */
7073
private array $analysedFiles = [];
7174

‎src/Analyser/StmtHandler/DoWhileHandler.php‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ public function processStmt(
5858
$bodyScope = $scope;
5959
$writtenVariableNames = null;
6060
$count = 0;
61+
$iterationLimitReached = false;
6162
$hasYield = false;
6263
$throwPoints = [];
6364
$impurePoints = [];
@@ -140,13 +141,22 @@ public function processStmt(
140141
$bodyScope = $prevScope->generalizeWith($bodyScope, $writtenVariableNames, $loopEntryScope);
141142
}
142143
$count++;
143-
} while ($count < NodeScopeResolver::LOOP_SCOPE_ITERATIONS);
144-
$iterationLimitReached = $count >= NodeScopeResolver::LOOP_SCOPE_ITERATIONS;
145-
if ($iterationLimitReached) {
146-
// the limit is only a safety net - a scope still changing after it
147-
// is not a fixpoint, so nothing the loop writes keeps a type
148-
$bodyScope = $bodyScope->forgetLoopWrittenVariables($writtenVariableNames);
149-
}
144+
if ($count < NodeScopeResolver::LOOP_SCOPE_ITERATIONS) {
145+
continue;
146+
}
147+
// the limit is only a safety net - the variables still changing
148+
// are forgotten while the loop iterates on
149+
$forgottenScope = $count < NodeScopeResolver::LOOP_SCOPE_ITERATIONS + NodeScopeResolver::LOOP_SCOPE_FORGETTING_ITERATIONS_LIMIT
150+
? $bodyScope->forgetChangedLoopVariables($prevScope)
151+
: null;
152+
if ($forgottenScope === null) {
153+
// what still changes is not a variable, so nothing the loop writes keeps a type
154+
$iterationLimitReached = true;
155+
$bodyScope = $bodyScope->forgetLoopWrittenVariables($writtenVariableNames);
156+
break;
157+
}
158+
$bodyScope = $forgottenScope;
159+
} while (true);
150160

151161
if (!$entryConverged) {
152162
// a body state that did not converge may still reach the guards

‎src/Analyser/StmtHandler/ForHandler.php‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -281,13 +281,22 @@ public function processStmt(
281281
$bodyScope = $prevScope->generalizeWith($bodyScope, $writtenVariableNames, $loopEntryScope);
282282
}
283283
$count++;
284-
} while ($count < NodeScopeResolver::LOOP_SCOPE_ITERATIONS);
285-
$iterationLimitReached = $count >= NodeScopeResolver::LOOP_SCOPE_ITERATIONS;
286-
if ($iterationLimitReached) {
287-
// the limit is only a safety net - a scope still changing after it
288-
// is not a fixpoint, so nothing the loop writes keeps a type
289-
$bodyScope = $bodyScope->forgetLoopWrittenVariables($writtenVariableNames);
290-
}
284+
if ($count < NodeScopeResolver::LOOP_SCOPE_ITERATIONS) {
285+
continue;
286+
}
287+
// the limit is only a safety net - the variables still changing
288+
// are forgotten while the loop iterates on
289+
$forgottenScope = $count < NodeScopeResolver::LOOP_SCOPE_ITERATIONS + NodeScopeResolver::LOOP_SCOPE_FORGETTING_ITERATIONS_LIMIT
290+
? $bodyScope->forgetChangedLoopVariables($prevScope)
291+
: null;
292+
if ($forgottenScope === null) {
293+
// what still changes is not a variable, so nothing the loop writes keeps a type
294+
$iterationLimitReached = true;
295+
$bodyScope = $bodyScope->forgetLoopWrittenVariables($writtenVariableNames);
296+
break;
297+
}
298+
$bodyScope = $forgottenScope;
299+
} while (true);
291300
}
292301

293302
$storage = $originalStorage;

‎src/Analyser/StmtHandler/ForeachHandler.php‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -296,13 +296,22 @@ static function () use ($condResult, $emptyArrayType): Type {
296296
$bodyScope = $prevScope->generalizeWith($bodyScope, $writtenVariableNames, $loopEntryScope);
297297
}
298298
$count++;
299-
} while ($count < NodeScopeResolver::LOOP_SCOPE_ITERATIONS);
300-
$iterationLimitReached = $count >= NodeScopeResolver::LOOP_SCOPE_ITERATIONS;
301-
if ($iterationLimitReached) {
302-
// the limit is only a safety net - a scope still changing after it
303-
// is not a fixpoint, so nothing the loop writes keeps a type
304-
$bodyScope = $bodyScope->forgetLoopWrittenVariables($writtenVariableNames);
305-
}
299+
if ($count < NodeScopeResolver::LOOP_SCOPE_ITERATIONS) {
300+
continue;
301+
}
302+
// the limit is only a safety net - the variables still changing
303+
// are forgotten while the loop iterates on
304+
$forgottenScope = $count < NodeScopeResolver::LOOP_SCOPE_ITERATIONS + NodeScopeResolver::LOOP_SCOPE_FORGETTING_ITERATIONS_LIMIT
305+
? $bodyScope->forgetChangedLoopVariables($prevScope)
306+
: null;
307+
if ($forgottenScope === null) {
308+
// what still changes is not a variable, so nothing the loop writes keeps a type
309+
$iterationLimitReached = true;
310+
$bodyScope = $bodyScope->forgetLoopWrittenVariables($writtenVariableNames);
311+
break;
312+
}
313+
$bodyScope = $forgottenScope;
314+
} while (true);
306315
}
307316
}
308317

‎src/Analyser/StmtHandler/WhileHandler.php‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -165,13 +165,22 @@ public function processStmt(
165165
$bodyScope = $prevScope->generalizeWith($bodyScope, $writtenVariableNames, $loopEntryScope);
166166
}
167167
$count++;
168-
} while ($count < NodeScopeResolver::LOOP_SCOPE_ITERATIONS);
169-
$iterationLimitReached = $count >= NodeScopeResolver::LOOP_SCOPE_ITERATIONS;
170-
if ($iterationLimitReached) {
171-
// the limit is only a safety net - a scope still changing after it
172-
// is not a fixpoint, so nothing the loop writes keeps a type
173-
$bodyScope = $bodyScope->forgetLoopWrittenVariables($writtenVariableNames);
174-
}
168+
if ($count < NodeScopeResolver::LOOP_SCOPE_ITERATIONS) {
169+
continue;
170+
}
171+
// the limit is only a safety net - the variables still changing
172+
// are forgotten while the loop iterates on
173+
$forgottenScope = $count < NodeScopeResolver::LOOP_SCOPE_ITERATIONS + NodeScopeResolver::LOOP_SCOPE_FORGETTING_ITERATIONS_LIMIT
174+
? $bodyScope->forgetChangedLoopVariables($prevScope)
175+
: null;
176+
if ($forgottenScope === null) {
177+
// what still changes is not a variable, so nothing the loop writes keeps a type
178+
$iterationLimitReached = true;
179+
$bodyScope = $bodyScope->forgetLoopWrittenVariables($writtenVariableNames);
180+
break;
181+
}
182+
$bodyScope = $forgottenScope;
183+
} while (true);
175184
}
176185

177186
if (!$entryConverged) {
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Analyser;
4+
5+
use PhpParser\Node\Expr\MethodCall;
6+
use PHPStan\Reflection\MethodReflection;
7+
use PHPStan\Type\DynamicMethodReturnTypeExtension;
8+
use PHPStan\Type\Type;
9+
use function uniqid;
10+
11+
/**
12+
* Like phpstan-doctrine's QueryBuilderType::append(), every call returns a
13+
* type with a new identity, so a loop calling it never converges.
14+
*/
15+
final class Bug15872ReturnTypeExtension implements DynamicMethodReturnTypeExtension
16+
{
17+
18+
public function getClass(): string
19+
{
20+
return 'Bug15872\Builder';
21+
}
22+
23+
public function isMethodSupported(MethodReflection $methodReflection): bool
24+
{
25+
return $methodReflection->getName() === 'where';
26+
}
27+
28+
public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): Type
29+
{
30+
return new Bug15872TrackedBuilderType(uniqid());
31+
}
32+
33+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Analyser;
4+
5+
use PHPStan\Testing\TypeInferenceTestCase;
6+
use PHPUnit\Framework\Attributes\DataProvider;
7+
8+
class Bug15872Test extends TypeInferenceTestCase
9+
{
10+
11+
public static function dataFileAsserts(): iterable
12+
{
13+
yield from self::gatherAssertTypes(__DIR__ . '/data/bug-15872.php');
14+
}
15+
16+
/**
17+
* @param mixed ...$args
18+
*/
19+
#[DataProvider('dataFileAsserts')]
20+
public function testFileAsserts(
21+
string $assertType,
22+
string $file,
23+
...$args,
24+
): void
25+
{
26+
$this->assertFileAsserts($assertType, $file, ...$args);
27+
}
28+
29+
public static function getAdditionalConfigFiles(): array
30+
{
31+
return [
32+
__DIR__ . '/bug-15872.neon',
33+
];
34+
}
35+
36+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Analyser;
4+
5+
use PHPStan\Type\IsSuperTypeOfResult;
6+
use PHPStan\Type\ObjectType;
7+
use PHPStan\Type\Type;
8+
9+
/**
10+
* Like phpstan-doctrine's BranchingQueryBuilderType, equals() compares an
11+
* identity each call of the extension creates anew.
12+
*/
13+
final class Bug15872TrackedBuilderType extends ObjectType
14+
{
15+
16+
public function __construct(public readonly string $id)
17+
{
18+
parent::__construct('Bug15872\Builder');
19+
}
20+
21+
public function equals(Type $type): bool
22+
{
23+
return $type instanceof self && $type->id === $this->id;
24+
}
25+
26+
public function isSuperTypeOf(Type $type): IsSuperTypeOfResult
27+
{
28+
return $type instanceof self ? IsSuperTypeOfResult::createFromBoolean($this->equals($type)) : parent::isSuperTypeOf($type);
29+
}
30+
31+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
services:
2+
-
3+
class: PHPStan\Analyser\Bug15872ReturnTypeExtension
4+
tags:
5+
- phpstan.broker.dynamicMethodReturnTypeExtension

0 commit comments

Comments
 (0)