Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -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 ([
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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),
Expand Down
120 changes: 120 additions & 0 deletions tests/PHPStan/Analyser/nsrt/float-range-loop-generalize.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?php declare(strict_types = 1);

namespace FloatRangeLoopGeneralize;

use function PHPStan\Testing\assertType;

/** @param list<float<0, 1>> $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<int<0, 1>> $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<float<0, 1>> $costs */
function budget(array $costs): float
{
$budget = 10.0;
foreach ($costs as $cost) {
$budget -= $cost;
}
assertType('float<min, 10.0>', $budget);

return $budget;
}

/** @param list<float<1, 2>> $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<list<float<0, 1>>> $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<float<0, 1>> $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;
}
Original file line number Diff line number Diff line change
Expand Up @@ -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'], []);
}

}
62 changes: 61 additions & 1 deletion turbo-ext/src/MutatingScope.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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++) {
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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())));
Expand Down
Loading