Skip to content

Narrow the left side of ?? to non-null when a comparison type rules out the right side - #7096

Merged
VincentLanglet merged 5 commits into
phpstan:2.3.xfrom
phpstan-bot:create-pull-request/patch-xg16i6v
Nov 17, 2026
Merged

VincentLanglet merged 5 commits into
phpstan:2.3.xfrom
phpstan-bot:create-pull-request/patch-xg16i6v

Conversation

@phpstan-bot

@phpstan-bot phpstan-bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

if (($x ?? '') == '') return; no longer narrowed ?string $x to non-empty-string in 2.3.6. When a comparison rules out the right side of ??, PHPStan now concludes that the left side is not null.

Changes

  • src/Analyser/ExprHandler/CoalesceHandler.php (createTypesCallback): when the narrowing type rules the right side in (falsey context) or out (truthy context), the left side is narrowed by TypeCombinator::addNull($type) (falsey) or TypeCombinator::removeNull($type) (truthy), instead of by $type alone.
  • src/Analyser/TypeSpecifier.php (createForExpr): same change in the legacy coalesce unwrap, which is still reachable (e.g. MethodSignatureRuleTest::testBug12073).
  • turbo-ext/src/CoalesceHandler.cpp, turbo-ext/src/TypeSpecifier.cpp: native mirrors of both changes. The extension builds with strict warnings, tests/smoke.php prints ALL OK, and the regression test passes with the extension loaded.

Root cause

For $left ?? $right narrowed by a type T:

  • If $right is always in T and the result is not T, the left side was not null. A null left side would have produced $right.
  • If $right is never in T and the result is T, the same holds.

The handler unwrapped the coalesce to its left side but only applied T, so null survived on the left. In 2.3.5 the reported loose case (== '') worked by accident: the loose comparison narrowed by ''|null, which also removed null. Since the loose comparison rework in 2.3.6, that type comes from the coalesce's own non-nullable type (string), so it is just '' and null was no longer removed. The strict forms (=== '', !== '') were broken in 2.3.5 as well.

Test

tests/PHPStan/Analyser/nsrt/bug-15748.php:

  • The reproducer from the issue, plus !=, ===, !==, and integer == 0 / === 0.
  • Analogous cases that failed before:
    • array offset ($a['k'] ?? '') !== ''
    • ($b ?? false) !== false
    • !in_array($x ?? '', [...], true)
    • nullsafe ($o?->bar ?? '') !== ''
    • ($x ?? 'a') === null (now *NEVER*)
  • A case that must not narrow: ($x ?? '') !== 'abc' stays string|null.

All of these fail without the fix. Already correct before the fix: ($i ?? 0) > 0, strlen($x ?? '') > 0, and chained $x ?? $y ?? ''.

Fixes phpstan/phpstan#15748
Fixes phpstan/phpstan#9946

… out the right side

- CoalesceHandler createTypesCallback: when the narrowing type rules the right
  side of `$left ?? $right` in (falsey context, e.g. `($x ?? '') !== ''`) or
  out (truthy context), the left side cannot be null, because a null left side
  would make the coalesce evaluate to the right side. Narrow the left side by
  `$type|null` in the falsey context and `$type` without null in the truthy one.
- Same change in the legacy TypeSpecifier::createForExpr() coalesce unwrap,
  which is still reached (e.g. MethodSignatureRuleTest::testBug12073).
- Mirror both changes in turbo-ext/src/CoalesceHandler.cpp and
  turbo-ext/src/TypeSpecifier.cpp.
- In 2.3.5, `($x ?? '') == ''` happened to narrow through the loose comparison's
  `''|null` type. Since 2.3.6 that type is computed from the coalesce's
  non-nullable type, which lost the null removal. Strict `===`/`!==`, integer
  and bool right sides, `in_array()`, array offsets and nullsafe fetches on the
  left side never narrowed null away; they do now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@VincentLanglet VincentLanglet left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add non-regression test for phpstan/phpstan#9946

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@phpstan-bot

Copy link
Copy Markdown
Collaborator Author

