facebook / jscodeshift

A JavaScript codemod toolkit.
https://jscodeshift.com
MIT License
9.23k stars 477 forks source link

Parentheses lost when recreating a member expression #442

Open anka-213 opened 3 years ago

anka-213 commented 3 years ago

Here is an example:

const j = api.jscodeshift;

j('(a = b)[c]')
  .find(j.MemberExpression)
  .replaceWith(({node: {object, property, computed}}) => j.memberExpression(object, property, computed))
  .toSource()

gives the result

a = b[c]

instead of the expected

(a = b)[c]
anka-213 commented 3 years ago

If I reconstruct it one level deeper it gives the correct parentheses again:

j('(a = b)[c]')
  .find(j.MemberExpression)
  .replaceWith(({node: {object: {operator,left,right}, property, computed}}) => 
     j.memberExpression(j.assignmentExpression(operator,left,right), property, computed))
  .toSource()

gives

'(a = b)[c]'
mobily commented 2 years ago

@anka-213 seems like you need to add object.extra.parenthised = true to get correct (same) output

j('(a = b)[c]')
  .find(j.MemberExpression)
  .replaceWith(({node: {object, property, computed}}) => {
    object.extra.parenthised = true
    return j.memberExpression(object, property, computed)
  })
  .toSource()