Skip to content

Commit

Permalink
Allow arrow functions everywhere
Browse files Browse the repository at this point in the history
  • Loading branch information
fabpot committed Oct 7, 2024
1 parent 5ac03a4 commit a3ebb78
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 12 deletions.
1 change: 1 addition & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# 3.15.0 (2024-XX-XX)

* Allow arrow functions everywhere
* Deprecate passing a string or an array to Twig callable arguments accepting arrow functions (pass a `\Closure`)
* Add support for triggering deprecations for future operator precedence changes
* Deprecate using the `not` unary operator in an expression with ``*``, ``/``, ``//``, or ``%`` without using explicit parentheses to clarify precedence
Expand Down
26 changes: 26 additions & 0 deletions doc/templates.rst
Original file line number Diff line number Diff line change
Expand Up @@ -960,6 +960,32 @@ The following operators don't fit into any of the other categories:
Support for expanding the arguments of a function call was introduced in
Twig 3.15.

* ``=>``: The arrow operator allows the creation of functions. A function is
made of arguments (use parentheses for multiple arguments) and an arrow
(``=>``) followed by an expression to execute. The expression has access to
all passed arguments. Arrow functions are supported as arguments for filters,
functions, tests, macros, and method calls.

For instance, the built-in ``map``, ``reduce``, ``sort``, ``filter``, and
``find`` filters accept arrow functions as arguments:

.. code-block:: twig
{{ people|map(p => p.first_name)|join(', ') }}
Arrow functions can be stored in variables:

.. code-block:: twig
{% set first_name_fn = (p) => p.first_name %}
{{ people|map(first_name_fn)|join(', ') }}
.. versionadded:: 3.15

Arrow function support for functions, macros, and method calls was added in
Twig 3.15 (filters and tests were already supported).

Operators
~~~~~~~~~

Expand Down
51 changes: 39 additions & 12 deletions src/ExpressionParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ class ExpressionParser
private $binaryOperators;
private $readyNodes = [];
private array $precedenceChanges = [];
private bool $deprecationCheck = true;

public function __construct(
private Parser $parser,
Expand Down Expand Up @@ -86,9 +87,13 @@ public function __construct(
}
}

