Skip to content

Do not keep narrowed mixed returned from a branch as its witness type - #7304

Merged
ondrejmirtes merged 1 commit into
2.3.xfrom
narrowed-mixed-branch-witness
Dec 3, 2026
Merged

ondrejmirtes merged 1 commit into
2.3.xfrom
narrowed-mixed-branch-witness

Conversation

@ondrejmirtes

Copy link
Copy Markdown
Member

A ternary, a match arm or an assignment in a branch that returned a value narrowed from mixed handed the narrowed type to joinValues() as if a path produced it, so is_array($v) ? $v : $v became mixed+array and was reported when passed to a string parameter (with checkMixedWitnessTypes).

  • TernaryHandler and MatchHandler read the type each branch value was narrowed from (MutatingScope::getNarrowedFromType()) and join through the new TypeCombinator::joinNarrowedValues(): a value narrowed from mixed brings only the part of that mixed's own witness it still allows.
  • $x = $v keeps $v's narrowing origin in $x's holder (MutatingScope::assignNarrowedFrom()), so the scope merge after if (is_array($v)) { $x = $v; } else { $x = $v; } does not keep it either.
  • Values a branch really produces are still reported: $c ? $mixed : 1, $mixed ?? null.
  • The native extension mirrors it; output is byte-identical with the extension on and off, and the test suite passes both ways.

Closes phpstan/phpstan#15943

Amp thread: https://ampcode.com/threads/T-01a23bcd-cba2-71f9-9bd1-dcc3a51bd5c6

A ternary, a match arm or an assignment in a branch that returned a value
narrowed from mixed handed the narrowed type to joinValues() as if a path
produced it: `is_array($v) ? $v : $v` became mixed+array and failed a
string parameter with checkMixedWitnessTypes.

TernaryHandler and MatchHandler now read the type each branch value was
narrowed from (MutatingScope::getNarrowedFromType()) and join through
TypeCombinator::joinNarrowedValues(), where a value narrowed from mixed
brings only the part of that mixed's own witness it still allows. An
assignment of a narrowed value keeps its origin in the new holder
(MutatingScope::assignNarrowedFrom()), so a scope merge of `$x = $v` in
both branches does not keep it either. The native extension mirrors it.

Amp-Thread-ID: https://ampcode.com/threads/T-01a23bcd-cba2-71f9-9bd1-dcc3a51bd5c6
@ondrejmirtes
ondrejmirtes merged commit 0e950e9 into 2.3.x Dec 3, 2026
898 of 916 checks passed
@ondrejmirtes
ondrejmirtes deleted the narrowed-mixed-branch-witness branch December 3, 2026 13:23
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.

Narrowed mixed returned from a ternary, match or if/else branch becomes a witness type: is_array($v) ? $v : $v is reported

1 participant