Skip to content

Commit 22d8d95

Browse files
committed
Walk a for loop's exit condition instead of narrowing the back edge by it
After the loop expressions ran, the loop exits through the last condition evaluated again. The post-loop scope was the back-edge scope narrowed by the condition's falsey types, without the condition itself running there, so an assignment or side effect in it narrowed the body's stale value instead of replacing it: in `for ($i = 0; $row = ($i === 0 ? ['a' => 1] : fetchRow()); $i++)` $row became never after the loop, and in `for ($i = 0; $i++ < 10;)` so did $i. The condition is now walked on the back-edge scope and the loop exits through its falsey scope, as in WhileHandler. Amp-Thread-ID: https://ampcode.com/threads/T-01a21df9-ea78-720b-93d7-07b36502da60
1 parent 5bb7f27 commit 22d8d95

3 files changed

Lines changed: 50 additions & 31 deletions

File tree

‎src/Analyser/StmtHandler/ForHandler.php‎

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
use PHPStan\Analyser\NoopNodeCallback;
2424
use PHPStan\Analyser\StatementContext;
2525
use PHPStan\Analyser\StmtHandler;
26-
use PHPStan\Analyser\TypeSpecifierContext;
2726
use PHPStan\Analyser\VariableFlow;
2827
use PHPStan\Analyser\VariableFlowBuilder;
2928
use PHPStan\Dependency\Dependencies;
@@ -342,17 +341,19 @@ public function processStmt(
342341
$finalScope = $loopScope;
343342

344343
if ($lastCondExpr !== null) {
345-
// the loop condition narrows the post-loop scope to its falsey branch,
346-
// priced on the GENERALIZED exit scope. The condition's stored result
347-
// was walked before generalizeWith() widened the counter, so its
348-
// verdict is stale here: `$k <= $d` with a literal `$k` reads as
349-
// always-true, whose falsey branch is unreachable - and that narrowed
350-
// every operand to never, killing the enclosing loop's counter
351-
// (a nested loop's counter never widened). Same shape as WhileHandler.
352-
$finalScope = $finalScope->applySpecifiedTypes(
353-
$nodeScopeResolver->processExprOnDemand($lastCondExpr, $finalScope, $storage->duplicate())
354-
->getSpecifiedTypesForScope($finalScope, TypeSpecifierContext::createFalsey()),
355-
);
344+
// the loop exits when the condition, evaluated again after the loop
345+
// expressions ran, is falsey - walk it on $finalScope and take its
346+
// falsey scope, so the assignments and side effects it makes
347+
// (`$row = fetch()`, `$i++ < 10`) apply instead of the body's stale
348+
// values being narrowed by them. The duplicate keeps this walk's
349+
// results out of the final walk's storage. Same as WhileHandler.
350+
$exitCondStorage = $storage->duplicate();
351+
$scope->pushExpressionResultStorage($exitCondStorage);
352+
try {
353+
$finalScope = $nodeScopeResolver->processExprNode($stmt, $lastCondExpr, $finalScope, $exitCondStorage, new NoopNodeCallback(), ExpressionContext::createDeep(resolveTemplateArguments: false))->getFalseyScope();
354+
} finally {
355+
$scope->popExpressionResultStorage();
356+
}
356357
}
357358

358359
$breakExitPoints = $finalScopeResult->getExitPointsByType(Break_::class);

‎tests/PHPStan/Analyser/data/bug-15851-without-loop-pollution.php‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,18 @@ function lessThanUnknown(int $n): void
2929
assertType('int<0, max>', $i);
3030
assertType('5', $j);
3131
}
32+
33+
function assignmentInConditionAlwaysTrueAtFirst(): void
34+
{
35+
for ($i = 0; $row = ($i === 0 ? ['a' => 1] : fetchRow()); $i++) {
36+
echo $row['a'];
37+
}
38+
assertType('false', $row);
39+
}
40+
41+
function sideEffectInCondition(): void
42+
{
43+
for ($i = 0; $i++ < 10;) {
44+
}
45+
assertType('11', $i);
46+
}

