Do not let conditional expression undo explicit type narrowing#5710
Merged
ondrejmirtes merged 1 commit intoMay 19, 2026
Merged
Conversation
When filterBySpecifiedTypes processes a condition like `$this->b !== null`, it narrows the expression and then resolves conditional expression holders. A CE chain could derive `$this->a = null` (from mutual exclusion) and then use that to trigger a "remove $this->b from scope" CE, undoing the explicit narrowing. This fix skips certainty-No CEs for expressions that were already narrowed by the original type specifications. Closes phpstan/phpstan#14645
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
if (A && B) throwleaked narrowing across laterif (B !== null)checks, causing "Cannot call method on X|null" false positivefilterBySpecifiedTypes, skip conditional expression holders with certaintyNo(remove from scope) when the target expression was already explicitly narrowed by the current type specificationsRoot cause
When processing
if ($this->b !== null):$this->bis narrowed to non-null (from the condition)$this->bis non-null, then$this->ais null" (from earlier mutual exclusion)$this->ais null, remove$this->bfrom scope" — this undoes the narrowing from step 1Step 3 contradicts the explicit condition. The fix prevents "remove from scope" CEs from overriding expressions that were directly narrowed by the current type specification.
Test plan
tests/PHPStan/Analyser/nsrt/bug-14645.phpfails without fix, passes with fixmake tests— all 12121 tests passmake phpstan— no errorsmake cs-fix— no violationsCloses phpstan/phpstan#14645