phpstan icon indicating copy to clipboard operation
phpstan copied to clipboard

Closure return type lost during analysis?

Open devnix opened this issue 1 year ago • 1 comments

Bug report

In the given example, there's this piece of code

$value1 = $value->map(function ($value) {
	PHPStan\dumpType($value[0]);
	PHPStan\dumpType($value[1]);
	return $value[0] + $value[1];
});

PHPStan\dumpType($value1);

that is said to return a sum of two integers, but in the generic the type is inferred as a union:

Option<(array|float|int)>

Code snippet that reproduces the problem

https://phpstan.org/r/e53857ea-5194-433e-ade5-725a7126864b

Expected output

If we manually type the return of the closure

$value2 = $value->map(function ($value): int {
	PHPStan\dumpType($value[0]);
	PHPStan\dumpType($value[1]);
	return $value[0] + $value[1];
});

PHPStan\dumpType($value2);

then the correct generic is inferred:

Option<int>

While this is manageable by typing the return type of the closure, maybe having this bug fixed would help to infer more precise types to a whole codebase

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

I absolutely love PHPStan!

devnix avatar Dec 06 '23 09:12 devnix

@devnix After the latest push in 1.11.x, PHPStan now reports different result with your code snippet:

@@ @@
 66: Dumped type: Option<array{int, int}>
 69: Dumped type: int
 70: Dumped type: int
-74: Dumped type: Option<(array|float|int)>
+74: Dumped type: Option<int>
 77: Dumped type: int
 78: Dumped type: int
 82: Dumped type: Option<int>
@@ @@
 66: Dumped type: Option<array{int, int}>
 69: Dumped type: int
 70: Dumped type: int
-74: Dumped type: Option<(array|float|int)>
+74: Dumped type: Option<int>
 77: Dumped type: int
 78: Dumped type: int
 82: Dumped type: Option<int>
Full report

PHP 8.0 – 8.3 (7 errors)

Line Error
66 Dumped type: Option<array{int, int}>
69 Dumped type: int
70 Dumped type: int
74 Dumped type: Option<int>
77 Dumped type: int
78 Dumped type: int
82 Dumped type: Option<int>

PHP 7.2 – 7.4 (8 errors)

Line Error
10 Promoted properties are supported only on PHP 8.0 and later.
66 Dumped type: Option<array{int, int}>
69 Dumped type: int
70 Dumped type: int
74 Dumped type: Option<int>
77 Dumped type: int
78 Dumped type: int
82 Dumped type: Option<int>

phpstan-bot avatar May 17 '24 11:05 phpstan-bot

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

github-actions[bot] avatar Jun 19 '24 01:06 github-actions[bot]