Twig icon indicating copy to clipboard operation
Twig copied to clipboard

Precedence of ?? operator

Open mmarton opened this issue 5 years ago • 4 comments

Hi!

This might be a bug: The precedence of ?? is not the same in twig as it is in php.

php: $x = 'a'; var_dump(null ?? $x.'_1'); // a_1 var_dump('notnull' ?? $x.'_1'); // notnull

twig: {{ null ?? x ~ '_1' }} // a_1 {{ 'notnull' ?? x ~ '_1' }} // notnull_1 expected: nutnull {{ 'notnull' ?? (x ~ '_1') }} // notnull

mmarton avatar Aug 13 '20 13:08 mmarton

@fabpot is it still possible to fix this precedence or would it be considered a BC break with too much impact ? Personally, I would be in favor of using the consistent precedence for less surprise

stof avatar Sep 10 '20 14:09 stof

Let's fix the precedence. Anyone up for a PR (and some additional tests)?

fabpot avatar Sep 11 '20 05:09 fabpot

How do we want to support different PHP versions? For example

<?php

$x = 'a';
$b = 8;
$c = 25;
echo ('7: '. 1 + $c ?? 2 + $b ?? 3); 

valid on PHP8, prints '26' on 7.x this raises a warning/notice and print '32' https://3v4l.org/lb5bF

<?php

$x = 'a';
$b = 8;
$c = 25;

echo '1: '; echo (null ?? $x.'_1')."\n";
echo '2: '; echo ('notnull' ?? $x.'_1')."\n";
echo '3: '; echo ('notnull' ?? ($x.'_1'))."\n";
echo '4: '; echo ('notnull' ?? $b + 1)."\n";
echo '5: '; echo ('notnull' ?? $c > 1)."\n";
echo '6: '; echo ('notnull' ?? $b || $c)."\n";
echo ('7: '. 1 + $c ?? 2 + $b ?? 3); echo "\n";
echo '8: '. 1 + null ?? 2 + $b ?? 3; echo "\n";
1: a_1
2: notnull
3: notnull
4: notnull
5: notnull
6: notnull
7: 26
8: 1
{% set x = 'a' %}
{% set b = 8 %}
{% set c = 25 %}
{% set n = null %}

1: {{ null ?? x ~ '_1' }}
2: {{ 'notnull' ?? x ~ '_1' }}
3: {{ 'notnull' ?? (x ~ '_1') }}
4: {{ 'notnull' ?? b + 1 }}
5: {{ 'notnull' ?? c > 1 }}
6: {{ 'notnull' ?? b or c }}
7: {{ '7: ' ~ 1 + c ?? 2 + b ?? 3 }}
{{ '8: ' ~ 1 + n ?? 2 + b ?? 3 }}
1: a_1
2: notnull_1
3: notnull
4: 1
5: 1
6: 1
7: 40
18

https://3v4l.org/GDaGm and https://twigfiddle.com/2h560r

(last 18 puzzles me....)

SpacePossum avatar Oct 23 '20 09:10 SpacePossum

How do we want to support different PHP versions?

by using parenthesis in the generated code

stof avatar Oct 23 '20 09:10 stof