Skip to content

fix(algebra): a falsy variable holding a condition narrows to its negation - #14441

Merged
orklah merged 4 commits into
vimeo:masterfrom
jirkace:fix/14253-falsy-flag-negates-its-condition
Nov 22, 2026
Merged

orklah merged 4 commits into
vimeo:masterfrom
jirkace:fix/14253-falsy-flag-negates-its-condition

Conversation

@jirkace

@jirkace jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

A condition stored in a variable narrows only where the variable is truthy: where it is falsy (after if ($flag) { return; }, in if (!$flag) or in the else), the negation of the condition is not applied.

Before

<?php
function earlyReturn(?Node $initial): void {
    $missing = $initial === null;
    if ($missing) {
        return;
    }
    takesNode($initial); // PossiblyNullArgument
}

function elseOfAnInstanceofFlag(Node|Leaf $n): void {
    $is_node = $n instanceof Node;
    if ($is_node) {
        takesNode($n);
    } else {
        takesLeaf($n); // PossiblyInvalidArgument: ... possibly different type Leaf|Node provided
    }
}

After

    takesNode($initial); // no issue
        takesLeaf($n); // no issue

Fixes #14253

…ation vimeo#14253

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

jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Behaviour change

A boolean variable assigned a condition ($flag = <comparison, instanceof, isset, empty, call with assertions, && / ||>) now also gives the converse clause: where $flag is falsy, the negation of the condition holds ($flag || !cond), next to the existing !$flag || cond. The negation is computed by Algebra::negateFormula() like for if (!cond); a condition too complicated to negate keeps only the existing clause.

Effects: fewer PossiblyNull* / PossiblyInvalid* issues after if ($flag) { return; }, in if (!$flag) and in the else of if ($flag); possibly new RedundantCondition / TypeDoesNotContainType where code re-checks what the falsy flag now proves. A falsy && flag still narrows nothing ($both = $a !== null && $b !== null; if (!$both) keeps $a as Node|null, asserted in the new test).

No existing test expectation was edited; the existing stored-condition cases I ran one by one pass (instanceofStoredInVariableNarrowsInIfBody, instanceofStoredInVariableNarrowsAfterEarlyReturn, isArrayStoredInVariableKeptAfterOffsetAssignment, negatedFunctionCallStoredInVariableNarrows, issetAndNotEmptyStoredInVariableNarrow, nullCheckStoredInVariableKeptWhenAnElseLeavesAReassignedVariableAlone, negatedCallWithTooManyAssertionsStoredInVariableDoesNotCrash, notLooselyEqualStoredInVariableIsForgottenWhenABranchAssignsAnEqualValue, flagOnAnArrayOffsetNarrowsItInAnIfOnTheOffset). Full self-analysis reports nothing new.

Not run: the full PHPUnit suite (CI runs it). Run locally: the new test case on the branch (passes) and on master (fails), phpcs, full self-analysis. A corpus check follows.

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

✅ Performance: unchanged · Types: decreased

Project Memory (MB) Wall (s) Issues Weighted (types) Taint
✅ laravel 1 751 96.9 $\color{gray}{\textsf{+0.3\%}}$ 25 908 53 462 682
✅ symfony 3 600 168.8 $\color{gray}{\textsf{-0.4\%}}$ 50 610 $\color{gray}{\textsf{+0}}$ $\color{green}{\textsf{-1}}$ 98 402 $\color{green}{\textsf{-3}}$ 1 528
✅ doctrine-orm 381 21.0 $\color{gray}{\textsf{-0.2\%}}$ 3 480 $\color{gray}{\textsf{+0}}$ $\color{green}{\textsf{-1}}$ 6 142 $\color{green}{\textsf{-1}}$ 0
✅ psl 617 27.1 1 375 5 615 1
✅ phpunit 455 14.5 $\color{gray}{\textsf{+1.4\%}}$ 1 731 3 410 18
✅ php-parser 226 9.6 $\color{gray}{\textsf{+2.1\%}}$ 17 132 21 025 0
✅ tempest 895 27.3 $\color{gray}{\textsf{+1.1\%}}$ 5 047 10 528 252
✅ amphp-amp 68 1.9 $\color{gray}{\textsf{+0.5\%}}$ 29 49 0
✅ webmozarts-assert 272 4.8 $\color{gray}{\textsf{+1.3\%}}$ 575 $\color{gray}{\textsf{+0}}$ $\color{green}{\textsf{-2}}$ 2 714 $\color{green}{\textsf{-6}}$ 0
✅ guzzle-promises 44 1.6 155 434 2
✅ monolog 135 5.8 $\color{gray}{\textsf{+0.5\%}}$ 913 2 479 10
✅ drupal 4 842 182.0 $\color{gray}{\textsf{+1.0\%}}$ 97 591 169 293 583
Total 13 285 561.2 $\color{gray}{\textsf{+0.4\%}}$ 204 546 $\color{gray}{\textsf{+0}}$ $\color{green}{\textsf{-4}}$ 373 553 $\color{green}{\textsf{-10}}$ 3 076
How to read this table
  • Memory: Psalm's own peak figure, threads=1. More than +5 % fails, unless the PR changes composer.json.
  • Wall: base and head run on the same runner; ±10 % is noise. Above +20 % warns, never fails. re-run: a reversed second run was taken and the faster kept.
  • Issues: head count over all categories, then $\color{red}{\textsf{+added}}$ $\color{green}{\textsf{-removed}}$ against base.
  • Weighted (types): type issues weighted by error level (levels 1–8 as is, always-errors 10, strictness checks 1). Taint and dead-code issues are not weighed. The projects' own code is pinned and their dependencies resolve identically for base and head, so a change means Psalm reports more, fewer or differently serious issues. A rise is not necessarily a regression.
  • Taint: head count of Tainted* issues, then $\color{orange}{\textsf{+added}}$ $\color{orange}{\textsf{-removed}}$ against base. Both are orange as either direction needs review: more can be new detection or false positives, fewer can be fixed false positives or lost detection.
  • Dead code: head count of unused-code issues, shown only when a run reported some (findUnusedCode). More is red, fewer is green.
  • Total: sum over the projects compared on both sides. Thresholds apply per project, not to the total.
  • Colors: $\color{red}{\textsf{red}}$ past a fail or warn threshold (or more issues), $\color{green}{\textsf{green}}$ an improvement past noise (or fewer issues), $\color{orange}{\textsf{orange}}$ needs review, $\color{gray}{\textsf{gray}}$ noise.
  • Performance: regressed if a head run crashed or timed out or a memory or wall delta is red, else improved if one is green, else unchanged. Its icon is the check result: ❌ fail · ⚠️ warn · ✅ pass; the icon next to each project is that project's result, 💥 = not comparable: base crashed or timed out (counts as ⚠️).
  • Types (heading): direction of the total weighted change, increased · decreased · unchanged. Taint and Dead code (heading): added and removed counts, present only when non-zero. Informational, never fails the check.
