Repository navigation
Return bool from toBoolean() of object, object{} and interfaces that SimpleXMLElement, GMP or BcMath\Number can implement - #6892
Conversation
…es that `SimpleXMLElement`, `GMP` or `BcMath\Number` can implement
- Instances of SimpleXMLElement, GMP and BcMath\Number can cast to false.
ObjectType::toBoolean() already returned `bool` for those classes and
their subclasses. Every other object type returned `true`, so
`if ($object)` was reported as always true.
- Add ObjectType::POSSIBLY_FALSY_CLASSES. ObjectType, ObjectWithoutClassType
and ObjectShapeType::toBoolean() now return `bool` when the type (or a
template's bound) is a supertype of one of these classes. This covers
`object`, `T of object`, `object{}`, `Countable`, `Stringable`,
`Traversable`, `Iterator`, `ArrayAccess` and `T of Countable`. Unrelated
classes, unrelated interfaces, `object{foo: int}` and `object` minus all
three classes stay `true`.
- Port the change to the turbo-ext mirrors: a shared
pt_type_is_super_type_of_possibly_falsy_class() helper, the native
POSSIBLY_FALSY_CLASSES constant, toBoolean() of ObjectWithoutClassType and
ObjectShapeType, and the regenerated declaration headers. Add type-family
coverage for them.
- Update test data that used `object` as an always-truthy example. The
phpDoc-tip tests now use `\stdClass`. The bcmath-number and settype
expectations become `bool`.
- Not changed: the falsey branch of `if ($x)` still narrows these object
types to `*NEVER*`. That comes from StaticTypeFactory::truthy() being
`mixed~falsey`, and changing it broke many unrelated descriptions and
narrowings.
| return new BooleanType(); | ||
| } | ||
|
|
||
| // e.g. Countable or Stringable, implemented by these classes |
There was a problem hiding this comment.
remove the above logic which does the same thing as this added code. if other places exist in the codebase which can be expressed via self::POSSIBLY_FALSY_CLASSES also refactor it
There was a problem hiding this comment.
I removed the hardcoded isInstanceOf('SimpleXMLElement' / 'BcMath\Number' / 'GMP') block in ObjectType::toBoolean(), but I couldn't drop that check entirely as the review asked, because it isn't the same thing as the new code.
Why the old check is still needed: the new code asks whether the type is a supertype of a falsy class (like Countable). The old code asked whether it is a subtype (like class Sx extends \SimpleXMLElement). A subclass is not a supertype of SimpleXMLElement, so with the old block deleted, (bool) $sx became true instead of bool. The Sx assertion in tests/PHPStan/Analyser/nsrt/bug-15617.php caught this and failed.
What I changed instead: toBoolean() now has one loop over self::POSSIBLY_FALSY_CLASSES that returns bool if either $this->isInstanceOf($className) or $type->isSuperTypeOf(new self($className)) says yes. The C++ mirror in turbo-ext/src/ObjectType.cpp now loops over the same native class list instead of the hardcoded { "SimpleXMLElement", "BcMath\\Number", "GMP" } literal.
Other places I checked and left alone: toNumber(), toInteger() and toFloat() check only SimpleXMLElement and GMP, and toString() checks only BcMath\Number and GMP. InvalidIncDecOperationRule lists which objects are allowed in ++/--. These are different sets about numeric or string conversion, not about whether an object can be falsy, so they can't use POSSIBLY_FALSY_CLASSES. There were no other spots that list all three classes.
Verification: make tests and make phpstan pass. The full test suite also passes with the turbo extension loaded. The strict turbo build, smoke.php and signature-parity.php pass too.
The change is one commit, 5f45281a4, pushed to the PR branch.
A background job hit its time limit and was stopped. It was only a loop waiting for the test runs to finish, and it probably never exited because it kept matching its own command line. Nothing is lost: those runs had already finished and passed (make tests, make phpstan, and the full suite with the turbo extension loaded), and commit 5f45281a4 is pushed. There's nothing to restart.
…n ObjectType::toBoolean() Replaces the hardcoded isInstanceOf() checks with the POSSIBLY_FALSY_CLASSES constant. Both checks are still needed: a subclass of SimpleXMLElement is not a supertype of SimpleXMLElement. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| use function PHPStan\Testing\assertType; | ||
|
|
||
| /** @var object $object */ | ||
| /** @var \stdClass $object */ |
There was a problem hiding this comment.
don't change pre-existing phpdoc typese in tests
There was a problem hiding this comment.
I put the original object types back in all the test fixtures I'd changed to \stdClass, not just switch-instanceof-truthy.php. I updated the expected results to match the new behaviour. make tests and make phpstan pass. The change is pushed as commit bc319c7d6.
Fixtures restored: switch-instanceof-truthy.php, boolean-and-not-phpdoc.php, boolean-or-not-phpdoc.php, boolean-not-not-phpdoc.php, if-condition-not-phpdoc.php, elseif-condition-not-phpdoc.php, ternary-not-phpdoc.php, logical-xor.php and constant-condition-function-call.php.
How the expectations changed:
- "Always true" errors removed:
objectcan be a falsyGMP,SimpleXMLElementorBcMath\Number, so conditions on it are no longer reported as always true. I removed those expected errors from the If, ElseIf, Ternary, BooleanAnd, BooleanOr, BooleanNot and LogicalXor rule tests. InLogicalXorConstantConditionRuleTestthis left the$tipTextvariable unused, so I deleted it. switch-instanceof-truthy.php: insidecase $baz instanceof Baz:the type of$bazis now*ERROR*instead ofSwitchInstanceOf\Baz. That is correct: if$objectis a falsyGMP(0), the case also matches when$bazis not aBaz, so PHPStan can no longer narrow it.constant-condition-function-call.php: this fixture exists to test a function whose return value is always truthy, andretObj(): objectno longer is. I keptretObj()as it was. That condition is no longer reported. I added a newretStdClass(): \stdClasscall at the end of the function to keep covering that case. That is new code rather than a changed type, and the expected error moved from line 19 to line 25.
Summary
if ($object)withobject $objectwas reported as "If condition is always true". That is wrong: instances ofGMP,SimpleXMLElementandBcMath\Numbercan cast tofalse. With this change, an object type converts tobool(nottrue) whenever it can hold an instance of one of those classes.Changes
src/Type/ObjectType.php: addsPOSSIBLY_FALSY_CLASSES.toBoolean()still returnsboolfor subtypes of those classes, and now also for supertypes of them (Countable,Stringable,Traversable,Iterator,ArrayAccess, …). For template types it checks the bound.src/Type/ObjectWithoutClassType.php: newtoBoolean()with the same supertype check. This coversobjectandT of object;objectminus all three classes staystrue.src/Type/ObjectShapeType.php: newtoBoolean().object{}givesbool;object{foo: int}staystruebecause none of the three classes satisfy it.turbo-ext/: ports this to the native mirrors.pt_type_is_super_type_of_possibly_falsy_class()inObjectType.cpp.POSSIBLY_FALSY_CLASSESconstant.toBoolean()added toObjectWithoutClassType.cppandObjectShapeType.cpp;ObjectType::toBoolean()extended.generated/ObjectShapeType.handgenerated/ObjectWithoutClassType.h.tests/type-family.phpsubjects:objectminus the falsy classes,Stringable, andCountableminusSimpleXMLElement.true: unrelated classes (Foo), unrelated interfaces (Bar),T of Foo,object{foo: int}.Root cause
ObjectType::toBoolean()only said "maybe falsy" when the type was definitely one of the three classes (isInstanceOf(...)->yes()).ObjectWithoutClassTypeandObjectShapeTypeusedTruthyBooleanTypeTrait. So every type that could still hold such an instance (object,object{}, interfaces those classes implement, templates bounded by them) claimed to be always truthy. The fix asks the type whether it is a supertype of one of these classes, with a template answering through its bound.Not addressed here: in the falsey branch of
if ($x), these types still narrow to*NEVER*, becauseStaticTypeFactory::truthy()ismixed~falsey. I tried also subtracting the three classes fromtruthy(). Narrowing became precise (object→BcMath\Number|GMP|SimpleXMLElementin the else branch), but it changed type descriptions and narrowing results in ~57 unrelated tests, so I left it out.Test
tests/PHPStan/Rules/Comparison/data/bug-15617.phpwithIfConstantConditionRuleTest::testBug15617(): the issue's reproducer verbatim, plusCountable,Stringable,Traversable,ArrayAccess,T of objectandobject{}conditions. These are no longer reported. An unrelated class and an unrelated interface are still reported.tests/PHPStan/Analyser/nsrt/bug-15617.php:(bool)casts of all the probed types,!$object, a ternary, andobjectafter excluding the three classes.objectas an always-truthy example (*-not-phpdoc.php,logical-xor.php,constant-condition-function-call.php,switch-instanceof-truthy.php) now use\stdClass, so they keep testing the same thing. Inbcmath-number.php(Number || object,Number || Stringable) and inset-type-type-specifying.php(settype($object, 'bool')) the expected type is nowbool.make tests(also with the turbo extension loaded),make phpstan, turbosmoke.phpandsignature-parity.php, the strict-warnings turbo build, and identical analysis output with and without the extension.Fixes phpstan/phpstan#15617
🤖 Generated with Claude Code