Treat Expr\UnaryMinus with scalar operand as scalar literal in isExprSafeToProjectThroughVariable and comparison type specifying#5557
Merged
ondrejmirtes merged 2 commits intophpstan:2.1.xfrom Apr 28, 2026
Conversation
…xprSafeToProjectThroughVariable` and comparison type specifying - In PHP Parser v5, negative literals like `-1` are represented as `Expr\UnaryMinus(Scalar\Int_(1))`, not `Scalar\Int_(-1)`. The `isExprSafeToProjectThroughVariable` filter in AssignHandler only checked for `instanceof Node\Scalar`, missing the `UnaryMinus` wrapper. This allowed a sure type with expression string `"-1"` (a numeric string) to enter the conditional expressions array. PHP's array key autocasting then turned it into an integer key, causing a TypeError when passed to `addConditionalExpressions(string $exprString, ...)`. - Added `Expr\UnaryMinus && $expr->expr instanceof Node\Scalar` to the filter in `isExprSafeToProjectThroughVariable`, matching what `MutatingScope::filterBySpecifiedTypes` already does. - Added the same `UnaryMinus(Scalar)` check to TypeSpecifier's `Smaller`/`SmallerOrEqual` handling, which skips creating sure types for scalar literals but was missing the negated-scalar case. - Added defensive `(string)` casts in three locations in AssignHandler where expression string keys from `getSureTypes()`/`getSureNotTypes()` are consumed, matching the pattern already used in `MutatingScope::filterBySpecifiedTypes`.
ondrejmirtes
requested changes
Apr 28, 2026
Member
ondrejmirtes
left a comment
There was a problem hiding this comment.
And regenerate the baseline with make phpstan-generate-baseline and commit that
| $this->assertNoErrors($errors); | ||
| } | ||
|
|
||
| public function testBug14542(): void |
Collaborator
Author
There was a problem hiding this comment.
Done. Both review comments are addressed:
- Added
#[RequiresPhp('>= 8.0.0')]totestBug14542because the test data file uses themixedtype which requires PHP 8.0+. - Regenerated the baseline with
make phpstan-generate-baseline— theAssignHandler.phpentry moved to its correct alphabetical position.
Tests (11936 passing) and static analysis (no errors) both verified clean.
The test uses `mixed` type which requires PHP 8.0+. Baseline regenerated with `make phpstan-generate-baseline` to fix entry ordering. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
ondrejmirtes
approved these changes
Apr 28, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes a crash (
TypeError: Argument #1 ($exprString) must be of type string, int given) when analysing code with comparisons against negative integer literals in ternary assignments, such as$x = array_search($a, $ids) > -1 ? $index : PHP_INT_MAX.Changes
src/Analyser/ExprHandler/AssignHandler.php:Expr\UnaryMinus && $expr->expr instanceof Node\Scalarto theisExprSafeToProjectThroughVariablefilter, preventing negated scalar literals (which are not valid narrowing targets) from entering the conditional expressions map.(string)casts inprocessSureTypesForConditionalExpressionsAfterAssign,processSureNotTypesForConditionalExpressionsAfterAssign, and the consumingforeachloop as defense-in-depth against PHP's numeric-string array-key autocasting.src/Analyser/TypeSpecifier.php:Smaller/SmallerOrEqualcomparison handling to skip creating sure types forUnaryMinus(Scalar)expressions, matching the existingNode\Scalarfilter.phpstan-baseline.neon:(string)casts inAssignHandler.php(matching existing baseline for same pattern inMutatingScope.php).tests/PHPStan/Analyser/AnalyserIntegrationTest.php+tests/PHPStan/Analyser/data/bug-14542.php:Root cause
In PHP Parser v5, negative integer literals like
-1are represented asExpr\UnaryMinus(Scalar\Int_(1)), notScalar\Int_(-1). TheisExprSafeToProjectThroughVariablemethod checked forinstanceof Node\Scalarto skip scalar literals, butUnaryMinusis not aScalarnode, so-1bypassed the filter. Its expression string"-1"is a numeric string, which PHP's array key semantics auto-cast toint(-1). When the code later iterated over the array and passed the key toaddConditionalExpressions(string $exprString, ...), the integer caused aTypeError.MutatingScope::filterBySpecifiedTypesalready handled this case correctly (filteringExpr\UnaryMinus && $expr->expr instanceof Node\Scalarand casting to(string)), but the parallel code inAssignHandlerdid not.Analogous cases probed:
UnaryPlus(Scalar): Not a practical concern — PHP'sis_numeric()treats"+1"as numeric, but PHP Parser doesn't commonly produceUnaryPlusfor positive literals, andMutatingScope::filterBySpecifiedTypesdoesn't check for it either.TypeSpecifier(e.g.,processBooleanSureConditionalTypes): These filter toExpr\Variableonly, so numeric expression strings never reach them.SpecifiedTypes::intersectWith/unionWith/normalize: These propagate keys between arrays without typed consumption, so int keys don't cause TypeErrors (they're just passed through).Test
testBug14542inAnalyserIntegrationTest: reproduces the original crash witharray_search()result compared against-1in a ternary assignment. Without the fix, throwsTypeError; with the fix, analyses without errors.Fixes phpstan/phpstan#14542