enum a = 0; enum b = a ? 1 << a - 1 : 0; void main() { } Error: shift by -1 is outside the range `0..31`
Because AddExpression has precedence over ShiftExpression, it's parsed as: ``` enum b = a ? 1 << (a - 1) : 0; ``` Since a = 0, it results in a shift by -1, which gives an error. To fix, add parentheses around the shift: ``` enum b = a ? (1 << a) - 1 : 0; ```
The precedence is intended to be (a ? (1 << (a - 1)) : 0). Since 'a' is 0, the first branch of the conditional shouldn't be evaluated, and the expected result is 0. Compare that to the runtime version, which behaves as expected: void main() { int a = 0; int b = a ? 1 << a - 1 : 0; assert(b == 0); }
Similar case: enum l = 0; enum int[l] a = []; enum b = l ? a[l] : 0; Error: array index 0 is out of bounds `a[0 .. 0]` Or simply: enum a = 0 ? 1 << -1 : 0; enum int[0] a = []; enum b = 0 ? a[0] : 0;
(In reply to Max Samukha from comment #3) > enum b = l ? a[l] : 0; Should be: enum b = l ? a[l - 1] : 0;
Ah, thanks for clearing that up. I think this test illustrates the problem best: ``` enum a = false && (1 << -1); // passes enum b = false ? (1 << -1) : 0; // fails ``` I've updated the title
(In reply to Dennis from comment #5) > ``` > I've updated the title Great, thanks!
@BorisCarvajal created dlang/dmd pull request #13961 "Fix Issue 22988 - no short-circuiting when constant folding ternary operator" fixing this issue: - Fix Issue 22988 - no short-circuiting when constant folding ternary operator https://github.com/dlang/dmd/pull/13961
dlang/dmd pull request #13961 "Fix Issue 22988 - no short-circuiting when constant folding ternary operator" was merged into master: - befbc46fd7309ffb6e640822fa74280a750cf65e by Boris Carvajal: Fix Issue 22988 - no short-circuiting when constant folding ternary operator https://github.com/dlang/dmd/pull/13961