Skip to content

Commit 2a70999

Browse files
committed
Walk a while loop's exit condition instead of narrowing the body's scope by it
After the body ran, the loop exits through the condition evaluated again. The post-loop scope was the body's back-edge scope narrowed by the condition's falsey types, without the condition itself running there, so an assignment in it narrowed the body's stale value instead of replacing it: in `while ($row = fetchRow())` the body's array{mixed} $row became never. Matching conditional expressions on a never guard then fixed variables set under a condition on $row to their our-branch type, such as $printed to true. The condition is now walked on the back-edge scope and the loop exits through its falsey scope, which also counts side effects such as `$i++` in the condition. When the loop may not run at all, the post-loop scope merges the exit scope with the scope where the first condition was falsey. These are alternative paths like an if's branches, so the merge now keeps a conditional expression that only one path records when the other path makes it vacuously true, as IfHandler does. Without it, the correlation `$rows !== 0` implies `$stop` after `while (!($stop = $s->stop()) && ($rows = $s->next()))` was lost when polluteScopeWithLoopInitialAssignments is off (as in strict-rules). Amp-Thread-ID: https://ampcode.com/threads/T-01a1d722-328d-734b-b55e-1eb10133f833
1 parent 1cc0ba8 commit 2a70999

6 files changed

Lines changed: 200 additions & 30 deletions

File tree

