Skip to content

Add range() throw type extension - #6539

Merged
staabm merged 4 commits into
phpstan:2.3.xfrom
zonuexe:range/throw-type
Nov 16, 2026
Merged

staabm merged 4 commits into
phpstan:2.3.xfrom
zonuexe:range/throw-type

Conversation

@zonuexe

@zonuexe zonuexe commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

PhpStorm stubs declare @throws \ValueError on range(), so every call is an explicit throw point and PHPStan does not report a catch around a valid call as dead:

try {
	$a = range(1, 10);
} catch (\ValueError $e) { // not reported before this PR
}

On PHP 8.0+, range() throws ValueError for:

  • a step of 0, or one wider than the range, which covers an infinite step;
  • a negative step on an increasing range, a NAN step and a step of PHP_INT_MIN (8.3+);
  • an infinite boundary, and a NAN one since 8.3;
  • a range with more items than an array can hold.

PHP 7 reported these with a warning and a false return value.

The extension looks at native types. It returns VoidType on PHP 7, and on PHP 8 when it can prove the call succeeds:

  • every argument is a constant number or string, and the step a number;
  • RangeFunctionArgumentsHelper finds that no analysed PHP version rejects the arguments. It checks the PHP 8.3 rules and the older ones separately. For a range of at most ARRAY_COUNT_LIMIT items it also uses the verdict of calling range(), but only when PHPStan itself runs on PHP 8.3 or newer;
  • the range has fewer items than RANGE_SIZE_LIMIT, the HT_MAX_SIZE of a 32-bit PHP. A range whose number of items does not fit into a float, such as range(-1.0e308, 1.0e308), keeps the throw point.

Otherwise it keeps the declared ValueError. Two cases stay undecided on purpose:

  • A string boundary before PHP 8.3. range('1', 'a', 30) is a character range on 8.3, while 8.2 turns '1' into a number and 'a' into 0, and throws because 30 exceeds the range 1..0.
  • Integers beyond 2 ** 53, which PHP compares exactly and a float cannot. range(0, 2 ** 60 - 1, 2 ** 60) throws on 8.2.

Since the extension reads $scope->getPhpVersion(), I split the test data by PHP_VERSION_ID. As in the sibling tests, a second method expects every catch to be dead on PHP 7, which has no ValueError, and the test expects range('a', 'z') to be decided for PHP 8.3 only when it runs on PHP 8.3 or newer. On PHP 7 the self-analysis reports the catch in RangeFunctionArgumentsHelper::callRange() as dead, so build/baseline-pre-8.0.neon ignores it. RangeFunctionArgumentsHelperTest covers the cases that depend on the PHP running PHPStan. The tests fail without the extension.

#6492 changes the return type of range() and uses the same helper. I cherry-picked the helper commits into it, so the two PRs merge in either order.

@phpstan-bot

Copy link
Copy Markdown
Collaborator

This pull request has been marked as ready for review.

@zonuexe
zonuexe marked this pull request as draft October 6, 2026 16:40
@zonuexe
zonuexe changed the base branch from 2.2.x to 2.3.x October 6, 2026 16:43
@zonuexe
zonuexe marked this pull request as ready for review October 6, 2026 16:49
@phpstan-bot

Copy link
Copy Markdown
Collaborator

This pull request has been marked as ready for review.

@zonuexe
zonuexe marked this pull request as draft November 2, 2026 15:41
@zonuexe
zonuexe force-pushed the range/throw-type branch 2 times, most recently from 7bc920f to 37f4ee3 Compare November 2, 2026 15:59
@zonuexe
zonuexe marked this pull request as ready for review November 2, 2026 17:42
@phpstan-bot

Copy link
Copy Markdown
Collaborator

This pull request has been marked as ready for review.

@staabm staabm left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry for coming back to this PR so late. I just rebased it.

ondrej recently added float ranges support to PHPStan, so this might be something which can be made use of here?

did you have a real world use-case which motivated this PR?
I am asking because I see the PR is very precise and detailled. I wonder whether its worth having all the php version specific details here and whether it helps the analysis to give more useful results

@zonuexe

zonuexe commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

I have no real-world case for it. PHP 8.3 changed when range() throws a ValueError, so I modelled each version. Only the latest version matters. If the pre-8.3 details aren't worth keeping, I can drop them and keep the declared ValueError when the analysed version is older than 8.3.

