Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions build/baseline-pre-8.0.neon
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion src/Type/Php/RangeFunctionReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
129 changes: 129 additions & 0 deletions src/Type/Php/RangeFunctionThrowTypeExtension.php
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) {
Comment thread
staabm marked this conversation as resolved.
Resolved
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();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use PHPStan\Testing\CompositeRule;
use PHPStan\Testing\RuleTestCase;
use PHPUnit\Framework\Attributes\RequiresPhp;
use const PHP_VERSION_ID;

/**
* @extends RuleTestCase<CompositeRule>
Expand Down Expand Up @@ -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,
],
]);
}

}
141 changes: 141 additions & 0 deletions tests/PHPStan/Rules/Exceptions/data/range-throw-type.php
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) {

}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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

}
}

}
Loading