‎src/Analyser/StmtHandler/WhileHandler.php‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
use PHPStan\Analyser\RecordingNodeCallback;
1616
use PHPStan\Analyser\StatementContext;
1717
use PHPStan\Analyser\StmtHandler;
18-
use PHPStan\Analyser\TypeSpecifierContext;
1918
use PHPStan\Analyser\VariableFlow;
2019
use PHPStan\Dependency\Dependencies;
2120
use PHPStan\DependencyInjection\AutowiredParameter;
@@ -196,12 +195,18 @@ public function processStmt(
196195
$backEdgeScope = $finalScopeResult->getLoopBackEdgeScope();
197196
$backEdgeDead = $backEdgeScope === null;
198197
$finalScope = $backEdgeScope ?? $finalScopeResult->getScope();
199-
// the loop condition narrows the post-loop scope to its falsey branch;
200-
// $finalScope (after the body ran) is a different scope than the condition's
201-
// own, so reprocess the condition there rather than re-running its result.
202-
// The duplicate lets subresults whose state did not change in the body
203-
// answer from the final pass instead of being re-priced.
204-
$finalScope = $finalScope->applySpecifiedTypes($nodeScopeResolver->processExprOnDemand($stmt->cond, $finalScope, $storage->duplicate())->getSpecifiedTypesForScope($finalScope, TypeSpecifierContext::createFalsey()));
198+
// the loop exits when the condition, evaluated again after the body ran,
199+
// is falsey - walk it on $finalScope and take its falsey scope, so the
200+
// assignments it makes (`while ($row = fetch())`) replace the body's
201+
// values instead of the body's stale values being narrowed by them.
202+
// The duplicate keeps this walk's results out of the final pass's storage.
203+
$exitCondStorage = $storage->duplicate();
204+
$scope->pushExpressionResultStorage($exitCondStorage);
205+
try {
206+
$finalScope = $nodeScopeResolver->processExprNode($stmt, $stmt->cond, $finalScope, $exitCondStorage, new NoopNodeCallback(), ExpressionContext::createDeep(resolveTemplateArguments: false))->getFalseyScope();
207+
} finally {
208+
$scope->popExpressionResultStorage();
209+
}
205210

206211
$alwaysIterates = false;
207212
$neverIterates = false;
@@ -236,7 +241,10 @@ public function processStmt(
236241
if (!$this->polluteScopeWithLoopInitialAssignments) {
237242
$condScope = $condScope->mergeWith($scope);
238243
}
239-
$finalScope = $finalScope === null ? $condScope : $finalScope->mergeWith($condScope);
244+
// the loop either ran or exited on its first condition, so these are
245+
// alternative paths like an if's branches: keep a conditional that only
246+
// one path records when the other path makes it vacuously true
247+
$finalScope = $finalScope === null ? $condScope : $finalScope->mergeWith($condScope, true);
240248
}
241249
$finalScope ??= $finalScopeResult->getScope();
242250

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 Bug15722WithoutLoopPollutionTest extends TypeInferenceTestCase
9+
{
10+
11+
public static function dataFileAsserts(): iterable
12+
{
13+
yield from self::gatherAssertTypes(__DIR__ . '/data/bug-15722-without-loop-pollution.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__ . '/../Rules/without-loop-pollution.neon',
33+
];
34+
}
35+
36+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug15722WithoutLoopPollution;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
interface Source
8+
{
9+
public function stop(): bool;
10+
public function next(): int;
11+
}
12+
13+
function loop(Source $s): void
14+
{
15+
$rows = 0;
16+
while (!($stop = $s->stop()) && ($rows = $s->next())) {
17+
}
18+
19+
if ($rows !== 0) {
20+
assertType('true', $stop);
21+
}
22+
23+
if ($rows === 0) {
24+
assertType('bool', $stop);
25+
} else {
26+
assertType('true', $stop);
27+
}
28+
}
29+
30+
function noCorrelation(): void
31+
{
32+
$n = 0;
33+
$flag = false;
34+
while (rand(0, 1)) {
35+
$n = 1;
36+
$flag = (bool) rand(0, 1);
37+
}
38+
if ($n === 1) {
39+
assertType('bool', $flag);
40+
}
41+
}
42+
43+
function guardOverlaps(): void
44+
{
45+
$n = rand(0, 2);
46+
$flag = false;
47+
while (rand(0, 1)) {
48+
$n = 1;
49+
$flag = true;
50+
}
51+
if ($n === 1) {
52+
// the loop may not have run, with $n = 1 and $flag still false
53+
assertType('bool', $flag);
54+
}
55+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug15726;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
/** @return array{mixed}|false */
8+
function fetchRow()
9+
{
10+
return rand(0, 1) === 1 ? [rand(0, 1)] : false;
11+
}
12+
13+
function foo(): void
14+
{
15+
$prev = -1;
16+
$printed = false;
17+
while ($row = fetchRow()) {
18+
if ($row[0]) {
19+
$printed = true;
20+
}
21+
$prev = rand(0, 3);
22+
}
23+
assertType('false', $row);
24+
if ($prev !== -1) {
25+
assertType('bool', $printed); // the last row's [0] can be falsy
26+
}
27+
if ($prev != -1) {
28+
assertType('bool', $printed);
29+
}
30+
}
31+
32+
function postDecrement(): void
33+
{
34+
$i = 10;
35+
while ($i-- > 0) {
36+
assertType('int<0, 9>', $i);
37+
}
38+
assertType('-1', $i);
39+
}
40+
41+
// https://github.com/phpstan/phpstan/issues/15722 Problem B
42+
43+
interface Source
44+
{
45+
public function stop(): bool;
46+
public function next(): int;
47+
}
48+
49+
function loop(Source $s): void
50+
{
51+
$rows = 0;
52+
while (!($stop = $s->stop()) && ($rows = $s->next())) {
53+
}
54+
55+
if ($rows !== 0) {
56+
assertType('true', $stop);
57+
}
58+
59+
if ($rows === 0) {
60+
assertType('bool', $stop);
61+
} else {
62+
assertType('true', $stop);
63+
}
64+
}

‎tests/PHPStan/Analyser/nsrt/while-loop-variables.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ function () {
4949
assertType('int<1, 10>', $i);
5050
}
5151

52-
assertType('int<0, 10>', $i);
52+
assertType('int<0, 11>', $i); // the condition increments $i to 11 when $i++ < 10 fails
5353

5454
assertType('LoopVariables\Bar|LoopVariables\Foo|LoopVariables\Lorem|null', $foo);
5555

‎turbo-ext/src/WhileHandler.cpp‎

Lines changed: 28 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -294,27 +294,31 @@ class WhileHandler
294294
} else {
295295
finalScope = std::move(backEdgeScope);
296296
}
297-
// the loop condition narrows the post-loop scope to its falsey branch;
298-
// $finalScope (after the body ran) is a different scope than the condition's
299-
// own, so reprocess the condition there rather than re-running its result.
300-
// The duplicate lets subresults whose state did not change in the body
301-
// answer from the final pass instead of being re-priced.
297+
// the loop exits when the condition, evaluated again after the body ran,
298+
// is falsey - walk it on $finalScope and take its falsey scope, so the
299+
// assignments it makes (`while ($row = fetch())`) replace the body's
300+
// values instead of the body's stale values being narrowed by them.
301+
// The duplicate keeps this walk's results out of the final pass's storage.
302302
{
303-
zval *cond = ptsh::readNodeProperty(pt_wh_cond_site, stmt, PT_LC("cond"));
304-
if (UNEXPECTED(cond == NULL)) return zv::Val();
305-
zv::Val condHold = zv::Val::copyOf(zv::Ref(cond));
306-
zv::Val duplicate = pt_expression_result_storage_duplicate(finalStorage);
307-
if (UNEXPECTED(duplicate.isUndef())) return zv::Val();
308-
zv::Val onDemand = pt_node_scope_resolver_process_expr_on_demand(nodeScopeResolver, condHold.raw(), finalScope.raw(), duplicate.raw());
309-
if (UNEXPECTED(onDemand.isUndef())) return zv::Val();
310-
zend_object *falsey = pt_type_specifier_context_create_falsey();
311-
if (UNEXPECTED(falsey == NULL)) return zv::Val();
312-
zval falseyContext;
313-
ZVAL_OBJ(&falseyContext, falsey);
314-
zv::Val specifiedTypes = pt_expression_result_get_specified_types_for_scope(onDemand.raw(), finalScope.raw(), &falseyContext);
315-
if (UNEXPECTED(specifiedTypes.isUndef())) return zv::Val();
316-
finalScope = pt_mutating_scope_apply_specified_types(Z_OBJ_P(finalScope.raw()), specifiedTypes.raw());
317-
if (UNEXPECTED(finalScope.isUndef())) return zv::Val();
303+
zv::Val exitCondStorage = pt_expression_result_storage_duplicate(finalStorage);
304+
if (UNEXPECTED(exitCondStorage.isUndef())) return zv::Val();
305+
if (UNEXPECTED(!pt_mutating_scope_push_expression_result_storage(Z_OBJ_P(scope.raw()), exitCondStorage.raw()))) return zv::Val();
306+
zv::Val falseyScope;
307+
[&]() {
308+
zval *cond = ptsh::readNodeProperty(pt_wh_cond_site, stmt, PT_LC("cond"));
309+
if (UNEXPECTED(cond == NULL)) return;
310+
zv::Val condHold = zv::Val::copyOf(zv::Ref(cond));
311+
zv::Val noop = ptlh::newNoopNodeCallback();
312+
if (UNEXPECTED(noop.isUndef())) return;
313+
zv::Val expressionContext = pt_expression_context_create_deep(false);
314+
if (UNEXPECTED(expressionContext.isUndef())) return;
315+
zv::Val exitCondResult = pt_node_scope_resolver_process_expr_node(nodeScopeResolver, stmt, condHold.raw(), finalScope.raw(), exitCondStorage.raw(), noop.raw(), expressionContext.raw());
316+
if (UNEXPECTED(exitCondResult.isUndef())) return;
317+
falseyScope = pt_expression_result_get_falsey_scope(exitCondResult.raw());
318+
}();
319+
pt_finally([&]() { (void) pt_mutating_scope_pop_expression_result_storage(Z_OBJ_P(scope.raw())); });
320+
if (UNEXPECTED(EG(exception))) return zv::Val();
321+
finalScope = std::move(falseyScope);
318322
}
319323

320324
bool alwaysIterates = false;
@@ -376,7 +380,10 @@ class WhileHandler
376380
if (finalScope.isNull()) {
377381
finalScope = zv::Val::copyOf(condScope.ref());
378382
} else {
379-
finalScope = pt_mutating_scope_merge_with(Z_OBJ_P(finalScope.raw()), condScope.raw());
383+
// the loop either ran or exited on its first condition, so these are
384+
// alternative paths like an if's branches: keep a conditional that only
385+
// one path records when the other path makes it vacuously true
386+
finalScope = pt_mutating_scope_merge_with(Z_OBJ_P(finalScope.raw()), condScope.raw(), true);
380387
if (UNEXPECTED(finalScope.isUndef())) return zv::Val();
381388
}
382389
}

0 commit comments

Comments
 (0)