Float ranges fit the return type in #6492 better: a long range of floats could become list<float<1.0, 100.0>> instead of list<float>. I'll try that there.

@staabm

staabm commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

please resolve conflicts and rebase

@zonuexe
zonuexe marked this pull request as draft November 13, 2026 05:57
@zonuexe
zonuexe marked this pull request as ready for review November 13, 2026 06:54
@phpstan-bot

Copy link
Copy Markdown
Collaborator

This pull request has been marked as ready for review.

@staabm

staabm commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

//cc @SanderMuller

Comment on lines +81 to +83
if (!$type->isConstantScalarValue()->yes()) {
return null;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we don't need this IF beforehand

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dropped the check in 1e42f83. getConstantScalarValues() is empty unless every member of the type is a constant, so an empty result is enough to bail out. Without it a range(1, 10, $int) call would loop over no steps and be treated as non-throwing.

@SanderMuller SanderMuller left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I compared this with real PHP 8.0, 8.2, 8.3 and 8.5 on a grid of 20,480 calls. Each call has the form try { $r = range(a, b, c); } catch (\ValueError $e) {}. The boundaries are ints, floats, numeric and non-numeric strings, INF, -INF, NAN, PHP_INT_MAX, PHP_INT_MIN, 1e300 and 2 ** 53 + 1. The steps include 0, negative steps, INF, NAN, PHP_INT_MIN and 2 ** 60.

  • I analysed it with a single phpVersion from 80000 to 80500, and with the ranges 8.0–8.2, 8.0–8.5 and 8.2–8.3. No catch is reported as dead when one of those versions throws. This is the same with PHPStan on PHP 8.2 and on PHP 8.5.
  • With phpVersion: 80500, 3,840 of the 4,412 calls that do not throw get a dead catch on PHP 8.5, and 857 on PHP 8.2. This matches the runtime verdict in your description.

One problem: with phpVersion: {min: 70400, max: 80500}, every catch is reported as dead, also around range(1, 10, 0) and range(1, $i). In the grid that is 16,121 calls that throw on at least one PHP 8 version. The extension gets maybe from throwsValueErrorForInternalFunctions(), but $functionReflection->getThrowType() is null for this version range. When the extension returns null, the call has no throw point. On 2.3.x these catches are not reported. I tried this at the four places that return the declared type:

return $functionReflection->getThrowType() ?? new ObjectType(ValueError::class);

With it, no catch in the grid is wrongly dead for 7.4–8.5, and 857 calls keep a dead catch, as for 8.0–8.5. testRangeThrowType still passes. ArrayChunkFunctionThrowTypeExtension on 2.3.x has the same problem: array_chunk([1], $i) gets a dead catch with this version range.

About the inline question on isConstantScalarValue(): the check is needed. For int, getConstantScalarValues() returns [], so without the check the loops do not run and the extension returns VoidType. I removed it, and range(1, $i), range($s, 'z') and range(1, 10, $f) all got a dead catch.

testRangeThrowType fails without the extension and passes with it. testRangeThrowTypeBeforePhp8 only runs on PHP 7, so I did not run it.

On 3768b18 the full test suite, make phpstan and phpcs pass. The five red CI jobs are also red on #7050 or on the 2.3.x tip. Performance: I analysed the file with the 20,480 calls 8 times on each side. 2.3.x takes 12.31 s (σ 0.37 s) and this PR 12.38 s (σ 0.02 s), which is within the noise.

@staabm

staabm commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

The last change was not covered by a test

@zonuexe

zonuexe commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

You're right, and I could not write one: the change has no reachable difference. getConstantScalarValues() is empty unless every member is a constant, so for a union, an intersection and a template type the two checks agree, and range() gives the same throw type with and without it. It only dropped the second call, so I reverted it.

@SanderMuller

Copy link
Copy Markdown
Contributor

The version range problem from my review is still there on b2e8a92. With phpVersion: {min: 70400, max: 80500}, the catches around range(1, 10, 0) and range(1, $i) are reported as dead. With phpVersion: 80500 they are not. The ?? new ObjectType(ValueError::class) fallback from the review fixes it.

@zonuexe

zonuexe commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in 6914c88 with your fallback. For a version range that starts before PHP 8 the reflection of range() has no @throws, so the extension returned no throw type. CatchWithUnthrownExceptionRuleConfigPhp73Test now checks range(1, 10, 0) and range(1, $i) with the PHP 7.3 to 8.5 range.

@SanderMuller

Copy link
Copy Markdown
Contributor

Thanks. The version range case is fixed. On 6914c88 no catch in the grid is dead around a call that throws on PHP 8, also with the 7.4 to 8.5 range.

The PHP 7.4 jobs of "Tests with old PHPUnit" now fail in testRangeThrowTypeBeforePhp8. They passed on b2e8a92. I think the new behaviour is right, and the expectations are out of date. After if (PHP_VERSION_ID < 80000) { ... return; }, PHPStan narrows PHP_VERSION_ID to int<80000, max>, also with phpVersion: 70400. In the rest of doFoo(), range(1, 10, 0) gets the PHP 7 reflection without @throws, so before the fallback its catch was reported as dead.

From the CI log, the dead catches on PHP 7.4 are now on lines 14, 23, 29, 35, 88 and 136. Lines 41, 47, 53, 60, 67, 74, 81, 95, 102, 109, 115 and 128 are no longer reported. I could not run the test on PHP 7.4 here. With phpVersion: 70400 on PHP 8.5, line 60 is also reported, so the range('a', 'z') result depends on the PHP that runs the analysis.

On 6914c88 the full test suite on PHP 8.5, make phpstan and phpcs pass. The new CatchWithUnthrownExceptionRuleConfigPhp73Test case fails without the fallback. The other red jobs are also red on #7050 or on the 2.3.x tip.

zonuexe and others added 4 commits November 16, 2026 11:06
PhpStorm stubs declare `@throws \ValueError` on range(), so every call
became an explicit throw point and a catch around a valid call was never
reported as dead.

The extension returns void on PHP 7, which does not throw, and on PHP 8
when the native argument types are constant numbers or strings,
RangeFunctionArgumentsHelper finds that no analysed PHP version rejects
them, and the range has fewer items than RANGE_SIZE_LIMIT, the
HT_MAX_SIZE of a 32-bit PHP. A range whose number of items does not fit
into a float keeps the throw point as well.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
A guard on both sides of PHP 8.0 leaves undecided whether range() throws
a ValueError at all, and a boundary that is only partly a constant leaves
the arguments undecided. Both keep the throw point.
…fore PHP 8

The reflection of range() has no @throws when the analysed PHP version range starts before PHP 8, so returning its throw type left the call without a throw point, and catches around a call that throws on PHP 8 were reported as dead.
…n PHP 7

After if (PHP_VERSION_ID < 80000) { return; } the rest of the method is analysed as PHP 8 with the reflection of PHP 7, which has no @throws. Since the ValueError fallback, the catches around the calls that throw on PHP 8 are no longer dead there.
@zonuexe

zonuexe commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

Updated the PHP 7 expectations in dbdb6b9 to the lines from the CI log: 14, 23, 29, 35, 88 and 136. After the PHP_VERSION_ID < 80000 guard, the method is analysed as PHP 8 with the reflection of PHP 7, so the fallback keeps the ValueError there. I also rebased onto the current 2.3.x and dropped the getConstantScalarValues() commit together with its revert.

@staabm

staabm commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

//cc @SanderMuller please have another look

@SanderMuller SanderMuller left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PHP 7 expectations in dbdb6b9 are right. After the PHP_VERSION_ID < 80000 guard, the rest of doFoo() is analysed as PHP 8, so the fallback keeps the ValueError. Line 136 is dead on a PHP 7 runtime, which is correct because PHP 7 has no ValueError.

The src change is the same as on 6914c88. testRangeThrowType fails without it and passes with it. The PHP 7.4 jobs of "Tests with old PHPUnit" pass now.

The three red jobs do not come from this PR. phpstan-laravel and phpstan-dba are red on every open PR against 2.3.x. The Windows failure is ResultCacheManagerCollectedDataTest, which ab33112 on 2.3.x fixes.

Performance is the same as in my earlier measurement on 3768b18. The only src change since then is the ValueError fallback.

@staabm
staabm merged commit 526b668 into phpstan:2.3.x Nov 16, 2026
904 of 907 checks passed
@staabm

staabm commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants