Skip to content

Commit 614b589

Browse files
phpstan-botondrejmirtesclaude
authored
Narrow array element type after a keyless foreach whose body guards each element with an early exit (#5877)
Co-authored-by: ondrejmirtes <104888+ondrejmirtes@users.noreply.github.com> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
1 parent e0612d8 commit 614b589

4 files changed

Lines changed: 223 additions & 43 deletions

File tree

‎src/Analyser/ExprHandler/MatchHandler.php‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -271,9 +271,8 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
271271
$conditionCases = [];
272272
$conditionExprs = [];
273273
foreach ($arm->conds as $j => $cond) {
274-
if (!$cond instanceof Expr\ClassConstFetch) {
275-
throw new ShouldNotHappenException();
276-
}
274+
// The pre-validation loop above already guaranteed (via break 2)
275+
// that every reached condition is an enum-case ClassConstFetch.
277276
if (!$cond->class instanceof Name) {
278277
throw new ShouldNotHappenException();
279278
}

‎src/Analyser/NodeScopeResolver.php‎

Lines changed: 55 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1491,11 +1491,26 @@ public function processStmtNode(
14911491
$finalScope = $finalScopeResult->getScope();
14921492
$scopesWithIterableValueType = [];
14931493

1494+
$keyVarExpr = null;
14941495
$originalKeyVarExpr = null;
1495-
$continueExitPointHasUnoriginalKeyType = false;
14961496
if ($stmt->keyVar instanceof Variable && is_string($stmt->keyVar->name)) {
1497+
$keyVarExpr = $stmt->keyVar;
14971498
$originalKeyVarExpr = new OriginalForeachKeyExpr($stmt->keyVar->name);
1498-
if ($finalScope->hasExpressionType($originalKeyVarExpr)->yes()) {
1499+
}
1500+
$originalValueExpr = null;
1501+
if ($stmt->valueVar instanceof Variable && is_string($stmt->valueVar->name)) {
1502+
$originalValueExpr = new OriginalForeachValueExpr($stmt->valueVar->name);
1503+
}
1504+
1505+
// With a key variable, each iteration is tracked through the original key
1506+
// expression and the narrowed element is projected onto the array dim fetch.
1507+
// Without one (`foreach ($a as $v)`) we instead track the original value
1508+
// expression and rewrite the array value type directly from the value var.
1509+
$trackingExpr = $originalKeyVarExpr ?? $originalValueExpr;
1510+
1511+
$continueExitPointHasUnoriginalKeyType = false;
1512+
if ($trackingExpr !== null) {
1513+
if ($finalScope->hasExpressionType($trackingExpr)->yes()) {
14991514
$scopesWithIterableValueType[] = $finalScope;
15001515
} else {
15011516
$continueExitPointHasUnoriginalKeyType = true;
@@ -1505,7 +1520,7 @@ public function processStmtNode(
15051520
foreach ($finalScopeResult->getExitPointsByType(Continue_::class) as $continueExitPoint) {
15061521
$continueScope = $continueExitPoint->getScope();
15071522
$finalScope = $continueScope->mergeWith($finalScope);
1508-
if ($originalKeyVarExpr === null || !$continueScope->hasExpressionType($originalKeyVarExpr)->yes()) {
1523+
if ($trackingExpr === null || !$continueScope->hasExpressionType($trackingExpr)->yes()) {
15091524
$continueExitPointHasUnoriginalKeyType = true;
15101525
continue;
15111526
}
@@ -1526,58 +1541,59 @@ public function processStmtNode(
15261541
count($breakExitPoints) === 0
15271542
&& count($scopesWithIterableValueType) > 0
15281543
&& !$continueExitPointHasUnoriginalKeyType
1529-
&& $stmt->keyVar !== null
1544+
&& ($keyVarExpr !== null || $originalValueExpr !== null)
15301545
&& (!$hasExpr->no() || !$stmt->expr instanceof Variable)
15311546
&& $exprType->isArray()->yes()
15321547
&& $exprType->isConstantArray()->no()
15331548
) {
1534-
$arrayExprDimFetch = new ArrayDimFetch($stmt->expr, $stmt->keyVar);
1535-
$originalValueExpr = null;
1536-
if ($stmt->valueVar instanceof Variable && is_string($stmt->valueVar->name)) {
1537-
$originalValueExpr = new OriginalForeachValueExpr($stmt->valueVar->name);
1538-
}
15391549
$arrayDimFetchLoopTypes = [];
1540-
$keyLoopTypes = [];
1541-
foreach ($scopesWithIterableValueType as $scopeWithIterableValueType) {
1542-
$dimFetchType = $scopeWithIterableValueType->getType($arrayExprDimFetch);
1543-
// Condition-based narrowings like `is_string($type)` apply to the value
1544-
// variable but not automatically to the array dim fetch, even though the
1545-
// two describe the same element for a given iteration. If the value var
1546-
// hasn't been reassigned (OriginalForeachValueExpr still tracked) we use
1547-
// the narrowed value-var type in place of the broader dim fetch type so
1548-
// the loop's final array rewrite below picks up the sharper element type.
1549-
if ($originalValueExpr !== null && $scopeWithIterableValueType->hasExpressionType($originalValueExpr)->yes()) {
1550-
$valueVarType = $scopeWithIterableValueType->getType($stmt->valueVar);
1551-
if ($dimFetchType->isSuperTypeOf($valueVarType)->yes()) {
1552-
$dimFetchType = $valueVarType;
1553-
}
1554-
}
1555-
$arrayDimFetchLoopTypes[] = $dimFetchType;
1556-
$keyLoopTypes[] = $scopeWithIterableValueType->getType($stmt->keyVar);
1557-
}
1558-
1559-
$arrayDimFetchLoopType = TypeCombinator::union(...$arrayDimFetchLoopTypes);
1560-
$keyLoopType = TypeCombinator::union(...$keyLoopTypes);
1561-
15621550
$arrayDimFetchLoopNativeTypes = [];
1551+
$keyLoopTypes = [];
15631552
$keyLoopNativeTypes = [];
15641553
foreach ($scopesWithIterableValueType as $scopeWithIterableValueType) {
1565-
$dimFetchNativeType = $scopeWithIterableValueType->getNativeType($arrayExprDimFetch);
1566-
if ($originalValueExpr !== null && $scopeWithIterableValueType->hasExpressionType($originalValueExpr)->yes()) {
1567-
$valueVarNativeType = $scopeWithIterableValueType->getNativeType($stmt->valueVar);
1568-
if ($dimFetchNativeType->isSuperTypeOf($valueVarNativeType)->yes()) {
1569-
$dimFetchNativeType = $valueVarNativeType;
1554+
if ($keyVarExpr !== null) {
1555+
$arrayExprDimFetch = new ArrayDimFetch($stmt->expr, $keyVarExpr);
1556+
$dimFetchType = $scopeWithIterableValueType->getType($arrayExprDimFetch);
1557+
$dimFetchNativeType = $scopeWithIterableValueType->getNativeType($arrayExprDimFetch);
1558+
// Condition-based narrowings like `is_string($type)` apply to the value
1559+
// variable but not automatically to the array dim fetch, even though the
1560+
// two describe the same element for a given iteration. If the value var
1561+
// hasn't been reassigned (OriginalForeachValueExpr still tracked) we use
1562+
// the narrowed value-var type in place of the broader dim fetch type so
1563+
// the loop's final array rewrite below picks up the sharper element type.
1564+
if ($originalValueExpr !== null && $scopeWithIterableValueType->hasExpressionType($originalValueExpr)->yes()) {
1565+
$valueVarType = $scopeWithIterableValueType->getType($stmt->valueVar);
1566+
if ($dimFetchType->isSuperTypeOf($valueVarType)->yes()) {
1567+
$dimFetchType = $valueVarType;
1568+
}
1569+
$valueVarNativeType = $scopeWithIterableValueType->getNativeType($stmt->valueVar);
1570+
if ($dimFetchNativeType->isSuperTypeOf($valueVarNativeType)->yes()) {
1571+
$dimFetchNativeType = $valueVarNativeType;
1572+
}
15701573
}
1574+
$keyLoopTypes[] = $scopeWithIterableValueType->getType($keyVarExpr);
1575+
$keyLoopNativeTypes[] = $scopeWithIterableValueType->getType($keyVarExpr);
1576+
} else {
1577+
// No key variable: the narrowed value var is the array element type directly.
1578+
$dimFetchType = $scopeWithIterableValueType->getType($stmt->valueVar);
1579+
$dimFetchNativeType = $scopeWithIterableValueType->getNativeType($stmt->valueVar);
15711580
}
1581+
$arrayDimFetchLoopTypes[] = $dimFetchType;
15721582
$arrayDimFetchLoopNativeTypes[] = $dimFetchNativeType;
1573-
$keyLoopNativeTypes[] = $scopeWithIterableValueType->getType($stmt->keyVar);
15741583
}
15751584

1585+
$arrayDimFetchLoopType = TypeCombinator::union(...$arrayDimFetchLoopTypes);
15761586
$arrayDimFetchLoopNativeType = TypeCombinator::union(...$arrayDimFetchLoopNativeTypes);
1577-
$keyLoopNativeType = TypeCombinator::union(...$keyLoopNativeTypes);
15781587

15791588
$valueTypeChanged = !$arrayDimFetchLoopType->equals($exprType->getIterableValueType());
1580-
$keyTypeChanged = !$keyLoopType->equals($exprType->getIterableKeyType());
1589+
$keyTypeChanged = false;
1590+
$keyLoopType = $exprType->getIterableKeyType();
1591+
$keyLoopNativeType = $scope->getNativeType($stmt->expr)->getIterableKeyType();
1592+
if ($keyVarExpr !== null) {
1593+
$keyLoopType = TypeCombinator::union(...$keyLoopTypes);
1594+
$keyLoopNativeType = TypeCombinator::union(...$keyLoopNativeTypes);
1595+
$keyTypeChanged = !$keyLoopType->equals($exprType->getIterableKeyType());
1596+
}
15811597

15821598
if ($valueTypeChanged || $keyTypeChanged) {
15831599
$newExprType = $exprType;
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
<?php // lint >= 8.0
2+
3+
declare(strict_types = 1);
4+
5+
namespace Bug5755;
6+
7+
use function PHPStan\Testing\assertType;
8+
9+
/**
10+
* @param list<mixed> $ids
11+
* @return list<string>|null
12+
*/
13+
function validate(array $ids): array|null
14+
{
15+
foreach ($ids as $id) {
16+
if (!is_string($id)) {
17+
return null;
18+
}
19+
}
20+
21+
assertType('list<string>', $ids);
22+
23+
return $ids;
24+
}
25+
26+
class Test
27+
{
28+
29+
/**
30+
* @return array<int|string>|float|int|string|false|null
31+
*/
32+
private function value(): mixed
33+
{
34+
$values = ['a', 1, false, null, 3.4, [], [2, 3, 4], ['a', 'b', 'c']];
35+
$index = rand(0, 7);
36+
return $values[$index];
37+
}
38+
39+
/**
40+
* @return array<string>|null
41+
*/
42+
public function strings(): ?array
43+
{
44+
$values = $this->value();
45+
if (!is_array($values)) {
46+
return null;
47+
}
48+
foreach ($values as $value) {
49+
if (!is_string($value)) {
50+
return null;
51+
}
52+
}
53+
54+
assertType('array<string>', $values);
55+
56+
return $values;
57+
}
58+
59+
}
60+
61+
/**
62+
* @param array<string, int|string> $map
63+
*/
64+
function withGuardContinue(array $map): void
65+
{
66+
foreach ($map as $value) {
67+
if (is_int($value)) {
68+
continue;
69+
}
70+
}
71+
72+
// The continue keeps int around, no narrowing happens.
73+
assertType('array<string, int|string>', $map);
74+
}
75+
76+
/**
77+
* @param array<string, int|string> $map
78+
*/
79+
function narrowKeyless(array $map): void
80+
{
81+
foreach ($map as $value) {
82+
if (!is_string($value)) {
83+
return;
84+
}
85+
}
86+
87+
assertType('array<string, string>', $map);
88+
}
89+
90+
/**
91+
* @param list<int|string> $list
92+
*/
93+
function reassignValueVarKeyless(array $list): void
94+
{
95+
foreach ($list as $value) {
96+
// Reassigning the value variable must not narrow the array element type.
97+
$value = 'foo';
98+
}
99+
100+
assertType('list<int|string>', $list);
101+
}
102+
103+
interface Foo
104+
{
105+
}
106+
107+
/**
108+
* @param list<Foo|string> $list
109+
*/
110+
function instanceofKeyless(array $list): void
111+
{
112+
foreach ($list as $value) {
113+
if (!$value instanceof Foo) {
114+
return;
115+
}
116+
}
117+
118+
assertType('list<Bug5755\Foo>', $list);
119+
}
120+
121+
/**
122+
* @param list<int|string> $list
123+
*/
124+
function throwKeyless(array $list): void
125+
{
126+
foreach ($list as $value) {
127+
if (!is_string($value)) {
128+
throw new \Exception();
129+
}
130+
}
131+
132+
assertType('list<string>', $list);
133+
}
134+
135+
/**
136+
* @param list<int|string> $list
137+
*/
138+
function byRefKeyless(array $list): void
139+
{
140+
foreach ($list as &$value) {
141+
if (!is_string($value)) {
142+
return;
143+
}
144+
}
145+
146+
assertType('list<string>', $list);
147+
}
148+
149+
/**
150+
* @param array<int|string, array{int}> $a
151+
*/
152+
function keyedWithDestructuredValue(array $a): void
153+
{
154+
// The value is destructured, so there is no value variable to track, but a key
155+
// variable is still present. Key narrowing must keep working through the key path.
156+
foreach ($a as $k => [$v]) {
157+
if (!is_int($k)) {
158+
return;
159+
}
160+
}
161+
162+
assertType('array<int, array{int}>', $a);
163+
}

‎tests/PHPStan/Analyser/nsrt/bug-7076.php‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,9 @@ function noKeyVar(array $arguments): void
123123
}
124124
}
125125

126-
assertType('array<int|string, mixed>', $arguments);
126+
// Even without a key variable, every element is guaranteed to be a string
127+
// after the loop, so the value type is narrowed.
128+
assertType('array<int|string, string>', $arguments);
127129
}
128130

129131
/**

0 commit comments

Comments
 (0)