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
87 changes: 86 additions & 1 deletion 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 @@ -122,8 +123,10 @@
use function get_class;
use function implode;
use function in_array;
use function is_nan;
use function is_string;
use function ltrim;
use function max;
use function md5;
use function min;
use function preg_match;
Expand All @@ -136,6 +139,8 @@
use function substr;
use function uksort;
use function usort;
use const INF;
use const NAN;
use const PHP_INT_MAX;
use const PHP_INT_MIN;

Expand Down Expand Up @@ -5218,7 +5223,6 @@ private function generalizeType(Type $a, Type $b, int $depth): Type

$resultTypes = [];
foreach ([
$constantFloats,
$constantBooleans,
$constantStrings,
] as $constantTypes) {
Expand Down Expand Up @@ -5378,6 +5382,16 @@ private function generalizeType(Type $a, Type $b, int $depth): Type
$resultTypes[] = TypeCombinator::union(...$generalArrays['b']);
}

if (count($constantFloats['a']) > 0) {
if (count($constantFloats['b']) === 0) {
$resultTypes[] = TypeCombinator::union(...$constantFloats['a']);
} else {
$resultTypes[] = $this->generalizeConstantFloats($constantFloats['a'], $constantFloats['b']);
}
} elseif (count($constantFloats['b']) > 0) {
$resultTypes[] = TypeCombinator::union(...$constantFloats['b']);
}

if (count($constantIntegers['a']) > 0) {
if (count($constantIntegers['b']) === 0) {
$resultTypes[] = TypeCombinator::union(...$constantIntegers['a']);
Expand Down Expand Up @@ -5534,6 +5548,77 @@ private function generalizeType(Type $a, Type $b, int $depth): Type
), ...$otherTypes);
}

/**
* Constant floats widen like the constant integers in generalizeType(): a
* bound that moved between the iterations is opened. NAN has no place in
* the order, so it is set aside and added back to the result.
*
* @param non-empty-list<ConstantFloatType> $a
* @param non-empty-list<ConstantFloatType> $b
*/
private function generalizeConstantFloats(array $a, array $b): Type
{
$constantFloatsA = TypeCombinator::union(...$a);
$constantFloatsB = TypeCombinator::union(...$b);
if ($constantFloatsA->equals($constantFloatsB)) {
return $constantFloatsA;
}

$hasNan = false;
$orderedA = [];
foreach ($a as $float) {
if (is_nan($float->getValue())) {
$hasNan = true;
continue;
}
$orderedA[] = $float;
}
$orderedB = [];
foreach ($b as $float) {
if (is_nan($float->getValue())) {
$hasNan = true;
continue;
}
$orderedB[] = $float;
}

if ($orderedA === [] || $orderedB === []) {
$result = TypeCombinator::union(...$orderedA, ...$orderedB);
} else {
$min = INF;
$max = -INF;
foreach ($orderedA as $float) {
$min = min($min, $float->getValue());
$max = max($max, $float->getValue());
}

$newMin = $min;
$newMax = $max;
foreach ($orderedB as $float) {
$newMin = min($newMin, $float->getValue());
$newMax = max($newMax, $float->getValue());
}

$gotGreater = $newMax > $max;
$gotSmaller = $newMin < $min;
if ($gotGreater && $gotSmaller) {
$result = FloatRangeType::fromInterval($newMin, $newMax);
} elseif ($gotGreater) {
$result = FloatRangeType::fromInterval($min, INF);
} elseif ($gotSmaller) {
$result = FloatRangeType::fromInterval(-INF, $max);
} else {
$result = TypeCombinator::union(...$orderedA, ...$orderedB);
}
}

if ($hasNan) {
return TypeCombinator::union($result, new ConstantFloatType(NAN));
}

return $result;
}

