escodegen icon indicating copy to clipboard operation
escodegen copied to clipboard

Broken parens on return statement

Open retrohacker opened this issue 6 years ago • 5 comments

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

retrohacker avatar Mar 19 '18 23:03 retrohacker

This only happens when comments are included inside the parentheses.

retrohacker avatar Mar 19 '18 23:03 retrohacker

Same problem for throw statements.

micschro avatar Feb 26 '19 13:02 micschro

This issue is still present in v2.0.0.

lucivpav avatar Oct 07 '20 09:10 lucivpav

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.

lucivpav avatar Oct 13 '20 12:10 lucivpav

The issue is about wrong code generation when using comments in return, throw and arrow function expressions.

lucivpav avatar Jan 04 '21 11:01 lucivpav