Skip to content

Commit f0b92e1

Browse files
committed
Infer closure parameter types in array arguments
Closes phpstan/phpstan#6430 Closes phpstan/phpstan#11215
1 parent 1f2c00c commit f0b92e1

9 files changed

Lines changed: 262 additions & 12 deletions

File tree

‎src/Analyser/ExprHandler/ArrayHandler.php‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
use PhpParser\Node\Arg;
66
use PhpParser\Node\Expr;
77
use PhpParser\Node\Expr\Array_;
8+
use PhpParser\Node\Expr\ArrowFunction;
9+
use PhpParser\Node\Expr\Closure;
810
use PhpParser\Node\Expr\FuncCall;
911
use PhpParser\Node\Name\FullyQualified;
1012
use PhpParser\Node\Stmt;
@@ -25,7 +27,11 @@
2527
use PHPStan\Node\Variable\VariableWrite;
2628
use PHPStan\Reflection\InitializerExprTypeResolver;
2729
use PHPStan\ShouldNotHappenException;
30+
use PHPStan\Type\ArrayType;
2831
use PHPStan\Type\CallableType;
32+
use PHPStan\Type\Constant\ConstantIntegerType;
33+
use PHPStan\Type\IntegerType;
34+
use PHPStan\Type\MixedType;
2935
use PHPStan\Type\Type;
3036
use PHPStan\Type\TypeCombinator;
3137
use function array_key_exists;
@@ -68,6 +74,9 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
6874
if ($literalWrite !== null && $literalWrite->isOffsetWrite()) {
6975
$literalWrite = null;
7076
}
77+
$passedToType = $this->getExpectedArrayType($context->getPassedToType());
78+
$nativePassedToType = $this->getExpectedArrayType($context->getNativePassedToType());
79+
$hasExpectedType = $passedToType !== null || $nativePassedToType !== null;
7180
$nextIndex = 0;
7281
foreach ($expr->items as $arrayItem) {
7382
$itemNodes[] = new LiteralArrayItem($scope, $arrayItem);
@@ -85,7 +94,11 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
8594
}
8695

8796
$valueContext = $context->enterDeepKeepingValueFlow();
88-
if ($literalWrite !== null) {
97+
$keyType = null;
98+
if ($hasExpectedType && !$arrayItem->unpack && ($arrayItem->value instanceof Array_ || $arrayItem->value instanceof Closure || $arrayItem->value instanceof ArrowFunction)) {
99+
$keyType = $keyResult !== null ? $keyResult->getType()->toArrayKey() : ($nextIndex !== null ? new ConstantIntegerType($nextIndex) : new IntegerType());
100+
}
101+
if ($literalWrite !== null || $hasExpectedType) {
89102
if ($arrayItem->unpack) {
90103
$offset = null;
91104
$nextIndex = null;
@@ -102,10 +115,18 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
102115
$nextIndex = max($nextIndex, $offset + 1);
103116
}
104117
}
118+
}
119+
if ($literalWrite !== null) {
105120
$itemWrite = new VariableWrite($literalWrite->getVariableName(), $arrayItem, spl_object_id($arrayItem), VariableWrite::KIND_ARRAY_LITERAL_ITEM, true, $offset, $literalWrite->getId());
106121
$variableFlows[] = VariableFlow::write($itemWrite);
107122
$valueContext = $context->enterDeep()->enterValueFlow($itemWrite, false);
108123
}
124+
if ($keyType !== null) {
125+
$valueContext = $valueContext->enterPassedToType(
126+
$this->getExpectedValueType($passedToType, $keyType),
127+
$this->getExpectedValueType($nativePassedToType, $keyType),
128+
);
129+
}
109130
$valueResult = $nodeScopeResolver->processExprNode($stmt, $arrayItem->value, $scope, $storage, $nodeCallback, $valueContext);
110131
$itemResults[spl_object_id($arrayItem->value)] = $valueResult;
111132
$variableFlows[] = $valueResult->getVariableFlow();
@@ -174,4 +195,26 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
174195
);
175196
}
176197

198+
private function getExpectedArrayType(?Type $type): ?Type
199+
{
200+
if ($type === null || $type->isIterable()->no()) {
201+
return null;
202+
}
203+
204+
if ($type->isArray()->yes()) {
205+
return $type;
206+
}
207+
208+
return TypeCombinator::intersect($type, new ArrayType(new MixedType(), new MixedType()));
209+
}
210+
211+
private function getExpectedValueType(?Type $arrayType, Type $keyType): ?Type
212+
{
213+
if ($arrayType === null || $arrayType->hasOffsetValueType($keyType)->no()) {
214+
return null;
215+
}
216+
217+
return $arrayType->getOffsetValueType($keyType);
218+
}
219+
177220
}