I added the regression test for phpstan/phpstan#9946 that you asked for. It's committed locally as 817ac4212, not pushed.

The test uses the code from the issue's playground link unchanged (($bObj->valA?->value ?? 0) !== 0, then reading $bObj->valA->value), and covers it twice:

  • Rule test: testBug9946 in tests/PHPStan/Rules/Properties/AccessPropertiesRuleTest.php, with data in tests/PHPStan/Rules/Properties/data/bug-9946.php. It expects no errors, where the issue reported "Cannot access property $value on A|null".
  • Type inference test: tests/PHPStan/Analyser/nsrt/bug-9946.php checks that inside the if, $bObj->valA is Bug9946\A and $bObj->valA->value is int<min, -1>|int<1, max>.

Both tests pass with the fix. With the old CoalesceHandler.php and TypeSpecifier.php temporarily put back, both fail as expected: the rule test reports the "Cannot access property" error, and the types come out as A|null and int|null.

make tests passes (23864 tests, 116 skipped) and make phpstan reports no errors.

@VincentLanglet VincentLanglet left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deduplicate the bug-9946 file (which will also solve the Name Collision Detector)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@phpstan-bot

Copy link
Copy Markdown
Collaborator Author

I removed the duplicate bug-9946 file and committed the change locally as b59392868. It isn't pushed.

  • What I changed: I deleted tests/PHPStan/Rules/Properties/data/bug-9946.php. It declared the same Bug9946\A and Bug9946\B classes as tests/PHPStan/Analyser/nsrt/bug-9946.php, which is the name collision CI reported. testBug9946 in AccessPropertiesRuleTest now analyses the nsrt file (__DIR__ . '/../../Analyser/nsrt/bug-9946.php'). The rule test still covers the original reproducer, and the nsrt file keeps the assertType() checks.
  • Tests: make tests passes (23863 tests, 116 skipped) and make phpstan reports no errors.
  • Collision check: make name-collision doesn't run here. The local PHP version can't parse an unrelated file, readonly-property-assign-clone-with.php. I checked by hand instead: the only other Bug9946 declaration is Bug9946\Foo in tests/PHPStan/Rules/Classes/data/bug-9946.php, which doesn't clash with these classes. The CI job will confirm.

