From bb31df052c95606e3b43425d717bdb767ba09321 Mon Sep 17 00:00:00 2001 From: USAMI Kenta Date: Mon, 16 Nov 2026 12:26:37 +0900 Subject: [PATCH] Widen a float range that grows in a loop like an integer range --- src/Analyser/MutatingScope.php | 53 ++++++++ .../nsrt/float-range-loop-generalize.php | 120 ++++++++++++++++++ ...isonOperatorsConstantConditionRuleTest.php | 5 + turbo-ext/src/MutatingScope.cpp | 62 ++++++++- 4 files changed, 239 insertions(+), 1 deletion(-) create mode 100644 tests/PHPStan/Analyser/nsrt/float-range-loop-generalize.php diff --git a/src/Analyser/MutatingScope.php b/src/Analyser/MutatingScope.php index bf19f368357..77cac3f2992 100644 --- a/src/Analyser/MutatingScope.php +++ b/src/Analyser/MutatingScope.php @@ -79,6 +79,7 @@ use PHPStan\Type\Constant\ConstantStringType; use PHPStan\Type\ConstantTypeHelper; use PHPStan\Type\ErrorType; +use PHPStan\Type\FloatRangeType; use PHPStan\Type\GeneralizePrecision; use PHPStan\Type\Generic\TemplateTypeHelper; use PHPStan\Type\Generic\TemplateTypeMap; @@ -124,6 +125,7 @@ use function in_array; use function is_string; use function ltrim; +use function max; use function md5; use function min; use function preg_match; @@ -136,6 +138,7 @@ use function substr; use function uksort; use function usort; +use const INF; use const PHP_INT_MAX; use const PHP_INT_MIN; @@ -5176,6 +5179,7 @@ private function generalizeType(Type $a, Type $b, int $depth): Type $constantArrays = ['a' => [], 'b' => []]; $generalArrays = ['a' => [], 'b' => []]; $integerRanges = ['a' => [], 'b' => []]; + $floatRanges = ['a' => [], 'b' => []]; $otherTypes = []; foreach ([ @@ -5211,6 +5215,10 @@ private function generalizeType(Type $a, Type $b, int $depth): Type $integerRanges[$key][] = $type; continue; } + if ($type instanceof FloatRangeType) { + $floatRanges[$key][] = $type; + continue; + } $otherTypes[] = $type; } @@ -5518,6 +5526,51 @@ private function generalizeType(Type $a, Type $b, int $depth): Type $resultTypes[] = TypeCombinator::union(...$integerRanges['b']); } + // float ranges widen like integer ranges above: a bound that moved + // between the iterations is opened, so a loop accumulating a bounded + // float does not stop at the range the last iteration reached + if (count($floatRanges['a']) > 0) { + if (count($floatRanges['b']) === 0) { + $resultTypes[] = TypeCombinator::union(...$floatRanges['a']); + } else { + $floatRangesA = TypeCombinator::union(...$floatRanges['a']); + $floatRangesB = TypeCombinator::union(...$floatRanges['b']); + + if ($floatRangesA->equals($floatRangesB)) { + $resultTypes[] = $floatRangesA; + } else { + $min = INF; + $max = -INF; + foreach ($floatRanges['a'] as $range) { + $min = min($min, $range->getMin()); + $max = max($max, $range->getMax()); + } + + $newMin = $min; + $newMax = $max; + foreach ($floatRanges['b'] as $range) { + $newMin = min($newMin, $range->getMin()); + $newMax = max($newMax, $range->getMax()); + } + + $gotGreater = $newMax > $max; + $gotSmaller = $newMin < $min; + + if ($gotGreater && $gotSmaller) { + $resultTypes[] = FloatRangeType::fromInterval($newMin, $newMax); + } elseif ($gotGreater) { + $resultTypes[] = FloatRangeType::fromInterval($min, INF); + } elseif ($gotSmaller) { + $resultTypes[] = FloatRangeType::fromInterval(-INF, $max); + } else { + $resultTypes[] = TypeCombinator::union($floatRangesA, $floatRangesB); + } + } + } + } elseif (count($floatRanges['b']) > 0) { + $resultTypes[] = TypeCombinator::union(...$floatRanges['b']); + } + $accessoryTypes = array_map( static fn (Type $type): Type => $type->generalize(GeneralizePrecision::moreSpecific()), TypeUtils::getAccessoryTypes($a), diff --git a/tests/PHPStan/Analyser/nsrt/float-range-loop-generalize.php b/tests/PHPStan/Analyser/nsrt/float-range-loop-generalize.php new file mode 100644 index 00000000000..bb34989f38b --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/float-range-loop-generalize.php @@ -0,0 +1,120 @@ +> $weights */ +function total(array $weights): float +{ + $sum = 0.0; + foreach ($weights as $weight) { + $sum += $weight; + } + assertType('float<0.0, max>', $sum); + if ($sum > 4.0) { + echo "heavy\n"; + } + + return $sum; +} + +/** @param list> $weights */ +function totalInt(array $weights): int +{ + $sum = 0; + foreach ($weights as $weight) { + $sum += $weight; + } + assertType('int<0, max>', $sum); + + return $sum; +} + +/** @param float<0, 1> $step */ +function walk(float $step): float +{ + for ($x = 0.0; $x < 10; $x += $step) { + assertType('float<0.0, 9.999999999999998>', $x); + } + assertType('float<10.0, max>', $x); + + return $x; +} + +/** @param int<0, 1> $step */ +function walkInt(int $step): int +{ + for ($x = 0; $x < 10; $x += $step) { + assertType('int<0, 9>', $x); + } + assertType('int<10, max>', $x); + + return $x; +} + +function dice(int $rolls): float +{ + $total = 0.0; + for ($i = 0; $i < $rolls; $i++) { + $total += random_int(1, 6) / 2; + } + assertType('0.0|float<0.5, max>', $total); + + return $total; +} + +/** @param list> $costs */ +function budget(array $costs): float +{ + $budget = 10.0; + foreach ($costs as $cost) { + $budget -= $cost; + } + assertType('float', $budget); + + return $budget; +} + +/** @param list> $factors */ +function compound(array $factors): float +{ + $amount = 100.0; + foreach ($factors as $factor) { + $amount *= $factor; + } + assertType('float<100.0, max>', $amount); + + return $amount; +} + +/** + * @param list>> $rows + * @return array{total: float} + */ +function nested(array $rows): array +{ + $result = ['total' => 0.0]; + foreach ($rows as $row) { + foreach ($row as $value) { + $result['total'] += $value; + } + } + assertType('array{total: float<0.0, max>}', $result); + + return $result; +} + +/** @param list> $weights */ +function unchanged(array $weights): float +{ + $max = 0.0; + foreach ($weights as $weight) { + if ($weight > $max) { + $max = $weight; + } + } + assertType('float<0.0, 1.0>', $max); + + return $max; +} diff --git a/tests/PHPStan/Rules/Comparison/NumberComparisonOperatorsConstantConditionRuleTest.php b/tests/PHPStan/Rules/Comparison/NumberComparisonOperatorsConstantConditionRuleTest.php index 641e408e303..0bdc2f5a8d0 100644 --- a/tests/PHPStan/Rules/Comparison/NumberComparisonOperatorsConstantConditionRuleTest.php +++ b/tests/PHPStan/Rules/Comparison/NumberComparisonOperatorsConstantConditionRuleTest.php @@ -342,4 +342,9 @@ public function testShiftLeftUnboundedRange(): void $this->analyse([__DIR__ . '/../../Analyser/nsrt/shift-left-unbounded-range.php'], []); } + public function testFloatRangeLoopGeneralize(): void + { + $this->analyse([__DIR__ . '/../../Analyser/nsrt/float-range-loop-generalize.php'], []); + } + } diff --git a/turbo-ext/src/MutatingScope.cpp b/turbo-ext/src/MutatingScope.cpp index 3f1097828e0..9c07853db26 100644 --- a/turbo-ext/src/MutatingScope.cpp +++ b/turbo-ext/src/MutatingScope.cpp @@ -9486,7 +9486,7 @@ class MutatingScope * can be re-wrapped at the end (see the twin's comment) */ bool wrapBenevolent = zv::Ref(a).instanceOf(pt_ce_benevolent_union_type) || zv::Ref(b).instanceOf(pt_ce_benevolent_union_type); - GeneralizeBucket constantIntegers, constantFloats, constantBooleans, constantStrings, constantArrays, generalArrays, integerRanges; + GeneralizeBucket constantIntegers, constantFloats, constantBooleans, constantStrings, constantArrays, generalArrays, integerRanges, floatRanges; zv::Arr otherTypes = zv::Arr::create(0); for (int side = 0; side < 2; side++) { @@ -9532,6 +9532,10 @@ class MutatingScope integerRanges.list[side].push(type); continue; } + if (instanceof_function(ce, pt_ce_float_range_type)) { + floatRanges.list[side].push(type); + continue; + } otherTypes.push(type); } @@ -9938,6 +9942,62 @@ class MutatingScope resultTypes.push(std::move(united)); } + /* float ranges widen like integer ranges (see the twin's comment) */ + if (floatRanges.count(0) > 0) { + if (floatRanges.count(1) == 0) { + zv::Val united = unionOfList(floatRanges.table(0)); + if (UNEXPECTED(united.isUndef())) return zv::Val(); + resultTypes.push(std::move(united)); + } else { + zv::Val floatRangesA = unionOfList(floatRanges.table(0)); + if (UNEXPECTED(floatRangesA.isUndef())) return zv::Val(); + zv::Val floatRangesB = unionOfList(floatRanges.table(1)); + if (UNEXPECTED(floatRangesB.isUndef())) return zv::Val(); + bool same; + if (UNEXPECTED(!typeEquals(floatRangesA.raw(), floatRangesB.raw(), same))) return zv::Val(); + if (same) { + resultTypes.push(std::move(floatRangesA)); + } else { + /* PHP's min()/max() over floats that are never NAN */ + double min = INFINITY, max = -INFINITY; + for (auto rangeEntry : zv::TableRef(floatRanges.table(0))) { + double rangeMin, rangeMax; + if (UNEXPECTED(!pt_float_range_bounds(rangeEntry.value().deref().asObject(), rangeMin, rangeMax))) return zv::Val(); + if (rangeMin < min) min = rangeMin; + if (rangeMax > max) max = rangeMax; + } + + double newMin = min, newMax = max; + for (auto rangeEntry : zv::TableRef(floatRanges.table(1))) { + double rangeMin, rangeMax; + if (UNEXPECTED(!pt_float_range_bounds(rangeEntry.value().deref().asObject(), rangeMin, rangeMax))) return zv::Val(); + if (rangeMin < newMin) newMin = rangeMin; + if (rangeMax > newMax) newMax = rangeMax; + } + + bool gotGreater = newMax > max; + bool gotSmaller = newMin < min; + + zv::Val result; + if (gotGreater && gotSmaller) { + result = pt_float_range_from_interval(newMin, newMax); + } else if (gotGreater) { + result = pt_float_range_from_interval(min, INFINITY); + } else if (gotSmaller) { + result = pt_float_range_from_interval(-INFINITY, max); + } else { + result = unionTypes(floatRangesA.raw(), floatRangesB.raw()); + } + if (UNEXPECTED(result.isUndef())) return zv::Val(); + resultTypes.push(std::move(result)); + } + } + } else if (floatRanges.count(1) > 0) { + zv::Val united = unionOfList(floatRanges.table(1)); + if (UNEXPECTED(united.isUndef())) return zv::Val(); + resultTypes.push(std::move(united)); + } + zv::Val accessoryTypes = pt_type_call_static_ce(pt_ce_type_utils, PT_LC("getaccessorytypes"), 1, a); if (UNEXPECTED(accessoryTypes.isUndef() || Z_TYPE_P(accessoryTypes.raw()) != IS_ARRAY)) return zv::Val(); zv::Arr generalizedAccessories = zv::Arr::create(zend_hash_num_elements(Z_ARRVAL_P(accessoryTypes.raw())));