Skip to content

Commit c28ca92

Browse files
zonuexeclaude
authored andcommitted
Put the keys of a list in ascending order and require the ones below a required key
makeList() turned a maybe-list shape into a list by flipping its isList flag, keeping the keys in the order they were written and their optionality as it was. A list has its keys in ascending order and one with the key k has every key below k, and positional operations such as array_values() trust both - so array{1?: int, 0?: string} narrowed by array_is_list() became list{1?: int, 0?: string} and its array_values() list{0?: int, 1?: string}, the value types swapped. The keys are now put in ascending order (the integer ones first where unsealed extras keep every key) and the ones below the highest required key are made required, in sealed shapes and in shapes without the unsealed marker alike. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Amp-Thread-ID: https://ampcode.com/threads/T-01a196f7-a83c-7170-a45b-f1d9db4220df
1 parent 92a35f5 commit c28ca92

6 files changed

Lines changed: 311 additions & 51 deletions

File tree

‎src/Type/Constant/ConstantArrayType.php‎

Lines changed: 63 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@
8888
use function in_array;
8989
use function is_int;
9090
use function is_string;
91+
use function ksort;
9192
use function max;
9293
use function min;
9394
use function pow;
@@ -3373,36 +3374,77 @@ public function makeList(): Type
33733374
return new NeverType();
33743375
}
33753376