@staabm staabm left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment on lines +21 to +25
if (($bObj->valA?->value ?? 0) !== 0) {
assertType('Bug9946\A', $bObj->valA);
assertType('int<min, -1>|int<1, max>', $bObj->valA->value);
$test = $bObj->valA->value;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PHPStan reports this ?-> access is not necessary.

we should assert the types when people don't use ?-> in addition:

Suggested change
if (($bObj->valA?->value ?? 0) !== 0) {
assertType('Bug9946\A', $bObj->valA);
assertType('int<min, -1>|int<1, max>', $bObj->valA->value);
$test = $bObj->valA->value;
}
if (($bObj->valA?->value ?? 0) !== 0) {
assertType('Bug9946\A', $bObj->valA);
assertType('int<min, -1>|int<1, max>', $bObj->valA->value);
$test = $bObj->valA->value;
}
// without null-safe operator
if (($bObj->valA->value ?? 0) !== 0) {
assertType('Bug9946\A', $bObj->valA);
assertType('int<min, -1>|int<1, max>', $bObj->valA->value);
$test = $bObj->valA->value;
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added the case you suggested, without ?->, to tests/PHPStan/Analyser/nsrt/bug-9946.php. It failed: PHPStan inferred Bug9946\A|null for $bObj->valA, and the rule test reported "Cannot access property $value on Bug9946\A|null" twice. So I fixed that as well, in one local commit (c45842962). It isn't pushed.

The gap: ($bObj->valA->value ?? 0) !== 0 narrowed $bObj->valA->value, but not $bObj->valA. Without the fix, ($b->a->value ?? null) !== null doesn't narrow $b->a either. If the comparison rules out the right side of ??, the left side was set. So $bObj->valA can't be null, which is what isset($bObj->valA->value) already concludes.

The fix:

  • src/Analyser/ExprHandler/CoalesceHandler.php: in createTypesCallback, when the comparison type rules the right side in or out, the result now also includes the narrowing that isset() applies to every link in the left chain (createIssetTruthyChainTypes).
  • turbo-ext/src/CoalesceHandler.cpp: the same change in the native version. Its createTypesCallback now also captures $chainResults, like the PHP closure.

Checks:

  • bug-9946.php and AccessPropertiesRuleTest::testBug9946 failed before the fix and pass after it, with and without the extension. bug-15748.php still passes.
  • make tests passes (23863 tests, 116 skipped). The full suite also passes with the turbo extension loaded.
  • The extension builds with the strict warning flags, and tests/smoke.php prints ALL OK.
  • make phpstan reports no errors.

One case is still not narrowed: a bare truthy check like if ($b->a->value ?? false) leaves $b->a as A|null. It goes through a different callback, so I left it out of this PR.

I couldn't see the details of the mutant from the earlier CI run. If the mutation testing job still reports it after this push, the log will show which line needs another test.

phpstan-bot and others added 2 commits November 17, 2026 11:03
Matches the turbo-ext mirror, which already starts from the original type,
and drops the `$exprType ?? $type` fallbacks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Kills the mutants of the true()/false() branch choice in CoalesceHandler and
TypeSpecifier: the negated-true context (`!== true`), legacy
TypeSpecifier::create() calls from type-specifying extensions, and
create() called directly on a coalesce with a nullable type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@phpstan-bot

Copy link
Copy Markdown
Collaborator Author

I added tests that kill the escaped mutants and made one small cleanup in TypeSpecifier. Both are committed locally and not pushed. I couldn't read the linked CI log because there's no GitHub token here. So I rebuilt the likely mutants by hand on the changed lines and checked each one against the new tests. Every one now fails.

Why mutants survived: the code now narrows the left side of ?? with removeNull($type) in a true context and addNull($type) in a false one. Existing tests didn't distinguish those branches from their mutations in three places:

  • true() → truthy(): the two only differ in the negated-true context, which … !== true produces. No test used it, in either CoalesceHandler or TypeSpecifier.
  • Legacy TypeSpecifier::createForExpr() unwrap: in the whole suite only testBug12073 reached it. It's hit when a type-specifying extension calls $typeSpecifier->create() on a coalesce, as is_array() and is_callable() do.
  • The truthy $sureTypes entry in the legacy path: a change there only shows up when the narrowing type itself contains null. No built-in extension passes one, so the only way to test it is to call create() directly.

Commits:

  1. 33e00cb39: createForExpr() now sets $exprType = $type; up front and uses it directly, instead of $exprType ?? $type. That removes the ?? mutants and matches the C++ mirror, which already starts from the original type, so turbo-ext/ needs no change.
  2. 26a953591: the new tests.
    • In tests/PHPStan/Analyser/nsrt/bug-15748.php:
      • is_callable($x ?? 1), is_callable($x ?? 'strlen') !== true and !is_array($z ?? []), which go through the legacy path.
      • (($x ?? '') === '') !== true and a ternary with a ?? branch, which produce the negated-true context.
    • TypeSpecifierTest::testCreateForCoalesce calls create() directly on a coalesce, with a nullable type in a true context and with string in a false context.

Mutants checked: each was applied on its own, and each made at least one new test fail.

  • In CoalesceHandler: true()→truthy(), and swapping the two ternary branches.
  • In TypeSpecifier:
    • the same two mutations
    • removing the assignment
    • putting back the original $type in the false entry
    • putting back the original $type in the true entry

make tests passes (23865 tests, 116 skipped). make phpstan and make cs report no errors.

@VincentLanglet
VincentLanglet merged commit a60e937 into phpstan:2.3.x Nov 17, 2026
1966 of 1979 checks passed
@VincentLanglet
VincentLanglet deleted the create-pull-request/patch-xg16i6v branch November 17, 2026 15:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

condition ($x ?? '') != '' no longer narrows $x to non-null Implicit isset check with null coalescing operator and default value fails

3 participants