Skip to content

Commit 5de1fa8

Browse files
SanderMullerclaude
andcommitted
Map each possible list of unpacked arrays, and support a null callback
For an unpacked union of list shapes, map each list of arrays the shapes can pass as a known number of arrays, and union the results. Skip a list with fewer arrays than a closure written in the call requires, because PHP then throws an ArgumentCountError. Before, a null callback with an unknown number of arrays fell back to the array return type of the function signature. For general arrays the number of arrays is not known. With a null callback, assume more than one array, so each value is a list with one item per array. One array is returned as it is, but the type system cannot tell that case apart. Add null to the items as for a known number of arrays whose sizes are not all the same. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 89849a1 commit 5de1fa8

3 files changed

Lines changed: 195 additions & 8 deletions

File tree

‎src/Type/Php/ArrayMapFunctionReturnTypeExtension.php‎

Lines changed: 152 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,9 @@
3737
final class ArrayMapFunctionReturnTypeExtension implements DynamicFunctionReturnTypeExtension
3838
{
3939

40+
/** The largest number of array lists that unpacked list shapes can pass and that are mapped one by one */
41+
private const UNPACKED_ARRAY_LISTS_LIMIT = 16;
42+
4043
public function isFunctionSupported(FunctionReflection $functionReflection): bool
4144
{
4245
return $functionReflection->getName() === 'array_map';
@@ -47,17 +50,134 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
4750
$args = $functionCall->getArgs();
4851
if (count($args) >= 2 && in_array(true, array_map(static fn (Node\Arg $arg) => $arg->unpack, $args), true)) {
4952
$arrayArgs = array_slice($args, 1);
50-
[$arrayTypes, $restType] = UnpackedArgumentTypes::expand(
51-
array_map(static fn (Node\Arg $arg) => $scope->getType($arg->value), $arrayArgs),
52-
array_map(static fn (Node\Arg $arg) => $arg->unpack, $arrayArgs),
53-
);
53+
$argTypes = array_map(static fn (Node\Arg $arg) => $scope->getType($arg->value), $arrayArgs);
54+
$unpacked = array_map(static fn (Node\Arg $arg) => $arg->unpack, $arrayArgs);
55+
56+
$arrayLists = self::getUnpackedArrayLists($argTypes, $unpacked);
57+
if ($arrayLists !== null) {
58+
$requiredParametersCount = self::getRequiredParametersCount($args[0]->value);
59+
$types = [];
60+
foreach ($arrayLists as $arrayList) {
61+
// PHP throws an ArgumentCountError when the callback gets fewer values than it requires
62+
if (count($arrayList) < $requiredParametersCount) {
63+
continue;
64+
}
65+
66+
$type = $this->getTypeFromArgs($scope, [$args[0], ...array_map(static fn (Type $arrayType) => new Node\Arg(new TypeExpr($arrayType)), $arrayList)]);
67+
if ($type === null) {
68+
return null;
69+
}
70+
$types[] = $type;
71+
}
72+
73+
if ($types === []) {
74+
return null;
75+
}
76+
77+
return TypeCombinator::union(...$types);
78+
}
79+
80+
[$arrayTypes, $restType] = UnpackedArgumentTypes::expand($argTypes, $unpacked);
5481
if ($restType !== null) {
5582
return self::getTypeForUnknownArrayCount($scope, $args[0]->value, $arrayTypes, $restType);
5683
}
5784

5885
$args = [$args[0], ...array_map(static fn (Type $arrayType) => new Node\Arg(new TypeExpr($arrayType)), $arrayTypes)];
5986
}
6087

88+
return $this->getTypeFromArgs($scope, $args);
89+
}
90+
91+
/**
92+
* Returns each list of arrays the args can pass, when every unpacked arg is
93+
* a union of list shapes, so that each list can be mapped as a known number
94+
* of arrays. Returns null when the number of arrays is not known.
95+
*
96+
* @param list<Type> $argTypes
97+
* @param list<bool> $unpacked
98+
* @return list<list<Type>>|null
99+
*/
100+
private static function getUnpackedArrayLists(array $argTypes, array $unpacked): ?array
101+
{
102+
$arrayLists = [[]];
103+
foreach ($argTypes as $i => $argType) {
104+
$choices = [[$argType]];
105+
if ($unpacked[$i]) {
106+
$constantArrays = $argType->getConstantArrays();
107+
if ($constantArrays === []) {
108+
return null;
109+
}
110+
111+
$choices = [];
112+
foreach ($constantArrays as $constantArray) {
113+
foreach ($constantArray->getAllArrays() as $array) {
114+
if (!self::hasPositionKeys($array)) {
115+
continue;
116+
}
117+
$choices[] = $array->getValueTypes();
118+
}
119+
}
120+
if ($choices === []) {
121+
return null;
122+
}
123+
}
124+
125+
$nextArrayLists = [];
126+
foreach ($arrayLists as $arrayList) {
127+
foreach ($choices as $choice) {
128+
$nextArrayLists[] = [...$arrayList, ...$choice];
129+
}
130+
}
131+
if (count($nextArrayLists) > self::UNPACKED_ARRAY_LISTS_LIMIT) {
132+
return null;
133+
}
134+
$arrayLists = $nextArrayLists;
135+
}
136+
137+
return $arrayLists;
138+
}
139+
140+
/**
141+
* Whether the keys are 0, 1, 2 and so on. The optional keys of a list shape
142+
* also give arrays with a gap, which the list cannot be, and string keys
143+
* are passed as named args.
144+
*/
145+
private static function hasPositionKeys(ConstantArrayType $array): bool
146+
{
147+
foreach ($array->getKeyTypes() as $position => $keyType) {
148+
if ($keyType->getValue() !== $position) {
149+
return false;
150+
}
151+
}
152+
153+
return true;
154+
}
155+
156+
/**
157+
* The number of values a closure written in the call requires, 0 for other callbacks.
158+
*/
159+
private static function getRequiredParametersCount(Node\Expr $callback): int
160+
{
161+
if (!$callback instanceof Node\Expr\Closure && !$callback instanceof Node\Expr\ArrowFunction) {
162+
return 0;
163+
}
164+
165+
$count = 0;
166+
foreach ($callback->params as $param) {
167+
if ($param->default !== null || $param->variadic) {
168+
break;
169+
}
170+
$count++;
171+
}
172+
173+
return $count;
174+
}
175+
176+
/**
177+
* @param list<Node\Arg> $args
178+
*/
179+
private function getTypeFromArgs(Scope $scope, array $args): ?Type
180+
{
61181
$numArgs = count($args);
62182
if ($numArgs < 2) {
63183
return null;
@@ -194,11 +314,38 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
194314
private static function getTypeForUnknownArrayCount(Scope $scope, Node\Expr $callback, array $arrayTypes, Type $restArrayType): ?Type
195315
{
196316
$callableType = $scope->getType($callback);
317+
[$valueTypes, $restValueType] = ArrayMapCallbackParameterTypes::getCallbackValueTypes($arrayTypes, $restArrayType);
318+
if ($callableType->isNull()->yes()) {
319+
// One array is returned as it is, more arrays give a list with one value per array.
320+
// The type system cannot say how many general arrays there are, so assume more than one.
321+
$tupleValueTypes = [];
322+
$size = null;
323+
$addNull = false;
324+
foreach ([...$arrayTypes, $restArrayType] as $arrayType) {
325+
$tupleValueTypes[] = $arrayType->getIterableValueType();
326+
$arraySizes = $arrayType->getArraySize()->getConstantScalarValues();
327+
if (count($arraySizes) !== 1 || ($size !== null && $size !== $arraySizes[0])) {
328+
$addNull = true;
329+
}
330+
$size = $arraySizes[0] ?? null;
331+
}
332+
// as for a known number of arrays, null pads each array that can be shorter
333+
$tupleValueType = TypeCombinator::union(...$tupleValueTypes);
334+
if ($addNull) {
335+
$tupleValueType = TypeCombinator::addNull($tupleValueType);
336+
}
337+
$tupleType = TypeCombinator::intersect(
338+
new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), $tupleValueType),
339+
new AccessoryArrayListType(),
340+
new NonEmptyArrayType(),
341+
);
342+
343+
return TypeCombinator::intersect(new ArrayType(IntegerRangeType::createAllGreaterThanOrEqualTo(0), $tupleType), new AccessoryArrayListType());
344+
}
197345
if (!$callableType->isCallable()->yes()) {
198346
return null;
199347
}
200348

201-
[$valueTypes, $restValueType] = ArrayMapCallbackParameterTypes::getCallbackValueTypes($arrayTypes, $restArrayType);
202349
$callArgs = [];
203350
foreach ($valueTypes as $valueType) {
204351
$callArgs[] = new Node\Arg(new TypeExpr($valueType));

‎tests/PHPStan/Analyser/nsrt/array-map-unpacked-args-first-class-callable.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,5 @@ function identity($value)
2121
function genericCallbackWithUnknownCount(array $lists, array $shorterFirst): void
2222
{
2323
assertType('list<int>', array_map(identity(...), ...$lists));
24-
assertType('list<1|null>', array_map(identity(...), ...$shorterFirst));
24+
assertType('non-empty-list<1|null>', array_map(identity(...), ...$shorterFirst));
2525
}

‎tests/PHPStan/Analyser/nsrt/array-map-unpacked-args.php‎

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ public function shorterArrayWithUnknownCount(array $shorterFirst, array $shorter
104104
assertType('4|null', $b);
105105
}, ...$shorterRest);
106106

107-
assertType('list<1|null>', array_map(fn ($a) => $a, ...$shorterFirst));
107+
assertType('non-empty-list<1|null>', array_map(fn ($a) => $a, ...$shorterFirst));
108108
}
109109

110110
/**
@@ -142,10 +142,50 @@ public function defaultAfterKnownPositions(array $maybePair, array $maybeTwoArra
142142
public function genericCallbackWithUnknownCount(array $lists, array $shorterFirst, array $maps): void
143143
{
144144
assertType('list<int>', array_map('ArrayMapUnpackedArgs\\identity', ...$lists));
145-
assertType('list<1|null>', array_map('ArrayMapUnpackedArgs\\identity', ...$shorterFirst));
145+
assertType('non-empty-list<1|null>', array_map('ArrayMapUnpackedArgs\\identity', ...$shorterFirst));
146146
assertType('array<int<0, max>|string, int>', array_map('ArrayMapUnpackedArgs\\identity', ...$maps));
147147
}
148148

149+
/**
150+
* @param mixed[][] $arrays
151+
* @param list<list<int>> $lists
152+
* @param array{0: array{1}, 1?: array{2, 3}} $shorterFirst
153+
* @param array{array{1}}|array{array{2}, array{3}} $either
154+
* @param list<array{1, 2}> $pairs
155+
*/
156+
public function nullCallback(array $arrays, array $lists, array $shorterFirst, array $either, array $pairs): void
157+
{
158+
assertType('list<non-empty-list<1|2>>', array_map(null, ...$pairs));
159+
assertType('list<non-empty-list<mixed>>', array_map(null, ...$arrays));
160+
assertType('list<non-empty-list<int|null>>', array_map(null, ...$lists));
161+
assertType('non-empty-list<1|array{1|null, 2|3|null}>', array_map(null, ...$shorterFirst));
162+
assertType('non-empty-list<1|array{2, 3}>', array_map(null, ...$either));
163+
assertType('non-empty-list<1|2>', array_map(fn ($a) => $a, ...$either));
164+
}
165+
166+
/**
167+
* @param array{0: array{1}, 1?: array{2}, 2?: array{3}} $twoOptional
168+
* @param array{0: array{1}, 1?: array{2}} $optional
169+
*/
170+
public function eachListOfArrays(array $twoOptional, array $optional, string $maybeCallable): void
171+
{
172+
assertType('non-empty-list<1|array{0: 1, 1: 2, 2?: 3}>', array_map(null, ...$twoOptional));
173+
// one array throws an ArgumentCountError, because the callback requires two values
174+
assertType('non-empty-list<2>', array_map(fn ($a, $b) => $b, ...$optional));
175+
assertType('non-empty-list', array_map($maybeCallable, ...$optional));
176+
}
177+
178+
/**
179+
* @param list<array<int, int>> $maybeLists
180+
* @param list<list<int>> $lists
181+
*/
182+
public function unknownCountEdges(array $maybeLists, array $lists, string $maybeCallable, ?callable $maybeNull): void
183+
{
184+
assertType('array<int, int>', array_map(fn ($a) => $a, ...$maybeLists));
185+
assertType('array', array_map($maybeCallable, ...$lists));
186+
assertType('array', array_map($maybeNull, ...$lists));
187+
}
188+
149189
public function shorterUnpackedArray(): void
150190
{
151191
array_map(function ($a, $b) {

0 commit comments

Comments
 (0)