Repository navigation
Add range() throw type extension #6539
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
54184aa
Add range() throw type extension
zonuexe bc91112
Test the range() throw type for undecided PHP versions and boundaries
zonuexe 5789d36
Keep the ValueError of range() for a PHP version range that starts be…
zonuexe dbdb6b9
Expect the ValueError of range() after a PHP 8 guard when analysing o…
zonuexe File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| <?php declare(strict_types = 1); | ||
|
|
||
| namespace PHPStan\Type\Php; | ||
|
|
||
| use PhpParser\Node\Expr\FuncCall; | ||
| use PHPStan\Analyser\Scope; | ||
| use PHPStan\DependencyInjection\AutowiredService; | ||
| use PHPStan\Reflection\FunctionReflection; | ||
| use PHPStan\TrinaryLogic; | ||
| use PHPStan\Type\Constant\ConstantArrayTypeBuilder; | ||
| use PHPStan\Type\DynamicFunctionThrowTypeExtension; | ||
| use PHPStan\Type\ObjectType; | ||
| use PHPStan\Type\Type; | ||
| use PHPStan\Type\VoidType; | ||
| use ValueError; | ||
| use function count; | ||
| use function is_float; | ||
| use function is_int; | ||
| use function is_numeric; | ||
| use function is_string; | ||
|
|
||
| /** | ||
| * range() throws ValueError since PHP 8.0 for an invalid step, a non-finite boundary, | ||
| * and a range with more items than an array can hold. | ||
| */ | ||
| #[AutowiredService] | ||
| final class RangeFunctionThrowTypeExtension implements DynamicFunctionThrowTypeExtension | ||
| { | ||
|
|
||
| /** HT_MAX_SIZE of a 32-bit PHP, the smallest array size range() refuses to create */ | ||
| private const RANGE_SIZE_LIMIT = 0x02000000; | ||
|
|
||
| public function isFunctionSupported(FunctionReflection $functionReflection): bool | ||
| { | ||
| return $functionReflection->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<int|float|string> : list<int|float>)|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(); | ||
| } | ||
|
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
141 changes: 141 additions & 0 deletions
141
tests/PHPStan/Rules/Exceptions/data/range-throw-type.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| <?php | ||
|
|
||
| namespace RangeThrowType; | ||
|
|
||
| class Foo | ||
| { | ||
|
|
||
| public function doFoo(int $i): void | ||
| { | ||
| if (PHP_VERSION_ID < 80000) { | ||
| // PHP 7 reported an invalid step with a warning instead of a ValueError | ||
| try { | ||
| $a = range(1, 10, 0); | ||
| } catch (\ValueError $e) { | ||
|
|
||
| } | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| try { | ||
| $a = range(1, 10); | ||
| } catch (\ValueError $e) { | ||
|
|
||
| } | ||
|
|
||
| try { | ||
| $a = range(0, 1000); | ||
| } catch (\ValueError $e) { | ||
|
|
||
| } | ||
|
|
||
| try { | ||
| $a = range(10, 1, -1); | ||
| } catch (\ValueError $e) { | ||
|
|
||
| } | ||
|
|
||
| try { | ||
| $a = range(1, 10, 0); | ||
| } catch (\ValueError $e) { | ||
|
|
||
| } | ||
|
|
||
| try { | ||
| $a = range(1, $i); | ||
| } catch (\ValueError $e) { | ||
|
|
||
| } | ||
|
|
||
| try { | ||
| $a = range(0, 2000000000); | ||
| } catch (\ValueError $e) { | ||
|
|
||
| } | ||
|
|
||
| if (PHP_VERSION_ID >= 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) { | ||
|
|
||
| } | ||
| } | ||
|
|
||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.