Skip to content

Commit 47fb6eb

Browse files
ondrejmirtesclaude
andcommitted
Propagate conditional expressions through derived assignments
A variable assigned from a pure expression reading a variable that existing conditional expressions describe now receives conditional expressions of its own: the right-hand side is re-evaluated under each source holder's conditions and consequent, so e.g. the per-key value implications recorded by foreach over a constant array survive $functionToCall = 'fetch' . $functionName. The added precision proves two conditions in PHPStan's own source always-true/always-false; they are removed here to keep self-analysis clean. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CGhnJQpUWRRpg6H5LuWJkA
1 parent 4c90645 commit 47fb6eb

6 files changed

Lines changed: 163 additions & 2 deletions

File tree

‎src/Analyser/ExprHandler/AssignHandler.php‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
use PhpParser\Node\Expr\Variable;
2222
use PhpParser\Node\Name;
2323
use PhpParser\Node\Stmt;
24+
use PhpParser\NodeFinder;
2425
use PHPStan\Analyser\AssignTargetWalkMode;
2526
use PHPStan\Analyser\ConditionalExpressionHolder;
2627
use PHPStan\Analyser\ExpressionContext;
@@ -79,6 +80,7 @@
7980
use PHPStan\Type\TypeUtils;
8081
use PHPStan\Type\UnionType;
8182
use TypeError;
83+
use function array_key_exists;
8284
use function array_key_last;
8385
use function array_merge;
8486
use function array_pop;
@@ -100,6 +102,8 @@ final class AssignHandler implements ExprHandler
100102

101103
private const TERNARY_ARM_EXCLUDED_VALUES_LIMIT = 3;
102104

