Skip to content

Commit 286fc16

Browse files
committed
Do not treat PHPDoc shapes with explicit keys as lists with bleeding edge
array{0: int, 1: string} says that the keys 0 and 1 are present, not that they come in this order, so [1 => 'a', 0 => 1] fits it too. With bleeding edge such a shape is a list only maybe, when its keys sorted could form one, and a list that has to name its keys describes itself as list{...}. list{...} and array{...}&list keep being lists, with their keys in ascending order. Likewise, values appended to a builder in no known order make a list only maybe. turbo-ext: the same in ConstantArrayType, ConstantArrayTypeBuilder and LateResolvableArrayShapeType. Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
1 parent d9145a6 commit 286fc16

61 files changed

Lines changed: 605 additions & 295 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/Type/Constant/ConstantArrayType.php‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3180,7 +3180,8 @@ private function getKeysOrValuesArray(array $types, ?Type $unsealedSourceType):
31803180

31813181
public function describe(VerbosityLevel $level): string
31823182
{
3183-
$arrayName = $this->shouldBeDescribedAsAList() ? 'list' : 'array';
3183+
$arrayName = $this->shouldBeDescribedAsAList(true) ? 'list' : 'array';
3184+
$typeOnlyArrayName = $this->shouldBeDescribedAsAList(false) ? 'list' : 'array';
31843185

31853186
$describeValue = function (bool $truncate) use ($level, $arrayName): string {
31863187
$items = [];
@@ -3249,7 +3250,8 @@ public function describe(VerbosityLevel $level): string
32493250
);
32503251
};
32513252
return $level->handle(
3252-
function () use ($arrayName, $level): string {
3253+
function () use ($typeOnlyArrayName, $level): string {
3254+
$arrayName = $typeOnlyArrayName;
32533255
if ($this->isIterableAtLeastOnce()->no()) {
32543256
return $arrayName;
32553257
}
@@ -3267,7 +3269,8 @@ function () use ($arrayName, $level): string {
32673269
);
32683270
}
32693271

3270-
private function shouldBeDescribedAsAList(): bool
3272+
/** @param bool $namingKeys whether the description names the keys, as a shape does */
3273+
private function shouldBeDescribedAsAList(bool $namingKeys = true): bool
32713274
{
32723275
if (!$this->isList->yes()) {
32733276
return false;
@@ -3277,7 +3280,8 @@ private function shouldBeDescribedAsAList(): bool
32773280
return false;
32783281
}
32793282

3280-
if (count($this->optionalKeys) > 1) {
3283+
// with bleeding edge, a shape that lists two or more keys is not a list
3284+
if (count($this->optionalKeys) > 1 || ($namingKeys && count($this->keyTypes) > 1 && BleedingEdgeToggle::isBleedingEdge())) {
32813285
return true;
32823286
}
32833287

@@ -4087,6 +4091,12 @@ public function makeList(): Type
40874091
return new NeverType();
40884092
}
40894093

4094+
if (!$this->isKeyOrderKnown()) {
4095+
// a list has its keys in ascending order
4096+
$sorted = $this->sortKeys();
4097+
return (new self($sorted->keyTypes, $sorted->valueTypes, $sorted->nextAutoIndexes, $sorted->optionalKeys, $sorted->isList, $sorted->unsealedDeclaration ?? $sorted->unsealed, true))->makeList();
4098+
}
4099+
40904100
// isList is Maybe. In a sealed shape a key past a gap in the 0..n sequence
40914101
// (or any non-integer key) can never appear in a list, so keep only the
40924102
// contiguous 0..m prefix. Unsealed extras may fill the gaps, so keep every

‎src/Type/Constant/ConstantArrayTypeBuilder.php‎

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,17 @@
1919
use PHPStan\Type\TypeCombinator;
2020
use PHPStan\Type\TypeUtils;
2121
use function array_filter;
22+
use function array_keys;
2223
use function array_map;
2324
use function array_unique;
2425
use function array_values;
2526
use function count;
2627
use function in_array;
2728
use function is_float;
29+
use function is_int;
2830
use function max;
2931
use function min;
32+
use function usort;
3033

3134
/**
3235
* @api
@@ -133,6 +136,32 @@ public function forgetKeyOrder(): void
133136
$this->keyOrderKnown = false;
134137
}
135138

139+
/**
140+
* The keys come in any order, so the array can be a list when they could come in ascending
141+
* order, but does not surely come as one.
142+
*/
143+
public function forgetListKeyOrder(): void
144+
{
145+
// a builder that degrades has keys without a value to sort them by
146+
if ($this->degradeToGeneralArray) {
147+
$this->isList = $this->isList->and(TrinaryLogic::createMaybe());
148+
return;
149+
}
150+
151+
/** @var list<ConstantIntegerType|ConstantStringType> $keyTypes */
152+
$keyTypes = $this->keyTypes;
153+
$indices = array_keys($keyTypes);
154+
usort($indices, static fn (int $a, int $b): int => [!is_int($keyTypes[$a]->getValue()), $keyTypes[$a]->getValue()] <=> [!is_int($keyTypes[$b]->getValue()), $keyTypes[$b]->getValue()]);
155+
156+
$sorted = self::createEmpty();
157+
foreach ($indices as $i) {
158+
$sorted->setOffsetValueType($keyTypes[$i], $this->valueTypes[$i], in_array($i, $this->optionalKeys, true));
159+
}
160+
161+
// a single key has no order to forget
162+
$this->isList = count($this->keyTypes) < 2 ? $sorted->isList : $sorted->isList->and(TrinaryLogic::createMaybe());
163+
}
164+
136165
public function makeUnsealed(Type $keyType, Type $valueType): void
137166
{
138167
$this->setUnsealed([$keyType, $valueType]);
@@ -526,6 +555,7 @@ public function disableArrayDegradation(): void
526555
public function getArray(): Type
527556
{
528557
$keyTypesCount = count($this->keyTypes);
558+
$isList = $this->getListness();
529559
if ($keyTypesCount === 0) {
530560
if ($this->unsealed !== null) {
531561
$isExplicitNever = $this->unsealed[0] instanceof NeverType && $this->unsealed[0]->isExplicit();
@@ -544,7 +574,7 @@ public function getArray(): Type
544574
if (!$this->degradeToGeneralArray) {
545575
/** @var list<ConstantIntegerType|ConstantStringType> $keyTypes */
546576
$keyTypes = $this->keyTypes;
547-
$array = new ConstantArrayType($keyTypes, $this->valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $this->isList, $this->getUnsealedForArray(), $this->keyOrderKnown);
577+
$array = new ConstantArrayType($keyTypes, $this->valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $isList, $this->getUnsealedForArray(), $this->keyOrderKnown);
548578
if ($this->isNonEmpty->yes() && !$array->isIterableAtLeastOnce()->yes()) {
549579
return TypeCombinator::intersect($array, new NonEmptyArrayType());
550580
}
@@ -591,7 +621,7 @@ public function getArray(): Type
591621
$types[] = new OversizedArrayType();
592622
}
593623

594-
if ($this->isList->yes()) {
624+
if ($isList->yes()) {
595625
$types[] = new AccessoryArrayListType();
596626
}
597627

@@ -604,7 +634,17 @@ public function getArray(): Type
604634

605635
public function isList(): bool
606636
{
607-
return $this->isList->yes();
637+
return $this->getListness()->yes();
638+
}
639+
640+
private function getListness(): TrinaryLogic
641+
{
642+
// keys set in no known order do not say they come as a list, only that they can
643+
if (!$this->keyOrderKnown && count($this->keyTypes) > 1 && BleedingEdgeToggle::isBleedingEdge()) {
644+
return $this->isList->and(TrinaryLogic::createMaybe());
645+
}
646+
647+
return $this->isList;
608648
}
609649

610650
}

‎src/Type/LateResolvableArrayShapeType.php‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace PHPStan\Type;
44

5+
use PHPStan\DependencyInjection\BleedingEdgeToggle;
56
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode;
67
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode;
78
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode;
@@ -222,6 +223,8 @@ protected function getResult(): Type
222223
// a shape that names its keys only says they are present, not in which order
223224
if ($explicitKeyValues === []) {
224225
$builder->makeKeyOrderKnown();
226+
} elseif (BleedingEdgeToggle::isBleedingEdge()) {
227+
$builder->forgetListKeyOrder();
225228
}
226229

227230
$isList = in_array($this->kind, [

‎tests/PHPStan/Analyser/NoBleedingEdgeTypeInferenceTest.php‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ public static function dataAsserts(): iterable
1818
yield from self::gatherAssertTypes(__DIR__ . '/data/bug-15749.php');
1919
yield from self::gatherAssertTypes(__DIR__ . '/data/bug-15760.php');
2020
yield from self::gatherAssertTypes(__DIR__ . '/nsrt/bug-15780.php');
21-
yield from self::gatherAssertTypes(__DIR__ . '/nsrt/bug-15820.php');
21+
// a list that names its keys describes itself as list{...} only with bleeding edge
22+
yield from self::gatherAssertTypes(__DIR__ . '/data/bug-15820-no-bleeding-edge.php');
2223
yield from self::gatherAssertTypes(__DIR__ . '/nsrt/bug-15860.php');
2324
yield from self::gatherAssertTypes(__DIR__ . '/nsrt/bug-15869.php');
2425
// a shape whose keys come in any order lists them in the order the merges building it come to
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug15820NoBleedingEdge;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
final class Recommender
8+
{
9+
private const CATEGORIES = [
10+
'signup' => ['reasonKey' => 'signup', 'tokens' => ['s0', 's1', 's2', 's3', 's4', 's5', 's6', 's7', 's8', 's9', 's10', 's11', 's12', 's13', 's14', 's15', 's16', 's17', 's18', 's19', 's20', 's21', 's22', 's23', 's24', 's25', 's26', 's27', 's28', 's29', 's30', 's31', 's32', 's33', 's34', 's35', 's36', 's37', 's38', 's39', 's40', 's41', 's42', 's43', 's44', 's45', 's46', 's47', 's48', 's49', 's50', 's51', 's52', 's53', 's54', 's55', 's56', 's57', 's58', 's59', 's60', 's61', 's62', 's63', 's64', 's65', 's66', 's67', 's68', 's69', 's70', 's71', 's72', 's73', 's74', 's75', 's76', 's77', 's78', 's79', 's80', 's81', 's82', 's83', 's84', 's85']],
11+
'demo' => ['reasonKey' => 'demo', 'eventName' => 'quote-request', 'tokens' => ['d0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'd10', 'd11', 'd12', 'd13', 'd14', 'd15', 'd16', 'd17', 'd18', 'd19', 'd20', 'd21', 'd22', 'd23', 'd24', 'd25', 'd26', 'd27', 'd28', 'd29', 'd30', 'd31', 'd32', 'd33', 'd34', 'd35', 'd36', 'd37', 'd38', 'd39', 'd40', 'd41', 'd42', 'd43', 'd44', 'd45', 'd46', 'd47', 'd48', 'd49', 'd50', 'd51', 'd52', 'd53', 'd54', 'd55', 'd56', 'd57', 'd58', 'd59', 'd60', 'd61', 'd62', 'd63', 'd64', 'd65', 'd66', 'd67', 'd68', 'd69', 'd70', 'd71', 'd72', 'd73', 'd74', 'd75', 'd76', 'd77', 'd78', 'd79', 'd80', 'd81', 'd82', 'd83', 'd84', 'd85']],
12+
'contact' => ['reasonKey' => 'contact', 'tokens' => ['c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10', 'c11', 'c12', 'c13', 'c14', 'c15', 'c16', 'c17', 'c18', 'c19', 'c20', 'c21', 'c22', 'c23', 'c24', 'c25', 'c26', 'c27', 'c28', 'c29', 'c30', 'c31', 'c32', 'c33', 'c34', 'c35', 'c36', 'c37', 'c38', 'c39', 'c40', 'c41', 'c42', 'c43', 'c44', 'c45', 'c46', 'c47', 'c48', 'c49', 'c50', 'c51', 'c52', 'c53', 'c54', 'c55', 'c56', 'c57', 'c58', 'c59', 'c60', 'c61', 'c62', 'c63', 'c64', 'c65', 'c66', 'c67', 'c68', 'c69', 'c70', 'c71', 'c72', 'c73', 'c74', 'c75', 'c76', 'c77', 'c78', 'c79', 'c80', 'c81', 'c82', 'c83', 'c84', 'c85']],
13+
];
14+
15+
public function eventName(string $category): ?string
16+
{
17+
$definition = self::CATEGORIES[$category];
18+
assertType("array{0: 'reasonKey', 1: 'eventName'|'tokens', 2?: 'tokens'}", array_keys($definition));
19+
if (isset($definition['eventName'])) {
20+
assertType("'quote-request'", $definition['eventName']);
21+
return $definition['eventName'];
22+
}
23+
24+
return null;
25+
}
26+
}
27+

‎tests/PHPStan/Analyser/nsrt/array-chunk.php‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,9 @@ public function chunkUnionTypeLength(array $arr, $positiveRange, $positiveUnion)
6464
if (rand(0, 1)) {
6565
unset($arr['b']);
6666
}
67-
assertType('array{array{0: 0, 1: 1|2, 2?: 2}}|array{list{0: 0, 1?: 1|2, 2?: 2}, array{0?: 2}}', array_chunk($arr, $positiveRange));
67+
assertType('array{list{0: 0, 1: 1|2, 2?: 2}}|array{list{0: 0, 1?: 1|2, 2?: 2}, array{0?: 2}}', array_chunk($arr, $positiveRange));
6868
assertType('array{array{a: 0, b?: 1, c: 2}}|array{array{a: 0, b?: 1, c?: 2}, array{c?: 2}}', array_chunk($arr, $positiveRange, true));
69-
assertType('array{array{0: 0, 1: 1|2, 2?: 2}}|array{list{0: 0, 1?: 1|2, 2?: 2}, array{0?: 2}}', array_chunk($arr, $positiveUnion));
69+
assertType('array{list{0: 0, 1: 1|2, 2?: 2}}|array{list{0: 0, 1?: 1|2, 2?: 2}, array{0?: 2}}', array_chunk($arr, $positiveUnion));
7070
assertType('array{array{a: 0, b?: 1, c: 2}}|array{array{a: 0, b?: 1, c?: 2}, array{c?: 2}}', array_chunk($arr, $positiveUnion, true));
7171
}
7272

@@ -88,7 +88,7 @@ function testLimits(array $arr, int $oneToFour, int $tooBig) {
8888
if (rand(0, 1)) {
8989
unset($arr['b']);
9090
}
91-
assertType('array{array{0: 0, 1: 1|2, 2: 2|3, 3?: 3}}|array{array{0}, list{0?: 1|2, 1?: 2}, list{0?: 2|3, 1?: 3}, array{0?: 3}}|array{list{0: 0, 1: 1|2, 2?: 2|3, 3?: 3}, array{0?: 3}}|array{list{0: 0, 1?: 1|2, 2?: 2}, array{0: 2|3, 1?: 3}}', array_chunk($arr, $oneToFour));
91+
assertType('array{array{0}, list{0?: 1|2, 1?: 2}, list{0?: 2|3, 1?: 3}, array{0?: 3}}|array{list{0: 0, 1: 1|2, 2: 2|3, 3?: 3}}|array{list{0: 0, 1: 1|2, 2?: 2|3, 3?: 3}, array{0?: 3}}|array{list{0: 0, 1?: 1|2, 2?: 2}, list{0: 2|3, 1?: 3}}', array_chunk($arr, $oneToFour));
9292
assertType('non-empty-list<non-empty-list<0|1|2|3>>', array_chunk($arr, $tooBig));
9393
}
9494

‎tests/PHPStan/Analyser/nsrt/array-combine-php8.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ function onlyKeysUnsealed(array $keys)
189189

190190
/**
191191
* @param list<'1'|'2'> $constantIntStrings
192-
* @param array{0: '1', 1: '2'} $sealedIntStrings
192+
* @param array{'1', '2'} $sealedIntStrings
193193
*/
194194
function withConstantIntStringKeys(array $constantIntStrings, array $sealedIntStrings): void
195195
{

‎tests/PHPStan/Analyser/nsrt/array-keys-branches.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ function (array $generalArray) {
5656
assertType("array{i: 3, j: int, k: 2, l: 1, m: 5, key: DateTimeImmutable, n?: 'str'}", $array);
5757
assertType('non-empty-array&hasOffsetValue(\'key\', mixed~null)', $generalArray);
5858
assertType('mixed~null+DateTimeImmutable', $generalArray['key']);
59-
assertType('array{0: \'foo\', 1: \'bar\', 2?: \'baz\'}', $arrayAppendedInIf);
59+
assertType('list{0: \'foo\', 1: \'bar\', 2?: \'baz\'}', $arrayAppendedInIf);
6060
assertType('non-empty-list<\'bar\'|\'baz\'|\'foo\'>', $arrayAppendedInForeach);
6161
assertType('non-empty-array<int<0, max>, literal-string&lowercase-string&non-falsy-string>', $anotherArrayAppendedInForeach);
6262
assertType('\'str\'', $array['n']);
@@ -122,7 +122,7 @@ function (array $generalArray, array $xs) {
122122
assertType('array{i: (float|int), j: int, k: int<1, max>, l: 1, m: 5, key: DateTimeImmutable, n?: \'str\'}|array{i: 0, j: int, k: 0, l: 1, m: 5, key: DateTimeImmutable, n?: \'str\'}', $array);
123123
assertType('non-empty-array&hasOffsetValue(\'key\', mixed~null)', $generalArray);
124124
assertType('mixed~null+DateTimeImmutable', $generalArray['key']);
125-
assertType('array{0: \'foo\', 1: \'bar\', 2?: \'baz\'}', $arrayAppendedInIf);
125+
assertType('list{0: \'foo\', 1: \'bar\', 2?: \'baz\'}', $arrayAppendedInIf);
126126
assertType('non-empty-list<\'bar\'|\'baz\'|\'foo\'>', $arrayAppendedInForeach);
127127
assertType('non-empty-array<int<0, max>, literal-string&lowercase-string&non-falsy-string>', $anotherArrayAppendedInForeach);
128128
assertType('\'str\'', $array['n']);

‎tests/PHPStan/Analyser/nsrt/array-shape-key-order.php‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,8 @@ function literalShapeHoldsPhpDocShape(array &$segments, array $call): void
9595
function positionsOfShapeWithKeysInAnyOrder(array $a): void
9696
{
9797
// any of the keys can come at any position
98-
assertType("array{0: 'bar'|'baz'|'foo', 1: 'bar'|'baz'|'foo', 2?: 'bar'|'baz'|'foo'}", array_keys($a));
99-
assertType('array{0: float|int|string, 1: float|int|string, 2?: float|int|string}', array_values($a));
98+
assertType("list{0: 'bar'|'baz'|'foo', 1: 'bar'|'baz'|'foo', 2?: 'bar'|'baz'|'foo'}", array_keys($a));
99+
assertType('list{0: float|int|string, 1: float|int|string, 2?: float|int|string}', array_values($a));
100100
assertType('array{foo?: int, bar?: string, baz?: float}', array_slice($a, 0, 1));
101101
assertType('array{baz?: float, bar: string, foo: int}', array_reverse($a));
102102

@@ -167,7 +167,7 @@ function columnsOfRowsInAnyOrder(
167167
// the rows without the index are numbered by their positions, which are not known
168168
assertType('array{1|2, 1|2}', array_column($rows, 'v', 'nope'));
169169
assertType('0', array_key_first(array_column($rows, 'v', 'nope')));
170-
assertType('array{0: 1|2, 1?: 1|2}', array_column($optionalRows, 'v'));
170+
assertType('list{0: 1|2, 1?: 1|2}', array_column($optionalRows, 'v'));
171171
assertType('array{a: 1, 0: 2|3, 1: 2|3}', array_column($stringIndexed, 'v', 'id'));
172172
assertType('array{1|2|3, 1|2|3, ...<2>}', array_column($unsealedRows, 'v'));
173173
assertType('array{1|2|3, 1|2|3, ...<3>}', array_column($stringIndexedExtras, 'v', 'nope'));

‎tests/PHPStan/Analyser/nsrt/array-shape-list-optional.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ public function doFoo(
2828
// The trailing keys can never appear in a list (4 sits past the gap at
2929
// 3; foo is not an integer), so they are dropped, leaving the valid
3030
// list projection rather than an empty *NEVER*.
31-
assertType('array{0: string, 1: int, 2?: string}', $invalid1);
32-
assertType('array{0: string, 1: int, 2?: string}', $invalid2);
31+
assertType('list{0: string, 1: int, 2?: string}', $invalid1);
32+
assertType('list{0: string, 1: int, 2?: string}', $invalid2);
3333
}
3434

3535
}

0 commit comments

Comments
 (0)