benjamn / recast

JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator
MIT License
4.95k stars 346 forks source link

missing parentheses in exponentiation with unary left side #1357

Closed j4k0xb closed 1 year ago

j4k0xb commented 1 year ago

reproduction: https://stackblitz.com/edit/stackblitz-starters-9gkcmv?file=index.js&view=editor

const { parse, print, types } = require('recast');
const b = types.builders;

const { code } = print(
  b.binaryExpression(
    '**',
    b.unaryExpression('-', b.numericLiteral(1)),
    b.numericLiteral(2)
  )
);

console.log(code);
console.log(eval(code));

it prints -1 ** 2 which is invalid syntax:

Uncaught SyntaxError: Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedence

expected: (-1) ** 2

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence#table 2.

related but not fixed by #363

eventualbuddha commented 1 year ago

Thanks for reporting this, @j4k0xb! Mind trying #1361 to see if that fixes it for you?

j4k0xb commented 1 year ago

yes that fixed it, thanks!

j4k0xb commented 1 year ago

a bit related but parsing (-1) ** 2 also fails

eventualbuddha commented 1 year ago

I'm not sure why it's hardcoded to ecmaVersion: 6. I'm guessing it was added when that was the latest standard.