Skip to content

Commit 024ac54

Browse files
committed
Keep the list in an intersection of a list shape with another shape
intersectDefiniteConstantArrays() rebuilt the intersection key by key, and the builder cannot tell from optional keys that may each be left out alone that the result is a list: list{0: int, 1?: int, 2?: int} & list{...} became array{0: int, 1?: int, 2?: int}. The intersection with a list is a list. In a loop of conditional appends, such a shape reached the widening of the loop and degraded the list to array<int<0, max>, T>. Amp-Thread-ID: https://ampcode.com/threads/T-01a21c4a-d1b7-7397-8625-b131900ac0d3
1 parent 7279769 commit 024ac54

2 files changed

Lines changed: 42 additions & 1 deletion

File tree

‎src/Type/ArrayAlgebra.php‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -435,7 +435,14 @@ private static function intersectDefiniteConstantArrays(ConstantArrayType $a, Co
435435
$newArray->setOffsetValueType($keyType, $value, $optional);
436436
}
437437

438-
return $newArray->getArray();
438+
$newArrayType = $newArray->getArray();
439+
// optional keys rebuilt one by one may each be left out alone, so the
440+
// builder cannot tell a list from the keys - the inputs can
441+
if ($a->isList()->yes() || $b->isList()->yes()) {
442+
$newArrayType = TypeCombinator::intersect($newArrayType, new AccessoryArrayListType());
443+
}
444+
445+
return $newArrayType;
439446
}
440447

441448
/** @see Type::tryIntersect() */
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 Bug15857;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
abstract class Target {}
8+
final class T1 extends Target {}
9+
final class T2 extends Target {}
10+
final class T3 extends Target {}
11+
final class T4 extends Target {}
12+
final class T5 extends Target {}
13+
final class T6 extends Target {}
14+
final class T7 extends Target {}
15+
16+
/** @param list<Target> $targets */
17+
function take(array $targets): void {}
18+
19+
/** @param list<int> $items */
20+
function f(array $items): void
21+
{
22+
$targets = [];
23+
foreach ($items as $m) {
24+
if ($m === 1) { $targets[] = new T1(); }
25+
if ($m === 2) { $targets[] = new T2(); }
26+
if ($m === 3) { $targets[] = new T3(); }
27+
if ($m === 4) { $targets[] = new T4(); }
28+
if ($m === 5) { $targets[] = new T5(); }
29+
if ($m === 6) { $targets[] = new T6(); }
30+
if ($m === 7) { $targets[] = new T7(); }
31+
}
32+
assertType('list<Bug15857\T1|Bug15857\T2|Bug15857\T3|Bug15857\T4|Bug15857\T5|Bug15857\T6|Bug15857\T7>', $targets);
33+
take($targets);
34+
}

0 commit comments

Comments
 (0)