Skip to content

Closure passed to a callable parameter is typed from a previous call of a captured closure (bleedingEdge, 2.3.6) #15757

Open
phpstan/phpstan-src
#7093

Description

@gnutix

Bug report

With bleedingEdge enabled, an arrow function that calls a captured closure is reported as not matching the callable parameter it is passed to, when an earlier arrow function in the same scope called that closure with a different argument.

The template type U is inferred from the call $doubleFn(1) (-2..7), but the closure that is checked against it is typed as if $doubleFn(1) returned what the previous $doubleFn($index) call returned (0..18), so it ends up as Closure(int): (-18..9). Both sides describe the same arrow function, so they should agree.

  • Only with bleedingEdge: the same code analyses without errors when bleedingEdge is off.
  • Removing the first mapx() call, or calling the closure with the same argument in both, makes the error go away.
  • New in 2.3.6 for us (2.3.5 did not report it); it still reproduces on the playground.

Code snippet that reproduces the problem

https://phpstan.org/r/fb39bcee-1e96-4b0c-8a42-369b4a9468b2

<?php declare(strict_types = 1);

/**
 * @template K of array-key
 * @template T
 * @template U
 * @param array<K, T> $array
 * @param callable(T, K): U $fn
 * @return array<K, U>
 */
function mapx(array $array, callable $fn): array
{
	$result = [];
	foreach ($array as $key => $value) {
		$result[$key] = $fn($value, $key);
	}
	return $result;
}

function probe(): void
{
	$indexes = range(0, 9);
	$doubleFn = static fn (int $value): int => $value * 2;
	mapx($indexes, static fn (int $index): int => $doubleFn($index));
	mapx($indexes, static fn (int $index): int => $index - $doubleFn(1));
}

Expected output

No error. Currently:

Parameter #2 $fn of function mapx expects callable(0|1|2|3|4|5|6|7|8|9, 0|1|2|3|4|5|6|7|8|9): (-2|-1|0|1|2|3|4|5|6|7), Closure(int): (-18|-17|…|8|9) given.

Did PHPStan help you today? Did it make you happy in any way?

Yes: 2.3.6 found two redundant assertions and a stale ignore in our code base, and its float ranges sharpened several types.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions