55use PhpParser \Node \Expr \FuncCall ;
66use PHPStan \Analyser \Scope ;
77use PHPStan \DependencyInjection \AutowiredService ;
8+ use PHPStan \Php \PhpVersion ;
89use PHPStan \Reflection \FunctionReflection ;
910use PHPStan \Type \Accessory \AccessoryArrayListType ;
11+ use PHPStan \Type \Accessory \AccessoryLiteralStringType ;
12+ use PHPStan \Type \Accessory \AccessoryNonEmptyStringType ;
1013use PHPStan \Type \Accessory \NonEmptyArrayType ;
1114use PHPStan \Type \ArrayType ;
1215use PHPStan \Type \BenevolentUnionType ;
1619use PHPStan \Type \Constant \ConstantStringType ;
1720use PHPStan \Type \DynamicFunctionReturnTypeExtension ;
1821use PHPStan \Type \FloatType ;
19- use PHPStan \Type \GeneralizePrecision ;
2022use PHPStan \Type \IntegerRangeType ;
2123use PHPStan \Type \IntegerType ;
2224use PHPStan \Type \IntersectionType ;
25+ use PHPStan \Type \NeverType ;
2326use PHPStan \Type \StringType ;
2427use PHPStan \Type \Type ;
2528use PHPStan \Type \TypeCombinator ;
2629use PHPStan \Type \UnionType ;
2730use ValueError ;
31+ use function abs ;
2832use function count ;
2933use function is_array ;
34+ use function is_finite ;
35+ use function is_float ;
36+ use function is_string ;
3037use 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 ([
0 commit comments