Skip to content

Commit

Permalink
Improve dead code detection after nested function calls with conditio…
Browse files Browse the repository at this point in the history
…nal never return type
  • Loading branch information
rvanvelzen authored and ondrejmirtes committed Sep 2, 2022
1 parent c057aa9 commit d37f51d
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 5 deletions.
8 changes: 3 additions & 5 deletions src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -1661,11 +1661,9 @@ private function findEarlyTerminatingExpr(Expr $expr, Scope $scope): ?Expr
return $expr;
}

if ($expr instanceof Expr\CallLike || $expr instanceof Expr\Match_) {
$exprType = $scope->getType($expr);
if ($exprType instanceof NeverType && $exprType->isExplicit()) {
return $expr;
}
$exprType = $scope->getType($expr);
if ($exprType instanceof NeverType && $exprType->isExplicit()) {
return $expr;
}

return null;
Expand Down
11 changes: 11 additions & 0 deletions tests/PHPStan/Rules/DeadCode/UnreachableStatementRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,4 +120,15 @@ public function testBug4370(): void
$this->analyse([__DIR__ . '/data/bug-4370.php'], []);
}

public function testBug7188(): void
{
$this->treatPhpDocTypesAsCertain = true;
$this->analyse([__DIR__ . '/data/bug-7188.php'], [
[
'Unreachable statement - code above always terminates.',
22,
],
]);
}

}
23 changes: 23 additions & 0 deletions tests/PHPStan/Rules/DeadCode/data/bug-7188.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php declare(strict_types = 1);

namespace Bug7188;

use Exception;

/**
* @param int $x
* @return ($x is 0 ? never : float)
*/
function inverse($x): float
{
if ($x===0) {
throw new Exception('Division durch Null.');
}

return 1/$x;
}

function () {
$result = inverse(0);
echo "expect to unreachable\n";
};

0 comments on commit d37f51d

Please sign in to comment.