Skip to content

fix(mixed): a non-empty mixed is never a falsy value, nor an empty mixed a truthy one - #12672

Merged
orklah merged 11 commits into
vimeo:masterfrom
jirkace:fix/8511-non-empty-mixed-container
Nov 21, 2026
Merged

orklah merged 11 commits into
vimeo:masterfrom
jirkace:fix/8511-non-empty-mixed-container

Conversation

@jirkace

@jirkace jirkace commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

A non-empty-mixed was treated as possibly identical to any type, so a conditional return type kept the branch for a falsy condition ($arg is false) for an argument that cannot be falsy.

Before:

/**
 * @param mixed $arg
 * @return ($arg is false ? string|false : int)
 */
function bar($arg) {}

/** @var mixed $foo */
if (!empty($foo)) {
    $result = bar($foo); // false|int|string
    if ($foo === false) {} // no issue
}

After:

/**
 * @param mixed $arg
 * @return ($arg is false ? string|false : int)
 */
function bar($arg) {}

/** @var mixed $foo */
if (!empty($foo)) {
    $result = bar($foo); // int
    if ($foo === false) {} // TypeDoesNotContainType
}

Fixes #8511

…xed a truthy one vimeo#8511

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ktu9y737NuDDE88xCYTSix
@jirkace

jirkace commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

Behaviour change: non-empty-mixed and empty-mixed are no longer "possibly identical" to every type. A strict comparison of a non-empty-mixed with an always-falsy value (false, null, 0, '') is now TypeDoesNotContainType/DocblockTypeContradiction, and the same for an empty-mixed with an always-truthy one. A conditional return type on such an argument takes the branch the argument can be in (($arg is false ? A : B) with a non-empty-mixed gives B).

# Conflicts:
#	tests/Template/ConditionalReturnTypeTest.php
@github-actions

github-actions Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

✅ Performance: unchanged · Types: increased

Project Memory (MB) Wall (s) Issues Weighted (types) Taint
✅ laravel 1 765 72.7 $\color{gray}{\textsf{-1.1\%}}$ 25 917 $\color{gray}{\textsf{+0}}$ $\color{green}{\textsf{-1}}$ 53 208 $\color{green}{\textsf{-2}}$ 578
✅ symfony 3 622 198.6 $\color{gray}{\textsf{-1.5\%}}$ 50 660 $\color{red}{\textsf{+1}}$ $\color{green}{\textsf{-1}}$ 98 733 1 443
✅ doctrine-orm 393 14.7 $\color{gray}{\textsf{+0.8\%}}$ 3 479 6 160 0
✅ psl 632 17.8 $\color{gray}{\textsf{+1.0\%}}$ 1 305 5 461 1
✅ phpunit 471 20.1 $\color{gray}{\textsf{-1.6\%}}$ 1 742 3 452 17
✅ php-parser 236 13.9 $\color{gray}{\textsf{+0.4\%}}$ 17 133 21 035 0
✅ tempest 899 36.0 $\color{gray}{\textsf{-0.6\%}}$ 5 021 10 514 221
✅ amphp-amp 61 1.6 $\color{gray}{\textsf{-1.2\%}}$ 29 49 0
✅ webmozarts-assert 285 3.5 $\color{gray}{\textsf{+0.9\%}}$ 577 2 722 0
✅ guzzle-promises 55 1.7 $\color{gray}{\textsf{+6.8\%}}$ 158 435 2
✅ monolog 153 4.5 $\color{gray}{\textsf{-1.1\%}}$ 903 2 403 10
✅ drupal 4 821 293.1 $\color{gray}{\textsf{-4.4\%}}$ 97 527 $\color{red}{\textsf{+1}}$ $\color{gray}{\textsf{-0}}$ 169 335 $\color{red}{\textsf{+4}}$ 508
Total 13 395 678.2 $\color{gray}{\textsf{-2.5\%}}$ 204 451 $\color{red}{\textsf{+2}}$ $\color{green}{\textsf{-2}}$ 373 507 $\color{red}{\textsf{+2}}$ 2 780
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.
✅ laravel: issues +0 −1

Memory 1 765 → 1 765 MB (<0.1 %) · Wall 73.5 → 72.7 s (−1.1 %)

Weighted 53 210 → 53 208 (−2, <0.01 %): L2 −1

Issue type added removed
RedundantConditionGivenDocblockType 0 1

Removed (1)

  • src/Illuminate/Support/Str.php:349 RedundantConditionGivenDocblockType (error): Operand of type true is always truthy
✅ symfony: issues +1 −1

Memory 3 622 → 3 622 MB (<0.1 %) · Wall 201.7 → 198.6 s (−1.5 %)

Issue type added removed
MixedArgument 0 1
MixedReturnStatement 1 0