private static function getArrayDepth(Type $type): int
{
$depth = 0;
Expand Down
94 changes: 94 additions & 0 deletions tests/PHPStan/Analyser/nsrt/float-constant-loop-generalize.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php declare(strict_types = 1);

namespace FloatConstantLoopGeneralize;

use function PHPStan\Testing\assertType;

/** @param non-negative-float $x */
function takesNonNegativeFloat(float $x): void
{
}

/** @param non-negative-int $x */
function takesNonNegativeInt(int $x): void
{
}

/** @param list<string> $items */
function constantStep(array $items): void
{
$total = 0.0;
foreach ($items as $item) {
$total += 1.5;
}
assertType('0.0|1.5|float<3.0, max>', $total);
takesNonNegativeFloat($total);

$count = 0;
foreach ($items as $item) {
$count += 2;
}
assertType('0|2|int<4, max>', $count);
takesNonNegativeInt($count);
}

function counter(int $limit): void
{
for ($x = 0.0; $x < $limit; $x += 0.25) {
assertType('0.0|float<0.25, max>', $x);
}

for ($i = 0; $i < $limit; $i += 1) {
assertType('int<0, max>', $i);
}
}

/** @param list<string> $items */
function decreasing(array $items): void
{
$budget = 10.0;
foreach ($items as $item) {
$budget -= 0.5;
}
assertType('9.5|10.0|float<min, 9.0>', $budget);
}

/** @param list<string> $items */
function halving(array $items): void
{
$size = 1.0;
foreach ($items as $item) {
$size /= 2;
}
assertType('0.5|1.0|float<min, 0.25>', $size);
}

/** @param list<string> $items */
function withNan(array $items, bool $b): void
{
$value = $b ? NAN : 0.0;
foreach ($items as $item) {
$value += 1.0;
}
assertType('0.0|1.0|NAN|float<2.0, max>', $value);
}

/** @param list<string> $items */
function onlyNan(array $items): void
{
$value = NAN;
foreach ($items as $item) {
$value = 2.0;
}
assertType('2.0|NAN', $value);
}

/** @param list<string> $items */
function toggled(array $items): void
{
$sign = 1.0;
foreach ($items as $item) {
$sign = -$sign;
}
assertType('float<min, max>', $sign);
}
Original file line number Diff line number Diff line change
Expand Up @@ -171,11 +171,19 @@ public function testStrictComparison(): void
368,
],
[
'Strict comparison using === between float and \'string\' will always evaluate to false.',
'Strict comparison using === between 2.0|float<min, 0.4> and 1000000.0 will always evaluate to false.',
383,
],
[
'Strict comparison using === between 2.0|float<min, 0.4> and \'string\' will always evaluate to false.',
386,
],
[
'Strict comparison using === between float and \'string\' will always evaluate to false.',
'Strict comparison using === between 2.0|10.0|float<min, 0.4> and 1000000.0 will always evaluate to false.',
391,
],
[
'Strict comparison using === between 2.0|10.0|float<min, 0.4> and \'string\' will always evaluate to false.',
394,
],
[
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3664,4 +3664,9 @@ public function testUnknownDefaultValue(): void
]);
}

