Skip to content

Re-price a stored condition operand that does not answer on the assign scope - #6749

Open
HawkForge wants to merge 2 commits into
phpstan:2.3.xfrom
HawkForge:fix/stored-condition-array-offset-null
Open

HawkForge wants to merge 2 commits into
phpstan:2.3.xfrom
HawkForge:fix/stored-condition-array-offset-null

Conversation

@HawkForge

Copy link
Copy Markdown
Contributor

Closes phpstan/phpstan#15479. Thanks @PupFuzz for the report and the version table.

When a condition is assigned to a variable, AssignHandler adds conditional holders for each expression the condition narrows. The holder type is the narrowing intersected with the expression's current type, and currentTypeForConditionalHolder() read that current type from the subexpression's stored result.

For $ok = $a['k'] === null || is_int($a['k']), the truthy specified types hold int|null for $a['k'], but the node they carry is the $a['k'] from the right operand. That node was walked on the left operand's falsey branch, so its stored type is mixed~null. Intersecting the two gave int, and if ($ok) narrowed $a['k'] to int. Variables were not affected because they are read from the scope state, which is why i() in the issue still worked. 2.2.17 used $scope->getType($expr) here.

The stored result is now used only when answersOnScope() holds for the assign scope. Otherwise the expression is processed on demand on that scope, the same way SwitchHandler, MatchHandler and CoalesceCompositionHelper handle a stored result that does not answer. The change is mirrored in turbo-ext/src/AssignHandler.cpp, followed by the expected turbo version bump.

tests/PHPStan/Analyser/nsrt/bug-15479.php uses the code from the issue. It fails without the fix (f() and g() give int) and passes with it, with and without the Turbo extension loaded.

…n scope

When a condition is stored in a variable, the conditional holders for the
narrowed expressions intersect the narrowing with the expression's current
type. That type was read from the stored result of the subexpression, but
the specified types of `$a['k'] === null || is_int($a['k'])` carry the
`$a['k']` node from the right operand, which was walked on the left's
falsey branch and so has the type mixed~null. Intersecting it with int|null
dropped null, and `if ($ok)` then narrowed `$a['k']` to int.

The stored result is now only used when it answers on the assign scope;
otherwise the expression is re-priced on that scope.

Closes phpstan/phpstan#15479
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 offset loses null when narrowed through a stored boolean of $a['k'] === null || is_int($a['k']) (regression in 2.3.0)

1 participant