Am I expecting too much from the analyser here? #4694
-
... or am I having another senior moment? Consider (https://phpstan.org/r/3d974ed6-7d4b-4f91-8dcf-7187222d3004): <?php declare(strict_types = 1);
/**
* @return no-return
*/
function no_return(){
echo "Dying\n";
die(1);
}
/**
* @param int|null $u
* @param int|null $a
* @return array<int, int>
*/
function foo($u=null, $a=null){
if (is_null($u) && is_null($a)){
no_return();
return [0,0]; // line 18
}
if ($u){
$a = $u;
}else if ($a){
$u = $a;
}
return [$u, $a]; // line 25
}
print_r(foo(1)); // first only
print_r(foo(null,2)); // second only
print_r(foo(1,2)); // both
print_r(foo()); // none - will die() and not return Output from execution: Array
(
[0] => 1
[1] => 1
)
Array
(
[0] => 2
[1] => 2
)
Array
(
[0] => 1
[1] => 1
)
Dying All as I expect. From the playground: 18 | Unreachable statement - code above always terminates.
-- | --
25 | Function foo() should return array<int, int> but returns array<int, int|null>. Line 18, I expect - I put it in there to make sure the But line 25? Am I expecting too much of the parser here, or is there something here that I'm missing and should be wary of in my own code that's doing this? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Yes, the code is very complicated. Feel free to open an issue, I'll file it under dependent types: https://github.com/phpstan/phpstan/milestone/12 |
Beta Was this translation helpful? Give feedback.
-
ISTR the playground doesn't give the same messages as I get on the command line, but does |
Beta Was this translation helpful? Give feedback.
-
@pauljherring this is a nontrivial problem – I recently wrote an article about how Psalm solves it here: https://psalm.dev/articles/the-truth-matters |
Beta Was this translation helpful? Give feedback.
Yes, the code is very complicated. Feel free to open an issue, I'll file it under dependent types: https://github.com/phpstan/phpstan/milestone/12