diff --git a/build/baseline-pre-8.0.neon b/build/baseline-pre-8.0.neon index 0e94aa40013..a59e5c583a4 100644 --- a/build/baseline-pre-8.0.neon +++ b/build/baseline-pre-8.0.neon @@ -265,3 +265,9 @@ parameters: identifier: property.internalClass count: 3 path: ../src/Analyser/Ignore/LineIgnoreFixer.php + + - + rawMessage: 'Dead catch - ValueError is never thrown in the try block.' + identifier: catch.neverThrown + count: 1 + path: ../src/Type/Php/RangeFunctionArgumentsHelper.php diff --git a/src/Type/Php/RangeFunctionReturnTypeExtension.php b/src/Type/Php/RangeFunctionReturnTypeExtension.php index 2c78439d7c2..64ea02da531 100644 --- a/src/Type/Php/RangeFunctionReturnTypeExtension.php +++ b/src/Type/Php/RangeFunctionReturnTypeExtension.php @@ -212,7 +212,7 @@ private static function getGeneralType(Type $startType, Type $endType, Type $ste * only calling it tells - for a character range, which has at most 256 * items, and for a zero, infinite or NAN argument, for which it throws. */ - private static function getRangeLength(int|float|string $start, int|float|string $end, int|float $step): ?float + public static function getRangeLength(int|float|string $start, int|float|string $end, int|float $step): ?float { if (is_string($start) && is_string($end) && !is_numeric($start) && !is_numeric($end)) { return null; diff --git a/src/Type/Php/RangeFunctionThrowTypeExtension.php b/src/Type/Php/RangeFunctionThrowTypeExtension.php new file mode 100644 index 00000000000..67ba0462cb5 --- /dev/null +++ b/src/Type/Php/RangeFunctionThrowTypeExtension.php @@ -0,0 +1,129 @@ +getName() === 'range'; + } + + public function getThrowTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $funcCall, Scope $scope): Type + { + // PHP 7 reported these with a warning and a false return value + $phpVersions = $scope->getPhpVersion(); + if ($phpVersions->throwsValueErrorForInternalFunctions()->no()) { + return new VoidType(); + } + + $args = $funcCall->getArgs(); + foreach ($args as $arg) { + if ($arg->unpack || $arg->name !== null) { + return self::getDeclaredThrowType($functionReflection); + } + } + + if (count($args) < 2) { + return self::getDeclaredThrowType($functionReflection); + } + + $starts = self::getConstantValues($scope->getNativeType($args[0]->value), true); + $ends = self::getConstantValues($scope->getNativeType($args[1]->value), true); + $steps = count($args) >= 3 ? self::getConstantValues($scope->getNativeType($args[2]->value), false) : [1]; + if ($starts === null || $ends === null || $steps === null) { + return self::getDeclaredThrowType($functionReflection); + } + + $hasStricterRange = $phpVersions->hasStricterRangeFunction(); + foreach ($starts as $start) { + foreach ($ends as $end) { + foreach ($steps as $step) { + if (self::mightThrow($hasStricterRange, $start, $end, $step)) { + return self::getDeclaredThrowType($functionReflection); + } + } + } + } + + return new VoidType(); + } + + /** + * The reflection of a PHP version range that starts before PHP 8 has no @throws, + * but range() throws on the PHP 8 versions in it. + */ + private static function getDeclaredThrowType(FunctionReflection $functionReflection): Type + { + return $functionReflection->getThrowType() ?? new ObjectType(ValueError::class); + } + + /** + * @return ($allowString is true ? list : list)|null + */ + private static function getConstantValues(Type $type, bool $allowString): ?array + { + if (!$type->isConstantScalarValue()->yes()) { + return null; + } + + $values = []; + foreach ($type->getConstantScalarValues() as $value) { + if (!is_int($value) && !is_float($value) && (!$allowString || !is_string($value))) { + return null; + } + + $values[] = $value; + } + + return $values; + } + + private static function mightThrow(TrinaryLogic $hasStricterRange, int|float|string $start, int|float|string $end, int|float $step): bool + { + $length = RangeFunctionReturnTypeExtension::getRangeLength($start, $end, $step); + if ($length === null) { + // only a character range has no number of items, any other one did not fit into a float + if (!is_string($start) || !is_string($end) || is_numeric($start) || is_numeric($end)) { + return true; + } + } elseif ($length >= self::RANGE_SIZE_LIMIT) { + return true; + } + + // calling range() tells about the step and the boundaries of a short range + $runtimeRejects = null; + if ($length === null || $length <= ConstantArrayTypeBuilder::ARRAY_COUNT_LIMIT) { + $runtimeRejects = RangeFunctionArgumentsHelper::callRange($start, $end, $step) === false; + } + + return !RangeFunctionArgumentsHelper::rejects($hasStricterRange, $start, $end, $step, $runtimeRejects)->no(); + } + +} diff --git a/tests/PHPStan/Rules/Exceptions/CatchWithUnthrownExceptionRuleTest.php b/tests/PHPStan/Rules/Exceptions/CatchWithUnthrownExceptionRuleTest.php index d43a9500e84..4cda7f9c7e8 100644 --- a/tests/PHPStan/Rules/Exceptions/CatchWithUnthrownExceptionRuleTest.php +++ b/tests/PHPStan/Rules/Exceptions/CatchWithUnthrownExceptionRuleTest.php @@ -10,6 +10,7 @@ use PHPStan\Testing\CompositeRule; use PHPStan\Testing\RuleTestCase; use PHPUnit\Framework\Attributes\RequiresPhp; +use const PHP_VERSION_ID; /** * @extends RuleTestCase @@ -1565,4 +1566,73 @@ public function testUnserializeThrowTypeBeforePhp8(): void ]); } + #[RequiresPhp('>= 8.0.0')] + public function testRangeThrowType(): void + { + $errors = [ + [ + 'Dead catch - ValueError is never thrown in the try block.', + 14, + ], + [ + 'Dead catch - ValueError is never thrown in the try block.', + 23, + ], + [ + 'Dead catch - ValueError is never thrown in the try block.', + 29, + ], + [ + 'Dead catch - ValueError is never thrown in the try block.', + 35, + ], + ]; + + // the helper decides a character range by the PHP 8.3 rules only when it runs on PHP 8.3 or newer + if (PHP_VERSION_ID >= 80300) { + $errors[] = [ + 'Dead catch - ValueError is never thrown in the try block.', + 60, + ]; + } + + $errors[] = [ + 'Dead catch - ValueError is never thrown in the try block.', + 88, + ]; + + $this->analyse([__DIR__ . '/data/range-throw-type.php'], $errors); + } + + #[RequiresPhp('< 8.0.0')] + public function testRangeThrowTypeBeforePhp8(): void + { + $this->analyse([__DIR__ . '/data/range-throw-type.php'], [ + [ + 'Dead catch - ValueError is never thrown in the try block.', + 14, + ], + [ + 'Dead catch - ValueError is never thrown in the try block.', + 23, + ], + [ + 'Dead catch - ValueError is never thrown in the try block.', + 29, + ], + [ + 'Dead catch - ValueError is never thrown in the try block.', + 35, + ], + [ + 'Dead catch - ValueError is never thrown in the try block.', + 88, + ], + [ + 'Dead catch - ValueError is never thrown in the try block.', + 136, + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/Exceptions/data/range-throw-type.php b/tests/PHPStan/Rules/Exceptions/data/range-throw-type.php new file mode 100644 index 00000000000..45bcefc8bff --- /dev/null +++ b/tests/PHPStan/Rules/Exceptions/data/range-throw-type.php @@ -0,0 +1,141 @@ += 80300) { + try { + $a = range('a', 'z'); + } catch (\ValueError $e) { + + } + + // PHP 8.3 rejects a negative step on an increasing range + try { + $a = range(1, 1000, -1); + } catch (\ValueError $e) { + + } + + // PHP 8.3 builds a character range, in which 2 exceeds the range from '9' to ':' + try { + $a = range('9', ':', 2); + } catch (\ValueError $e) { + + } + + // PHP 8.3 compares an integral float step exactly, and 2 ** 60 exceeds the range up to 2 ** 60 - 1 + try { + $a = range(0, 1152921504606846975, 1152921504606846976.0); + } catch (\ValueError $e) { + + } + } else { + // the sign of the step used to be ignored + try { + $a = range(1, 1000, -1); + } catch (\ValueError $e) { + + } + + // '1' used to be a number next to a non-numeric string, so the step exceeds the range 1..0 + try { + $a = range('1', 'a', 30); + } catch (\ValueError $e) { + + } + + // integers are compared exactly, and 2 ** 60 exceeds the range up to 2 ** 60 - 1 + try { + $a = range(0, 1152921504606846975, 1152921504606846976); + } catch (\ValueError $e) { + + } + + // the number of items does not fit into a float, which exceeds every array size + try { + $a = range(-1.0e308, 1.0e308); + } catch (\ValueError $e) { + + } + + try { + $a = range(0, 1, 1.0e-320); + } catch (\ValueError $e) { + + } + } + } + + public function doBar(bool $flag, string $s): void + { + // a guard with an upper bound only would leave the analysed PHP version at 8.0 + if (PHP_VERSION_ID >= 70400 && PHP_VERSION_ID < 80100) { + // PHP 7 does not throw, PHP 8.0 does + try { + $a = range(1, 10, 0); + } catch (\ValueError $e) { + + } + } + + // only a part of the boundary is a constant + try { + $a = range($flag ? 1 : $s, 10); + } catch (\ValueError $e) { + + } + } + +} diff --git a/tests/PHPStan/Rules/Exceptions/data/unthrown-exception-php-version-range.php b/tests/PHPStan/Rules/Exceptions/data/unthrown-exception-php-version-range.php index fc8496598b0..812e2c652a4 100644 --- a/tests/PHPStan/Rules/Exceptions/data/unthrown-exception-php-version-range.php +++ b/tests/PHPStan/Rules/Exceptions/data/unthrown-exception-php-version-range.php @@ -56,4 +56,22 @@ public function stringCast(ThrowsOnToString $o): string } } + public function rangeWithInvalidStep(): void + { + try { + range(1, 10, 0); + } catch (\ValueError $e) { // PHP 8 throws, PHP 7 returns false + + } + } + + public function rangeWithUnknownBoundary(int $i): void + { + try { + range(1, $i); + } catch (\ValueError $e) { // a range too long for an array throws on PHP 8 + + } + } + }