public function testFloatConstantLoopGeneralize(): void
{
$this->analyse([__DIR__ . '/../../Analyser/nsrt/float-constant-loop-generalize.php'], []);
}

}
83 changes: 81 additions & 2 deletions turbo-ext/src/MutatingScope.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,7 @@ extern "C" {
#include "zend_smart_str.h"

#include <cctype>
#include <cmath>
#include <cstring>

zend_class_entry *pt_ce_mutating_scope = nullptr;
Expand Down Expand Up @@ -9412,6 +9413,72 @@ class MutatingScope

/* the 'a' / 'b' pair of type lists generalizeType() sorts its inputs
* into (the twin's `['a' => [], 'b' => []]`) */
/* private (twin generalizeConstantFloats()) — constant floats widen
* like constant integers, NAN set aside; UNDEF = pending exception */
zv::Val generalizeConstantFloats(HashTable *a, HashTable *b)
{
zv::Val constantFloatsA = unionOfList(a);
if (UNEXPECTED(constantFloatsA.isUndef())) return zv::Val();
zv::Val constantFloatsB = unionOfList(b);
if (UNEXPECTED(constantFloatsB.isUndef())) return zv::Val();
bool same;
if (UNEXPECTED(!typeEquals(constantFloatsA.raw(), constantFloatsB.raw(), same))) return zv::Val();
if (same) return constantFloatsA;

bool hasNan = false;
zv::Arr ordered[2] = { zv::Arr::create(0), zv::Arr::create(0) };
HashTable *sides[2] = { a, b };
for (int side = 0; side < 2; side++) {
for (auto entry : zv::TableRef(sides[side])) {
double value;
if (UNEXPECTED(!pt_constant_float_get_value(entry.value().deref().asObject(), value))) return zv::Val();
if (std::isnan(value)) {
hasNan = true;
continue;
}
ordered[side].push(entry.value().deref());
}
}

zv::Val result;
if (zend_hash_num_elements(ordered[0].table()) == 0 || zend_hash_num_elements(ordered[1].table()) == 0) {
result = unionOfLists(ordered[0].table(), ordered[1].table());
} else {
double min = INFINITY, max = -INFINITY;
for (auto entry : zv::TableRef(ordered[0].table())) {
double value;
if (UNEXPECTED(!pt_constant_float_get_value(entry.value().deref().asObject(), value))) return zv::Val();
if (value < min) min = value;
if (value > max) max = value;
}
double newMin = min, newMax = max;
for (auto entry : zv::TableRef(ordered[1].table())) {
double value;
if (UNEXPECTED(!pt_constant_float_get_value(entry.value().deref().asObject(), value))) return zv::Val();
if (value < newMin) newMin = value;
if (value > newMax) newMax = value;
}

bool gotGreater = newMax > max;
bool gotSmaller = newMin < min;
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 = unionOfLists(ordered[0].table(), ordered[1].table());
}
}
if (UNEXPECTED(result.isUndef())) return zv::Val();

if (!hasNan) return result;
zv::Val nan = pt_type_new_constant_float(NAN);
if (UNEXPECTED(nan.isUndef())) return zv::Val();
return unionTypes(result.raw(), nan.raw());
}

struct GeneralizeBucket
{
zv::Arr list[2];
Expand Down Expand Up @@ -9538,8 +9605,8 @@ class MutatingScope
}

zv::Arr resultTypes = zv::Arr::create(0);
GeneralizeBucket *scalarBuckets[3] = { &constantFloats, &constantBooleans, &constantStrings };
for (uint32_t i = 0; i < 3; i++) {
GeneralizeBucket *scalarBuckets[2] = { &constantBooleans, &constantStrings };
for (uint32_t i = 0; i < 2; i++) {
GeneralizeBucket &bucket = *scalarBuckets[i];
if (bucket.count(0) == 0) {
if (bucket.count(1) > 0) {
Expand Down Expand Up @@ -9806,6 +9873,18 @@ class MutatingScope
resultTypes.push(std::move(united));
}

if (constantFloats.count(0) > 0) {
zv::Val united = constantFloats.count(1) == 0
? unionOfList(constantFloats.table(0))
: generalizeConstantFloats(constantFloats.table(0), constantFloats.table(1));
if (UNEXPECTED(united.isUndef())) return zv::Val();
resultTypes.push(std::move(united));
} else if (constantFloats.count(1) > 0) {
zv::Val united = unionOfList(constantFloats.table(1));
if (UNEXPECTED(united.isUndef())) return zv::Val();
resultTypes.push(std::move(united));
}

if (constantIntegers.count(0) > 0) {
if (constantIntegers.count(1) == 0) {
zv::Val united = unionOfList(constantIntegers.table(0));
Expand Down
Loading
Loading