‎src/Analyser/ExprHandler/ArrowFunctionHandler.php‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public function supports(Expr $expr): bool
4141

4242
public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Expr $expr, MutatingScope $scope, ExpressionResultStorage $storage, callable $nodeCallback, ExpressionContext $context): ExpressionResult
4343
{
44-
$arrowFunctionResult = $nodeScopeResolver->processArrowFunctionNode($stmt, $expr, $scope, $storage, $nodeCallback, null, null, $context);
44+
$arrowFunctionResult = $nodeScopeResolver->processArrowFunctionNode($stmt, $expr, $scope, $storage, $nodeCallback, $context->getPassedToType(), $context->getNativePassedToType(), $context);
4545
$result = $arrowFunctionResult->getExpressionResult();
4646

4747
// A plain typeCallback recursing through getClosureType() would re-walk
@@ -63,6 +63,8 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
6363
$arrowFunctionResult->getInvalidateExpressions(),
6464
false,
6565
$storage,
66+
$context->getPassedToType(),
67+
$context->getNativePassedToType(),
6668
);
6769
$nativeType = $this->closureTypeResolver->buildClosureTypeForArrowFunction(
6870
$scope,
@@ -73,6 +75,8 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
7375
$arrowFunctionResult->getInvalidateExpressions(),
7476
true,
7577
$storage,
78+
$context->getPassedToType(),
79+
$context->getNativePassedToType(),
7680
);
7781

7882
return $this->expressionResultFactory->create(

‎src/Analyser/ExprHandler/ClosureHandler.php‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public function supports(Expr $expr): bool
4141

4242
public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Expr $expr, MutatingScope $scope, ExpressionResultStorage $storage, callable $nodeCallback, ExpressionContext $context): ExpressionResult
4343
{
44-
$processClosureResult = $nodeScopeResolver->processClosureNode($stmt, $expr, $scope, $storage, $nodeCallback, $context, null);
44+
$processClosureResult = $nodeScopeResolver->processClosureNode($stmt, $expr, $scope, $storage, $nodeCallback, $context, $context->getPassedToType(), $context->getNativePassedToType());
4545

4646
// A plain typeCallback recursing through getClosureType() would re-walk
4747
// the body each getType() ask before the cache populates and hang;
@@ -67,6 +67,8 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
6767
$processClosureResult->getInvalidateExpressions(),
6868
false,
6969
$storage,
70+
$context->getPassedToType(),
71+
$context->getNativePassedToType(),
7072
);
7173
$nativeType = $type;
7274

