Skip to content

Convert int and decimal-int-string to a finite float range in toFloat() and float arithmetic - #7102

Open
phpstan-bot wants to merge 2 commits into
phpstan:2.3.xfrom
phpstan-bot:create-pull-request/patch-2rexbio
Open

phpstan-bot wants to merge 2 commits into
phpstan:2.3.xfrom
phpstan-bot:create-pull-request/patch-2rexbio

Conversation

@phpstan-bot

Copy link
Copy Markdown
Collaborator

Summary

PHPStan typed (float) $int and (float) $decimalIntString as plain float, so they could not be returned as finite-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() returns FloatRangeType::fromInterval((float) PHP_INT_MIN, (float) PHP_INT_MAX). This matches what IntegerRangeType::toFloat() already did for bounded ranges. Everything built on toFloat() 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 returns float, 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_MAX instead of ±INF. As a result, $int + 0.0, $int * 1.0, $int += 0.0, $int / 2 and int<0, max> + 0.0 are finite float ranges instead of float / float<0.0, max>.
  • turbo-ext mirrors ported: IntegerType.cpp, AccessoryDecimalIntegerStringType.cpp, NumberSet.cpp. The extension builds, tests/smoke.php prints ALL OK, and the full suite passes with the extension loaded.
  • Probed and left unchanged:
    • 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() returned FloatType.
  • 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, settype with float and double, arithmetic and compound assignment with float operands, int<0, max>, non-decimal-int-string (stays float), overflow ($int * 1e300 stays float), and is_finite/is_nan.
  • ReturnTypeRuleTest::testBug15767: no error for returning (float) $int, (float) $decimalIntString, $int + 0.0 or a settyped int as finite-float. The error is still reported for a non-decimal-int-string.
  • Updated existing nsrt assertions that now get more precise types. Examples: 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 now numeric-string&uppercase-string, because the float is finite.

Fixes phpstan/phpstan#15767

🤖 Generated with Claude Code

…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 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.

What about

  • int-range to float
  • union-type to float
  • bool to float

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@phpstan-bot

Copy link
Copy Markdown
Collaborator Author

All three cases you asked about already give finite floats, so no source change was needed. I added tests that lock this in.

Results:

  • Int ranges (this already worked before this PR): IntegerRangeType::toFloat() keeps any finite bounds and caps an open side at the float closest to PHP_INT_MIN/PHP_INT_MAX.
    • int<0, 10> → float<0.0, 10.0>
    • int<0, max> → float<0.0, 9.223372036854776E+18>
    • int<min, 5> → float<-9.223372036854776E+18, 5.0>
    • 1|2|3 → 1.0|2.0|3.0
    • int<0, 10> + 0.0 → float<0.0, 10.0>
  • Bool (also already worked): (float) $bool → 0.0|1.0, and (float) true → 1.0.
  • Unions: each member is converted on its own and the results are combined. Before this PR, the int member became plain float, so the whole union did too. Now:
    • int|bool, int|decimal-int-string and ?int → float<-9.223372036854776E+18, 9.223372036854776E+18>, both through (float) and floatval().
    • int|string stays float, because a string like "1e999" becomes INF.
    • int|float stays float, because the float member can be INF or NAN.

Tests added:

  • tests/PHPStan/Analyser/nsrt/bug-15767.php: a new review() function asserts every case above.
  • ReturnTypeRuleTest::testBug15767: returning (float) $x as finite-float gives no error for int<0, max>, bool, or int|bool|decimal-int-string|null. It still gives an error for int|string.

make tests passed (23903 tests, 116 skipped) and make phpstan reported no errors. Everything is in one commit (56235b6dc), not pushed yet.

@staabm

staabm commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

@zonuexe you are the float expert. do you have objections to this PR? :)

@VincentLanglet

Copy link
Copy Markdown
Contributor

@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 zonuexe 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.

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_MAX is 1.844674407370955E+20, and power(10, 400) is INF.
  • $y = (float) $n; while ($y < 1.0e30) { $y *= 2; } reports smaller.alwaysTrue and makes the code after the loop unreachable.
  • On the base, all of these are float and nothing is reported.
  • MutatingScope::generalizeType() has no bucket for FloatRangeType, 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 to float<0.0, max> again. A sum of list<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> gives int<-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.php and weird-array_key_exists-issue.php.
  • Before PHP 8, a division by zero does not throw, so $a / $b of two ints is (-INF|INF|NAN|float<-9.223372036854776E+18, 9.223372036854776E+18>|int). float used to absorb those members.
  • The type is correct; the updated expectations need a PHP_VERSION_ID split. 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" gives 1.0E+30 and "1e999" gives INF at runtime.
  • ValueSet::toOperandNumbers() leaves the string member of the benevolent array-key out, so only the int interval reaches NumberSet::integerToFloatInterval(). The leniency is older, but the ±INF bound used to hide it, and the cast and + 0.0 now 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.0 and ArrayIterator<int, float> fail the same way.
  • The range also comes back to ints: (int) round($i * 0.5) is int<-4611686018427387904, 4611686018427387904>, where the base has int.
  • 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) in src/Core/Framework/Util/Random.php:59.

5. Int overflow becomes visible through the float (unsound, low severity)

  • (float) ($a * $b) > 9.3e18 is reported as always false. At runtime, (float) (PHP_INT_MAX * PHP_INT_MAX) is 8.507059173023462E+37.
  • This follows from typing int * int as int, which the base already does for is_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> becoming float<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 now NAN|float<0.0, 3037000499.97605>, and fmod($int, 2) is float<-2.0, 2.0>.
  • round(), floor() and ceil() on a plain int are listed in the description but not asserted.

Suggested order

  1. Loop widening for float ranges, including bounds that grow in both directions (#7084, with that case reconsidered).
  2. Keep the string part of array-key operands, or keep such operands at float.
  3. Decide how inferred template arguments should generalize a float range, since this PR makes them appear for every int-to-float conversion.
  4. Then this PR, with the PHP 7.4 expectations split.

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.

Casting an int (or a decimal-int-string) as float yields a finite-float

4 participants