diff --git a/src/Parser/UnaryExpressionTrait.php b/src/Parser/UnaryExpressionTrait.php index e273551d..c4a92e6a 100644 --- a/src/Parser/UnaryExpressionTrait.php +++ b/src/Parser/UnaryExpressionTrait.php @@ -125,6 +125,14 @@ protected function parseUnaryMinus(Expr\UnaryMinus $expr): string } $code = $this->parseExprAsValue($expr->expr); + // An operand that already starts with `-` (a nested unary minus, a + // negative literal) would paste into the C++ pre-decrement token: + // `- -$a` -> `--a`. Parenthesize exactly then, so plain literals + // keep their compact `-7L` form. + if (str_starts_with($code, '-')) { + return '-(' . $code . ')'; + } + return '-' . $code; } diff --git a/tests/compiler/operator/unary-minus-nested.phpt b/tests/compiler/operator/unary-minus-nested.phpt new file mode 100644 index 00000000..b9f988ad --- /dev/null +++ b/tests/compiler/operator/unary-minus-nested.phpt @@ -0,0 +1,35 @@ +--TEST-- +Nested unary minus must not emit the C++ pre-decrement token +--FILE-- + +--EXPECT-- +5 +5 +7 +1.5 +9 +-3