Don't always omit parentheses for argument-less yield

We may need parentheses around an argument-less yield to distinguish
(yield) - $a from yield -$a and similar.

Treat argument-less yield like a prefix operator. This will print
parentheses a bit more often than is really required, because the
arity ambiguity only exists for certain operators. This seems like
a reasonably good approximation through, as it only affects
argument-less yield on the LHS of infix operators.
This commit is contained in:
Nikita Popov 2023-03-04 12:04:47 +01:00
parent 7877e0302d
commit 698ff1ca46
2 changed files with 14 additions and 1 deletions

View File

@ -720,7 +720,8 @@ class Standard extends PrettyPrinter {
protected function pExpr_Yield(Expr\Yield_ $node, int $precedence, int $lhsPrecedence): string {
if ($node->value === null) {
return 'yield';
$opPrecedence = $this->precedenceMap[Expr\Yield_::class][0];
return $opPrecedence >= $lhsPrecedence ? '(yield)' : 'yield';
} else {
if (!$this->phpVersion->supportsYieldWithoutParentheses()) {
return '(yield ' . $this->pKey($node->key) . $this->p($node->value) . ')';

View File

@ -22,6 +22,9 @@ function gen()
match ($x) {
yield $a, (yield $b) => $c,
};
yield -$a;
(yield) - $a;
yield * $a;
}
-----
function gen()
@ -44,6 +47,9 @@ function gen()
match ($x) {
yield $a, (yield $b) => $c,
};
yield -$a;
(yield) - $a;
(yield) * $a;
}
-----
<?php
@ -68,6 +74,9 @@ function gen()
match ($x) {
yield $a, (yield $b) => $c,
};
yield -$a;
(yield) - $a;
yield * $a;
}
-----
!!version=5.6
@ -91,4 +100,7 @@ function gen()
match ($x) {
(yield $a), (yield $b) => $c,
};
(yield -$a);
(yield) - $a;
(yield) * $a;
}