Added (1)

  • src/Symfony/Component/Emoji/EmojiTransliterator.php:117 MixedReturnStatement (error): Possibly-mixed return value

Removed (1)

  • src/Symfony/Component/HttpClient/NativeHttpClient.php:273 MixedArgument (error): Argument 6 of Symfony\Component\HttpClient\NativeHttpClient::createRedirectResolver cannot be Closure[impure](mixed...):never|Closure[read-props]():never|empty-mixed, expecting Closure[impure]|null
✅ drupal: issues +1 −0

Memory 4 821 → 4 821 MB (<0.1 %) · Wall 306.6 → 293.1 s (−4.4 %)

Weighted 169 331 → 169 335 (+4, <0.01 %): L4 +1

Issue type added removed
RedundantCondition 1 0

Added (1)

  • core/includes/install.core.inc:874 RedundantCondition (error): non-empty-mixed can never be false

head f0e0aed · base 67cfa84 (merge-base) · workflow run

jirkace and others added 3 commits November 11, 2026 10:35
# Conflicts:
#	tests/TypeReconciliation/EmptyTest.php
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@jirkace

jirkace commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

Checked the report's findings against current master (07f4c6d) by running this PR's cases singly: conditionalReturnTypeOnNonEmptyMixedTakesTheElseBranchOfAFalsyCondition, nonEmptyMixedIsNeverFalse, nonEmptyMixedIsNeverAnEmptyString and emptyMixedIsNeverTrue fail on master and pass here, while conditionalReturnTypeOnNonEmptyMixedKeepsBothBranchesOfATruthyCondition, nonEmptyMixedMayStillBeAnyTruthyValue and emptyMixedMayStillBeAnyFalsyValue pass on master (they guard the limits of the change).

Not changed, read only: finding 1 (canExpressionTypesBeIdentical() has about ten callers, so the new rule reaches every identity check on a non-empty-mixed), 2 (possibly_undefined unions), 3 (TypeDoesNotContainType vs DocblockTypeContradiction in the invalid cases) and 4 (moving isDisjoint() ahead of the containment fallback in replaceConditional() changes every conditional type, not only mixed; the perf run is the evidence for that one).

Ran: the seven cases on master. No code change pushed.

@alies-dev alies-dev 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.

🤖 The comparator change is at the right layer, but the reorder in TemplateInferredTypeReplacer introduces a regression for a template-param argument, visible in the perf report as new errors on Laravel.

Already fixed on master: no. On upstream/master the issue's example traces $result as false|int|string; at the PR head it is int.

Overlap / conflicts: conflicts with current master in UnionTypeComparator.php only because master added hasTemplateKeyOrValueOf() right where this PR inserts isMixedOfOppositeTruthiness(); trivial. No alternative PR.

Findings

  1. src/Psalm/Internal/Type/TemplateInferredTypeReplacer.php:551: calling isDisjoint() before intersectUnionTypes() makes a conditional return resolve to the else branch when the argument is a generated template param whose bound is mixed. Repro (PR head vs its merge-base):
/**
 * @param mixed $arg
 * @return ($arg is (Countable|array<mixed>) ? string : int)
 */
function inner($arg) { return 1; }

/**
 * @param mixed $arg
 * @return ($arg is (Countable|array<mixed>) ? string : int)
 */
function outer($arg) { $r = inner($arg); /** @psalm-trace $r */ echo 1; return $r; }

$r is int|string on the base and int on the PR (a plain mixed parameter stays int|string). Laravel's Eloquent\Builder::findOrFail() has exactly this shape (find($id) with ($id is Arrayable|array ? Collection<int, TModel> : TModel|null)), and the perf report shows count($result) going from PossiblyInvalidArgument to InvalidArgument on TModel|null at Builder.php:667, HasOneOrManyThrough.php:495 and :534, (the BelongsToMany.php lines only change message text). Reverting only the reorder restores int|string here but also brings back false|int|string for the issue's own example, so the reorder is needed and must be narrowed: let isDisjoint() look through a TTemplateParam candidate to its as type (a template whose bound is mixed is never decidably disjoint), and add a test for a template-param argument.

Recommendations (non-blocking)

  • Sibling gap: after if (empty($foo)) return;, $foo === false, === "" and === 0 now report TypeDoesNotContainType, but $foo === null still reports nothing at the PR head (null is just as falsy). If that path is a separate shortcut in AssertionFinder, a test or a note would help.
  • canExpressionTypesBeIdentical() has about 25 callers (in_array provider, shape comparators, TypeVariableTracker, purity analyzers); the new TypeDoesNotContainType/DocblockTypeContradiction results for non-empty-mixed are correct, but one in_array() or array-shape case would show the blast radius is understood.

jirkace and others added 2 commits November 18, 2026 10:04
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…t from a conditional's type

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

