From 22569d8e3455443001faf3e980e1929239488621 Mon Sep 17 00:00:00 2001 From: USAMI Kenta Date: Sat, 14 Nov 2026 04:10:40 +0900 Subject: [PATCH 1/4] Do not narrow a comparison operand whose counterpart can be NAN Every ordering comparison with NAN is false, so the false branch of one tells nothing about the side opposite a NAN operand. The narrowing kept NAN on the side it narrowed, but still narrowed each side as if the other one were ordered, which turned a constant into never and cut ranges that the comparison leaves untouched. --- src/Analyser/ExprHandler/BinaryOpHandler.php | 19 +++- tests/PHPStan/Analyser/nsrt/bug-15713.php | 86 +++++++++++++++++++ ...isonOperatorsConstantConditionRuleTest.php | 11 +++ turbo-ext/src/BinaryOpHandler.cpp | 27 +++++- 4 files changed, 137 insertions(+), 6 deletions(-) create mode 100644 tests/PHPStan/Analyser/nsrt/bug-15713.php diff --git a/src/Analyser/ExprHandler/BinaryOpHandler.php b/src/Analyser/ExprHandler/BinaryOpHandler.php index 608399829d4..d5df84fea6a 100644 --- a/src/Analyser/ExprHandler/BinaryOpHandler.php +++ b/src/Analyser/ExprHandler/BinaryOpHandler.php @@ -667,21 +667,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) + && $nanType->isSuperTypeOf($rightType)->no() + ) { $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) + && $nanType->isSuperTypeOf($leftType)->no() + ) { $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), diff --git a/tests/PHPStan/Analyser/nsrt/bug-15713.php b/tests/PHPStan/Analyser/nsrt/bug-15713.php new file mode 100644 index 00000000000..15b3d4eb6b6 --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/bug-15713.php @@ -0,0 +1,86 @@ + $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)); + } + + public function finiteRanges(float $f, float $g): void + { + if (is_nan($f) || is_nan($g)) { + return; + } + if ($f < $g) { + return; + } + assertType('float', $f); + assertType('float', $g); + } + +} diff --git a/tests/PHPStan/Rules/Comparison/NumberComparisonOperatorsConstantConditionRuleTest.php b/tests/PHPStan/Rules/Comparison/NumberComparisonOperatorsConstantConditionRuleTest.php index 4e1074b480a..641e408e303 100644 --- a/tests/PHPStan/Rules/Comparison/NumberComparisonOperatorsConstantConditionRuleTest.php +++ b/tests/PHPStan/Rules/Comparison/NumberComparisonOperatorsConstantConditionRuleTest.php @@ -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 treatPhpDocTypesAsCertain: false in your %configurationFile%.', + ], + ]); + } + public function testShiftLeftUnboundedRange(): void { $this->analyse([__DIR__ . '/../../Analyser/nsrt/shift-left-unbounded-range.php'], []); diff --git a/turbo-ext/src/BinaryOpHandler.cpp b/turbo-ext/src/BinaryOpHandler.cpp index 7eba662c64f..2a0982405ea 100644 --- a/turbo-ext/src/BinaryOpHandler.cpp +++ b/turbo-ext/src/BinaryOpHandler.cpp @@ -1423,6 +1423,17 @@ class BinaryOpHandler return pt_type_combinator_call(PT_LC("union"), 2, args); } + /* (new ConstantFloatType(NAN))->isSuperTypeOf($type)->no() — a NAN operand + * makes the comparison false for every value of the other operand, so the + * false branch tells nothing about a side whose counterpart can be NAN; + * -1 = pending exception */ + static int cannotBeNan(zval *type) + { + zv::Val nan = pt_type_new_constant_float(static_cast(NAN)); + if (UNEXPECTED(nan.isUndef())) return -1; + return superTypeVerdict(nan.raw(), type, PT_TRI_NO); + } + /* $this->defaultNarrowingHelper->createForSubject($subject, $type, * $context, $scope)->setRootExpr($expr) */ zv::Val subjectTypes(zval *subject, zval *type, zval *context, zval *scope, zval *expr) const @@ -1824,7 +1835,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"))); @@ -1835,7 +1852,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"))); From 9aeb7480796e71735178b934253bfb0579511782 Mon Sep 17 00:00:00 2001 From: USAMI Kenta Date: Sat, 14 Nov 2026 04:19:04 +0900 Subject: [PATCH 2/4] Do not invert a count() comparison against an operand that can be NAN The rewrite of count($a) < $x into $x <= count($a) with the negated context holds only under a total order: both comparisons are false for a NAN $x, so the false branch of the first one is not the true branch of the second, and it dropped NAN from $x. --- src/Analyser/ExprHandler/BinaryOpHandler.php | 7 +++++++ tests/PHPStan/Analyser/nsrt/bug-15713.php | 18 ++++++++++++++++++ turbo-ext/src/BinaryOpHandler.cpp | 17 ++++++++++++++++- 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/Analyser/ExprHandler/BinaryOpHandler.php b/src/Analyser/ExprHandler/BinaryOpHandler.php index d5df84fea6a..af21561e00a 100644 --- a/src/Analyser/ExprHandler/BinaryOpHandler.php +++ b/src/Analyser/ExprHandler/BinaryOpHandler.php @@ -372,6 +372,13 @@ 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 the + // false branch of this one is not the true branch of the inverse + !$context->false() + || (new ConstantFloatType(NAN))->isSuperTypeOf($nativeTypesPromoted ? $rightResult->getNativeType() : $rightResult->getType())->no() + ) ) { $inverseOperator = $expr instanceof BinaryOp\Smaller ? new BinaryOp\SmallerOrEqual($expr->right, $expr->left) diff --git a/tests/PHPStan/Analyser/nsrt/bug-15713.php b/tests/PHPStan/Analyser/nsrt/bug-15713.php index 15b3d4eb6b6..410a99cc40c 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-15713.php +++ b/tests/PHPStan/Analyser/nsrt/bug-15713.php @@ -71,6 +71,24 @@ public function minMax(int $r, int $i): void assertType('NAN|int<-5, -1>', min(NAN, $r)); } + /** + * @param array $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)) { diff --git a/turbo-ext/src/BinaryOpHandler.cpp b/turbo-ext/src/BinaryOpHandler.cpp index 2a0982405ea..16a24ce64ad 100644 --- a/turbo-ext/src/BinaryOpHandler.cpp +++ b/turbo-ext/src/BinaryOpHandler.cpp @@ -1462,7 +1462,22 @@ 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 the + // false branch of this one is not the true branch of the inverse + bool contextFalseHere = false; + if (UNEXPECTED(!pt_type_specifier_context_false(Z_OBJ_P(context), contextFalseHere))) return zv::Val(); + if (contextFalseHere) { + 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(); From 6896c23013f3cf617e3bc713f46f93d1ea330d7f Mon Sep 17 00:00:00 2001 From: USAMI Kenta Date: Sat, 14 Nov 2026 04:57:17 +0900 Subject: [PATCH 3/4] Ask whether an operand can be NAN by removing NAN from its type Removing NAN from a type that cannot hold it leaves the type as it was. Asked as isSuperTypeOf() of the NAN constant, never came out as possibly NAN, because every type is a supertype of never. The count() rewrite skips a falsey context rather than only an exactly-false one, which keeps NAN out of the operand where the comparison is known not to be false. --- src/Analyser/ExprHandler/BinaryOpHandler.php | 24 ++++++--- tests/PHPStan/Analyser/nsrt/bug-15713.php | 14 ++++++ turbo-ext/src/BinaryOpHandler.cpp | 52 ++++++++++++++------ turbo-ext/src/generated/BinaryOpHandler.h | 6 ++- 4 files changed, 73 insertions(+), 23 deletions(-) diff --git a/src/Analyser/ExprHandler/BinaryOpHandler.php b/src/Analyser/ExprHandler/BinaryOpHandler.php index af21561e00a..78b49578a5a 100644 --- a/src/Analyser/ExprHandler/BinaryOpHandler.php +++ b/src/Analyser/ExprHandler/BinaryOpHandler.php @@ -374,10 +374,10 @@ static function () use ($expr, $nativeTypesPromoted, $typeCallback): Type { ) && ( // 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 the - // false branch of this one is not the true branch of the inverse - !$context->false() - || (new ConstantFloatType(NAN))->isSuperTypeOf($nativeTypesPromoted ? $rightResult->getNativeType() : $rightResult->getType())->no() + // operand can be NAN: both of them are false for a NAN, so what + // this one being false tells is not what the inverse being true tells + !$context->falsey() + || self::cannotBeNan($nativeTypesPromoted ? $rightResult->getNativeType() : $rightResult->getType()) ) ) { $inverseOperator = $expr instanceof BinaryOp\Smaller @@ -680,7 +680,7 @@ static function () use ($expr, $nativeTypesPromoted, $typeCallback): Type { if ( !$expr->left instanceof Scalar && !($expr->left instanceof Expr\UnaryMinus && $expr->left->expr instanceof Scalar) - && $nanType->isSuperTypeOf($rightType)->no() + && self::cannotBeNan($rightType) ) { $result = $result->unionWith( $this->defaultNarrowingHelper->createForSubject( @@ -694,7 +694,7 @@ static function () use ($expr, $nativeTypesPromoted, $typeCallback): Type { if ( !$expr->right instanceof Scalar && !($expr->right instanceof Expr\UnaryMinus && $expr->right->expr instanceof Scalar) - && $nanType->isSuperTypeOf($leftType)->no() + && self::cannotBeNan($leftType) ) { $result = $result->unionWith( $this->defaultNarrowingHelper->createForSubject( @@ -929,4 +929,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); + } + } diff --git a/tests/PHPStan/Analyser/nsrt/bug-15713.php b/tests/PHPStan/Analyser/nsrt/bug-15713.php index 410a99cc40c..270013e2d60 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-15713.php +++ b/tests/PHPStan/Analyser/nsrt/bug-15713.php @@ -101,4 +101,18 @@ public function finiteRanges(float $f, float $g): void assertType('float', $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); + } + } + } diff --git a/turbo-ext/src/BinaryOpHandler.cpp b/turbo-ext/src/BinaryOpHandler.cpp index 16a24ce64ad..09a8a792fb7 100644 --- a/turbo-ext/src/BinaryOpHandler.cpp +++ b/turbo-ext/src/BinaryOpHandler.cpp @@ -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(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 { @@ -1423,17 +1444,6 @@ class BinaryOpHandler return pt_type_combinator_call(PT_LC("union"), 2, args); } - /* (new ConstantFloatType(NAN))->isSuperTypeOf($type)->no() — a NAN operand - * makes the comparison false for every value of the other operand, so the - * false branch tells nothing about a side whose counterpart can be NAN; - * -1 = pending exception */ - static int cannotBeNan(zval *type) - { - zv::Val nan = pt_type_new_constant_float(static_cast(NAN)); - if (UNEXPECTED(nan.isUndef())) return -1; - return superTypeVerdict(nan.raw(), type, PT_TRI_NO); - } - /* $this->defaultNarrowingHelper->createForSubject($subject, $type, * $context, $scope)->setRootExpr($expr) */ zv::Val subjectTypes(zval *subject, zval *type, zval *context, zval *scope, zval *expr) const @@ -1465,11 +1475,11 @@ class BinaryOpHandler 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 the - // false branch of this one is not the true branch of the inverse - bool contextFalseHere = false; - if (UNEXPECTED(!pt_type_specifier_context_false(Z_OBJ_P(context), contextFalseHere))) return zv::Val(); - if (contextFalseHere) { + // operand can be NAN: both of them are false for a NAN, so what + // this one being false tells is not what the inverse being true tells + bool contextFalseyHere = false; + if (UNEXPECTED(!pt_type_specifier_context_falsey(Z_OBJ_P(context), contextFalseyHere))) return zv::Val(); + if (contextFalseyHere) { zv::Val rightOperandType = specifyOperandType(captures, scope, nativeTypesPromoted, right); if (UNEXPECTED(rightOperandType.isUndef())) return zv::Val(); int rightCannotBeNan = cannotBeNan(rightOperandType.raw()); @@ -2052,6 +2062,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); } diff --git a/turbo-ext/src/generated/BinaryOpHandler.h b/turbo-ext/src/generated/BinaryOpHandler.h index fc6feb1a7dc..11aedaa2961 100644 --- a/turbo-ext/src/generated/BinaryOpHandler.h +++ b/turbo-ext/src/generated/BinaryOpHandler.h @@ -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 */ @@ -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; } // namespace sigtab @@ -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 From a916e03a3146dc9c0f88a1bd3d02ac8a3090ca4b Mon Sep 17 00:00:00 2001 From: USAMI Kenta Date: Sat, 14 Nov 2026 06:33:32 +0900 Subject: [PATCH 4/4] Skip the inverse count() comparison whenever an operand can be NAN Neither branch of count($a) < $x is a branch of $x <= count($a) when $x can be NAN, because both comparisons are false for a NAN. Restricting that to a falsey context left the true branch of the original computed as the false branch of the inverse, where the NAN guard then refused to narrow the count. The general path narrows each side on its own terms and keeps the bound. --- src/Analyser/ExprHandler/BinaryOpHandler.php | 12 +++--- tests/PHPStan/Analyser/nsrt/bug-15713.php | 42 ++++++++++++++++++++ turbo-ext/src/BinaryOpHandler.cpp | 19 ++++----- 3 files changed, 55 insertions(+), 18 deletions(-) diff --git a/src/Analyser/ExprHandler/BinaryOpHandler.php b/src/Analyser/ExprHandler/BinaryOpHandler.php index 78b49578a5a..08c20510ef6 100644 --- a/src/Analyser/ExprHandler/BinaryOpHandler.php +++ b/src/Analyser/ExprHandler/BinaryOpHandler.php @@ -372,13 +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 what - // this one being false tells is not what the inverse being true tells - !$context->falsey() - || self::cannotBeNan($nativeTypesPromoted ? $rightResult->getNativeType() : $rightResult->getType()) - ) + // 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) diff --git a/tests/PHPStan/Analyser/nsrt/bug-15713.php b/tests/PHPStan/Analyser/nsrt/bug-15713.php index 270013e2d60..ae1be18f036 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-15713.php +++ b/tests/PHPStan/Analyser/nsrt/bug-15713.php @@ -115,4 +115,46 @@ public function notFalseContext(array $a, string $s, float $x): void } } + /** + * @param list $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)); + } + } + } diff --git a/turbo-ext/src/BinaryOpHandler.cpp b/turbo-ext/src/BinaryOpHandler.cpp index 09a8a792fb7..dc1d2351773 100644 --- a/turbo-ext/src/BinaryOpHandler.cpp +++ b/turbo-ext/src/BinaryOpHandler.cpp @@ -1475,17 +1475,14 @@ class BinaryOpHandler 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 what - // this one being false tells is not what the inverse being true tells - bool contextFalseyHere = false; - if (UNEXPECTED(!pt_type_specifier_context_falsey(Z_OBJ_P(context), contextFalseyHere))) return zv::Val(); - if (contextFalseyHere) { - 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; - } + // 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};