From d133ab7e708b75e320efaf6039b827e7e94306fc Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Mon, 30 Sep 2024 11:52:45 +0200 Subject: [PATCH] Add support for detecting if an expression had explicit parentheses --- src/ExpressionParser.php | 9 ++------- src/Node/Expression/AbstractExpression.php | 15 +++++++++++++++ src/Node/Expression/Unary/AbstractUnary.php | 4 ++-- 3 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/ExpressionParser.php b/src/ExpressionParser.php index 97e3ae003..33da2b29e 100644 --- a/src/ExpressionParser.php +++ b/src/ExpressionParser.php @@ -169,15 +169,10 @@ class ExpressionParser return $this->parsePostfixExpression(new $class($expr, $token->getLine())); } elseif ($token->test(Token::PUNCTUATION_TYPE, '(')) { $this->parser->getStream()->next(); - $expr = $this->parseExpression(); + $expr = $this->parseExpression()->setExplicitParentheses(); $this->parser->getStream()->expect(Token::PUNCTUATION_TYPE, ')', 'An opened parenthesis is not properly closed'); - $expr = $this->parsePostfixExpression($expr); - if ($expr instanceof NegUnary) { - $expr->wrapInParentheses(); - } - - return $expr; + return $this->parsePostfixExpression($expr); } return $this->parsePrimaryExpression(); diff --git a/src/Node/Expression/AbstractExpression.php b/src/Node/Expression/AbstractExpression.php index 1692f5671..22d8617cd 100644 --- a/src/Node/Expression/AbstractExpression.php +++ b/src/Node/Expression/AbstractExpression.php @@ -25,4 +25,19 @@ abstract class AbstractExpression extends Node { return $this->hasAttribute('is_generator') && $this->getAttribute('is_generator'); } + + /** + * @return static + */ + public function setExplicitParentheses(): self + { + $this->setAttribute('with_parentheses', true); + + return $this; + } + + public function hasExplicitParentheses(): bool + { + return $this->hasAttribute('with_parentheses') && $this->getAttribute('with_parentheses'); + } } diff --git a/src/Node/Expression/Unary/AbstractUnary.php b/src/Node/Expression/Unary/AbstractUnary.php index b9b44ed4f..2482d1e70 100644 --- a/src/Node/Expression/Unary/AbstractUnary.php +++ b/src/Node/Expression/Unary/AbstractUnary.php @@ -30,14 +30,14 @@ abstract class AbstractUnary extends AbstractExpression public function compile(Compiler $compiler): void { - if ($this->getAttribute('with_parentheses')) { + if ($this->hasExplicitParentheses()) { $compiler->raw('('); } else { $compiler->raw(' '); } $this->operator($compiler); $compiler->subcompile($this->getNode('node')); - if ($this->getAttribute('with_parentheses')) { + if ($this->hasExplicitParentheses()) { $compiler->raw(')'); } }