Fix ignored parenthesis in expressions

This commit is contained in:
Fabien Potencier
2024-09-27 22:51:56 +02:00
parent 10bbdd5007
commit 1488238e32
4 changed files with 29 additions and 3 deletions
+1
View File
@@ -1,5 +1,6 @@
# 3.15.0 (2024-XX-XX)
* Fix `power` expressions with a negative number in parenthesis (`(-1) ** 2`)
* Deprecate instantiating `Node` directly. Use `EmptyNode` or `Nodes` instead.
* Add support for inline comments
* Add support for accessing class constants with the dot operator
+6 -1
View File
@@ -172,7 +172,12 @@ class ExpressionParser
$expr = $this->parseExpression();
$this->parser->getStream()->expect(Token::PUNCTUATION_TYPE, ')', 'An opened parenthesis is not properly closed');
return $this->parsePostfixExpression($expr);
$expr = $this->parsePostfixExpression($expr);
if ($expr instanceof NegUnary) {
$expr->wrapInParentheses();
}
return $expr;
}
return $this->parsePrimaryExpression();
+14 -2
View File
@@ -20,14 +20,26 @@ abstract class AbstractUnary extends AbstractExpression
{
public function __construct(Node $node, int $lineno)
{
parent::__construct(['node' => $node], [], $lineno);
parent::__construct(['node' => $node], ['with_parentheses' => false], $lineno);
}
public function wrapInParentheses(): void
{
$this->setAttribute('with_parentheses', true);
}
public function compile(Compiler $compiler): void
{
$compiler->raw(' ');
if ($this->getAttribute('with_parentheses')) {
$compiler->raw('(');
} else {
$compiler->raw(' ');
}
$this->operator($compiler);
$compiler->subcompile($this->getNode('node'));
if ($this->getAttribute('with_parentheses')) {
$compiler->raw(')');
}
}
abstract public function operator(Compiler $compiler): Compiler;
+8
View File
@@ -8,6 +8,10 @@ Twig parses power expressions
{{ a ** b }}
{{ b ** a }}
{{ b ** b }}
{{ -1**0 }}
{{ (-1)**0 }}
{{ -a**0 }}
{{ (-a)**0 }}
--DATA--
return ['a' => 4, 'b' => -2]
--EXPECT--
@@ -18,3 +22,7 @@ return ['a' => 4, 'b' => -2]
0.0625
16
0.25
-1
1
-1
1