benjamn / recast

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

`recast.print` modifies original source adding brackets around some statements #1191

Open phoenisx opened 2 years ago

phoenisx commented 2 years ago

Ref: https://github.com/facebook/jscodeshift/issues/176

For e.g. Let's consider the following source code as input passed to recast.print();

const code = [
  "async function add(a, b) {",
  "  const z = foo || await getFoo();",
  "  return z;",
  "}"
].join("\n");

const ast = recast.parse(code);
recast.print(ast);

Behaviour:

Prints a modified code, with await getFoo() surrounded by parentheses (normal brackets).

// PrintResult {
//   code: 'async function add(a, b) {\n' +
//     '  const z = foo || (await getFoo());\n' +
//     '  return z;\n' +
//     '}'
// }

Expected Behaviour:

Should not contain parenthesis if they were not present in the original code.

// PrintResult {
//   code: 'async function add(a, b) {\n' +
//     '  const z = foo || await getFoo();\n' +
//     '  return z;\n' +
//     '}'
// }

If there are any restrictions in supporting this, can it be possible to put this "adding auto parentheses" feature behind a recast options toggle?

Also if you need any support, I can work on this issue with some guidance 👍🏽 Thanks for all your efforts and creating this awesome library 🙇🏽 💯

liukaigsx commented 2 years ago

you can comment out this line at lib\printer.js shouldAddParens = path.needsParens();

phoenisx commented 2 years ago

Thanks @liukaigsx I tried modifying the code and could remove the parens keepingshouldAddParens === false.

I will raise a PR in some time to add a new config so that users can avoid adding parens while printing.