Parens are dropped, changing program semantics / introducing syntax error
- Dominant language
- TypeScript
- Stars
- 5.3k
- Forks
- 363
- Avg merge
- 3d 8h
- Merged PRs (30d)
- 3
Description
I'm using Babel and Recast in conjunction to transform my AST. When I use Babel alone, the output is fine (although not formatted correctly.) When I introduce Recast, it drops parens, changing the program semantics (or introducing a syntax error).
Input code:
```js
jest.mock('./my-module', () => () => ({
mockedFn: jest.fn()
}));
```
Babel plugin:
```js
const plugin = ({ types: t }) => ({
visitor: {
ArrowFunctionExpression(astPath) {
const getWrappedValue = (originalValue) =>
t.callExpression(t.identifier("wrapped"), [
originalValue
]);
const bodyPath = astPath.get("body");
bodyPath.replaceWith(getWrappedValue(bodyPath.node));
astPath.skip();
}
}
});
```
Transformed results:
```js
// Babel result
jest.mock('./my-module', () => wrapped(() => ({
mockedFn: jest.fn()
})));
// Recast result
jest.mock('./my-module', () => wrapped(() => {
mockedFn: jest.fn()
}));
```
[Full runnable repro](https://github.com/NickHeiner/repro/blob/master/cases/recast-dropping-parens/index.js).
We can see that the `()` around the arrow function return expression are dropped. When there are multiple members of the object, this results in a syntax error:
```js
() => ({a: true, b: false})
// Syntax error
() => {a: true, b: false}
```
Possibly related: #914, #327, #533, #81
Versions:
* `recast@0.20.5`
* `@babel/core@7.15.5`
Contributor guide
No contributing guide indexed for this repository
Research direction
Start with the runnable repro at cases/recast-dropping-parens/index.js and compare the Babel-only and Recast outputs shown in the issue. Trace how the Recast printer handles the arrow function body after the Babel transformation, then verify that parentheses are preserved and the resulting code remains valid for objects with multiple members.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100