Skip to content

Commit 2aa8657

Browse files
committed
Re-price a stored closure result when it is asked about under a different pushInFunctionCall() callable parameter
- ExpressionResult::askScopeVariableStateMatches() used to treat a stored closure/arrow function result as matching any asking scope, so Scope::getType() returned the walk-time closure type even when an extension had pushed its own callable parameter with pushInFunctionCall(). Untyped closure parameters then stayed `mixed` (phpstan-laravel's keyBy/groupBy typing, a regression from 2.2.x). - New ClosureCallContextMatcher::matches() decides whether the call context of the ask differs. The walk result is kept for identical stacks, for a shallower stack (the call site), for a parameter of equal type, and for the callee's own parameter that still references the callee's templates (the acceptor-selection and argument-check asks in ParametersAcceptorSelector and FunctionCallParametersCheck). Any other parameter at the same depth sends the ask on to ClosureTypeResolver::getClosureType(). Comparing the stacks alone, as the issue suggested, also re-priced PHPStan's own asks and changed generic inference (array_reduce, Ds\Pair mappers, ...). - turbo-ext: the ExpressionResult mirror answers identical stacks natively and calls the PHP helper otherwise (new class ref `closureCallContextMatcher`). - Tests cover functions, instance methods, closures and arrow functions, closures nested in an array argument, and a callable parameter typed with a class template.
1 parent 0b5b190 commit 2aa8657

9 files changed

Lines changed: 244 additions & 2 deletions
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Analyser;
4+
5+
use PHPStan\Reflection\FunctionReflection;
6+
use PHPStan\Reflection\MethodReflection;
7+
use PHPStan\Reflection\ParameterReflection;
8+
use PHPStan\Turbo\ReferencedByTurboExtension;
9+
use PHPStan\Type\Generic\TemplateType;
10+
use PHPStan\Type\Type;
11+
use PHPStan\Type\TypeTraverser;
12+
use function count;
13+
use function strtolower;
14+
15+
/**
16+
* Whether a closure's stored walk answers an ask made in another call context
17+
* (MutatingScope::$inFunctionCallsStack). An extension pushing its own callable
18+
* parameter with pushInFunctionCall() changes the contextual parameter types
19+
* of the closure, so it must be re-priced. The call site itself (a shallower
20+
* stack), the same parameter type, and a parameter referencing the callee's
21+
* own templates (acceptor selection before template resolution) keep the walk
22+
* answer - the walk already priced the closure in the resolved context.
23+
*
24+
* @internal
25+
*/
26+
#[ReferencedByTurboExtension(key: 'closureCallContextMatcher')]
27+
final class ClosureCallContextMatcher
28+
{
29+
30+
/**
31+
* @param list<array{FunctionReflection|MethodReflection|null, ParameterReflection|null}> $askStack
32+
* @param list<array{FunctionReflection|MethodReflection|null, ParameterReflection|null}> $positionStack
33+
*/
34+
public static function matches(array $askStack, array $positionStack): bool
35+
{
36+
if ($askStack === $positionStack) {
37+
return true;
38+
}
39+
$depth = count($askStack);
40+
if ($depth === 0 || $depth !== count($positionStack)) {
41+
return true;
42+
}
43+
44+
[, $askParameter] = $askStack[$depth - 1];
45+
[$callee, $positionParameter] = $positionStack[$depth - 1];
46+
if ($askParameter === null || $askParameter === $positionParameter) {
47+
return true;
48+
}
49+
$askType = $askParameter->getType();
50+
if ($positionParameter !== null && $askType->equals($positionParameter->getType())) {
51+
return true;
52+
}
53+
if ($callee === null) {
54+
return false;
55+
}
56+
57+
$calleeName = strtolower($callee->getName());
58+
$calleeIsMethod = $callee instanceof MethodReflection;
59+
$referencesCalleeTemplate = false;
60+
TypeTraverser::map($askType, static function (Type $type, callable $traverse) use ($calleeName, $calleeIsMethod, &$referencesCalleeTemplate): Type {
61+
if ($type instanceof TemplateType) {
62+
$templateScope = $type->getScope();
63+
$templateFunctionName = $templateScope->getFunctionName();
64+
if (
65+
$templateFunctionName !== null
66+
&& strtolower($templateFunctionName) === $calleeName
67+
&& ($templateScope->getClassName() !== null) === $calleeIsMethod
68+
) {
69+
$referencesCalleeTemplate = true;
70+
return $type;
71+
}
72+
}
73+
74+
return $traverse($type);
75+
});
76+
77+
return $referencesCalleeTemplate;
78+
}
79+
80+
}

‎src/Analyser/ExpressionResult.php‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -716,8 +716,9 @@ public function askScopeVariableStateMatches(MutatingScope $scope, bool $useNati
716716
// it at a foreign position would re-run the whole convergence loop. Its
717717
// body variables are not reads of the asking position, and the
718718
// position-sensitive TYPE is computed by getClosureType at ask sites.
719+
// An ask in a different callable-parameter context re-prices it.
719720
if ($this->expr instanceof Expr\Closure || $this->expr instanceof Expr\ArrowFunction) {
720-
return true;
721+
return ClosureCallContextMatcher::matches($scope->inFunctionCallsStack, $this->beforeScope->inFunctionCallsStack);
721722
}
722723
$names = $this->getReadVariableNames();
723724
if ($names === []) {

‎tests/PHPStan/Analyser/DynamicReturnTypeExtensionTypeInferenceTest.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ public static function dataAsserts(): iterable
2424
yield from self::gatherAssertTypes(__DIR__ . '/data/dynamic-return-enum-closure.php');
2525
}
2626
yield from self::gatherAssertTypes(__DIR__ . '/data/bug-7391b.php');
27+
yield from self::gatherAssertTypes(__DIR__ . '/data/bug-15303.php');
2728
}
2829

2930
/**

‎tests/PHPStan/Analyser/data/TestDynamicReturnTypeExtensions.php‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,3 +320,70 @@ public function getTypeFromMethodCall(
320320
return $methodReflection->getDeclaringClass()->getBackedEnumType();
321321
}
322322
}
323+
324+
class Bug15303DynamicFunctionReturnTypeExtension implements \PHPStan\Type\DynamicFunctionReturnTypeExtension
325+
{
326+
327+
public function isFunctionSupported(\PHPStan\Reflection\FunctionReflection $functionReflection): bool
328+
{
329+
return in_array($functionReflection->getName(), ['Bug15303\keyBy', 'Bug15303\groupBy'], true);
330+
}
331+
332+
public function getTypeFromFunctionCall(\PHPStan\Reflection\FunctionReflection $functionReflection, \PhpParser\Node\Expr\FuncCall $functionCall, Scope $scope): ?Type
333+
{
334+
$args = $functionCall->getArgs();
335+
$valueType = $scope->getType($args[0]->value)->getIterableValueType();
336+
$callback = $args[1]->value;
337+
if ($callback instanceof \PhpParser\Node\Expr\Array_) {
338+
$lastItem = $callback->items[count($callback->items) - 1];
339+
$callback = $lastItem->value;
340+
}
341+
342+
return Bug15303Helper::getKeyedArrayType($scope, $callback, $valueType);
343+
}
344+
345+
}
346+
347+
class Bug15303DynamicMethodReturnTypeExtension implements DynamicMethodReturnTypeExtension
348+
{
349+
350+
public function getClass(): string
351+
{
352+
return \Bug15303\Collection::class;
353+
}
354+
355+
public function isMethodSupported(MethodReflection $methodReflection): bool
356+
{
357+
return $methodReflection->getName() === 'keyBy';
358+
}
359+
360+
public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): ?Type
361+
{
362+
$args = $methodCall->getArgs();
363+
364+
return Bug15303Helper::getKeyedArrayType($scope, $args[0]->value, new ObjectType(\Bug15303\User::class));
365+
}
366+
367+
}
368+
369+
class Bug15303Helper
370+
{
371+
372+
public static function getKeyedArrayType(Scope $scope, \PhpParser\Node\Expr $callback, Type $valueType): ?Type
373+
{
374+
if (!$scope instanceof \PHPStan\Analyser\MutatingScope) {
375+
return null;
376+
}
377+
378+
$pushed = $scope->pushInFunctionCall(null, new \PHPStan\Reflection\Php\DummyParameter('callback', new \PHPStan\Type\CallableType([
379+
new \PHPStan\Reflection\Native\NativeParameterReflection('param', false, $valueType, \PHPStan\Reflection\PassedByReference::createNo(), false, null),
380+
], new \PHPStan\Type\MixedType()), false, \PHPStan\Reflection\PassedByReference::createNo(), false, null), false);
381+
$closure = $pushed->getType($callback);
382+
if (!$closure instanceof \PHPStan\Type\ClosureType) {
383+
return null;
384+
}
385+
386+
return new \PHPStan\Type\ArrayType($closure->getReturnType(), $valueType);
387+
}
388+
389+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug15303;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
class User { public int $id = 1; }
8+
9+
/**
10+
* @param array<mixed> $a
11+
* @param mixed $cb
12+
* @return array<mixed>
13+
*/
14+
function keyBy(array $a, $cb): array { return $a; }
15+
16+
/**
17+
* @param array<mixed> $a
18+
* @param mixed $cb
19+
* @return array<mixed>
20+
*/
21+
function groupBy(array $a, $cb): array { return $a; }
22+
23+
class Collection
24+
{
25+
26+
/**
27+
* @param mixed $cb
28+
* @return array<mixed>
29+
*/
30+
public function keyBy($cb): array { return []; }
31+
32+
}
33+
34+
/** @param array<int, User> $users */
35+
function test(array $users, Collection $collection): void {
36+
assertType('array<int, Bug15303\User>', keyBy($users, fn ($u) => $u->id));
37+
assertType('array<int, Bug15303\User>', keyBy($users, function ($u) { return $u->id; }));
38+
assertType('array<int, Bug15303\User>', groupBy($users, ['name', fn ($u) => $u->id]));
39+
assertType('array<int, Bug15303\User>', groupBy($users, ['name', function ($u) { return $u->id; }]));
40+
assertType('array<int, Bug15303\User>', $collection->keyBy(fn ($u) => $u->id));
41+
assertType('array<int, Bug15303\User>', $collection->keyBy(function ($u) { return $u->id; }));
42+
}
43+
44+
/** @template T of User */
45+
class Box
46+
{
47+
48+
/** @param array<int, T> $items */
49+
public function test(array $items): void
50+
{
51+
assertType('array<int, T of Bug15303\User (class Bug15303\Box, argument)>', keyBy($items, fn ($u) => $u->id));
52+
assertType('array<int, T of Bug15303\User (class Bug15303\Box, argument)>', keyBy($items, function ($u) { return $u->id; }));
53+
}
54+
55+
}

‎tests/PHPStan/Analyser/dynamic-return-type.neon‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,11 @@ services:
4343
class: PHPStan\Tests\BackedEnumGetValueDynamicReturnTypeExtension
4444
tags:
4545
- phpstan.broker.dynamicMethodReturnTypeExtension
46+
-
47+
class: PHPStan\Tests\Bug15303DynamicFunctionReturnTypeExtension
48+
tags:
49+
- phpstan.broker.dynamicFunctionReturnTypeExtension
50+
-
51+
class: PHPStan\Tests\Bug15303DynamicMethodReturnTypeExtension
52+
tags:
53+
- phpstan.broker.dynamicMethodReturnTypeExtension

‎turbo-ext/src/ExpressionResult.cpp‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,11 @@
1919

2020
#include "support.h"
2121
#include "generated/ExpressionResult.h"
22+
#include "generated/MutatingScope.h"
2223

2324
namespace slots = ptdecl::ExpressionResult::slot;
2425
namespace sigs = ptdecl::ExpressionResult::sig;
26+
namespace msSlots = ptdecl::MutatingScope::slot;
2527
#include "zv.h"
2628
#include "TypeTraits.h"
2729
#include "TypeOps.h"
@@ -41,6 +43,8 @@ namespace {
4143
/* the twin's READ_VARIABLE_NAMES_ATTRIBUTE, a permanent interned string */
4244
zend_string *pt_er_read_variable_names_attribute = nullptr;
4345

46+
pt_method_site pt_er_closure_call_context_matches_site;
47+
4448
/* the constructor's values: NULL stands for a null argument, the bools are
4549
* plain, the arrays and objects borrowed */
4650
struct ConstructorArgs
@@ -551,6 +555,27 @@ class ExpressionResult
551555
return askScopeVariableStateMatches(scope, useNativeTypes, false);
552556
}
553557

558+
/* ClosureCallContextMatcher::matches($scope->inFunctionCallsStack,
559+
* $this->beforeScope->inFunctionCallsStack) — the identical stacks of the
560+
* common ask answered here, the rest in the PHP helper; -1 = pending
561+
* exception, else 0/1 */
562+
[[nodiscard]] static zend_long closureCallContextMatches(zval *scope, zval *beforeScope)
563+
{
564+
zval *askStack = OBJ_PROP_NUM(Z_OBJ_P(scope), msSlots::inFunctionCallsStack);
565+
zval *positionStack = OBJ_PROP_NUM(Z_OBJ_P(beforeScope), msSlots::inFunctionCallsStack);
566+
if (UNEXPECTED(Z_TYPE_P(askStack) == IS_UNDEF || Z_TYPE_P(positionStack) == IS_UNDEF)) {
567+
zend_throw_error(NULL, "Typed property PHPStan\\Analyser\\MutatingScope::$inFunctionCallsStack must not be accessed before initialization");
568+
return -1;
569+
}
570+
if (zend_is_identical(askStack, positionStack)) return 1;
571+
zval argv[2];
572+
ZVAL_COPY_VALUE(&argv[0], askStack);
573+
ZVAL_COPY_VALUE(&argv[1], positionStack);
574+
zv::Val matches = pt_call_static_cached(pt_er_closure_call_context_matches_site, PT_CLASS_CLOSURE_CALL_CONTEXT_MATCHER, PT_LC("matches"), 2, argv);
575+
if (UNEXPECTED(matches.isUndef())) return -1;
576+
return matches.ref().isTrue() ? 1 : 0;
577+
}
578+
554579
/* Mirrors askScopeVariableStateMatches(); -1 = pending exception, else 0/1. */
555580
[[nodiscard]] zend_long askScopeVariableStateMatches(zval *scope, bool useNativeTypes, bool ruleFacingAsk)
556581
{
@@ -562,11 +587,14 @@ class ExpressionResult
562587
// it at a foreign position would re-run the whole convergence loop. Its
563588
// body variables are not reads of the asking position, and the
564589
// position-sensitive TYPE is computed by getClosureType at ask sites.
590+
// An ask in a different callable-parameter context re-prices it.
565591
zend_class_entry *closureCe = pt_class(PT_CLASS_CLOSURE_EXPR);
566592
zend_class_entry *arrowFunctionCe = pt_class(PT_CLASS_ARROW_FUNCTION);
567593
if (UNEXPECTED(closureCe == NULL || arrowFunctionCe == NULL)) return -1;
568594
zend_object *expr = Z_OBJ_P(slot(slots::expr));
569-
if (instanceof_function(expr->ce, closureCe) || instanceof_function(expr->ce, arrowFunctionCe)) return 1;
595+
if (instanceof_function(expr->ce, closureCe) || instanceof_function(expr->ce, arrowFunctionCe)) {
596+
return closureCallContextMatches(scope, beforeScope);
597+
}
570598
zv::Val names = getReadVariableNames();
571599
if (UNEXPECTED(names.isUndef())) return -1;
572600
if (zend_hash_num_elements(Z_ARRVAL_P(names.raw())) == 0) return 1;

‎turbo-ext/src/support.cpp‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,7 @@ static const pt_class_template pt_class_templates[PT_CLASS_COUNT] = {
410410
/* PT_CLASS_BETTER_REFLECTION_CLASS_CONSTANT */ {"betterReflectionClassConstant", "PHPStan\\BetterReflection\\Reflection\\ReflectionClassConstant"},
411411
/* PT_CLASS_RELATIVE_NAME */ {"relativeName", "PhpParser\\Node\\Name\\Relative"},
412412
/* PT_CLASS_ITERABLE_HELPER */ {"iterableHelper", "PHPStan\\Internal\\IterableHelper"},
413+
/* PT_CLASS_CLOSURE_CALL_CONTEXT_MATCHER */ {"closureCallContextMatcher", "PHPStan\\Analyser\\ClosureCallContextMatcher"},
413414
};
414415

415416
zend_class_entry *pt_class(int idx)

‎turbo-ext/src/support.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,7 @@ enum {
468468
/* the Name readers (NameNodeAccess.cpp) */
469469
PT_CLASS_RELATIVE_NAME,
470470
PT_CLASS_ITERABLE_HELPER,
471+
PT_CLASS_CLOSURE_CALL_CONTEXT_MATCHER,
471472
PT_CLASS_COUNT
472473
};
473474

0 commit comments

Comments
 (0)