Skip to content

Commit 247646e

Browse files
committed
Improve range() return type for invalid steps and long ranges
An invalid step makes `range()` throw a ValueError, so a call where all constant argument combinations throw is now `*NEVER*` instead of an array type. The constant arguments are folded by calling `range()` on the PHP version PHPStan itself runs on, so a caught ValueError is only turned into `never` when the analysed PHP version is known to reject the step as well: a step of 0 or one wider than the range has been a ValueError since PHP 8.0, while a negative step on an increasing range and a non-finite step only became one in PHP 8.3. Ranges longer than `RANGE_LENGTH_THRESHOLD` are generalized from the values the range consists of instead of from the argument types, so `range('A', 'z')` is a list of single byte strings and `range(1, 200, 1.0)` is a list of ints - the latter only since PHP 8.3, where an integral float step stopped producing floats. Ref phpstan/phpstan#10022
1 parent 1dfc161 commit 247646e

7 files changed

Lines changed: 241 additions & 11 deletions

File tree

‎src/Php/PhpVersion.php‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,4 +531,13 @@ public function throwsOnStringCast(): bool
531531
return $this->versionId >= 70400;
532532
}
533533

534+
/**
535+
* PHP 8.3 rejects a negative or non-finite step, always builds a character range
536+
* from two string boundaries and no longer turns an integral float step into floats.
537+
*/
538+
public function hasStricterRangeFunction(): bool
539+
{
540+
return $this->versionId >= 80300;
541+
}
542+
534543
}

‎src/Type/Php/RangeFunctionReturnTypeExtension.php‎

Lines changed: 117 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@
55
use PhpParser\Node\Expr\FuncCall;
66
use PHPStan\Analyser\Scope;
77
use PHPStan\DependencyInjection\AutowiredService;
8+
use PHPStan\Php\PhpVersion;
89
use PHPStan\Reflection\FunctionReflection;
910
use PHPStan\Type\Accessory\AccessoryArrayListType;
11+
use PHPStan\Type\Accessory\AccessoryLiteralStringType;
12+
use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
1013
use PHPStan\Type\Accessory\NonEmptyArrayType;
1114
use PHPStan\Type\ArrayType;
1215
use PHPStan\Type\BenevolentUnionType;
@@ -16,17 +19,21 @@
1619
use PHPStan\Type\Constant\ConstantStringType;
1720
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
1821
use PHPStan\Type\FloatType;
19-
use PHPStan\Type\GeneralizePrecision;
2022
use PHPStan\Type\IntegerRangeType;
2123
use PHPStan\Type\IntegerType;
2224
use PHPStan\Type\IntersectionType;
25+
use PHPStan\Type\NeverType;
2326
use PHPStan\Type\StringType;
2427
use PHPStan\Type\Type;
2528
use PHPStan\Type\TypeCombinator;
2629
use PHPStan\Type\UnionType;
2730
use ValueError;
31+
use function abs;
2832
use function count;
2933
use function is_array;
34+
use function is_finite;
35+
use function is_float;
36+
use function is_string;
3037
use function range;
3138

3239
#[AutowiredService]
@@ -35,6 +42,10 @@ final class RangeFunctionReturnTypeExtension implements DynamicFunctionReturnTyp
3542

3643
private const RANGE_LENGTH_THRESHOLD = 50;
3744

