Skip to content

Commit 3af229c

Browse files
committed
Type a closure's gathered return from parameters resolved by its siblings
The closure type gathered for template inference was read with the raw acceptor parameter, so its body saw T unresolved, while the body walk afterwards used the resolved T. In map([1, 2], fn ($x) => $x + 1) the result was list<float|int>, and in pipe2(1, fn ($x) => [$x], fn ($y) => $y) the template T leaked into the result. The gathered closure now sees the templates the already gathered siblings determine. A template that also occurs in a non-covariant position of the parameter, such as an accumulator in callable(T, int): T, is fed by the closure's own return and stays unresolved. Amp-Thread-ID: https://ampcode.com/threads/T-01a17eac-1199-74a6-b3f7-dfbd8a084465
1 parent 711c847 commit 3af229c

13 files changed

Lines changed: 435 additions & 83 deletions

‎src/Analyser/ArgumentsHandler.php‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
use PHPStan\Reflection\ExtendedMethodReflection;
3232
use PHPStan\Reflection\ExtendedParameterReflection;
3333
use PHPStan\Reflection\FunctionReflection;
34+
use PHPStan\Reflection\GenericParametersAcceptorResolver;
3435
use PHPStan\Reflection\MethodReflection;
3536
use PHPStan\Reflection\ParameterReflection;
3637
use PHPStan\Reflection\ParametersAcceptor;
@@ -235,7 +236,7 @@ public function processArgs(
235236
// resolution (see gatherClosureArgType()).
236237
$originalArgForGather = $arg->getAttribute(ArgumentsNormalizer::ORIGINAL_ARG_ATTRIBUTE) ?? $arg;
237238
$gatheredArgTypeByIndex[$i] = $typeDrivenAcceptorSelection
238-
? $this->gatherClosureArgType($parametersAcceptors, $i, $arg->value, $scope)
239+
? $this->gatherClosureArgType($parametersAcceptors, $i, $arg->value, $scope, $gatheredTypes)
239240
: $this->closureTypeResolver->getClosureType($scope, $arg->value, true, $storage);
240241
$this->addGatheredArgType($gatheredTypes, $gatheredUnpack, $gatheredHasName, $originalArgForGather, $i, $gatheredArgTypeByIndex[$i]);
241242
}
@@ -1067,16 +1068,17 @@ private function argConsumesResolvedParameterType(Expr $value): bool
10671068

