Skip to content

Keep the narrowing origin when generalizing loop variable holders - #7305

Merged
ondrejmirtes merged 1 commit into
2.3.xfrom
keep-narrowed-from-when-generalizing
Dec 3, 2026
Merged

ondrejmirtes merged 1 commit into
2.3.xfrom
keep-narrowed-from-when-generalizing

Conversation

@ondrejmirtes

Copy link
Copy Markdown
Member

MutatingScope::generalizeVariableTypeHolders() built the widened holder without narrowedFrom. The merge after a loop then took a value the loop only narrowed (a mixed iterated with foreach whose body assigns something) for a value of its own and kept it as the witness type, mixed+(array{}|object), so count($items) after the loop was reported.

The widened holder now comes from a new ExpressionTypeHolder::generalize(), which keeps the origin both passes were narrowed from, by the same rule ExpressionTypeHolder::and() uses. The turbo extension gets the same change (pt_holder_generalize(), used by the native generalizeVariableTypeHolders() and the native generalize()), with differential coverage in smoke.php.

Closes phpstan/phpstan#15942

Amp thread: https://ampcode.com/threads/T-01a23bcd-b5ed-748d-aae2-43defeba4aba

generalizeVariableTypeHolders() built the widened holder without
narrowedFrom, so the merge after a loop took a value the loop only
narrowed, like a mixed iterated with foreach, for a value of its own and
kept it as the witness type. The holder now keeps the origin both
passes were narrowed from, by the same rule ExpressionTypeHolder::and()
uses.

Amp-Thread-ID: https://ampcode.com/threads/T-01a23bcd-b5ed-748d-aae2-43defeba4aba
@ondrejmirtes
ondrejmirtes force-pushed the keep-narrowed-from-when-generalizing branch from 04d59b3 to accd486 Compare December 3, 2026 13:38
@ondrejmirtes
ondrejmirtes merged commit dcff353 into 2.3.x Dec 3, 2026
371 of 381 checks passed
@ondrejmirtes
ondrejmirtes deleted the keep-narrowed-from-when-generalizing branch December 3, 2026 13:39
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.

foreach over mixed still gives it a witness type when the loop body assigns something (follow-up to #15934)

1 participant