3376-
// isList is Maybe. In a sealed shape a key past a gap in the 0..n sequence
3377-
// (or any non-integer key) can never appear in a list, so keep only the
3378-
// contiguous 0..m prefix. Unsealed extras may fill the gaps, so keep every
3379-
// key there.
3380-
if ($this->isUnsealed()->no()) {
3381-
$positionByIndex = [];
3382-
foreach ($this->keyTypes as $position => $keyType) {
3383-
if (!$keyType instanceof ConstantIntegerType) {
3384-
continue;
3385-
}
3386-
$positionByIndex[$keyType->getValue()] = $position;
3377+
// isList is Maybe. A list has its keys in ascending order, and one that
3378+
// has the key k has every key below k too - positional operations on the
3379+
// 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.
3384+
$positionByIndex = [];
3385+
$otherPositions = [];
3386+
foreach ($this->keyTypes as $position => $keyType) {
3387+
if (!$keyType instanceof ConstantIntegerType) {
3388+
$otherPositions[] = $position;
3389+
continue;
33873390
}
3391+
$positionByIndex[$keyType->getValue()] = $position;
3392+
}
33883393

3394+
if ($this->isUnsealed()->no()) {
33893395
$keptPositions = [];
33903396
for ($index = 0; array_key_exists($index, $positionByIndex); $index++) {
33913397
$keptPositions[] = $positionByIndex[$index];
33923398
}
3399+
} else {
3400+
ksort($positionByIndex);
3401+
$keptPositions = array_merge(array_values($positionByIndex), $otherPositions);
3402+
}
33933403

3394-
if (count($keptPositions) < count($this->keyTypes)) {
3395-
$builder = ConstantArrayTypeBuilder::createEmpty();
3396-
foreach ($keptPositions as $position) {
3397-
$builder->setOffsetValueType(
3398-
$this->keyTypes[$position],
3399-
$this->valueTypes[$position],
3400-
$this->isOptionalKey($position),
3401-
);
3402-
}
3404+
$requiredLength = 0;
3405+
foreach ($keptPositions as $position) {
3406+
$keyType = $this->keyTypes[$position];
3407+
if (!$keyType instanceof ConstantIntegerType || $this->isOptionalKey($position)) {
3408+
continue;
3409+
}
34033410

3404-
return $builder->getArray();
3411+
$requiredLength = max($requiredLength, $keyType->getValue() + 1);
3412+
}
3413+
3414+
$optionalKeys = [];
3415+
foreach ($keptPositions as $newPosition => $position) {
3416+
if (!$this->isOptionalKey($position)) {
3417+
continue;
34053418
}
3419+
3420+
$keyType = $this->keyTypes[$position];
3421+
if ($keyType instanceof ConstantIntegerType && $keyType->getValue() >= 0 && $keyType->getValue() < $requiredLength) {
3422+
continue;
3423+
}
3424+
3425+
$optionalKeys[] = $newPosition;
3426+
}
3427+
3428+
if ($keptPositions !== array_keys($this->keyTypes) || count($optionalKeys) !== count($this->optionalKeys)) {
3429+
$builder = ConstantArrayTypeBuilder::createEmpty();
3430+
$builder->disableArrayDegradation();
3431+
foreach ($keptPositions as $newPosition => $position) {
3432+
$builder->setOffsetValueType(
3433+
$this->keyTypes[$position],
3434+
$this->valueTypes[$position],
3435+
in_array($newPosition, $optionalKeys, true),
3436+
);
3437+
}
3438+
3439+
$constantArrays = $builder->getArray()->getConstantArrays();
3440+
if (count($constantArrays) !== 1) {
3441+
throw new ShouldNotHappenException();
3442+
}
3443+
3444+
// The builder can answer maybe for an optional tail like `[0, 1?, 2?]`,
3445+
// but these are the keys of a list.
3446+
$list = $constantArrays[0];
3447+
return $this->recreate($list->keyTypes, $list->valueTypes, $list->nextAutoIndexes, $list->optionalKeys, TrinaryLogic::createYes(), $this->unsealed);
34063448
}
34073449

34083450
return $this->recreate($this->keyTypes, $this->valueTypes, $this->nextAutoIndexes, $this->optionalKeys, TrinaryLogic::createYes(), $this->unsealed);

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,8 @@ public function testUnsetNonConstant(array $a, array $b, array $c, int $int): vo
184184
unset($c[$int]);
185185
assertType('false', array_is_list($a));
186186
assertType('bool', array_is_list($b));
187-
assertType('bool', array_is_list($c));
187+
// the required key 3 makes the keys below it required in a list too
188+
assertType('false', array_is_list($c));
188189
}
189190

190191
/**

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ function doFoo(string $s): void
2121
function doBar(string $s): void
2222
{
2323
if (preg_match('/^(?:(?:(a))?(b)|(c))$/', $s, $matches)) {
24-
assertType("array{non-falsy-string, '', '', 'c'}|list{0: non-falsy-string, 1?: ''|'a', 2: 'b'}", $matches);
24+
// in a list, the required key 2 implies the key 1
25+
assertType("array{non-falsy-string, '', '', 'c'}|array{non-falsy-string, ''|'a', 'b'}", $matches);
2526
}
2627
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
namespace MakeListKeyOrder;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
class Foo
8+
{
9+
10+
/**
11+
* @param array{1?: int, 0?: string} $descending
12+
*/
13+
public function keysInAscendingOrder(array $descending): void
14+
{
15+
if (array_is_list($descending)) {
16+
// a list has its keys in ascending order, so the value of 0 comes first
17+
assertType('list{0?: string, 1?: int}', $descending);
18+
assertType('list{0?: string, 1?: int}', array_values($descending));
19+
}
20+
}
21+
22+
/**
23+
* @param array{0?: string, 1: int} $optionalBelowRequired
24+
* @param list{0: string, 1?: string, 2?: string, 3: string} $gapInList
25+
* @param 1|2 $i
26+
*/
27+
public function keysBelowARequiredKeyAreRequired(array $optionalBelowRequired, array $gapInList, int $i): void
28+
{
29+
if (array_is_list($optionalBelowRequired)) {
30+
// a list with the key 1 has the key 0 too
31+
assertType('array{string, int}', $optionalBelowRequired);
32+
}
33+
34+
assertType('array{string, string, string, string}', $gapInList);
35+
unset($gapInList[$i]);
36+
assertType('false', array_is_list($gapInList));
37+
}
38+
39+
}

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

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1680,6 +1680,90 @@ public function testMakeListProjectsSealedShapeButKeepsUnsealedKeys(bool $bleedi
16801680
});
16811681
}
16821682