‎src/Analyser/ExprHandler/Helper/ClosureTypeResolver.php‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -308,9 +308,11 @@ public function buildClosureTypeForClosure(
308308
array $invalidateExpressions,
309309
bool $native = false,
310310
?ExpressionResultStorage $storage = null,
311+
?Type $passedToType = null,
312+
?Type $nativePassedToType = null,
311313
): ClosureType
312314
{
313-
[$parameters, $isVariadic, $callableParameters, $nativeCallableParameters] = $this->buildParametersAndAcceptors($scope, $expr, $storage);
315+
[$parameters, $isVariadic, $callableParameters, $nativeCallableParameters] = $this->buildParametersAndAcceptors($scope, $expr, $storage, $passedToType, $nativePassedToType);
314316

315317
return $this->buildClosureTypeFromClosureWalk(
316318
$scope,
@@ -356,9 +358,11 @@ public function buildClosureTypeForArrowFunction(
356358
array $invalidateExpressions,
357359
bool $native = false,
358360
?ExpressionResultStorage $storage = null,
361+
?Type $passedToType = null,
362+
?Type $nativePassedToType = null,
359363
): ClosureType
360364
{
361-
[$parameters, $isVariadic, $callableParameters, $nativeCallableParameters] = $this->buildParametersAndAcceptors($scope, $expr, $storage);
365+
[$parameters, $isVariadic, $callableParameters, $nativeCallableParameters] = $this->buildParametersAndAcceptors($scope, $expr, $storage, $passedToType, $nativePassedToType);
362366

363367
$returnType = $this->resolveArrowFunctionReturnType($scope, $arrowScope, $expr, $native, $storage);
364368

@@ -784,14 +788,13 @@ private function buildParametersAndAcceptors(
784788
MutatingScope $scope,
785789
Node\Expr\Closure|ArrowFunction $expr,
786790
?ExpressionResultStorage $storage = null,
791+
?Type $passedToType = null,
792+
?Type $nativePassedToType = null,
787793
): array
788794
{
789795
[$parameters, $isVariadic] = $this->buildDeclaredParameters($scope, $expr);
790-
791-
$passedToType = null;
792-
$nativePassedToType = null;
793796
$inFunctionCallsStackCount = count($scope->inFunctionCallsStack);
794-
if ($inFunctionCallsStackCount > 0) {
797+
if ($passedToType === null && $inFunctionCallsStackCount > 0) {
795798
[, $inParameter] = $scope->inFunctionCallsStack[$inFunctionCallsStackCount - 1];
796799
if ($inParameter !== null) {
797800
$passedToType = $inParameter->getType();

‎src/Analyser/ExpressionContext.php‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ private function __construct(
2525
private bool $arrayDimFetchRoot = false,
2626
private bool $unsetTarget = false,
2727
private ?bool $valueConsumed = null,
28+
private ?Type $passedToType = null,
29+
private ?Type $nativePassedToType = null,
2830
)
2931
{
3032
}
@@ -46,7 +48,7 @@ public static function createDeep(bool $resolveTemplateArguments = true): self
4648
*/
4749
public function enterDeep(): self
4850
{
49-
if ($this->isDeep && $this->valueFlowTarget === null && !$this->arrayDimFetchRoot && !$this->unsetTarget) {
51+
if ($this->isDeep && $this->valueFlowTarget === null && !$this->arrayDimFetchRoot && !$this->unsetTarget && $this->passedToType === null && $this->nativePassedToType === null) {
5052
return $this;
5153
}
5254

@@ -74,7 +76,7 @@ public function enterDeepKeepingValueFlow(): self
7476
*/
7577
public function withoutValueFlow(): self
7678
{
77-
if ($this->valueFlowTarget === null && !$this->arrayDimFetchRoot && !$this->unsetTarget) {
79+
if ($this->valueFlowTarget === null && !$this->arrayDimFetchRoot && !$this->unsetTarget && $this->passedToType === null && $this->nativePassedToType === null) {
7880
return $this;
7981
}
8082

@@ -92,6 +94,30 @@ public function isValueConsumed(): bool
9294
return $this->valueFlowTarget !== null || ($this->valueConsumed ?? $this->isDeep);
9395
}
9496

97+
/** Applies only to this expression; child expressions must receive their own expected types. */
98+
public function enterPassedToType(?Type $type, ?Type $nativeType): self
99+
{
100+
if ($this->passedToType === $type && $this->nativePassedToType === $nativeType) {
101+
return $this;
102+
}
103+
104+
$context = clone $this;
105+
$context->passedToType = $type;
106+
$context->nativePassedToType = $nativeType;
107+
108+
return $context;
109+
}
110+
111+
public function getPassedToType(): ?Type
112+
{
113+
return $this->passedToType;
114+
}
115+
116+
public function getNativePassedToType(): ?Type
117+
{
118+
return $this->nativePassedToType;
119+
}
120+
95121
public function isDeep(): bool
96122
{
97123
return $this->isDeep;

‎src/Analyser/NodeScopeResolver.php‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3143,7 +3143,11 @@ public function processArgs(
31433143
if ($enterExpressionAssignForByRef) {
31443144
$scopeToPass = $scopeToPass->enterExpressionAssign($arg->value);
31453145
}
3146-
$exprResult = $this->processExprNode($stmt, $arg->value, $scopeToPass, $storage, $nodeCallback, $context->enterDeep());
3146+
$argContext = $context->enterDeep();
3147+
if (!$arg->unpack && $arg->value instanceof Expr\Array_) {
3148+
$argContext = $argContext->enterPassedToType($parameterType, $parameterNativeType);
3149+
}
3150+
$exprResult = $this->processExprNode($stmt, $arg->value, $scopeToPass, $storage, $nodeCallback, $argContext);
31473151
$argResults[spl_object_id($arg->value)] = $exprResult;
31483152
$exprType = $exprResult->getType();
31493153
$throwPoints = array_merge($throwPoints, $exprResult->getThrowPoints());
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
<?php // lint >= 8.0
2+
3+
declare(strict_types = 1);
4+
5+
namespace ArrayClosureParameters;
6+
7+
use Closure;
8+
use function PHPStan\Testing\assertNativeType;
9+
use function PHPStan\Testing\assertType;
10+
11+
/** @param list<callable(string, int): mixed> $callbacks */
12+
function callbacks(array $callbacks): void {}
13+
14+
callbacks([
15+
function ($value, $key) {
16+
assertType('string', $value);
17+
assertType('int', $key);
18+
assertNativeType('mixed', $value);
19+
assertNativeType('mixed', $key);
20+
return $value;
21+
},
22+
fn ($value, $key) => [assertType('string', $value), assertType('int', $key), assertNativeType('mixed', $value)],
23+
function (int $value, $key) {
24+
assertType('int', $value);
25+
assertType('int', $key);
26+
},
27+
]);
28+
29+
/** @param array{first: callable(string): mixed, second?: Closure(int): mixed} $callbacks */
30+
function shape(array $callbacks): void {}
31+
32+
shape(callbacks: [
33+
'second' => fn ($value) => assertType('int', $value),
34+
'first' => function ($value) {
35+
assertType('string', $value);
36+
$unrelated = [function ($other) {
37+
assertType('mixed', $other);
38+
}];
39+
},
40+
]);
41+
42+
/** @param array{callable(string): mixed, callable(int): mixed} $callbacks */
43+
function tuple(array $callbacks): void {}
44+
45+
tuple([
46+
fn ($value) => assertType('string', $value),
47+
fn ($value) => assertType('int', $value),
48+
]);
49+
50+
/** @param array{5: string, 6: callable(int): mixed} $callbacks */
51+
function numericShape(array $callbacks): void {}
52+
53+
numericShape([5 => 'value', fn ($value) => assertType('int', $value)]);
54+
55+
/** @param array<string, list<callable(string): mixed>> $callbacks */
56+
function nested(array $callbacks): void {}
57+
58+
nested(['first' => [function ($value) {
59+
assertType('string', $value);
60+
}]]);
61+
62+
/** @param list<callable(string): mixed>|null $callbacks */
63+
function nullable(?array $callbacks): void {}
64+
65+
nullable([fn ($value) => assertType('string', $value)]);
66+
67+
/** @param iterable<callable(string): mixed> $callbacks */
68+
function iterableCallbacks(iterable $callbacks): void {}
69+
70+
iterableCallbacks([fn ($value) => assertType('string', $value)]);
71+
72+
/**
73+
* @template T
74+
* @param T $value
75+
* @param list<callable(T): mixed> $callbacks
76+
*/
77+
function generic($value, array $callbacks): void {}
78+
79+
generic(new \stdClass(), [fn ($value) => assertType('stdClass', $value)]);
80+
81+
class Receiver
82+
{
83+
/** @param list<callable(string): mixed> $callbacks */
84+
public function __construct(array $callbacks) {}
85+
86+
/** @param list<callable(int): mixed> $callbacks */
87+
public static function run(array $callbacks): void {}
88+
89+
/** @param list<callable(string): mixed> ...$callbacks */
90+
public function variadic(array ...$callbacks): void {}
91+
}
92+
93+
$receiver = new Receiver([fn ($value) => assertType('string', $value)]);
94+
Receiver::run([fn ($value) => assertType('int', $value)]);
95+
$receiver->variadic([fn ($value) => assertType('string', $value)], [fn ($value) => assertType('string', $value)]);
96+
97+
$unrelated = [fn ($value) => assertType('mixed', $value)];
98+
callbacks($unrelated);
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug11215;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
class User {}
8+
9+
/** @template TModel */
10+
class Builder
11+
{
12+
}
13+
14+
/** @template TModel */
15+
class Collection
16+
{
17+
18+
/** @param callable(Builder<TModel>): mixed $relation */
19+
public function load($relation): void
20+
{
21+
//
22+
}
23+
24+
/** @param array<string, (callable(Builder<TModel>): mixed)|string> $relations */
25+
public function loadMany($relations): void
26+
{
27+
//
28+
}
29+
30+
}
31+
32+
/** @var Collection<User> $users */
33+
$users->load(function ($query) {
34+
assertType('Bug11215\Builder<Bug11215\User>', $query);
35+
});
36+
37+
$users->loadMany(['foo' => function ($query) {
38+
assertType('Bug11215\Builder<Bug11215\User>', $query);
39+
}]);

0 commit comments

Comments
 (0)