105+
private const DERIVED_CONDITIONAL_EXPRESSIONS_LIMIT = 16;
106+
103107
public function __construct(
104108
private VarAnnotationProcessor $varAnnotationProcessor,
105109
private TypeSpecifier $typeSpecifier,
@@ -950,6 +954,8 @@ public function applyWrite(
950954
$conditionalExpressions = $this->processInArrayForConditionalExpressionsAfterAssign($scopeBeforeAssignEval, $var->name, $conditionalExpressions, $assignedExpr, $type, $impurePoints);
951955
}
952956

957+
$conditionalExpressions = $this->processDerivedConditionalExpressionsAfterAssign($scopeBeforeAssignEval, $var->name, $conditionalExpressions, $assignedExpr, $type, $impurePoints);
958+
953959
$truthyType = TypeCombinator::removeFalsey($type);
954960
// Value comparison, not identity: remove() happens to hand back the very same
955961
// instance when it removes nothing, but that is not part of its contract — the
@@ -1663,6 +1669,87 @@ private function processMatchForConditionalExpressionsAfterAssign(
16631669
return $newConditionalExpressions;
16641670
}
16651671

1672+
/**
1673+
* Propagates conditional expressions through a derived assignment: when the
1674+
* right-hand side reads a variable that existing conditional expressions describe
1675+
* (e.g. `if $key = 'test1' then $functionName is 'Test'`), the assigned variable
1676+
* gets its own conditional expressions under the same conditions, with the
1677+
* right-hand side re-evaluated under each consequent
1678+
* (`if $key = 'test1' then $functionToCall is 'fetchTest'`).
1679+
*
1680+
* @param array<string, ConditionalExpressionHolder[]> $conditionalExpressions
1681+
* @param ImpurePoint[] $rhsImpurePoints
1682+
* @return array<string, ConditionalExpressionHolder[]>
1683+
*/
1684+
private function processDerivedConditionalExpressionsAfterAssign(
1685+
MutatingScope $scope,
1686+
string $variableName,
1687+
array $conditionalExpressions,
1688+
Expr $assignedExpr,
1689+
Type $assignedType,
1690+
array $rhsImpurePoints,
1691+
): array
1692+
{
1693+
if (count($rhsImpurePoints) > 0) {
1694+
return $conditionalExpressions;
1695+
}
1696+
$scopeConditionalExpressions = $scope->getConditionalExpressions();
1697+
if (count($scopeConditionalExpressions) === 0) {
1698+
return $conditionalExpressions;
1699+
}
1700+
1701+
$targetExprString = '$' . $variableName;
1702+
$evaluations = 0;
1703+
$seenReadExprStrings = [];
1704+
/** @var Variable[] $readVariables */
1705+
$readVariables = (new NodeFinder())->findInstanceOf([$assignedExpr], Variable::class);
1706+
foreach ($readVariables as $readVariable) {
1707+
if (!is_string($readVariable->name) || $readVariable->name === $variableName) {
1708+
continue;
1709+
}
1710+
$readExprString = '$' . $readVariable->name;
1711+
if (array_key_exists($readExprString, $seenReadExprStrings)) {
1712+
continue;
1713+
}
1714+
$seenReadExprStrings[$readExprString] = true;
1715+
1716+
foreach ($scopeConditionalExpressions[$readExprString] ?? [] as $holder) {
1717+
$consequent = $holder->getTypeHolder();
1718+
if (!$consequent->getCertainty()->yes()) {
1719+
continue;
1720+
}
1721+
1722+
$conditionHolders = $holder->getConditionExpressionTypeHolders();
1723+
$evalScope = $scope;
1724+
foreach ($conditionHolders as $conditionExprString => $conditionHolder) {
1725+
if ($conditionExprString === $targetExprString || !$conditionHolder->getCertainty()->yes()) {
1726+
// a condition on the just-overwritten variable is stale
1727+
continue 2;
1728+
}
1729+
$evalScope = $evalScope->assignExpression($conditionHolder->getExpr(), $conditionHolder->getType(), $conditionHolder->getType());
1730+
}
1731+
1732+
if (++$evaluations > self::DERIVED_CONDITIONAL_EXPRESSIONS_LIMIT) {
1733+
return $conditionalExpressions;
1734+
}
1735+
1736+
$evalScope = $evalScope->assignExpression($consequent->getExpr(), $consequent->getType(), $consequent->getType());
1737+
$derivedType = $evalScope->getType($assignedExpr);
1738+
if ($derivedType->equals($assignedType)) {
1739+
continue;
1740+
}
1741+
1742+
$derivedHolder = new ConditionalExpressionHolder(
1743+
$conditionHolders,
1744+
ExpressionTypeHolder::createYes(new Variable($variableName), $derivedType),
1745+
);
1746+
$conditionalExpressions[$targetExprString][$derivedHolder->getKey()] = $derivedHolder;
1747+
}
1748+
}
1749+
1750+
return $conditionalExpressions;
1751+
}
1752+
16661753
/**
16671754
* Records the reverse implication of a `$var = in_array($needle, [...known values])`
16681755
* assignment: a needle that is one of the haystack's always-present values makes the

‎src/Analyser/RuleErrorTransformer.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ private function fix(string $fixingFile, array $fileNodes, Node $originalNode, c
188188
}
189189
}
190190

191-
if (!$replacingVisitor->isFound() || $indent === null) {
191+
if (!$replacingVisitor->isFound()) {
192192
return null;
193193
}
194194

‎src/Analyser/StmtHandler/WhileHandler.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ public function processStmt(
9191
}
9292
// the candidate to replace the final walk when this pass's
9393
// entry turns out to be the fixpoint
94-
if ($condRecording instanceof RecordingNodeCallback && $bodyRecording instanceof RecordingNodeCallback) {
94+
if ($condRecording instanceof RecordingNodeCallback) {
9595
$replayCondRecording = $condRecording;
9696
$replayBodyRecording = $bodyRecording;
9797
$replayPassStorage = $storage;
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug13054;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
class Test {
8+
public function fetchTest(int $i): void {
9+
echo $i;
10+
}
11+
12+
public function fetchTest2(): void {
13+
echo 'test';
14+
}
15+
16+
public function exec(): void {
17+
$list = [
18+
'test1' => 'Test',
19+
'test2' => 'Test2',
20+
];
21+
22+
foreach ($list as $key => $functionName) {
23+
$functionToCall = 'fetch' . $functionName;
24+
25+
if ($key === 'test1') {
26+
assertType("'fetchTest'", $functionToCall);
27+
$this->$functionToCall(1);
28+
} else {
29+
assertType("'fetchTest2'", $functionToCall);
30+
$this->$functionToCall();
31+
}
32+
}
33+
}
34+
}

‎tests/PHPStan/Rules/Methods/CallMethodsRuleTest.php‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3857,6 +3857,16 @@ public function testBug13708(): void
38573857
$this->analyse([__DIR__ . '/data/bug-13708.php'], []);
38583858
}
38593859

3860+
public function testBug13054(): void
3861+
{
3862+
$this->checkThisOnly = false;
3863+
$this->checkNullables = false;
3864+
$this->checkUnionTypes = true;
3865+
$this->checkExplicitMixed = false;
3866+
3867+
$this->analyse([__DIR__ . '/data/bug-13054.php'], []);
3868+
}
3869+
38603870
public function testBug3396(): void
38613871
{
38623872
$this->checkThisOnly = false;
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug13054Rule;
4+
5+
class Test {
6+
public function fetchTest(int $i): void {
7+
echo $i;
8+
}
9+
10+
public function fetchTest2(): void {
11+
echo 'test';
12+
}
13+
14+
public function exec(): void {
15+
$list = [
16+
'test1' => 'Test',
17+
'test2' => 'Test2',
18+
];
19+
20+
foreach ($list as $key => $functionName) {
21+
$functionToCall = 'fetch' . $functionName;
22+
23+
if ($key === 'test1') {
24+
$this->$functionToCall(1);
25+
} else {
26+
$this->$functionToCall();
27+
}
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)