Repository navigation
Convert int and decimal-int-string to a finite float range in toFloat() and float arithmetic - #7102
phpstan-bot wants to merge 2 commits into
Conversation
…Float()` and float arithmetic - IntegerType::toFloat() returns float<(float) PHP_INT_MIN, (float) PHP_INT_MAX> instead of float, like IntegerRangeType::toFloat() already did for bounded ranges. This covers (float), floatval()/doubleval(), settype($x, 'float'|'double'), filter_var(FILTER_VALIDATE_FLOAT), round()/floor()/ceil() and the non-strict coerced argument type. - AccessoryDecimalIntegerStringType::toFloat() returns the same range when not inverted (a decimal-int-string always holds an int); the inverse still gives float. - NumberSet::integerToFloatInterval() bounds an unbounded integer side at the float closest to PHP_INT_MIN/PHP_INT_MAX instead of ±INF, so `$int + 0.0`, `$int * 1.0`, `$int / 2`, `$int += 0.0`, … are finite float ranges too, and int<0, max> + 0.0 no longer reaches INF. - Ported all three changes to the turbo-ext mirrors (IntegerType.cpp, AccessoryDecimalIntegerStringType.cpp, NumberSet.cpp). - Updated existing type assertions that now get more precise (finite bounds instead of `min`/`max`, `float` or ranges touching 0 for int divisors). - Probed but left alone: numeric-string/string casts (can be INF, e.g. "1e999"), fdiv() (has no range inference at all). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
staabm
left a comment
There was a problem hiding this comment.
What about
- int-range to float
- union-type to float
- bool to float
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
All three cases you asked about already give finite floats, so no source change was needed. I added tests that lock this in. Results:
Tests added:
|
|
@zonuexe you are the float expert. do you have objections to this PR? :) |
I wonder if we should also ask ondrej if he wants this change given the fact he introduces float range. |
zonuexe
left a comment
There was a problem hiding this comment.
This review is based on an adversarial review by Claude Opus 5.5 and Claude Fable 5.2. Every finding below was reproduced on the PR head (56235b6) and compared with the base, at level 10 on PHP 8.5 64bit unless stated.
The conversions themselves are right: an int or a decimal-int-string becomes a float within ±2^63. The problem is where the narrower type goes. Several paths relied on an int converted to float being plain float, and with a finite range they now produce unsound types and new errors on code that was clean.
1. Float accumulators fed by ints stop at a finite range in loops (unsound)
/** @param list<int> $ints */
function sum(array $ints): float
{
$sum = 0.0;
foreach ($ints as $i) {
$sum += $i;
}
if ($sum > 1e20) { // Comparison operation ">" between float<-3.6893488147419103E+19, 3.6893488147419103E+19> and 1.0E+20 is always false.
echo "huge\n";
}
return $sum;
}
function power(int $base, int $exp): float
{
$r = 1.0;
for ($k = 0; $k < $exp; $k++) {
$r *= $base;
}
if (is_infinite($r)) { // Call to function is_infinite() with float<-7.237005577332262E+75, 7.237005577332262E+75> will always evaluate to false.
throw new \OverflowException();
}
return $r;
}- At runtime, the sum of 20
PHP_INT_MAXis1.844674407370955E+20, andpower(10, 400)isINF. $y = (float) $n; while ($y < 1.0e30) { $y *= 2; }reportssmaller.alwaysTrueand makes the code after the loop unreachable.- On the base, all of these are
floatand nothing is reported. MutatingScope::generalizeType()has no bucket forFloatRangeType, so a growing float range is never widened and stays at what the last analysed iteration reached. Before this PR, an int converted to float was unbounded, which hid that.- #7084 adds the bucket. With it, a sum of
list<non-negative-int>widens tofloat<0.0, max>again. A sum oflist<int>still stays bounded, because both bounds grow at once, and #7084 keeps that case like integer ranges have since #5176 ($n += int<-1, 1>givesint<-4, 4>). - So this PR needs loop widening first, including bounds that grow in both directions.
2. CI fails on PHP 7.4 because of this PR
- The "Tests with old PHPUnit (7.4)" jobs fail on
binary.php,integer-range-types.phpandweird-array_key_exists-issue.php. - Before PHP 8, a division by zero does not throw, so
$a / $bof two ints is(-INF|INF|NAN|float<-9.223372036854776E+18, 9.223372036854776E+18>|int).floatused to absorb those members. - The type is correct; the updated expectations need a
PHP_VERSION_IDsplit. A project with a version range starting below 8.0 sees the five-member union in every message about such a division.
3. An array-key operand loses its string part (unsound)
/** @param array<int> $histogram */
function f(array $histogram): void
{
foreach ($histogram as $bucket => $count) {
\PHPStan\dumpType((float) $bucket); // float
\PHPStan\dumpType($bucket + 0.0); // float<-9.223372036854776E+18, 9.223372036854776E+18>
if ($bucket * 1.0 > 1.0e19) { // always false
echo "x";
}
}
}- A key
"1e30"gives1.0E+30and"1e999"givesINFat runtime. ValueSet::toOperandNumbers()leaves the string member of the benevolentarray-keyout, so only the int interval reachesNumberSet::integerToFloatInterval(). The leniency is older, but the ±INF bound used to hide it, and the cast and+ 0.0now disagree.
4. New errors through invariant generics, which also leak into ints
/** @template T */
final class Box
{
/** @param T $value */
public function __construct(public mixed $value) {}
}
/** @return Box<float> */
function makeBox(int $cents): Box
{
return new Box((float) $cents); // should return Box<float> but returns Box<float<-9.223372036854776E+18, 9.223372036854776E+18>>.
}- The base reports nothing.
Collection<int, float>built from$c / 100.0andArrayIterator<int, float>fail the same way. - The range also comes back to ints:
(int) round($i * 0.5)isint<-4611686018427387904, 4611686018427387904>, where the base hasint. - The shopware integration job shows this:
@var with type int<1, max> is not subtype of type int<1, 6917529027641081856>for(int) ceil($length * 0.75)insrc/Core/Framework/Util/Random.php:59.
5. Int overflow becomes visible through the float (unsound, low severity)
(float) ($a * $b) > 9.3e18is reported as always false. At runtime,(float) (PHP_INT_MAX * PHP_INT_MAX)is8.507059173023462E+37.- This follows from typing
int * intasint, which the base already does foris_float($a * $b). The PR extends that to the float side.
Integration jobs
- matomo, glpi, openemr, woocommerce, woocommerce-payments and wordpress-develop fail on changed messages, such as
float<2.0, max>becomingfloat<2.0, 3.0340039594917024E+17>. Their baselines would need regenerating. - shopware is finding 4. librenms is a new and correct
is_nan()report on?int / 10000000. - prado and phpstan-laravel fail the same way on #7103, so they are unrelated.
Untested behaviour changes
sqrt($int)is nowNAN|float<0.0, 3037000499.97605>, andfmod($int, 2)isfloat<-2.0, 2.0>.round(),floor()andceil()on a plainintare listed in the description but not asserted.
Suggested order
- Loop widening for float ranges, including bounds that grow in both directions (#7084, with that case reconsidered).
- Keep the string part of
array-keyoperands, or keep such operands atfloat. - Decide how inferred template arguments should generalize a float range, since this PR makes them appear for every int-to-float conversion.
- Then this PR, with the PHP 7.4 expectations split.
Summary
PHPStan typed
(float) $intand(float) $decimalIntStringas plainfloat, so they could not be returned asfinite-float. An int always converts to a finite float, and so does a decimal-int-string. Now these conversions, and float arithmetic with an int operand ($int + 0.0, which the issue comment mentions), give a finite float range.Changes
src/Type/IntegerType.php:toFloat()returnsFloatRangeType::fromInterval((float) PHP_INT_MIN, (float) PHP_INT_MAX). This matches whatIntegerRangeType::toFloat()already did for bounded ranges. Everything built ontoFloat()benefits:(float),floatval()/doubleval(),settype(..., 'float'|'double'),filter_var(..., FILTER_VALIDATE_FLOAT),round()/floor()/ceil(), and the coerced argument type.src/Type/Accessory/AccessoryDecimalIntegerStringType.php:toFloat()returns the same range when not inverted. The inverted type (non-decimal-int-string) still returnsfloat, because e.g."1e999"becomes INF.src/Type/NumberSet.php:integerToFloatInterval()now maps an unbounded integer side to(float) PHP_INT_MIN/(float) PHP_INT_MAXinstead of ±INF. As a result,$int + 0.0,$int * 1.0,$int += 0.0,$int / 2andint<0, max> + 0.0are finite float ranges instead offloat/float<0.0, max>.IntegerType.cpp,AccessoryDecimalIntegerStringType.cpp,NumberSet.cpp. The extension builds,tests/smoke.phpprints ALL OK, and the full suite passes with the extension loaded.numeric-string/string→ float can be INF, so it is correctly not finite.fdiv()has no range inference at all; that is a separate feature.Root cause
Two places modelled "any int as a float" as unbounded:
IntegerType::toFloat()returnedFloatType.NumberSet::integerToFloatInterval()stretched an unbounded integer side to ±INF.Both forgot that ints are bounded by
PHP_INT_MIN/PHP_INT_MAX. The bounded case (IntegerRangeType::toFloat()) already handled this correctly. The decimal-int-string accessory had the same gap.Test
tests/PHPStan/Analyser/nsrt/bug-15767.php: the issue's reproducer plus casts,floatval/doubleval,settypewithfloatanddouble, arithmetic and compound assignment with float operands,int<0, max>,non-decimal-int-string(staysfloat), overflow ($int * 1e300staysfloat), andis_finite/is_nan.ReturnTypeRuleTest::testBug15767: no error for returning(float) $int,(float) $decimalIntString,$int + 0.0or asettyped int asfinite-float. The error is still reported for anon-decimal-int-string.float<0.0, max>→float<0.0, 9.223372036854776E+18>,(float|int)→(float<…>|int)for int division, and quotients with an int divisor no longer touching 0.strval(rand() * 0.1)is nownumeric-string&uppercase-string, because the float is finite.Fixes phpstan/phpstan#15767
🤖 Generated with Claude Code