10681069
/**
10691070
* Resolves the type of a closure/arrow function argument for the generic
1070-
* gather, mirroring ParametersAcceptorSelector::selectFromArgs(): the closure
1071-
* type is read with the RAW (un-generic-resolved) acceptor parameter pushed
1072-
* onto the in-function-call stack, so its body sees the template parameter
1073-
* (effectively mixed for an untyped param) rather than a parameter already
1074-
* resolved from sibling args. That keeps the inferred return type (the U in
1075-
* callable(T): U) faithful to the closure's own declaration.
1071+
* gather: the acceptor parameter is pushed onto the in-function-call stack
1072+
* with the templates the already gathered sibling arguments determine
1073+
* resolved (the T in callable(T): U from list<T> $xs), so the closure's
1074+
* inferred return type - its contribution to U - comes from the same
1075+
* parameter types its body is later walked with. Templates the closure
1076+
* returns itself stay unresolved (see resolveParameterFromSiblings()).
10761077
*
10771078
* @param ParametersAcceptor[] $parametersAcceptors
1079+
* @param array<int|string, Type> $siblingTypes
10781080
*/
1079-
private function gatherClosureArgType(array $parametersAcceptors, int $i, Expr $closureExpr, MutatingScope $scope): Type
1081+
private function gatherClosureArgType(array $parametersAcceptors, int $i, Expr $closureExpr, MutatingScope $scope, array $siblingTypes): Type
10801082
{
10811083
$rawParameter = null;
10821084
if (count($parametersAcceptors) === 1) {
@@ -1089,6 +1091,9 @@ private function gatherClosureArgType(array $parametersAcceptors, int $i, Expr $
10891091
}
10901092

10911093
if ($rawParameter !== null) {
1094+
if ($siblingTypes !== []) {
1095+
$rawParameter = GenericParametersAcceptorResolver::resolveParameterFromSiblings($siblingTypes, $parametersAcceptors[0], $rawParameter);
1096+
}
10921097
$scope = $scope->pushInFunctionCall(null, $rawParameter, false);
10931098
}
10941099

‎src/Reflection/GenericParametersAcceptorResolver.php‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,60 @@
3030
final class GenericParametersAcceptorResolver
3131
{
3232

33+
/**
34+
* The parameter with the templates that the sibling argument types
35+
* determine resolved, for typing a closure passed to it before its own
36+
* type is known. A template that also occurs in a non-covariant position
37+
* of the parameter (the T in callable(T): T, an accumulator) is fed by
38+
* the closure's own return, so it stays unresolved.
39+
*
40+
* @param array<int|string, Type> $siblingTypes
41+
*/
42+
public static function resolveParameterFromSiblings(array $siblingTypes, ParametersAcceptor $parametersAcceptor, ParameterReflection $parameter): ParameterReflection
43+
{
44+
$parameterType = $parameter->getType();
45+
if (!$parameterType->hasTemplateOrLateResolvableType()) {
46+
return $parameter;
47+
}
48+
49+
$siblingTemplateTypes = [];
50+
foreach (self::resolve($siblingTypes, $parametersAcceptor)->getResolvedTemplateTypeMap()->getTypes() as $name => $type) {
51+
if ($type instanceof ErrorType) {
52+
continue;
53+
}
54+
$siblingTemplateTypes[$name] = $type;
55+
}
56+
foreach ($parameterType->getReferencedTemplateTypes(TemplateTypeVariance::createContravariant()) as $reference) {
57+
if ($reference->getPositionVariance()->covariant()) {
58+
continue;
59+
}
60+
unset($siblingTemplateTypes[$reference->getType()->getName()]);
61+
}
62+
if ($siblingTemplateTypes === []) {
63+
return $parameter;
64+
}
65+
66+
$parameterType = TemplateTypeHelper::resolveTemplateTypes($parameterType, new TemplateTypeMap($siblingTemplateTypes), TemplateTypeVarianceMap::createEmpty(), TemplateTypeVariance::createContravariant());
67+
68+
return new ExtendedDummyParameter(
69+
$parameter->getName(),
70+
$parameterType,
71+
$parameter->isOptional(),
72+
$parameter->passedByReference(),
73+
$parameter->isVariadic(),
74+
$parameter->getDefaultValue(),
75+
$parameter instanceof ExtendedParameterReflection ? $parameter->getNativeType() : new MixedType(),
76+
$parameterType,
77+
null,
78+
TrinaryLogic::createMaybe(),
79+
null,
80+
[],
81+
null,
82+
TrinaryLogic::createNo(),
83+
TrinaryLogic::createNo(),
84+
);
85+
}
86+
3387
/**
3488
* @api
3589
* @param array<int|string, Type> $argTypes
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug11182;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
/**
8+
* @template Tv
9+
* @template Ts
10+
*
11+
* @param iterable<Tv> $iterable Iterable to be mapped over
12+
* @param (callable(Tv): iterable<Ts>) $mapper
13+
*
14+
* @return list<Ts>
15+
*/
16+
function flat_map(iterable $iterable, callable $mapper): array
17+
{
18+
$flattened = [];
19+
foreach ($iterable as $value) {
20+
foreach ($mapper($value) as $item) {
21+
$flattened[] = $item;
22+
}
23+
}
24+
25+
return $flattened;
26+
}
27+
28+
29+
$rows = [
30+
['id' => 1],
31+
['id' => 2],
32+
];
33+
34+
$ids = flat_map($rows, function ($row) {
35+
$result = [$row['id']];
36+
assertType('array{1|2}', $result);
37+
return $result;
38+
});
39+
40+
assertType('list<1|2>', $ids);
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 Bug11664;
4+
5+
use DateTime;
6+
7+
/**
8+
* @template TValue
9+
* @template TNewValue
10+
* @param callable(TValue): TNewValue $callable
11+
* @param array<TValue> $array
12+
*
13+
* @return array<TNewValue>
14+
*/
15+
function map(callable $callable, array $array) : array
16+
{
17+
return array_map($callable, $array);
18+
}
19+
20+
$dates = [
21+
new DateTime('2023-04-01'),
22+
];
23+
\PHPStan\Testing\assertType('array{DateTime}', $dates);
24+
25+
$a = map(fn($date) => $date->format('C'), $dates);
26+
\PHPStan\Testing\assertType("array<'C'>", $a);
27+
28+
$b = map(fn(DateTime $date) => $date->format('C'), $dates);
29+
\PHPStan\Testing\assertType("array<'C'>", $b);
30+
31+
// array_map works perfectly fine
32+
$c = array_map(fn($date) => $date->format('C'), $dates);
33+
34+
\PHPStan\Testing\assertType("array{'C'}", $c);

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,5 +55,5 @@ function filterArrayNotNull(array $source): array
5555
filterArrayNotNull(...)
5656
);
5757

58-
assertType('array<int<0, max>, array<int|string, mixed>>', $mappedA);
58+
assertType('array<int<0, max>, array<string, int>>', $mappedA);
5959
assertType('array<int<0, max>, array<int|string, mixed>>', $mappedAWithFirstClassSyntax);
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php // lint >= 8.0
2+
3+
declare(strict_types=1);
4+
5+
namespace Bug11936;
6+
7+
use ArrayObject;
8+
use function PHPStan\Testing\assertType;
9+
10+
/**
11+
* @template A
12+
* @template B
13+
* @template C
14+
*
15+
* @param A $items
16+
* @param callable(A): B $ab
17+
* @param callable(B): C $bc
18+
* @return C
19+
*/
20+
function pipe(mixed $items, callable $ab, callable $bc): mixed
21+
{
22+
return $bc($ab($items));
23+
}
24+
25+
/**
26+
* @return ArrayObject<string, bool>
27+
*/
28+
function getObject(): ArrayObject
29+
{
30+
return new ArrayObject;
31+
}
32+
33+
$result = pipe(
34+
getObject(),
35+
function(ArrayObject $i) {
36+
assertType('ArrayObject<string, bool>', $i);
37+
return $i;
38+
},
39+
function(ArrayObject $i) {
40+
assertType('ArrayObject<string, bool>', $i);
41+
return $i;
42+
},
43+
);
44+
45+
assertType('ArrayObject<string, bool>', $result);
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug13164;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
class Arr {
8+
/**
9+
* @template TValue
10+
* @template TMapValue
11+
*
12+
* @param array<TValue> $array
13+
* @param callable(TValue): TMapValue $callback
14+
* @return array<TMapValue>
15+
*/
16+
public static function map(array $array, callable $callback): array
17+
{
18+
return array_map($callback, $array);
19+
}
20+
}
21+
22+
$people = [
23+
['name' => 'Liam', 'age' => 21],
24+
['name' => 'Sam', 'age' => 19],
25+
];
26+
27+
$ages = array_map(function(array $person) {
28+
assertType("array{name: 'Liam', age: 21}|array{name: 'Sam', age: 19}", $person);
29+
assertType('19|21', $person['age']);
30+
31+
return $person['age'];
32+
}, $people);
33+
assertType('array{21, 19}', $ages);
34+
35+
$ages2 = Arr::map($people, function(array $person) {
36+
assertType("array{name: 'Liam', age: 21}|array{name: 'Sam', age: 19}", $person);
37+
assertType('19|21', $person['age']);
38+
39+
return $person['age'];
40+
});
41+
assertType('array<19|21>', $ages2);
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
<?php // lint >= 8.0
2+
3+
declare(strict_types = 1);
4+
5+
namespace ClosureReturnFromSiblingResolvedParameter;
6+
7+
use function PHPStan\Testing\assertType;
8+
9+
/**
10+
* @template T
11+
* @template U
12+
* @param list<T> $xs
13+
* @param callable(T): U $f
14+
* @return list<U>
15+
*/
16+
function map(array $xs, callable $f): array
17+
{
18+
return array_map($f, $xs);
19+
}
20+
21+
/**
22+
* @template T
23+
* @template U
24+
* @template V
25+
* @param T $x
26+
* @param callable(T): U $f
27+
* @param callable(U): V $g
28+
* @return V
29+
*/
30+
function pipe2($x, callable $f, callable $g)
31+
{
32+
return $g($f($x));
33+
}
34+
35+
/**
36+
* @template T
37+
* @param list<int> $xs
38+
* @param callable(T, int): T $f
39+
* @param T $init
40+
* @return T
41+
*/
42+
function reduce(array $xs, callable $f, $init)
43+
{
44+
foreach ($xs as $x) {
45+
$init = $f($init, $x);
46+
}
47+
48+
return $init;
49+
}
50+
51+
final class Collection
52+
{
53+
54+
/**
55+
* @template T
56+
* @template U
57+
* @param list<T> $xs
58+
* @param callable(T): U $f
59+
* @return list<U>
60+
*/
61+
public function map(array $xs, callable $f): array
62+
{
63+
return array_map($f, $xs);
64+
}
65+
66+
}
67+
68+
function test(Collection $c): void
69+
{
70+
assertType('list<2|3>', map([1, 2], fn ($x) => $x + 1));
71+
assertType("list<'a'>", map([1, 2], fn ($x) => is_int($x) ? 'a' : null));
72+
assertType('list<2|3>', map(f: fn ($x) => $x + 1, xs: [1, 2]));
73+
assertType('list<2|3>', $c->map([1, 2], fn ($x) => $x + 1));
74+
assertType('array{1}', pipe2(1, fn ($x) => [$x], fn ($y) => $y));
75+
76+
// the closure's own return feeds T, so T is not taken from $init alone
77+
assertType("''|non-falsy-string", reduce([1, 2, 3], fn ($carry, $x) => $carry . 'a', ''));
78+
}

‎tests/PHPStan/Analyser/nsrt/generics.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ function testF($arrayOfInt, $callableOrNull)
156156
assertType('Closure(mixed): string', function ($a): string {
157157
return (string)$a;
158158
});
159-
assertType('array<string>', f($arrayOfInt, function ($a): string {
159+
assertType('array<decimal-int-string>', f($arrayOfInt, function ($a): string {
160160
return (string)$a;
161161
}));
162162
assertType('array<int>', f($arrayOfInt, function ($a) {

‎tests/PHPStan/Rules/Functions/CallToFunctionParametersRuleTest.php‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3693,6 +3693,12 @@ public function testBug15843(): void
36933693
$this->analyse([__DIR__ . '/data/bug-15843.php'], []);
36943694
}
36953695

3696+
public function testBug13164(): void
3697+
{
3698+
$this->checkExplicitMixed = true;
3699+
$this->analyse([__DIR__ . '/data/bug-13164.php'], []);
3700+
}
3701+
36963702
public function testFloatConstantLoopGeneralize(): void
36973703
{
36983704
$this->analyse([__DIR__ . '/../../Analyser/nsrt/float-constant-loop-generalize.php'], []);

0 commit comments

Comments
 (0)