Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 55 additions & 4 deletions src/Analyser/Fiber/FiberScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use PHPStan\Reflection\MethodReflection;
use PHPStan\Reflection\ParameterReflection;
use PHPStan\Type\Type;
use function array_pop;

final class FiberScope extends MutatingScope
{
Expand Down Expand Up @@ -140,14 +141,64 @@ private function preprocessScope(MutatingScope $scope): Scope
*/
public function pushInFunctionCall($reflection, ?ParameterReflection $parameter, bool $rememberTypes): self
{
// no need to track this in rules, the type will be correct anyway
return $this;
// Track the function call stack so closure types can be properly inferred
// when the closure is passed as a callable argument
$stack = $this->inFunctionCallsStack;
$stack[] = [$reflection, $parameter];

/** @var self $scope */
$scope = $this->scopeFactory->create(
$this->context,
$this->isDeclareStrictTypes(),
$this->getFunction(),
$this->getNamespace(),
$this->expressionTypes,
$this->nativeExpressionTypes,
$this->conditionalExpressions,
$this->inClosureBindScopeClasses,
$this->getAnonymousFunctionReflection(),
$this->isInFirstLevelStatement(),
$this->currentlyAssignedExpressions,
$this->currentlyAllowedUndefinedExpressions,
$stack,
$this->afterExtractCall,
parent::getParentScope(),
$this->nativeTypesPromoted,
);
$scope->truthyValueExprs = $this->truthyValueExprs;
$scope->falseyValueExprs = $this->falseyValueExprs;

return $scope;
}

public function popInFunctionCall(): self
{
// no need to track this in rules, the type will be correct anyway
return $this;
$stack = $this->inFunctionCallsStack;
array_pop($stack);

/** @var self $scope */
$scope = $this->scopeFactory->create(
$this->context,
$this->isDeclareStrictTypes(),
$this->getFunction(),
$this->getNamespace(),
$this->expressionTypes,
$this->nativeExpressionTypes,
$this->conditionalExpressions,
$this->inClosureBindScopeClasses,
$this->getAnonymousFunctionReflection(),
$this->isInFirstLevelStatement(),
$this->currentlyAssignedExpressions,
$this->currentlyAllowedUndefinedExpressions,
$stack,
$this->afterExtractCall,
parent::getParentScope(),
$this->nativeTypesPromoted,
);
$scope->truthyValueExprs = $this->truthyValueExprs;
$scope->falseyValueExprs = $this->falseyValueExprs;

return $scope;
}

public function getParentScope(): ?MutatingScope
Expand Down
5 changes: 2 additions & 3 deletions src/Reflection/ParametersAcceptorSelector.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
use Closure;
use PhpParser\Node;
use PHPStan\Analyser\ArgumentsNormalizer;
use PHPStan\Analyser\Fiber\FiberScope;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\Scope;
use PHPStan\Node\Expr\ParameterVariableOriginalValueExpr;
Expand Down Expand Up @@ -498,14 +497,14 @@ public static function selectFromArgs(
}
}

if ($parameter !== null && $scope instanceof MutatingScope && !$scope instanceof FiberScope) {
if ($parameter !== null && $scope instanceof MutatingScope) {
$rememberTypes = !$originalArg->value instanceof Node\Expr\Closure && !$originalArg->value instanceof Node\Expr\ArrowFunction;
$scope = $scope->pushInFunctionCall(null, $parameter, $rememberTypes);
}

$type = $scope->getType($originalArg->value);

if ($parameter !== null && $scope instanceof MutatingScope && !$scope instanceof FiberScope) {
if ($parameter !== null && $scope instanceof MutatingScope) {
$scope = $scope->popInFunctionCall();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
<?php // lint >= 8.1

namespace ClosurePassedToTypeFiberScope;

use Closure;
use function PHPStan\Testing\assertType;

/**
* Regression tests for closure parameter type inference in FiberScope.
* @see https://github.com/phpstan/phpstan/issues/13993
*
* These tests verify that closure parameter types are properly inferred from
* expected callable types when using FiberScope. Since FiberScope requires
* PHP 8.1+ (Fibers), this file requires PHP 8.1+.
*/

// ============================================================================
// Example 1: Closure parameter inference with array destructuring
// ============================================================================

class DateRange
{
public function format(): string
{
return '2024-01-01';
}
}

class Context {}

class Loader
{
/**
* @param Closure(Context, non-empty-array<array{DateRange, list<int>}>): iterable<array{int, string}, string> $loader
*/
public function __construct(
private Closure $loader,
) {}
}

/**
* Test: Closure parameter inference with array destructuring in constructor
* When a closure is passed to a constructor, the parameter types should be
* inferred from the expected Closure type, including array destructuring.
*/
$loader = new Loader(
loader: function (Context $context, array $items): iterable {
assertType('non-empty-array<array{ClosurePassedToTypeFiberScope\DateRange, list<int>}>', $items);
foreach ($items as [$dateRange, $ids]) {
assertType('ClosurePassedToTypeFiberScope\DateRange', $dateRange);
assertType('list<int>', $ids);
foreach ($ids as $id) {
assertType('int', $id);
yield [$id, $dateRange->format()] => 'value';
}
}
},
);

// ============================================================================
// Example 2: Generic callable parameter resolution
// ============================================================================

/**
* @template T
*/
class Vote
{
/**
* @param T $subject
*/
public function __construct(
public bool $granted,
public mixed $subject,
) {}
}

/**
* @template TSubject
*/
class Decision
{
/**
* @param list<Vote<TSubject>> $votes
*/
public function __construct(
private array $votes,
) {}

/**
* @template U
* @template K of array-key
*
* @param callable(Vote<TSubject> $vote): iterable<K, U> $fn
*
* @return array<K, U>
*/
public function collect(callable $fn): array
{
$result = [];
foreach ($this->votes as $vote) {
foreach ($fn($vote) as $key => $value) {
$result[$key] = $value;
}
}
return $result;
}
}

class Subject
{
public function id(): int
{
return 42;
}
}

/**
* Test: Generic callable parameter resolution
* When passing a closure to Decision<Subject>::collect(),
* the Vote parameter should be inferred as Vote<Subject>.
*/
$decision = new Decision([new Vote(granted: true, subject: new Subject())]);
$result = $decision->collect(static function (Vote $vote): iterable {
assertType('ClosurePassedToTypeFiberScope\Vote<ClosurePassedToTypeFiberScope\Subject>', $vote);
assertType('ClosurePassedToTypeFiberScope\Subject', $vote->subject);
if ($vote->granted) {
yield $vote->subject->id() => $vote->subject;
}
});
assertType('array<int, ClosurePassedToTypeFiberScope\Subject>', $result);
Loading