Prevent merging of consecutive -/+ more thoroughly

The unary -/+ or --/++ might not be the direct child. Instead
determine this by actually printing the operand and checking
whether it starts with -/+.
This commit is contained in:
Nikita Popov 2023-02-27 19:07:44 +01:00
parent cc34c2450c
commit fcd5934dae
3 changed files with 12 additions and 9 deletions

View File

@ -428,18 +428,10 @@ class Standard extends PrettyPrinterAbstract {
}
protected function pExpr_UnaryMinus(Expr\UnaryMinus $node, int $precedence, int $lhsPrecedence): string {
if ($node->expr instanceof Expr\UnaryMinus || $node->expr instanceof Expr\PreDec) {
// Enforce -(-$expr) instead of --$expr
return '-(' . $this->p($node->expr) . ')';
}
return $this->pPrefixOp(Expr\UnaryMinus::class, '-', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_UnaryPlus(Expr\UnaryPlus $node, int $precedence, int $lhsPrecedence): string {
if ($node->expr instanceof Expr\UnaryPlus || $node->expr instanceof Expr\PreInc) {
// Enforce +(+$expr) instead of ++$expr
return '+(' . $this->p($node->expr) . ')';
}
return $this->pPrefixOp(Expr\UnaryPlus::class, '+', $node->expr, $precedence, $lhsPrecedence);
}

View File

@ -378,7 +378,14 @@ abstract class PrettyPrinterAbstract {
$suffix = ')';
$lhsPrecedence = self::MAX_PRECEDENCE;
}
return $prefix . $operatorString . $this->p($node, $opPrecedence, $lhsPrecedence) . $suffix;
$printedArg = $this->p($node, $opPrecedence, $lhsPrecedence);
if (($operatorString === '+' && $printedArg[0] === '+') ||
($operatorString === '-' && $printedArg[0] === '-')
) {
// Avoid printing +(+$a) as ++$a and similar.
$printedArg = '(' . $printedArg . ')';
}
return $prefix . $operatorString . $printedArg . $suffix;
}
/**

View File

@ -44,6 +44,8 @@ clone ($a + $b);
+(+$a);
-(--$a);
+(++$a);
-(--$a)**$b;
+(++$a)**$b;
!$a = $b;
++$a ** $b;
@ -90,6 +92,8 @@ clone ($a + $b);
+(+$a);
-(--$a);
+(++$a);
-(--$a ** $b);
+(++$a ** $b);
!$a = $b;
++$a ** $b;
$a ** $b++;