Merge pull request #20 from AlessioGiacobbe/fix/unary-minus-parens

fix(parser): parenthesize unary minus operand to avoid C++ pre-decrement pasting
master
韩天峰 10 hours ago committed by GitHub
commit 589f1494d4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 8
      src/Parser/UnaryExpressionTrait.php
  2. 35
      tests/compiler/operator/unary-minus-nested.phpt

@ -125,6 +125,14 @@ trait UnaryExpressionTrait
}
$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;
}

@ -0,0 +1,35 @@
--TEST--
Nested unary minus must not emit the C++ pre-decrement token
--FILE--
<?php
function negNative(int $x): int
{
return - -$x;
}
function main(): void
{
$a = 5;
$b = - -$a;
echo $b, "\n";
echo $a, "\n";
$c = -(-7);
echo $c, "\n";
$f = 1.5;
$g = - -$f;
echo $g, "\n";
echo negNative(9), "\n";
echo - -(-3), "\n";
}
?>
--EXPECT--
5
5
7
1.5
9
-3
Loading…
Cancel
Save