Skip to content

Commit d29b7e1

Browse files
ondrejmirtesclaude
andcommitted
Do not decide statically which branches and loop bodies run in the variable flow
A usage in code that the analysis considers dead still counts: the variable flow no longer prunes if/elseif/else branches, loop bodies or blocks by the inferred or literal value of a condition, the type of the iterated value, the exhaustiveness of a switch without default, or the polluteScopeWithAlwaysIterableForeach, polluteScopeWithLoopInitialAssignments and polluteScopeWithBlock settings. Every branch, loop body and block may run or not - a write inside one does not make an earlier write dead, and a read inside one counts even when it can never run. A do-while body still runs once. Under polluteScopeWithBlock: false the block's variable flow was dropped altogether. InternalStatementResult::withVariableFlow() replaces the flow of the result a polluting block passes through. The DEAD flow kind, VariableFlow::dead() and the truthiness argument of VariableFlow::conditional() are gone. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Bm4YbtwnyY5UMgp64hK1ff
1 parent bdf33d3 commit d29b7e1

32 files changed

Lines changed: 630 additions & 356 deletions

‎src/Analyser/InternalStatementResult.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,14 @@ public function getVariableFlow(): ?VariableFlow
4545
return $this->variableFlow;
4646
}
4747

48+
public function withVariableFlow(?VariableFlow $variableFlow): self
49+
{
50+
$clone = clone $this;
51+
$clone->variableFlow = $variableFlow;
52+
53+
return $clone;
54+
}
55+
4856
/**
4957
* Whether execution can reach the end of the statements. Unlike isAlwaysTerminating(),
5058
* filterOutLoopExitPoints() does not reset it: a loop body left only through

‎src/Analyser/StmtHandler/BlockHandler.php‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
use PHPStan\Analyser\NodeScopeResolver;
1111
use PHPStan\Analyser\StatementContext;
1212
use PHPStan\Analyser\StmtHandler;
13+
use PHPStan\Analyser\VariableFlow;
1314
use PHPStan\DependencyInjection\AutowiredParameter;
1415
use PHPStan\DependencyInjection\AutowiredService;
1516
use PHPStan\Turbo\ShadowedByTurboExtension;
@@ -44,8 +45,12 @@ public function processStmt(
4445
): InternalStatementResult
4546
{
4647
$result = $nodeScopeResolver->processStmtNodesInternal($stmt, $stmt->stmts, $scope, $storage, $nodeCallback, $context);
48+
// like a loop body, the variable flow keeps the block optional whatever
49+
// polluteScopeWithBlock says: a write inside it does not make an
50+
// earlier write of the variable dead
51+
$variableFlow = VariableFlow::choice($result->getVariableFlow(), null);
4752
if ($this->polluteScopeWithBlock) {
48-
return $result;
53+
return $result->withVariableFlow($variableFlow);
4954
}
5055

5156
return new InternalStatementResult(
@@ -56,6 +61,7 @@ public function processStmt(
5661
throwPoints: $result->getThrowPoints(),
5762
impurePoints: $result->getImpurePoints(),
5863
endStatements: $result->getEndStatements(),
64+
variableFlow: $variableFlow,
5965
);
6066
}
6167

‎src/Analyser/StmtHandler/DoWhileHandler.php‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,8 @@ public function processStmt(
189189
exitPoints: $bodyScopeResult->getExitPointsForOuterLoop(),
190190
throwPoints: array_merge($throwPoints, $bodyScopeResult->getThrowPoints()),
191191
impurePoints: array_merge($impurePoints, $bodyScopeResult->getImpurePoints()),
192-
variableFlow: VariableFlow::loop(null, $bodyScopeResult->getVariableFlow(), $condResult->getVariableFlow(), true, !$alwaysIterates, !$condResult->getType()->toBoolean()->isFalse()->yes()),
192+
// the body runs once, then may repeat or not whatever the condition says
193+
variableFlow: VariableFlow::loop(null, $bodyScopeResult->getVariableFlow(), $condResult->getVariableFlow(), true, true),
193194
);
194195
}
195196

‎src/Analyser/StmtHandler/ForHandler.php‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -329,9 +329,9 @@ public function processStmt(
329329
}
330330
$condition = VariableFlow::sequence(...$conditionFlow);
331331
$update = VariableFlow::sequence(...$updateFlow);
332-
$loop = $isIterableAtLeastOnce->no()
333-
? VariableFlow::sequence($condition, VariableFlow::dead(VariableFlow::sequence($finalScopeResult->getVariableFlow(), $update)))
334-
: VariableFlow::loop($condition, $finalScopeResult->getVariableFlow(), $update, $isIterableAtLeastOnce->yes(), !$alwaysIterates->yes());
332+
// the body may run or not whatever the condition says: a write in it
333+
// does not make an earlier write dead, and a usage in it counts
334+
$loop = VariableFlow::loop($condition, $finalScopeResult->getVariableFlow(), $update, false, true);
335335
$initWrites = VariableFlowBuilder::writes(VariableFlow::sequence(...$initFlow));
336336
$bindings = [];
337337
foreach ($initWrites as $write) {

‎src/Analyser/StmtHandler/ForeachHandler.php‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -488,7 +488,10 @@ static function () use ($condResult, $emptyArrayType): Type {
488488
VariableFlowBuilder::targetWrite($stmt->valueVar, $stmt->keyVar !== null ? VariableWrite::KIND_FOREACH_VALUE_WITH_KEY : VariableWrite::KIND_FOREACH_VALUE, $finalScope, $storage),
489489
$stmt->byRef && $stmt->valueVar instanceof Variable && is_string($stmt->valueVar->name) ? VariableFlow::escape($stmt->valueVar->name) : null,
490490
);
491-
$loopFlow = VariableFlow::loop($traversableThrowPoint !== null ? VariableFlow::throwing($traversableThrowPoint->getType(), true) : null, VariableFlow::sequence($bindingFlow, $finalScopeResult->getVariableFlow()), null, $isIterableAtLeastOnce->yes() && $this->polluteScopeWithAlwaysIterableForeach, true);
491+
// the body may run or not whatever the iterated type says: a write in it
492+
// does not make an earlier write dead, and a read in it counts even
493+
// when the iterated value is inferred empty
494+
$loopFlow = VariableFlow::loop($traversableThrowPoint !== null ? VariableFlow::throwing($traversableThrowPoint->getType(), true) : null, VariableFlow::sequence($bindingFlow, $finalScopeResult->getVariableFlow()), null, false, true);
492495
$bindingWrites = VariableFlowBuilder::writes($bindingFlow);
493496
$bindings = [];
494497
foreach ($bindingWrites as $write) {
@@ -505,7 +508,7 @@ static function () use ($condResult, $emptyArrayType): Type {
505508
exitPoints: $finalScopeResult->getExitPointsForOuterLoop(),
506509
throwPoints: $throwPoints,
507510
impurePoints: $impurePoints,
508-
variableFlow: VariableFlow::sequence($condResult->getVariableFlow(), $isIterableAtLeastOnce->no() ? VariableFlow::dead($loopFlow) : $loopFlow),
511+
variableFlow: VariableFlow::sequence($condResult->getVariableFlow(), $loopFlow),
509512
);
510513
}
511514

‎src/Analyser/StmtHandler/IfHandler.php‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ public function processStmt(
6464
$alwaysTerminating = true;
6565
$hasYield = $condResult->hasYield();
6666
$branchScopeStatementResult = $nodeScopeResolver->processStmtNodesInternal($stmt, $stmt->stmts, $condResult->getTruthyScope(), $storage, $nodeCallback, $context);
67-
$flowBranches[] = [$condResult->getVariableFlow(), $branchScopeStatementResult->getVariableFlow(), $conditionType->isTrue()->yes() ? true : ($conditionType->isFalse()->yes() ? false : null)];
67+
$flowBranches[] = [$condResult->getVariableFlow(), $branchScopeStatementResult->getVariableFlow()];
6868
if (!$conditionType->isTrue()->no()) {
6969
$exitPoints = $branchScopeStatementResult->getExitPoints();
7070
$throwPoints = array_merge($throwPoints, $branchScopeStatementResult->getThrowPoints());
@@ -93,7 +93,7 @@ public function processStmt(
9393
$throwPoints = array_merge($throwPoints, $condResult->getThrowPoints());
9494
$impurePoints = array_merge($impurePoints, $condResult->getImpurePoints());
9595
$branchScopeStatementResult = $nodeScopeResolver->processStmtNodesInternal($elseif, $elseif->stmts, $condResult->getTruthyScope(), $storage, $nodeCallback, $context);
96-
$flowBranches[] = [$condResult->getVariableFlow(), $branchScopeStatementResult->getVariableFlow(), $elseIfConditionType->isTrue()->yes() ? true : ($elseIfConditionType->isFalse()->yes() ? false : null)];
96+
$flowBranches[] = [$condResult->getVariableFlow(), $branchScopeStatementResult->getVariableFlow()];
9797
if (
9898
!$ifAlwaysTrue
9999
&& !$lastElseIfConditionIsTrue
@@ -160,8 +160,10 @@ public function processStmt(
160160
$endStatements[] = new InternalEndStatementResult($stmt, new InternalStatementResult($finalScope, hasYield: $hasYield, isAlwaysTerminating: $alwaysTerminating, exitPoints: $exitPoints, throwPoints: $throwPoints, impurePoints: $impurePoints));
161161
}
162162

163-
foreach (array_reverse($flowBranches) as [$conditionFlow, $branchFlow, $truthy]) {
164-
$elseFlow = VariableFlow::conditional($conditionFlow, $branchFlow, $elseFlow, $truthy);
163+
// every branch may run in the variable flow, even one the condition's
164+
// type rules out: a usage in it counts
165+
foreach (array_reverse($flowBranches) as [$conditionFlow, $branchFlow]) {
166+
$elseFlow = VariableFlow::conditional($conditionFlow, $branchFlow, $elseFlow);
165167
}
166168
return new InternalStatementResult($finalScope, hasYield: $hasYield, isAlwaysTerminating: $alwaysTerminating, exitPoints: $exitPoints, throwPoints: $throwPoints, impurePoints: $impurePoints, endStatements: $endStatements, variableFlow: $elseFlow);
167169
}

‎src/Analyser/StmtHandler/SwitchHandler.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ public function processStmt(
175175
$finalScope = $scopeForBranches->mergeWith($finalScope);
176176
}
177177

178-
return new InternalStatementResult($finalScope, hasYield: $hasYield, isAlwaysTerminating: $alwaysTerminating, exitPoints: $exitPointsForOuterLoop, throwPoints: $throwPoints, impurePoints: $impurePoints, variableFlow: VariableFlow::switch($condResult->getVariableFlow(), $caseFlows, $hasDefaultCase || $exhaustive));
178+
return new InternalStatementResult($finalScope, hasYield: $hasYield, isAlwaysTerminating: $alwaysTerminating, exitPoints: $exitPointsForOuterLoop, throwPoints: $throwPoints, impurePoints: $impurePoints, variableFlow: VariableFlow::switch($condResult->getVariableFlow(), $caseFlows, $hasDefaultCase));
179179
}
180180

181181
}

‎src/Analyser/StmtHandler/WhileHandler.php‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -233,9 +233,9 @@ public function processStmt(
233233
exitPoints: $finalScopeResult->getExitPointsForOuterLoop(),
234234
throwPoints: $throwPoints,
235235
impurePoints: $impurePoints,
236-
variableFlow: $neverIterates
237-
? VariableFlow::sequence($condResult->getVariableFlow(), VariableFlow::dead($finalScopeResult->getVariableFlow()))
238-
: VariableFlow::loop($bodyCondResult->getVariableFlow(), $finalScopeResult->getVariableFlow(), null, $isIterableAtLeastOnce, !$alwaysIterates),
236+
// the body may run or not whatever the condition says: a write in
237+
// it does not make an earlier write dead, and a usage in it counts
238+
variableFlow: VariableFlow::loop($bodyCondResult->getVariableFlow(), $finalScopeResult->getVariableFlow(), null, false, true),
239239
);
240240
}
241241

‎src/Analyser/VariableFlow.php‎

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ abstract class VariableFlow
3333
public const READ_ALL = 'readAll';
3434
public const MENTION_ALL = 'mentionAll';
3535
public const OPAQUE = 'opaque';
36-
public const DEAD = 'dead';
3736
public const RETURN = 'return';
3837
public const BREAK = 'break';
3938
public const CONTINUE = 'continue';
@@ -94,16 +93,9 @@ public static function read(string $name, ?int $targetId = null, bool $container
9493
return new VariableAccessFlow(self::READ, $name, targetId: $targetId, container: $container, offset: $offset);
9594
}
9695

97-
public static function conditional(?self $condition, ?self $if, ?self $else, ?bool $truthy): ?self
96+
public static function conditional(?self $condition, ?self $if, ?self $else): ?self
9897
{
99-
if ($truthy === true) {
100-
$branch = self::sequence($if, self::dead($else));
101-
} elseif ($truthy === false) {
102-
$branch = self::sequence(self::dead($if), $else);
103-
} else {
104-
$branch = self::choice($if, $else);
105-
}
106-
return self::sequence($condition, $branch);
98+
return self::sequence($condition, self::choice($if, $else));
10799
}
108100

109101
/** @param list<array{self|null, self|null, bool}> $cases */
@@ -155,11 +147,6 @@ public static function throwing(Type $type, bool $canContinue, bool $canContainA
155147
return new VariableControlFlow(self::THROW, type: $type, canExit: $canContinue, canContainAnyThrowable: $canContainAnyThrowable);
156148
}
157149

