Skip to content

Commit dc81422

Browse files
zonuexeclaude
authored andcommitted
Reach makeList() from list<mixed> intersections and drop the keys a list cannot have
array_is_list() narrows by intersecting with list<mixed>. A shape that is not a subtype of array<int<0, max>, mixed> - one with a string or a negative key, or with extras - is rebuilt against that array first, and the rebuilt shape moved on without meeting the list accessory, so makeList() never ran: array{a?: bool, 1?: int, 0?: string} still became list{1?: int, 0?: string}. The rebuilt shape now meets the remaining members again. makeList() now also drops the negative and non-integer keys everywhere, not only in sealed shapes - keeping a negative key in front made the non-empty-list rule require it instead of the key 0 - and a shape whose dropped keys include a required one is never a list. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent c28ca92 commit dc81422

6 files changed

Lines changed: 175 additions & 71 deletions

File tree

‎src/Type/Constant/ConstantArrayType.php‎

Lines changed: 29 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3377,62 +3377,68 @@ public function makeList(): Type
33773377
// isList is Maybe. A list has its keys in ascending order, and one that
33783378
// has the key k has every key below k too - positional operations on the
33793379
// list trust both, so the keys are put in ascending order and the ones
3380-
// below a required key are made required. In a sealed shape a key past a
3381-
// gap in the 0..n sequence (or any non-integer key) can never appear in a
3382-
// list, so keep only the contiguous 0..m prefix. Unsealed extras may fill
3383-
// the gaps, so keep every key there, the integer ones first.
3380+
// below a required key are made required. A list never has a negative or
3381+
// a non-integer key, so those are dropped. In a sealed shape a key past a
3382+
// gap in the 0..n sequence can never appear in a list either, so only the
3383+
// contiguous 0..m prefix is kept; unsealed extras may fill the gaps, so
3384+
// every other key is kept there.
33843385
$positionByIndex = [];
3385-
$otherPositions = [];
3386+
$droppedPositions = [];
33863387
foreach ($this->keyTypes as $position => $keyType) {
3387-
if (!$keyType instanceof ConstantIntegerType) {
3388-
$otherPositions[] = $position;
3388+
if (!$keyType instanceof ConstantIntegerType || $keyType->getValue() < 0) {
3389+
$droppedPositions[] = $position;
33893390
continue;
33903391
}
33913392
$positionByIndex[$keyType->getValue()] = $position;
33923393
}
33933394

3395+
ksort($positionByIndex);
33943396
if ($this->isUnsealed()->no()) {
33953397
$keptPositions = [];
33963398
for ($index = 0; array_key_exists($index, $positionByIndex); $index++) {
33973399
$keptPositions[] = $positionByIndex[$index];
3400+
unset($positionByIndex[$index]);
3401+
}
3402+
foreach ($positionByIndex as $position) {
3403+
$droppedPositions[] = $position;
33983404
}
33993405
} else {
3400-
ksort($positionByIndex);
3401-
$keptPositions = array_merge(array_values($positionByIndex), $otherPositions);
3406+
$keptPositions = array_values($positionByIndex);
3407+
}
3408+
3409+
foreach ($droppedPositions as $position) {
3410+
if (!$this->isOptionalKey($position)) {
3411+
return new NeverType();
3412+
}
34023413
}
34033414

3415+
$indexByPosition = array_flip($keptPositions);
34043416
$requiredLength = 0;
3405-
foreach ($keptPositions as $position) {
3406-
$keyType = $this->keyTypes[$position];
3407-
if (!$keyType instanceof ConstantIntegerType || $this->isOptionalKey($position)) {
3417+
foreach ($keptPositions as $index => $position) {
3418+
if ($this->isOptionalKey($position)) {
34083419
continue;
34093420
}
34103421

3411-
$requiredLength = max($requiredLength, $keyType->getValue() + 1);
3422+
$requiredLength = $index + 1;
34123423
}
34133424

3414-
$optionalKeys = [];
3425+
$optionalPositions = [];
34153426
foreach ($keptPositions as $newPosition => $position) {
3416-
if (!$this->isOptionalKey($position)) {
3417-
continue;
3418-
}
3419-
3420-
$keyType = $this->keyTypes[$position];
3421-
if ($keyType instanceof ConstantIntegerType && $keyType->getValue() >= 0 && $keyType->getValue() < $requiredLength) {
3427+
if (!$this->isOptionalKey($position) || $indexByPosition[$position] < $requiredLength) {
34223428
continue;
34233429
}
34243430

3425-
$optionalKeys[] = $newPosition;
3431+
$optionalPositions[$newPosition] = true;
34263432
}
34273433

3428-
if ($keptPositions !== array_keys($this->keyTypes) || count($optionalKeys) !== count($this->optionalKeys)) {
3434+
if ($keptPositions !== array_keys($this->keyTypes) || count($optionalPositions) !== count($this->optionalKeys)) {
34293435
$builder = ConstantArrayTypeBuilder::createEmpty();
34303436
$builder->disableArrayDegradation();
34313437
foreach ($keptPositions as $newPosition => $position) {
34323438
$builder->setOffsetValueType(
34333439
$this->keyTypes[$position],
34343440
$this->valueTypes[$position],
3435-
in_array($newPosition, $optionalKeys, true),
3441+
isset($optionalPositions[$newPosition]),
34363442
);
34373443
}
34383444

‎src/Type/TypeCombinator.php‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2376,7 +2376,10 @@ public static function doIntersect(Type ...$types): Type
23762376
}
23772377

23782378
if ($constArrayIsI) {
2379-
$types[$i] = $newArrayType;
2379+
// The rebuilt shape meets the other members from the
2380+
// start again - the list accessory of `list<mixed>` can
2381+
// come after the array it is paired with.
2382+
$types[$i--] = $newArrayType;
23802383
array_splice($types, $j, 1);
23812384
} else {
23822385
$types[$j] = $newArrayType;

‎tests/PHPStan/Analyser/nsrt/make-list-key-order.php‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,38 @@ public function keysInAscendingOrder(array $descending): void
1919
}
2020
}
2121

22+
/**
23+
* @param array{a?: bool, 1?: int, 0?: string} $withStringKey
24+
* @param array{-1?: bool, 0?: string, 1: int} $withNegativeKey
25+
* @param array{1?: int, 0?: string, ...<int, float>} $withExtras
26+
*/
27+
public function keysThatAListCannotHave(array $withStringKey, array $withNegativeKey, array $withExtras): void
28+
{
29+
if (array_is_list($withStringKey)) {
30+
assertType('list{0?: string, 1?: int}', $withStringKey);
31+
assertType('list{0?: string, 1?: int}', array_values($withStringKey));
32+
}
33+
34+
if (array_is_list($withNegativeKey)) {
35+
assertType('array{string, int}', $withNegativeKey);
36+
}
37+
38+
if (array_is_list($withExtras)) {
39+
assertType('list{0?: string, 1?: int, ...<float>}', $withExtras);
40+
}
41+
}
42+
43+
/**
44+
* @param array{0?: string, 2?: int, 3: bool} $requiredPastAGap
45+
*/
46+
public function requiredKeyPastAGap(array $requiredPastAGap): void
47+
{
48+
if (array_is_list($requiredPastAGap)) {
49+
// a list with the key 3 has the key 1 too, which this shape never has
50+
assertType('*NEVER*', $requiredPastAGap);
51+
}
52+
}
53+
2254
/**
2355
* @param array{0?: string, 1: int} $optionalBelowRequired
2456
* @param list{0: string, 1?: string, 2?: string, 3: string} $gapInList

‎tests/PHPStan/Type/Constant/ConstantArrayTypeTest.php‎

Lines changed: 67 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@
77
use PHPStan\PhpDoc\TypeStringResolver;
88
use PHPStan\Testing\PHPStanTestCase;
99
use PHPStan\TrinaryLogic;
10+
use PHPStan\Type\Accessory\AccessoryArrayListType;
1011
use PHPStan\Type\Accessory\HasOffsetType;
1112
use PHPStan\Type\Accessory\HasOffsetValueType;
13+
use PHPStan\Type\Accessory\NonEmptyArrayType;
1214
use PHPStan\Type\ArrayType;
1315
use PHPStan\Type\BooleanType;
1416
use PHPStan\Type\CallableType;
@@ -1705,22 +1707,22 @@ public static function dataMakeListPutsKeysInAscendingOrderAndRequiresTheOnesBel
17051707
];
17061708
}
17071709

1708-
// Unsealed extras may fill the gaps, so a string key and a negative key
1709-
// stay (after the integer ones and optional), unlike in a sealed shape.
1710-
yield 'string key after the integer ones (unsealed === null)' => [
1710+
// A list never has a non-integer or a negative key, even where unsealed
1711+
// extras keep the keys past a gap.
1712+
yield 'string key is dropped (unsealed === null)' => [
17111713
false,
17121714
[[1, new IntegerType(), true], ['a', new BooleanType(), true], [0, new StringType(), true]],
17131715
false,
1714-
'list{0?: string, 1?: int, a?: bool}',
1715-
[0, 1, 'a'],
1716+
'list{0?: string, 1?: int}',
1717+
[0, 1],
17161718
];
17171719

1718-
yield 'negative key stays optional (unsealed === null)' => [
1720+
yield 'negative key is dropped (unsealed === null)' => [
17191721
false,
17201722
[[-1, new BooleanType(), true], [0, new StringType(), true], [1, new IntegerType(), false]],
17211723
false,
1722-
'list{-1?: bool, 0: string, 1: int}',
1723-
[-1, 0, 1],
1724+
'array{string, int}',
1725+
[0, 1],
17241726
];
17251727

17261728
yield 'real extras are kept' => [
@@ -1764,6 +1766,63 @@ public function testMakeListPutsKeysInAscendingOrderAndRequiresTheOnesBelowARequ
17641766
});
17651767
}
17661768

1769+
/**
1770+
* @return iterable<string, array{bool, list<array{int|string, Type, bool}>, bool, string}>
1771+
*/
1772+
public static function dataIntersectWithListPutsKeysInAscendingOrder(): iterable
1773+
{
1774+
foreach ([true, false] as $bleedingEdge) {
1775+
$suffix = $bleedingEdge ? ' (sealed)' : ' (unsealed === null)';
1776+
1777+
// these shapes are not subtypes of array<int<0, max>, mixed>, so the
1778+
// intersection rebuilds them before they meet the list accessory
1779+
yield 'string key' . $suffix => [
1780+
$bleedingEdge,
1781+
[['a', new BooleanType(), true], [1, new IntegerType(), true], [0, new StringType(), true]],
1782+
false,
1783+
'list{0?: string, 1?: int}',
1784+
];
1785+
1786+
yield 'negative key' . $suffix => [
1787+
$bleedingEdge,
1788+
[[-1, new BooleanType(), true], [0, new StringType(), true], [1, new IntegerType(), false]],
1789+
false,
1790+
'array{string, int}',
1791+
];
1792+
1793+
// the rule that requires the first optional key of a non-empty list
1794+
// must see the key 0 first, not the negative one
1795+
yield 'negative key in a non-empty list' . $suffix => [
1796+
$bleedingEdge,
1797+
[[0, new StringType(), true], [-1, new BooleanType(), true]],
1798+
true,
1799+
'array{string}',
1800+
];
1801+
}
1802+
}
1803+
1804+
/**
1805+
* @param list<array{int|string, Type, bool}> $items
1806+
*/
1807+
#[DataProvider('dataIntersectWithListPutsKeysInAscendingOrder')]
1808+
public function testIntersectWithListPutsKeysInAscendingOrder(bool $bleedingEdge, array $items, bool $nonEmpty, string $expected): void
1809+
{
1810+
BleedingEdgeToggle::withBleedingEdge($bleedingEdge, function () use ($items, $nonEmpty, $expected): void {
1811+
$types = [
1812+
$this->buildShape($items),
1813+
new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), new MixedType()),
1814+
new AccessoryArrayListType(),
1815+
];
1816+
if ($nonEmpty) {
1817+
$types[] = new NonEmptyArrayType();
1818+
}
1819+
1820+
$list = TypeCombinator::intersect(...$types);
1821+
$this->assertSame($expected, $list->describe(VerbosityLevel::precise()));
1822+
$this->assertSame(TrinaryLogic::createYes()->describe(), $list->isList()->describe());
1823+
});
1824+
}
1825+
17671826
/**
17681827
* @return iterable<string, array{bool, list<array{int|string, Type, bool}>, list<array{int|string, Type, bool}>, TrinaryLogic}>
17691828
*/

‎turbo-ext/src/ConstantArrayType.cpp‎

Lines changed: 39 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -5316,77 +5316,77 @@ class ConstantArrayType
53165316
* that has the key k has every key below k too - positional
53175317
* operations on the list trust both, so the keys are put in
53185318
* ascending order and the ones below a required key are made
5319-
* required. In a sealed shape a key past a gap in the 0..n sequence
5320-
* (or any non-integer key) can never appear in a list, so keep only
5321-
* the contiguous 0..m prefix. Unsealed extras may fill the gaps, so
5322-
* keep every key there, the integer ones first. */
5319+
* required. A list never has a negative or a non-integer key, so
5320+
* those are dropped. In a sealed shape a key past a gap in the 0..n
5321+
* sequence can never appear in a list either, so only the contiguous
5322+
* 0..m prefix is kept; unsealed extras may fill the gaps, so every
5323+
* other key is kept there. */
53235324
uint32_t keyCount = zend_hash_num_elements(Z_ARRVAL_P(k));
53245325
zv::ScratchTable positionByIndex(keyCount);
5325-
zv::Arr otherPositions = zv::Arr::create(0);
5326+
zv::Arr droppedPositions = zv::Arr::create(0);
53265327
for (zv::ArrayEntry entry : zv::ArrRef(k)) {
53275328
zval *keyType = entry.value().deref().raw();
53285329
zval position;
53295330
ZVAL_LONG(&position, (zend_long) entry.indexKey());
5330-
if (Z_TYPE_P(keyType) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(keyType), pt_ce_constant_integer_type)) {
5331-
otherPositions.push(zv::Ref(&position));
5331+
zend_long value = 0;
5332+
if (Z_TYPE_P(keyType) == IS_OBJECT && instanceof_function(Z_OBJCE_P(keyType), pt_ce_constant_integer_type)) {
5333+
if (UNEXPECTED(!pt_constant_integer_get_value(Z_OBJ_P(keyType), value))) return zv::Val();
5334+
} else {
5335+
value = -1;
5336+
}
5337+
if (value < 0) {
5338+
droppedPositions.push(zv::Ref(&position));
53325339
continue;
53335340
}
5334-
zend_long value;
5335-
if (UNEXPECTED(!pt_constant_integer_get_value(Z_OBJ_P(keyType), value))) return zv::Val();
53365341
zend_hash_index_update(positionByIndex.table(), (zend_ulong) value, &position);
53375342
}
53385343

5344+
/* ksort($positionByIndex) - the kept keys are all non-negative */
5345+
zend_hash_sort_ex(positionByIndex.table(), zend_sort, compareSignedIndexBuckets, 0);
53395346
zend_long unsealedness = thisIsUnsealed();
53405347
if (UNEXPECTED(unsealedness < 0)) return zv::Val();
53415348
zv::Arr keptPositions = zv::Arr::create(keyCount);
53425349
if (unsealedness == PT_TRI_NO) {
5343-
for (zend_long index = 0;; index++) {
5344-
zval *position = zend_hash_index_find(positionByIndex.table(), (zend_ulong) index);
5345-
if (position == NULL) break;
5346-
keptPositions.push(zv::Ref(position));
5350+
zend_long index = 0;
5351+
for (zv::ArrayEntry entry : zv::TableRef(positionByIndex.table())) {
5352+
/* the contiguous 0..m prefix is kept, every key after the
5353+
* first gap dropped */
5354+
if ((zend_long) entry.indexKey() == index) {
5355+
keptPositions.push(entry.value());
5356+
index++;
5357+
continue;
5358+
}
5359+
index = -1;
5360+
droppedPositions.push(entry.value());
53475361
}
53485362
} else {
5349-
/* ksort($positionByIndex); array_merge(array_values(...), $otherPositions) */
5350-
zend_hash_sort_ex(positionByIndex.table(), zend_sort, compareSignedIndexBuckets, 0);
53515363
for (zv::ArrayEntry entry : zv::TableRef(positionByIndex.table())) {
53525364
keptPositions.push(entry.value());
53535365
}
5354-
for (zv::ArrayEntry entry : otherPositions.arrRef()) {
5355-
keptPositions.push(entry.value());
5356-
}
5366+
}
5367+
5368+
for (zv::ArrayEntry entry : droppedPositions.arrRef()) {
5369+
bool optional;
5370+
if (UNEXPECTED(!thisIsOptionalKey(entry.value().asLong(), optional))) return zv::Val();
5371+
if (!optional) return neverType();
53575372
}
53585373

53595374
zend_long requiredLength = 0;
53605375
for (zv::ArrayEntry entry : keptPositions.arrRef()) {
5361-
zend_long position = entry.value().asLong();
5362-
zval *keyType = arrayIndexObject(k, position, "keyTypes");
5363-
if (UNEXPECTED(keyType == NULL)) return zv::Val();
5364-
if (!instanceof_function(Z_OBJCE_P(keyType), pt_ce_constant_integer_type)) continue;
53655376
bool optional;
5366-
if (UNEXPECTED(!thisIsOptionalKey(position, optional))) return zv::Val();
5377+
if (UNEXPECTED(!thisIsOptionalKey(entry.value().asLong(), optional))) return zv::Val();
53675378
if (optional) continue;
53685379

5369-
zend_long value;
5370-
if (UNEXPECTED(!pt_constant_integer_get_value(Z_OBJ_P(keyType), value))) return zv::Val();
5371-
/* max($requiredLength, $value + 1); at PHP_INT_MAX the twin's
5372-
* float compares like the saturated int below */
5373-
if (value >= requiredLength) requiredLength = value == ZEND_LONG_MAX ? ZEND_LONG_MAX : value + 1;
5380+
requiredLength = (zend_long) entry.indexKey() + 1;
53745381
}
53755382

5383+
/* $optionalPositions: $indexByPosition[$position] is the kept
5384+
* position itself, $keptPositions being a list */
53765385
zv::Arr newOptionalKeys = zv::Arr::create(0);
53775386
for (zv::ArrayEntry entry : keptPositions.arrRef()) {
5378-
zend_long position = entry.value().asLong();
53795387
bool optional;
5380-
if (UNEXPECTED(!thisIsOptionalKey(position, optional))) return zv::Val();
5381-
if (!optional) continue;
5382-
5383-
zval *keyType = arrayIndexObject(k, position, "keyTypes");
5384-
if (UNEXPECTED(keyType == NULL)) return zv::Val();
5385-
if (instanceof_function(Z_OBJCE_P(keyType), pt_ce_constant_integer_type)) {
5386-
zend_long value;
5387-
if (UNEXPECTED(!pt_constant_integer_get_value(Z_OBJ_P(keyType), value))) return zv::Val();
5388-
if (value >= 0 && value < requiredLength) continue;
5389-
}
5388+
if (UNEXPECTED(!thisIsOptionalKey(entry.value().asLong(), optional))) return zv::Val();
5389+
if (!optional || (zend_long) entry.indexKey() < requiredLength) continue;
53905390

53915391
zval newPosition;
53925392
ZVAL_LONG(&newPosition, (zend_long) entry.indexKey());

‎turbo-ext/src/TypeCombinator.cpp‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3886,8 +3886,12 @@ class TypeCombinator
38863886
}
38873887

38883888
if (constArrayIsI) {
3889+
/* The rebuilt shape meets the other members from the start
3890+
* again - the list accessory of `list<mixed>` can come after
3891+
* the array it is paired with. */
38893892
types[i] = std::move(newArrayType);
38903893
types.erase(types.begin() + (ptrdiff_t) j);
3894+
i--;
38913895
} else {
38923896
types[j] = std::move(newArrayType);
38933897
types.erase(types.begin() + (ptrdiff_t) i);

0 commit comments

Comments
 (0)