public function parseExpression($precedence = 0, $allowArrow = false, bool $deprecationCheck = true)
public function parseExpression($precedence = 0)
{
if ($allowArrow && $arrow = $this->parseArrow()) {
if (func_num_args() > 1) {
trigger_deprecation('twig/twig', '3.15', 'Passing a second argument ($allowArrow) to "%s()" is deprecated.', __METHOD__);
}

if ($arrow = $this->parseArrow()) {
return $arrow;
}

Expand All @@ -105,7 +110,12 @@ public function parseExpression($precedence = 0, $allowArrow = false, bool $depr
} elseif (isset($op['callable'])) {
$expr = $op['callable']($this->parser, $expr);
} else {
$expr1 = $this->parseExpression(self::OPERATOR_LEFT === $op['associativity'] ? $op['precedence'] + 1 : $op['precedence'], true);
$previous = $this->setDeprecationCheck(true);
try {
$expr1 = $this->parseExpression(self::OPERATOR_LEFT === $op['associativity'] ? $op['precedence'] + 1 : $op['precedence']);
} finally {
$this->setDeprecationCheck($previous);
}
$class = $op['class'];
$expr = new $class($expr, $expr1, $token->getLine());
}
Expand All @@ -116,7 +126,7 @@ public function parseExpression($precedence = 0, $allowArrow = false, bool $depr
$token = $this->parser->getCurrentToken();
}

if ($deprecationCheck) {
if ($this->deprecationCheck) {
$this->triggerPrecedenceDeprecations($expr, $previousToken);
}

Expand Down Expand Up @@ -178,7 +188,7 @@ private function parseArrow()
$names = [new AssignNameExpression($token->getValue(), $token->getLine())];
$stream->expect(Token::ARROW_TYPE);

return new ArrowFunctionExpression($this->parseExpression(0), new Nodes($names), $line);
return new ArrowFunctionExpression($this->parseExpression(), new Nodes($names), $line);
}

// first, determine if we are parsing an arrow function by finding => (long form)
Expand Down Expand Up @@ -219,7 +229,7 @@ private function parseArrow()
$stream->expect(Token::PUNCTUATION_TYPE, ')');
$stream->expect(Token::ARROW_TYPE);

return new ArrowFunctionExpression($this->parseExpression(0), new Nodes($names), $line);
return new ArrowFunctionExpression($this->parseExpression(), new Nodes($names), $line);
}

private function getPrimary(): AbstractExpression
Expand All @@ -238,7 +248,12 @@ private function getPrimary(): AbstractExpression
return $this->parsePostfixExpression($expr);
} elseif ($token->test(Token::PUNCTUATION_TYPE, '(')) {
$this->parser->getStream()->next();
$expr = $this->parseExpression(deprecationCheck: false)->setExplicitParentheses();
$previous = $this->setDeprecationCheck(false);
try {
$expr = $this->parseExpression()->setExplicitParentheses();
} finally {
$this->setDeprecationCheck($previous);
}
$this->parser->getStream()->expect(Token::PUNCTUATION_TYPE, ')', 'An opened parenthesis is not properly closed');

return $this->parsePostfixExpression($expr);
Expand Down Expand Up @@ -660,7 +675,7 @@ public function parseFilterExpressionRaw($node)
if (!$this->parser->getStream()->test(Token::PUNCTUATION_TYPE, '(')) {
$arguments = new EmptyNode();
} else {
$arguments = $this->parseArguments(true, false, true);
$arguments = $this->parseArguments(true);
}

$filter = $this->getFilter($token->getValue(), $token->getLine());
Expand Down Expand Up @@ -696,8 +711,12 @@ public function parseFilterExpressionRaw($node)
*
* @throws SyntaxError
*/
public function parseArguments($namedArguments = false, $definition = false, $allowArrow = false)
public function parseArguments($namedArguments = false, $definition = false)
{
if (func_num_args() > 2) {
trigger_deprecation('twig/twig', '3.15', 'Passing a third argument ($allowArrow) to "%s()" is deprecated.', __METHOD__);
}

$args = [];
$stream = $this->parser->getStream();

Expand All @@ -719,11 +738,11 @@ public function parseArguments($namedArguments = false, $definition = false, $al
} else {
if ($stream->nextIf(Token::SPREAD_TYPE)) {
$hasSpread = true;
$value = new SpreadUnary($this->parseExpression(0, $allowArrow), $stream->getCurrent()->getLine());
$value = new SpreadUnary($this->parseExpression(), $stream->getCurrent()->getLine());
} elseif ($hasSpread) {
throw new SyntaxError('Normal arguments must be placed before argument unpacking.', $stream->getCurrent()->getLine(), $stream->getSourceContext());
} else {
$value = $this->parseExpression(0, $allowArrow);
$value = $this->parseExpression();
}
}

Expand All @@ -741,7 +760,7 @@ public function parseArguments($namedArguments = false, $definition = false, $al
throw new SyntaxError('A default value for an argument must be a constant (a boolean, a string, a number, a sequence, or a mapping).', $token->getLine(), $stream->getSourceContext());
}
} else {
$value = $this->parseExpression(0, $allowArrow);
$value = $this->parseExpression();
}
}

Expand Down Expand Up @@ -921,4 +940,12 @@ private function checkConstantExpression(Node $node): bool

return true;
}

private function setDeprecationCheck(bool $deprecationCheck): bool
{
$current = $this->deprecationCheck;
$this->deprecationCheck = $deprecationCheck;

return $current;
}
}
19 changes: 19 additions & 0 deletions tests/Fixtures/macros/arrow_as_arg.test
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
--TEST--
macro
--TEMPLATE--
{% set people = [
{first: "Bob", last: "Smith"},
{first: "Alice", last: "Dupond"},
] %}

{% set first_name_fn = (p) => p.first %}

{{ _self.display_people(people, first_name_fn) }}

{% macro display_people(people, fn) %}
{{ people|map(fn)|join(', ') }}
{% endmacro %}
--DATA--
return []
--EXPECT--
Bob, Alice

0 comments on commit a3ebb78

Please sign in to comment.