45+
public function __construct(private PhpVersion $phpVersion)
46+
{
47+
}
48+
3849
public function isFunctionSupported(FunctionReflection $functionReflection): bool
3950
{
4051
return $functionReflection->getName() === 'range';
@@ -52,28 +63,39 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
5263
$stepType = count($args) >= 3 ? $scope->getType($args[2]->value) : new ConstantIntegerType(1);
5364

5465
$constantReturnTypes = [];
66+
$constantCombinations = 0;
67+
$throwingCombinations = 0;
68+
$hasSkippedCombination = false;
5569

5670
$startConstants = $startType->getConstantScalarTypes();
5771
foreach ($startConstants as $startConstant) {
5872
if (!$startConstant instanceof ConstantIntegerType && !$startConstant instanceof ConstantFloatType && !$startConstant instanceof ConstantStringType) {
73+
$hasSkippedCombination = true;
5974
continue;
6075
}
6176

6277
$endConstants = $endType->getConstantScalarTypes();
6378
foreach ($endConstants as $endConstant) {
6479
if (!$endConstant instanceof ConstantIntegerType && !$endConstant instanceof ConstantFloatType && !$endConstant instanceof ConstantStringType) {
80+
$hasSkippedCombination = true;
6581
continue;
6682
}
6783

6884
$stepConstants = $stepType->getConstantScalarTypes();
6985
foreach ($stepConstants as $stepConstant) {
7086
if (!$stepConstant instanceof ConstantIntegerType && !$stepConstant instanceof ConstantFloatType) {
87+
$hasSkippedCombination = true;
7188
continue;
7289
}
7390

91+
$constantCombinations++;
92+
7493
try {
7594
$rangeValues = @range($startConstant->getValue(), $endConstant->getValue(), $stepConstant->getValue());
7695
} catch (ValueError) {
96+
if ($this->throwsOnAnalysedVersion($startConstant->getValue(), $endConstant->getValue(), $stepConstant->getValue())) {
97+
$throwingCombinations++;
98+
}
7799
continue;
78100
}
79101

@@ -101,16 +123,11 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
101123
);
102124
}
103125

104-
if ($stepType->isFloat()->yes()) {
105-
return self::getNonEmptyListOfType(new FloatType());
106-
}
107-
108-
return self::getNonEmptyListOfType(
109-
TypeCombinator::union(
110-
$startConstant->generalize(GeneralizePrecision::moreSpecific()),
111-
$endConstant->generalize(GeneralizePrecision::moreSpecific()),
112-
$stepType->generalize(GeneralizePrecision::moreSpecific()),
113-
),
126+
return $this->getLargeRangeType(
127+
$rangeValues,
128+
$startConstant->getValue(),
129+
$endConstant->getValue(),
130+
$stepConstant->getValue(),
114131
);
115132
}
116133
$arrayBuilder = ConstantArrayTypeBuilder::createEmpty();
@@ -127,6 +144,18 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
127144
return TypeCombinator::union(...$constantReturnTypes);
128145
}
129146

147+
// nothing is returned when every combination of the constant arguments throws
148+
if (
149+
$constantCombinations > 0
150+
&& $throwingCombinations === $constantCombinations
151+
&& !$hasSkippedCombination
152+
&& $startType->isConstantScalarValue()->yes()
153+
&& $endType->isConstantScalarValue()->yes()
154+
&& $stepType->isConstantScalarValue()->yes()
155+
) {
156+
return new NeverType();
157+
}
158+
130159
$argType = TypeCombinator::union($startType, $endType);
131160
$isInteger = $argType->isInteger()->yes();
132161
$isStepInteger = $stepType->isInteger()->yes();
@@ -162,6 +191,83 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
162191
);
163192
}
164193