‎turbo-ext/src/ForHandler.cpp‎

Lines changed: 22 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -438,25 +438,28 @@ class ForHandler
438438
finalScope = zv::Val::copyOf(loopScope.ref());
439439

440440
if (lastCondExpr != NULL) {
441-
// the loop condition narrows the post-loop scope to its falsey branch,
442-
// priced on the GENERALIZED exit scope. The condition's stored result
443-
// was walked before generalizeWith() widened the counter, so its
444-
// verdict is stale here: `$k <= $d` with a literal `$k` reads as
445-
// always-true, whose falsey branch is unreachable - and that narrowed
446-
// every operand to never, killing the enclosing loop's counter
447-
// (a nested loop's counter never widened). Same shape as WhileHandler.
448-
zv::Val duplicate = pt_expression_result_storage_duplicate(storage);
449-
if (UNEXPECTED(duplicate.isUndef())) return zv::Val();
450-
zv::Val onDemand = pt_node_scope_resolver_process_expr_on_demand(nodeScopeResolver, lastCondExpr, finalScope.raw(), duplicate.raw());
451-
if (UNEXPECTED(onDemand.isUndef())) return zv::Val();
452-
zend_object *falsey = pt_type_specifier_context_create_falsey();
453-
if (UNEXPECTED(falsey == NULL)) return zv::Val();
454-
zval falseyContext;
455-
ZVAL_OBJ(&falseyContext, falsey);
456-
zv::Val specifiedTypes = pt_expression_result_get_specified_types_for_scope(onDemand.raw(), finalScope.raw(), &falseyContext);
457-
if (UNEXPECTED(specifiedTypes.isUndef())) return zv::Val();
458-
finalScope = pt_mutating_scope_apply_specified_types(Z_OBJ_P(finalScope.raw()), specifiedTypes.raw());
459-
if (UNEXPECTED(finalScope.isUndef())) return zv::Val();
441+
// the loop exits when the condition, evaluated again after the loop
442+
// expressions ran, is falsey - walk it on $finalScope and take its
443+
// falsey scope, so the assignments and side effects it makes
444+
// (`$row = fetch()`, `$i++ < 10`) apply instead of the body's stale
445+
// values being narrowed by them. The duplicate keeps this walk's
446+
// results out of the final walk's storage. Same as WhileHandler.
447+
zv::Val exitCondStorage = pt_expression_result_storage_duplicate(storage);
448+
if (UNEXPECTED(exitCondStorage.isUndef())) return zv::Val();
449+
if (UNEXPECTED(!pt_mutating_scope_push_expression_result_storage(Z_OBJ_P(scope), exitCondStorage.raw()))) return zv::Val();
450+
zv::Val falseyScope;
451+
[&]() {
452+
zv::Val noop = ptlh::newNoopNodeCallback();
453+
if (UNEXPECTED(noop.isUndef())) return;
454+
zv::Val expressionContext = pt_expression_context_create_deep(false);
455+
if (UNEXPECTED(expressionContext.isUndef())) return;
456+
zv::Val exitCondResult = pt_node_scope_resolver_process_expr_node(nodeScopeResolver, stmt, lastCondExpr, finalScope.raw(), exitCondStorage.raw(), noop.raw(), expressionContext.raw());
457+
if (UNEXPECTED(exitCondResult.isUndef())) return;
458+
falseyScope = pt_expression_result_get_falsey_scope(exitCondResult.raw());
459+
}();
460+
pt_finally([&]() { (void) pt_mutating_scope_pop_expression_result_storage(Z_OBJ_P(scope)); });
461+
if (UNEXPECTED(EG(exception))) return zv::Val();
462+
finalScope = std::move(falseyScope);
460463
}
461464

462465
zv::Val breakExitPoints = ptlh::breakExitPoints(result);

0 commit comments

Comments
 (0)