✅ symfony: issues +0 −1

Memory 3 600 → 3 600 MB (<0.1 %) · Wall 169.4 → 168.8 s (−0.4 %)

Weighted 98 405 → 98 402 (−3, <0.01 %): L3 −1

Issue type added removed
PossiblyNullArgument 0 1

Removed (1)

  • src/Symfony/Component/Messenger/Transport/Serialization/SigningSerializer.php:253 PossiblyNullArgument (error): Argument 2 of Symfony\Component\Messenger\Stamp\UnverifiedDecodingFailureStamp::__construct cannot be null, possibly null value provided
✅ doctrine-orm: issues +0 −1

Memory 381 → 381 MB (<0.1 %) · Wall 21.1 → 21.0 s (−0.2 %)

Weighted 6 143 → 6 142 (−1, −0.02 %): L1 −1

Issue type added removed
MixedMethodCall 0 1

Removed (1)

  • src/Tools/DebugUnitOfWorkListener.php:94 MixedMethodCall (error): Cannot determine the type of $value when calling method unwrap
✅ webmozarts-assert: issues +0 −2

Memory 272 → 272 MB (<0.1 %) · Wall 4.7 → 4.8 s (+1.3 %)

Weighted 2 720 → 2 714 (−6, −0.22 %): L3 −2

Issue type added removed
LessSpecificReturnStatement 0 1
MoreSpecificReturnType 0 1

Removed (2)

  • src/Assert.php:1656 MoreSpecificReturnType (error): The declared return type 'lowercase-string' for Webmozart\Assert\Assert::lower is more specific than the inferred return type 'string'
  • src/Assert.php:1677 LessSpecificReturnStatement (error): The type 'string' is more general than the declared return type 'lowercase-string' for Webmozart\Assert\Assert::lower

head 47a7b2e · base c5f4dfd (merge-base) · workflow run

…he variable is null vimeo#14253

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

jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Behaviour change (follow-up)

One existing test expectation changed in ae7ca78: booleanVariableNarrowingNotKeptInElseOfOr

$has = $b !== null;
if ($has || $c) {
    echo 1;
} else {
    echo $b->get(); // was PossiblyNullReference, now NullReference
}

In the else, $has is false, so $b is null: the falsy flag now applies its negation. The issue is still reported, as the test name says (the narrowing to Bag is not kept), only as the more precise NullReference (pinned with its location).

Corpus check (laravel and symfony sources, vs origin/master 4a0667b): no difference.

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks, the direction is right and the corpus removals are all fixed false positives. One problem with how the negation is built:

$right_clauses has already been through Context::filterClauses($var_id, ...), which drops the clauses that mention the assigned variable. Dropping a conjunct weakens the formula, which is fine for the truthy side, but it makes its negation stronger than what the code proves:

function selfRef(?Node $x, bool $ok): void {
    $ok = $x !== null && $ok;
    if (!$ok) {
        if ($x !== null) { echo "reachable"; } // TypeDoesNotContainType on this PR, nothing on master
    }
}

Could you negate the unfiltered formula with FormulaGenerator::getNegatedFormula() (the helper the other negation sites use; it also handles assigning right sides and lossy negations), then filter the result? Something like:

$cond_clauses = $right_clauses; // before filterClauses()
// ...
Context::filterClauses(
    $var_id,
    FormulaGenerator::getNegatedFormula(
        $cond_clauses,
        $assign_value,
        $cond_object_id,
        $context->self,
        $statements_analyzer,
        $codebase,
    ),
),

With that change the case above is clean and your two test cases still pass. Please add the selfRef case as a test.

@jirkace

jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

@orklah thanks, done in 5a45872: the negation is now built from the unfiltered condition with FormulaGenerator::getNegatedFormula() and filtered afterwards with Context::filterClauses(), as you suggested.

Your selfRef snippet is the new case TypeAlgebraTest::falsyStoredConditionThatReadsTheVariableItselfDoesNotNarrow: it reports TypeDoesNotContainType: Type null for $x is always null, so its negation can never be true on the commit before the fix and passes on the current head; the PR's earlier case falsyStoredConditionNarrowsToItsNegation still passes. CI is green apart from label. PHPUnit suite not run locally.

@orklah orklah added the release:fix The PR will be included in 'Fixes' section of the release notes label Nov 22, 2026

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks @jirkace!

@orklah
orklah merged commit 947e6ad into vimeo:master Nov 22, 2026
71 of 72 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release:fix The PR will be included in 'Fixes' section of the release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A stored $x === null flag does not narrow $x after an early return

2 participants