1683+
/**
1684+
* @return iterable<string, array{bool, list<array{int|string, Type, bool}>, bool, string, list<int|string>}>
1685+
*/
1686+
public static function dataMakeListPutsKeysInAscendingOrderAndRequiresTheOnesBelowARequiredKey(): iterable
1687+
{
1688+
foreach ([true, false] as $bleedingEdge) {
1689+
$suffix = $bleedingEdge ? ' (sealed)' : ' (unsealed === null)';
1690+
1691+
yield 'descending keys' . $suffix => [
1692+
$bleedingEdge,
1693+
[[1, new IntegerType(), true], [0, new StringType(), true]],
1694+
false,
1695+
'list{0?: string, 1?: int}',
1696+
[0, 1],
1697+
];
1698+
1699+
yield 'optional key below a required one' . $suffix => [
1700+
$bleedingEdge,
1701+
[[0, new StringType(), true], [1, new IntegerType(), false]],
1702+
false,
1703+
'array{string, int}',
1704+
[0, 1],
1705+
];
1706+
}
1707+
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)' => [
1711+
false,
1712+
[[1, new IntegerType(), true], ['a', new BooleanType(), true], [0, new StringType(), true]],
1713+
false,
1714+
'list{0?: string, 1?: int, a?: bool}',
1715+
[0, 1, 'a'],
1716+
];
1717+
1718+
yield 'negative key stays optional (unsealed === null)' => [
1719+
false,
1720+
[[-1, new BooleanType(), true], [0, new StringType(), true], [1, new IntegerType(), false]],
1721+
false,
1722+
'list{-1?: bool, 0: string, 1: int}',
1723+
[-1, 0, 1],
1724+
];
1725+
1726+
yield 'real extras are kept' => [
1727+
true,
1728+
[[1, new IntegerType(), true], [0, new StringType(), true]],
1729+
true,
1730+
'list{0?: string, 1?: int, ...<bool>}',
1731+
[0, 1],
1732+
];
1733+
}
1734+
1735+
/**
1736+
* @param list<array{int|string, Type, bool}> $items
1737+
* @param list<int|string> $expectedKeys
1738+
*/
1739+
#[DataProvider('dataMakeListPutsKeysInAscendingOrderAndRequiresTheOnesBelowARequiredKey')]
1740+
public function testMakeListPutsKeysInAscendingOrderAndRequiresTheOnesBelowARequiredKey(
1741+
bool $bleedingEdge,
1742+
array $items,
1743+
bool $unsealed,
1744+
string $expectedList,
1745+
array $expectedKeys,
1746+
): void
1747+
{
1748+
BleedingEdgeToggle::withBleedingEdge($bleedingEdge, function () use ($items, $unsealed, $expectedList, $expectedKeys): void {
1749+
$array = $this->buildShape($items);
1750+
if ($unsealed) {
1751+
$builder = ConstantArrayTypeBuilder::createFromConstantArray($array);
1752+
$builder->makeUnsealed(IntegerRangeType::createAllGreaterThanOrEqualTo(0), new BooleanType());
1753+
$array = $builder->getArray();
1754+
$this->assertInstanceOf(ConstantArrayType::class, $array);
1755+
}
1756+
$this->assertSame(TrinaryLogic::createMaybe()->describe(), $array->isList()->describe());
1757+
1758+
$list = $array->makeList();
1759+
$this->assertInstanceOf(ConstantArrayType::class, $list);
1760+
$this->assertSame($expectedList, $list->describe(VerbosityLevel::precise()));
1761+
$this->assertSame(TrinaryLogic::createYes()->describe(), $list->isList()->describe());
1762+
$this->assertSame($expectedKeys, array_map(static fn (ConstantIntegerType|ConstantStringType $key): int|string => $key->getValue(), $list->getKeyTypes()));
1763+
$this->assertSame($array->isUnsealed()->describe(), $list->isUnsealed()->describe());
1764+
});
1765+
}
1766+
16831767
/**
16841768
* @return iterable<string, array{bool, list<array{int|string, Type, bool}>, list<array{int|string, Type, bool}>, TrinaryLogic}>
16851769
*/

0 commit comments

Comments
 (0)