194+
/**
195+
* The constant arguments are folded by calling range() on the PHP version PHPStan
196+
* itself runs on, so a ValueError only says that the runtime rejects the step.
197+
* The analysed PHP version is consulted separately before it is turned into never.
198+
*/
199+
private function throwsOnAnalysedVersion(int|float|string $start, int|float|string $end, int|float $step): bool
200+
{
201+
if (!$this->phpVersion->throwsValueErrorForInternalFunctions()) {
202+
return false;
203+
}
204+
205+
if ($this->phpVersion->hasStricterRangeFunction()) {
206+
return true;
207+
}
208+
209+
if (is_string($start) || is_string($end)) {
210+
// how a string boundary was coerced before PHP 8.3 is not modelled here
211+
return false;
212+
}
213+
214+
$start = (float) $start;
215+
$end = (float) $end;
216+
if (!is_finite($start) || !is_finite($end)) {
217+
return false;
218+
}
219+
220+
if ($start === $end) {
221+
// a step of 0 was only rejected for integer boundaries in this case
222+
return false;
223+
}
224+
225+
// the sign of the step used to be ignored, so the step was only rejected
226+
// when it was 0 or wider than the range itself
227+
$step = abs((float) $step);
228+
229+
return $step === 0.0 || abs($end - $start) < $step;
230+
}
231+
232+
/**
233+
* @param non-empty-list<int|float|string> $rangeValues
234+
*/
235+
private function getLargeRangeType(array $rangeValues, int|float|string $start, int|float|string $end, int|float $step): IntersectionType
236+
{
237+
// range() only ever returns values of a single type
238+
$firstValue = $rangeValues[0];
239+
$lastValue = $rangeValues[count($rangeValues) - 1];
240+
241+
if (is_string($firstValue) || is_string($lastValue)) {
242+
// a character range consists of single bytes taken from constant boundaries
243+
return self::getNonEmptyListOfType(TypeCombinator::intersect(
244+
new StringType(),
245+
new AccessoryNonEmptyStringType(),
246+
new AccessoryLiteralStringType(),
247+
));
248+
}
249+
250+
if (
251+
is_float($firstValue)
252+
|| is_float($lastValue)
253+
// before PHP 8.3 a float argument produced floats even when none of
254+
// the arguments had a fractional part
255+
|| (
256+
!$this->phpVersion->hasStricterRangeFunction()
257+
&& (is_float($start) || is_float($end) || is_float($step))
258+
)
259+
) {
260+
return self::getNonEmptyListOfType(new FloatType());
261+
}
262+
263+
// the sequence is monotonic, so the first and the last value are its bounds
264+
if ($firstValue > $lastValue) {
265+
[$firstValue, $lastValue] = [$lastValue, $firstValue];
266+
}
267+
268+
return self::getNonEmptyListOfType(IntegerRangeType::fromInterval($firstValue, $lastValue));
269+
}
270+
165271
private static function getNonEmptyListOfType(Type $type): IntersectionType
166272
{
167273
return new IntersectionType([
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Analyser;
4+
5+
use PHPStan\Testing\TypeInferenceTestCase;
6+
use PHPUnit\Framework\Attributes\DataProvider;
7+
use const PHP_VERSION_ID;
8+
9+
class RangePhp82Test extends TypeInferenceTestCase
10+
{
11+
12+
public static function dataFileAsserts(): iterable
13+
{
14+
if (PHP_VERSION_ID < 80300) {
15+
// the asserts describe an analysed PHP 8.2 with the range() of PHP 8.3+
16+
return [];
17+
}
18+
19+
yield from self::gatherAssertTypes(__DIR__ . '/data/range-php82.php');
20+
}
21+
22+
/**
23+
* @param mixed ...$args
24+
*/
25+
#[DataProvider('dataFileAsserts')]
26+
public function testFileAsserts(
27+
string $assertType,
28+
string $file,
29+
...$args,
30+
): void
31+
{
32+
$this->assertFileAsserts($assertType, $file, ...$args);
33+
}
34+
35+
public static function getAdditionalConfigFiles(): array
36+
{
37+
return [
38+
__DIR__ . '/nodeScopeResolverPhp82.neon',
39+
];
40+
}
41+
42+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
namespace RangePhp82;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
// The analysed PHP version is 8.2, while the constant arguments are folded by
8+
// calling range() on the PHP 8.3+ that runs this test.
9+
10+
// a negative step on an increasing range is only a ValueError since PHP 8.3
11+
assertType('non-empty-list<int>', range(2, 5, -1));
12+
assertType('non-empty-list<string>', range('a', 'z', -1));
13+
14+
// a non-finite step is only rejected by name since PHP 8.3, but INF has always
15+
// exceeded the range spanned by the boundaries
16+
assertType('*NEVER*', range(1, 10, INF));
17+
assertType('non-empty-list<float|int>', range(1, 10, NAN));
18+
19+
// a step of 0 and a step wider than the range have been a ValueError since PHP 8.0
20+
assertType('*NEVER*', range(2, 5, 0));
21+
assertType('*NEVER*', range(5, 6, 3));
22+
23+
// before PHP 8.3 a float argument produced floats even when none of the
24+
// arguments had a fractional part
25+
assertType('non-empty-list<float>', range(1, 200, 1.0));
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
parameters:
2+
phpVersion: 80200 # PHP 8.2
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php // lint < 8.3
2+
3+
namespace Bug10022Php82;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
// before PHP 8.3 a numeric string boundary was implicitly cast to int
8+
assertType('array{1, 0}', range('1', 'a'));
9+
10+
// the sign of the step used to be ignored
11+
assertType('array{2, 3, 4, 5}', range(2, 5, -1));
12+
13+
// a float step with no fractional part used to produce floats
14+
assertType('non-empty-list<float>', range(1, 200, 1.0));
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php // lint >= 8.3
2+
3+
namespace Bug10022;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
// https://github.com/phpstan/phpstan/issues/10022
8+
assertType('array{\'1\', \'2\', \'3\', \'4\', \'5\', \'6\', \'7\', \'8\', \'9\', \':\', \';\', \'<\', \'=\', \'>\', \'?\', \'@\', \'A\', \'B\', \'C\', \'D\', \'E\', \'F\', \'G\', \'H\', \'I\', \'J\', \'K\', \'L\', \'M\', \'N\', \'O\', \'P\', \'Q\', \'R\', \'S\', \'T\', \'U\', \'V\', \'W\', \'X\', \'Y\', \'Z\', \'[\', \'\\\\\', \']\', \'^\', \'_\', \'`\', \'a\'}', range('1', 'a'));
9+
10+
// an invalid step is reported as a ValueError since PHP 8.0
11+
assertType('*NEVER*', range(2, 5, 0));
12+
assertType('*NEVER*', range('a', 'z', 0));
13+
assertType('*NEVER*', range(5, 6, 3));
14+
assertType('*NEVER*', range(2, 5, -1));
15+
assertType('*NEVER*', range('a', 'z', -1));
16+
assertType('*NEVER*', range(1, 10, INF));
17+
assertType('*NEVER*', range(1, 10, NAN));
18+
19+
function maybeInvalidStep(bool $flag): void
20+
{
21+
// only one of the constant combinations throws, the other one returns a range
22+
assertType('array{6}', range($flag ? 5 : 6, 6, 3));
23+
24+
// a step that is neither an int nor a float is not folded at all, so nothing
25+
// can be said about the combination it belongs to
26+
assertType('non-empty-list<float|int>', range(2, 5, $flag ? 0 : true));
27+
}
28+
29+
// ranges longer than the threshold are generalized from the returned values
30+
assertType('non-empty-list<int<1, 200>>', range(1, 200, 1.0));
31+
assertType('non-empty-list<float>', range(1.0, 100.0));
32+
assertType('non-empty-list<literal-string&non-empty-string>', range('A', 'z'));

0 commit comments

Comments
 (0)