Skip to content
Merged
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
36 changes: 32 additions & 4 deletions src/Analyser/ExprHandler/BinaryOpHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,11 @@ static function () use ($expr, $nativeTypesPromoted, $typeCallback): Type {
|| !$expr->right->name instanceof Name
|| !in_array(strtolower((string) $expr->right->name), ['count', 'sizeof', 'strlen', 'mb_strlen', 'preg_match'], true)
)
// the inverse operator is not the negation of this one when an operand
// can be NAN: both of them are false for a NAN, so neither branch of
// this one is a branch of the inverse. The general path below narrows
// each side on its own terms instead.
&& self::cannotBeNan($nativeTypesPromoted ? $rightResult->getNativeType() : $rightResult->getType())
) {
$inverseOperator = $expr instanceof BinaryOp\Smaller
? new BinaryOp\SmallerOrEqual($expr->right, $expr->left)
Expand Down Expand Up @@ -667,21 +672,32 @@ static function () use ($expr, $nativeTypesPromoted, $typeCallback): Type {
}
} elseif ($context->false()) {
// NAN is neither smaller nor greater than anything: the false branch keeps it
if (!$expr->left instanceof Scalar && !($expr->left instanceof Expr\UnaryMinus && $expr->left->expr instanceof Scalar)) {
// on the narrowed side, and tells nothing about the other side at all,
// because a NAN operand makes the comparison false for every value of it
$nanType = new ConstantFloatType(NAN);
if (
!$expr->left instanceof Scalar
&& !($expr->left instanceof Expr\UnaryMinus && $expr->left->expr instanceof Scalar)
&& self::cannotBeNan($rightType)
) {
$result = $result->unionWith(
$this->defaultNarrowingHelper->createForSubject(
$expr->left,
TypeCombinator::union($orEqual ? $rightType->getGreaterType($this->phpVersion) : $rightType->getGreaterOrEqualType($this->phpVersion), new ConstantFloatType(NAN)),
TypeCombinator::union($orEqual ? $rightType->getGreaterType($this->phpVersion) : $rightType->getGreaterOrEqualType($this->phpVersion), $nanType),
TypeSpecifierContext::createTruthy(),
$scope,
)->setRootExpr($expr),
);
}
if (!$expr->right instanceof Scalar && !($expr->right instanceof Expr\UnaryMinus && $expr->right->expr instanceof Scalar)) {
if (
!$expr->right instanceof Scalar
&& !($expr->right instanceof Expr\UnaryMinus && $expr->right->expr instanceof Scalar)
&& self::cannotBeNan($leftType)
) {
$result = $result->unionWith(
$this->defaultNarrowingHelper->createForSubject(
$expr->right,
TypeCombinator::union($orEqual ? $leftType->getSmallerType($this->phpVersion) : $leftType->getSmallerOrEqualType($this->phpVersion), new ConstantFloatType(NAN)),
TypeCombinator::union($orEqual ? $leftType->getSmallerType($this->phpVersion) : $leftType->getSmallerOrEqualType($this->phpVersion), $nanType),
TypeSpecifierContext::createTruthy(),
$scope,
)->setRootExpr($expr),
Expand Down Expand Up @@ -911,4 +927,16 @@ private function createRangeTypes(?Expr $rootExpr, Expr $expr, Type $type, TypeS
return (new SpecifiedTypes(sureNotTypes: $sureNotTypes))->setRootExpr($rootExpr);
}

/**
* NAN is the one float that no ordering comparison places, so narrowing by
* such a comparison is sound only for an operand that cannot hold it.
* Removing NAN from a type that cannot hold it leaves the type as it was.
* Asked as isSuperTypeOf() of the NAN constant instead, never would come out
* as possibly NAN, because every type is a supertype of never.
*/
private static function cannotBeNan(Type $type): bool
{
return TypeCombinator::remove($type, new ConstantFloatType(NAN))->equals($type);
}

}
160 changes: 160 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-15713.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
<?php declare(strict_types = 1);

namespace Bug15713;

use function PHPStan\Testing\assertType;

class Foo
{

/**
* @param float<0.0, 1.0> $ratio
* @param non-negative-float $total
*/
public function budget(int $used, float $ratio, float $total): string
{
$limit = $ratio * $total;
assertType('NAN|float<0.0, max>', $limit);
if ($used < $limit) {
return 'ok';
}
assertType('int', $used);
if ($used < 0) {
return 'refund';
}

return 'over';
}

/** @param float<-1.0, 1.0> $x */
public function root(float $x, int $n): void
{
$root = sqrt($x);
assertType('NAN|float<0.0, 1.0>', $root);
if ($root <= $n) {
return;
}
assertType('int', $n);
}

/** @param -1|-2 $n */
public function literalNan(int $n, int $i): void
{
if (NAN >= $n) {
return;
}
assertType('-2|-1', $n);

if ($i < NAN) {
return;
}
assertType('int', $i);
}

public function bothFinite(int $i, float $f): void
{
if (is_nan($f)) {
return;
}
if ($i < $f) {
return;
}
assertType('int', $i);
}

/** @param int<-5, -1> $r */
public function minMax(int $r, int $i): void
{
assertType('NAN|int<-5, -1>', max(NAN, $r));
assertType('NAN|int<-5, -1>', max($r, NAN));
assertType('NAN|int', max(NAN, $i));
assertType('NAN|int<-5, -1>', min(NAN, $r));
}

/**
* @param array<int> $a
* @param float<-1.0, 1.0> $x
*/
public function countAgainstNan(array $a, string $s, float $x): void
{
$root = sqrt($x);
if (count($a) < $root) {
return;
}
assertType('NAN|float<0.0, 1.0>', $root);

if (strlen($s) <= $root) {
return;
}
assertType('NAN|float<0.0, 1.0>', $root);
}

public function finiteRanges(float $f, float $g): void
{
if (is_nan($f) || is_nan($g)) {
return;
}
if ($f < $g) {
return;
}
assertType('float<min, max>', $f);
assertType('float<min, max>', $g);
}

/** @param float<-1.0, 1.0> $x */
public function notFalseContext(array $a, string $s, float $x): void
{
$root = sqrt($x) + 2.0;
assertType('NAN|float<2.0, 3.0>', $root);
// the comparison being anything but false is it being true, which no NAN is
if ((count($a) < $root) !== false) {
assertType('float<2.0, 3.0>', $root);
}
if ((strlen($s) < $root) !== false) {
assertType('float<2.0, 3.0>', $root);
}
}

/**
* @param list<int> $a
* @param NAN|float<0.0, 1.0> $root
* @param float<0.0, 1.0> $safe
*/
public function countBothBranches(array $a, string $s, float $root, float $safe): void
{
// a true ordering comparison rules out NAN, so the count is still bounded
if (count($a) < $root) {
assertType('0', count($a));
assertType('float<5.0E-324, 1.0>', $root);
} else {
assertType('int<0, max>', count($a));
assertType('NAN|float<0.0, 1.0>', $root);
}

if (strlen($s) < $root) {
assertType('0', strlen($s));
} else {
assertType('int<0, max>', strlen($s));
}

if (count($a) <= $root) {
assertType('int<0, 1>', count($a));
}

if (preg_match('/x/', $s) < $root) {
assertType('0|false', preg_match('/x/', $s));
}

// an operand that cannot be NAN narrows as it always did
if (count($a) < $safe) {
assertType('0', count($a));
} else {
assertType('int<0, max>', count($a));
}

if (strlen($s) < $safe) {
assertType('0', strlen($s));
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,17 @@ public function testBug15243(): void
$this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-15243.php'], []);
}

public function testBug15713(): void
{
$this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-15713.php'], [
[
'Comparison operation ">=" between NAN and -2|-1 is always false.',
43,
'Because the type is coming from a PHPDoc, you can turn off this check by setting <fg=cyan>treatPhpDocTypesAsCertain: false</> in your <fg=cyan>%configurationFile%</>.',
],
]);
}

public function testShiftLeftUnboundedRange(): void
{
$this->analyse([__DIR__ . '/../../Analyser/nsrt/shift-left-unbounded-range.php'], []);
Expand Down
61 changes: 58 additions & 3 deletions turbo-ext/src/BinaryOpHandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -815,6 +815,27 @@ class BinaryOpHandler
return pt_specified_types_union_with(Z_OBJ_P(specifiedTypes.raw()), formTypes.raw());
}

/* TypeCombinator::remove($type, new ConstantFloatType(NAN))->equals($type) —
* NAN is the one float that no ordering comparison places, so narrowing by
* such a comparison is sound only for an operand that cannot hold it, and
* removing NAN from such a type leaves the type as it was;
* -1 = pending exception */
static int cannotBeNan(zval *type)
{
zv::Val nan = pt_type_new_constant_float(static_cast<double>(NAN));
if (UNEXPECTED(nan.isUndef())) return -1;
zv::Args args{type, nan.raw()};
zv::Val removed = pt_type_combinator_call(PT_LC("remove"), 2, args);
if (UNEXPECTED(removed.isUndef())) return -1;
if (UNEXPECTED(Z_TYPE_P(removed.raw()) != IS_OBJECT)) {
zend_throw_error(NULL, "Call to a member function equals() on %s", zend_zval_value_name(removed.raw()));
return -1;
}
bool equals = false;
if (UNEXPECTED(!pt_type_op_bool(Z_OBJ_P(removed.raw()), PT_OP_EQUALS, 1, type, equals))) return -1;
return equals ? 1 : 0;
}

/* Mirrors createRangeTypes(); $rootExpr NULL or IS_NULL for null */
zv::Val createRangeTypes(zval *rootExpr, zval *expr, zval *type, zval *context) const
{
Expand Down Expand Up @@ -1451,7 +1472,19 @@ class BinaryOpHandler
NamedCall rightCall;
int rightIsCall = namedCall(right, false, rightCall);
if (UNEXPECTED(rightIsCall < 0)) return zv::Val();
if (!rightIsCall || !lowerNameIn(rightCall.name.get(), { "count", "sizeof", "strlen", "mb_strlen", "preg_match" })) {
bool useInverse = !rightIsCall || !lowerNameIn(rightCall.name.get(), { "count", "sizeof", "strlen", "mb_strlen", "preg_match" });
if (useInverse) {
// the inverse operator is not the negation of this one when an
// operand can be NAN: both of them are false for a NAN, so neither
// branch of this one is a branch of the inverse. The general path
// below narrows each side on its own terms instead.
zv::Val rightOperandType = specifyOperandType(captures, scope, nativeTypesPromoted, right);
if (UNEXPECTED(rightOperandType.isUndef())) return zv::Val();
int rightCannotBeNan = cannotBeNan(rightOperandType.raw());
if (UNEXPECTED(rightCannotBeNan < 0)) return zv::Val();
useInverse = rightCannotBeNan != 0;
}
if (useInverse) {
zv::Args inverseArgv{right, left};
zv::Val inverseOperator = pt_type_new(orEqual ? PT_CLASS_SMALLER_EXPR : PT_CLASS_SMALLER_OR_EQUAL_EXPR, 2, inverseArgv);
if (UNEXPECTED(inverseOperator.isUndef())) return zv::Val();
Expand Down Expand Up @@ -1824,7 +1857,13 @@ class BinaryOpHandler
if (UNEXPECTED(left == NULL)) return zv::Val();
int leftIsScalar = isScalarOrNegatedScalar(left);
if (UNEXPECTED(leftIsScalar < 0)) return zv::Val();
if (!leftIsScalar) {
bool narrowLeft = leftIsScalar == 0;
if (narrowLeft && !contextTrue) {
int rightCannotBeNan = cannotBeNan(rightType.raw());
if (UNEXPECTED(rightCannotBeNan < 0)) return zv::Val();
narrowLeft = rightCannotBeNan != 0;
}
if (narrowLeft) {
zv::Val narrowed = contextTrue
? (orEqual ? comparisonType(rightType.raw(), PT_LC("getsmallerorequaltype")) : comparisonType(rightType.raw(), PT_LC("getsmallertype")))
: withNan(orEqual ? comparisonType(rightType.raw(), PT_LC("getgreatertype")) : comparisonType(rightType.raw(), PT_LC("getgreaterorequaltype")));
Expand All @@ -1835,7 +1874,13 @@ class BinaryOpHandler
if (UNEXPECTED(right == NULL)) return zv::Val();
int rightIsScalar = isScalarOrNegatedScalar(right);
if (UNEXPECTED(rightIsScalar < 0)) return zv::Val();
if (!rightIsScalar) {
bool narrowRight = rightIsScalar == 0;
if (narrowRight && !contextTrue) {
int leftCannotBeNan = cannotBeNan(leftType.raw());
if (UNEXPECTED(leftCannotBeNan < 0)) return zv::Val();
narrowRight = leftCannotBeNan != 0;
}
if (narrowRight) {
zv::Val narrowed = contextTrue
? (orEqual ? comparisonType(leftType.raw(), PT_LC("getgreaterorequaltype")) : comparisonType(leftType.raw(), PT_LC("getgreatertype")))
: withNan(orEqual ? comparisonType(leftType.raw(), PT_LC("getsmallertype")) : comparisonType(leftType.raw(), PT_LC("getsmallerorequaltype")));
Expand Down Expand Up @@ -2014,6 +2059,16 @@ PT_MINIT_REGISTRATION(pt_register_binary_op_handler)
PT_RETURN_VAL(BinaryOpHandler(Z_OBJ_P(ZEND_THIS)).createRangeTypes(rootExpr, expr, type, context));
});

cls.method(sigs::cannotBeNan, [](INTERNAL_FUNCTION_PARAMETERS) {
zval *type;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_OBJECT(type)
ZEND_PARSE_PARAMETERS_END();
int cannot = BinaryOpHandler::cannotBeNan(type);
if (UNEXPECTED(cannot < 0)) RETURN_THROWS();
RETURN_BOOL(cannot != 0);
});

cls.shadow(&pt_ce_binary_op_handler);
pt_expr_handler_entry_register(&pt_ce_binary_op_handler, &BinaryOpHandler::processExprEntry);
}
Expand Down
6 changes: 5 additions & 1 deletion turbo-ext/src/generated/BinaryOpHandler.h
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ inline constexpr char strings[] =
"resolveEqualType\0" /* 1227 */
"rootExpr\0" /* 1244 */
"type\0" /* 1253 */
"createRangeTypes"; /* 1258 */
"createRangeTypes\0" /* 1258 */
"cannotBeNan"; /* 1275 */
inline constexpr reg::PackedArg args[] = {
reg::packed(0, 0, 28), /* __construct $initializerExprTypeResolver */
reg::packed(75, 0, 100), /* __construct $richerScopeGetTypeHelper */
Expand Down Expand Up @@ -140,6 +141,8 @@ inline constexpr reg::PackedArg args[] = {
reg::packed(1253, 0, 972), /* createRangeTypes $type */
reg::packed(846, 0, 1092), /* createRangeTypes $context */
reg::packed(659, 0, 1037), /* createRangeTypes return */
reg::packed(1253, 0, 972), /* cannotBeNan $type */
reg::packed(659, MAY_BE_BOOL), /* cannotBeNan return */
};
using Sig = reg::Sig<strings, args>;
} // namespace sigtab
Expand All @@ -154,6 +157,7 @@ inline constexpr sigtab::Sig specifyRememberedComparisonForms = { { 1130 /* spec
inline constexpr sigtab::Sig getEquivalentComparisonForms = { { 1163 /* getEquivalentComparisonForms */, 2, 30, 2, 32, ZEND_ACC_PRIVATE } };
inline constexpr sigtab::Sig resolveEqualType = { { 1227 /* resolveEqualType */, 4, 33, 4, 37, ZEND_ACC_PRIVATE } };
inline constexpr sigtab::Sig createRangeTypes = { { 1258 /* createRangeTypes */, 4, 38, 4, 42, ZEND_ACC_PRIVATE } };
inline constexpr sigtab::Sig cannotBeNan = { { 1275 /* cannotBeNan */, 1, 43, 1, 44, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } };
} // namespace sig

} // namespace ptdecl::BinaryOpHandler
Expand Down
Loading