158-
public static function dead(?self $flow): ?self
159-
{
160-
return $flow === null ? null : new VariableControlFlow(self::DEAD, [$flow]);
161-
}
162-
163150
public static function loop(?self $condition, ?self $body, ?self $update, bool $atLeastOnce, bool $canExit, bool $canRepeat = true): self
164151
{
165152
return new VariableControlFlow(self::LOOP, [$condition, $body, $update], atLeastOnce: $atLeastOnce, canExit: $canExit, canRepeat: $canRepeat);

‎src/Analyser/VariableLivenessResolver.php‎

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ public static function resolve(Node\FunctionLike $function, ?VariableFlow $flow)
155155
return new VariableWritesNode($function, array_values($self->writes), $self->observedIds + $self->readIds, $self->readIds, $self->coveredIds, $self->overwrittenIds, $self->readNames, $self->redundantTypes, $self->mentionedNames, $self->escapedNames, $self->variableOverwritingLoops, $self->opaque, $self->allNamesMentioned);
156156
}
157157

158-
private function collect(?VariableFlow $flow, bool $dead = false): void
158+
private function collect(?VariableFlow $flow): void
159159
{
160160
if ($flow === null || $flow instanceof VariableInputFlow) {
161161
return;
@@ -178,9 +178,6 @@ private function collect(?VariableFlow $flow, bool $dead = false): void
178178
if ($flow->type !== null) {
179179
$this->redundantTypes[$id] = $flow->type;
180180
}
181-
if ($dead) {
182-
$this->readIds[$id] = true;
183-
}
184181
}
185182
}
186183
if ($flow->kind === VariableFlow::READ_ALL) {
@@ -199,7 +196,7 @@ private function collect(?VariableFlow $flow, bool $dead = false): void
199196
throw new ShouldNotHappenException();
200197
}
201198
foreach ($flow->children as $child) {
202-
$this->collect($child, $dead || $flow->kind === VariableFlow::DEAD);
199+
$this->collect($child);
203200
}
204201
if (!$flow instanceof VariableControlFlow) {
205202
return;
@@ -218,11 +215,11 @@ private function collect(?VariableFlow $flow, bool $dead = false): void
218215
$this->escapedNames[$flow->name] = true;
219216
}
220217
foreach ($flow->cases as [$condition, $body]) {
221-
$this->collect($condition, $dead);
222-
$this->collect($body, $dead);
218+
$this->collect($condition);
219+
$this->collect($body);
223220
}
224221
foreach ($flow->catches as [, $catch]) {
225-
$this->collect($catch, $dead);
222+
$this->collect($catch);
226223
}
227224
}
228225

@@ -232,7 +229,7 @@ private function collect(?VariableFlow $flow, bool $dead = false): void
232229
*/
233230
private function liveBefore(?VariableFlow $flow, array $next, VariableFlowContext $context): array
234231
{
235-
if ($flow === null || $flow->kind === VariableFlow::DEAD) {
232+
if ($flow === null) {
236233
return $next;
237234
}
238235
if ($flow instanceof VariableInputFlow) {

0 commit comments

Comments
 (0)