jirkace commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Pushed a3c81e2 (master merged in earlier at 3eed2a6; the UnionTypeComparator.php conflict kept both isMixedOfOppositeTruthiness() and master's hasTemplateKeyOrValueOf()).

TemplateInferredTypeReplacer::isDisjoint() now looks through a TTemplateParam candidate to its bound: a template is disjoint from the condition only if every atomic of its bound is, so one bounded by mixed is never decidably disjoint. Added conditionalReturnOfAMixedTemplateArgumentKeepsBothBranches (the inner() / outer() snippet from the review, $r is int|string); it fails on the previous head with $r = int, passes now. The 7 cases this PR added pass as before.

Not done: the $foo === null sibling after if (empty($foo)) return; and a case showing the canExpressionTypesBeIdentical() blast radius (in_array() / shapes).

Run: the cases above one by one, phpcs, a full self-analysis (clean). Not run: the whole suite and laravel, so the Builder.php:667 / HasOneOrManyThrough.php deltas are not re-checked.

… empty mixed a truthy one

`$foo === null` after `empty($foo) → return` reported nothing although
`=== false` did: the comparator accepted any atomic in a TNonEmptyMixed
container. Same rule as the identity check added earlier in this PR.

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

jirkace commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Pushed f49e30f for the two non-blocking notes.

  • $foo === null after if (empty($foo)) return;: it reported nothing because AtomicTypeComparator accepted any atomic in a non-empty-mixed container (the === false path goes through canExpressionTypesBeIdentical(), === null through the reconciler). The comparator now rejects a falsy atomic for non-empty-mixed and a truthy one for empty-mixed. New case nonEmptyMixedIsNeverNull (fails on the previous head, passes now).
  • Blast radius of canExpressionTypesBeIdentical(): added nonEmptyMixedIsNeverInAListOfFalsyValues (in_array($foo, [0, "", null], true) after !empty($foo) reports TypeDoesNotContainType). It already passed before this commit, so it is a guard, not a regression test. I did not add cases for the other ~25 callers (shape comparators, TypeVariableTracker, purity analyzers).

Run: the two new cases single, plus 12 neighbouring single cases that mention non-empty-mixed (ForeachTest, ClosureTest, IssetTest, ScopeTest, ConditionalTest, ReconcilerTest-adjacent, etc.), all passing; self-analysis clean. Not run: the full suite (CI).

…xed comparison

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

jirkace commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

From the triage report generated 2026-11-19 05:16 UTC (reviewed head f49e30f); pushed dfe2f1f (tests only).

  • Minor finding 3 (the invalid cases pin only the issue type): the five invalid cases of this PR in EmptyTest now pin the position and the message (non-empty-mixed does not contain false, '' cannot be identical to non-empty-mixed, empty-mixed does not contain true, non-empty-mixed does not contain null, Operand of type false is always falsy). The difference the review noticed is real and still unexplained by me: empty-mixed against true is reported as DocblockTypeContradiction, the non-empty-mixed cases as TypeDoesNotContainType; I did not look into why.
  • Not done: findings 1 (the perf report of the reorder in replaceConditional() was not re-run on this head, I do not have those projects) and 2 (non-empty-mixed|null-like unions, possibly_undefined unions, untested 0.0/'0'/[] literals, the other ~25 callers of canExpressionTypesBeIdentical()).

Ran single: the five cases (pass), self-analysis clean (the first push attempt failed phpcs on a missing DIRECTORY_SEPARATOR import). Not run: the full suite (CI).

@jirkace

jirkace commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Local benchmark run for the triage report's perf findings (the benchmark runner itself is not available to me): Psalm on src/Illuminate of laravel/framework (shallow clone of its default branch, errorLevel 1, PHP 8.3, ensureArrayStringOffsetsExist, no baseline, --no-cache), this branch merged with current master vs master itself, issues compared as sorted lines.

  • fix(mixed): a non-empty mixed is never a falsy value, nor an empty mixed a truthy one #12672: +14 / -15, but the 14 added ones are the same 14 InvalidReturnType/InvalidReturnStatement of Http/Client/PendingRequest.php (860-974) with a different inferred type in the message (LazyPromise|Response instead of LazyPromise); one real removal, Support/Str.php:349 RedundantConditionGivenDocblockType. The review's Builder.php:667, HasOneOrManyThrough.php:495/534 deltas do not appear.

Limits: laravel only. Not run: the full suite (CI).

@alies-dev alies-dev 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.

🤖 Re-checked against the current head: nothing blocks this anymore, and it is ready to merge. Since the last review, other PRs landed on master and this branch now conflicts in src/Psalm/Internal/Type/TemplateInferredTypeReplacer.php, tests/Template/ConditionalReturnTypeTest.php and tests/TypeReconciliation/EmptyTest.php (mostly after #12883 and #12985). Please rebase onto master and keep both sides' test cases; I'll merge once CI is green.

jirkace and others added 2 commits November 20, 2026 02:50
# Conflicts:
#	src/Psalm/Internal/Type/TemplateInferredTypeReplacer.php
#	tests/Template/ConditionalReturnTypeTest.php
#	tests/TypeReconciliation/EmptyTest.php
…only when none of its parts can be of it

Master's conditionalOnClosureKeepsTheIfBranchForAnInterfaceNarrowedToClosure: Factory&Closure is not
contained by Closure in the comparator, so the whole-type check alone took it for disjoint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@orklah orklah added the release:fix The PR will be included in 'Fixes' section of the release notes label Nov 21, 2026
@orklah
orklah merged commit 8be1469 into vimeo:master Nov 21, 2026
70 of 71 checks passed
@orklah

orklah commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator

Thanks @jirkace!

alies-dev added a commit to psalm/psalm-plugin-laravel that referenced this pull request Nov 21, 2026
* build: require Psalm 7.14

- Psalm 7.14 changes what the type fixtures report (PHP deprecations, unrequired-package functions, mixed-widened templates), and the fixtures updated in this PR no longer pass on 7.13.
- Raise the floor in composer.json and in the Symfony Console job of tests.yml.

* test: give the type and emission fixtures the composer.json Psalm 7.14 needs

- Psalm 7.14 counts a vendor function as defined only if the composer.json next to the config requires its package (vimeo/psalm#14413); tests/Type and the EmissionApp fixture have none, so `now()`, `cache()`, `env()`, `trans()`, `route()` and `to_route()` became UndefinedFunction and `mixed` (22 type tests and `EmissionAppTest`).
- The type tests select a differently named `composer.fixture.json` through `COMPOSER`, which leaves the plugin's project-root detection (a `composer.json` in the working directory) untouched.

* test: expect the PHP deprecations Psalm 7.14 reports in collection callback fixtures

- `is_a($string, Class::class)` is deprecated since PHP 8.6 (DeprecatedFunction) and an implicitly nullable parameter since PHP 8.4 (DeprecatedSyntax); Psalm reports both regardless of the analysed PHP version (vimeo/psalm#14413).
- The fixtures keep those shapes because the narrowing of the two-argument `is_a()` and of a `= null` closure parameter is what they pin; the deprecation is now part of `--EXPECTF--`.

* test: pin that an unbounded template given to getOrPut() and queued() now resolves to mixed

- Psalm 7.14 no longer treats a bare template as decidably not a Closure for the `$value is callable` guard (vimeo/psalm#12672), so the result is widened with `mixed` and returning it as the template reports MixedReturnStatement; before, a possible Closure result stayed silent.
- Rename GetOrPutClosureDefaultKnownLimitation.phpt to GetOrPutClosureDefaultUnboundedTemplateTest.phpt (positive coverage) and rewrite the three stub docblocks that cited the limitation.

* test: pin the possibly-empty array-shape unpack of Paginator::fragment() as a known limitation

- Psalm 7.14 unpacks `array{0?: string}` like a `list<string>` (vimeo/psalm#14415), so the call no longer resolves both the getter and the setter branch of `fragment()`; 7.13.2 did.
- Rename PaginatorFragmentUnpackTest.phpt to PaginatorFragmentUnpackKnownLimitation.phpt and rewrite the docblocks of the stub and of RouteDomainKnownLimitation.phpt that cited the old behavior.

* test: suppress Psalm 7.14's static-call false positive on a trait constructor in the Blade taint fixture

- Psalm 7.14 analyses the synthetic constructor call for uninitialised properties as a static call on the parent's trait and reports InvalidStaticInvocation (a regression of vimeo/psalm#14413, reproducible without the plugin).
- `BladeComponentTaintTest::the_bridge_adds_no_non_taint_issue` asserts no other issue, so the fixture class suppresses it.

* fix: accept the value argument in Enumerable::when() and unless() callbacks

- Laravel's Enumerable interface docblock types the callbacks as callable($this) and $value as bool, but Conditionable calls $callback($this, $value) and accepts any value
- Psalm 7.13.2 keeps the concrete $this type in callable($this) (vimeo/psalm#14423), which surfaced the arity mismatch as InvalidScalarArgument
- Stub Enumerable::when() and unless() with the Conditionable signature

* docs: link the upstream Enumerable docblock fix from the when()/unless() stub

* test: link the filed Psalm issues from the workarounds and known limitations

- vimeo/psalm#14554 (trait constructor InvalidStaticInvocation), #14556 (array-shape unpack), #14555 (composer.json next to the config).
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.

conditional return incorrectly handles non-empty-mixed with false

3 participants