escodegen
escodegen copied to clipboard
Broken parens on return statement
Repro
escodegen strips parenthesis from return statements, changing the behavior of the code. This breaks ast serialization/deserialization for react here.
var acorn = require('acorn');
var escodegen = require('escodegen');
var file = `
console.log((function () {
return (
// do a thing
'hello world'
);
})());
`;
var tokens = [];
var comments = [];
var ast = acorn.parse(file,
{
onToken: tokens,
onComment: comments,
ranges: true,
});
escodegen.attachComments(ast, comments, tokens);
console.log(escodegen.generate(ast, { comment: true }));
Output
original
console.log((function () {
return (
// do a thing
'hello world'
);
})());
hello world
generated
console.log(function () {
return // do a thing
'hello world';
}());
undefined
This only happens when comments are included inside the parentheses.
Same problem for throw statements.
This issue is still present in v2.0.0.
The problem is more general. An expression that is within parentheses and contains a comment in the beginning, compiles incorrectly. Example:
let variable = (
// ahoj
3+3
);
compiles into:
let variable = // ahoj
3+3;
This does not happen in all cases, such as it does not happen if the expression is within an if
condition.
Note: the compiled code still works correctly, so this may not be a good example of the problem, but I think the parentheses should still be generated.
The issue is about wrong code generation when using comments in return
, throw
and arrow function expressions.