Skip to content

Widen an unresolvable closure accumulator to mixed and drop array_reduce()'s initial value for non-empty arrays - #7236

Merged
ondrejmirtes merged 2 commits into
2.3.xfrom
array-reduce-unresolvable-accumulator
Nov 28, 2026
Merged

ondrejmirtes merged 2 commits into
2.3.xfrom
array-reduce-unresolvable-accumulator

Conversation

@ondrejmirtes

Copy link
Copy Markdown
Member

Fixes the three forms of the array_reduce() regression introduced by 2b60ab0 ("Resolve accumulator templates of a closure to a fixed point"):

  1. *ERROR* in the accumulator: an accumulator round that solves to a type containing an error type (the closure body does not type with the accumulator) now widens to mixed, as before the fixed point.
  2. Leaked TIn for a mixed array: an accumulator containing a template of the called function itself (the closure's unresolved $item returned into the carry) also widens to mixed. Templates of other scopes, such as the caller's, are kept.
  3. |null for a non-empty array without $initial: ArrayReduceFunctionReturnTypeExtension now uses isIterableAtLeastOnce() of the array type instead of only checking constant arrays.

The two changed assertions in nsrt/array-functions.php reduce a non-empty-array, so the previous string|null / 1|string were the same bug.

Regression test: tests/PHPStan/Analyser/nsrt/bug-15874.php (the issue's three playground snippets, plus a maybe-empty control); it fails without the fix.

Closes phpstan/phpstan#15874

Amp thread: https://ampcode.com/threads/T-01a22076-55e7-74c4-b04d-1a7660d2f877

…uce()'s initial value for non-empty arrays

Since accumulator templates of a closure are resolved to a fixed point,
a round could solve the accumulator to a type with an error type, from a
closure body that does not type with it, or with a template of the called
function itself, as the TIn of array_reduce() a closure over a mixed
array returns. Such an accumulator cannot be resolved further and now
widens to mixed, as before the fixed point.

ArrayReduceFunctionReturnTypeExtension dropped the initial value only for
constant arrays; it now asks the array type whether it is iterable at
least once, so array_reduce() over a non-empty-list without $initial is
no longer nullable.

Amp-Thread-ID: https://ampcode.com/threads/T-01a22076-55e7-74c4-b04d-1a7660d2f877
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.

array_reduce() accumulator solved to a fixed point gets *ERROR*, leaks TIn, or keeps |null for a non-empty array (since phpstan-src 2b60ab0d0)

1 participant