Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Brocken parenthesizes around arrow function body when return an object #743

Closed
coderaiser opened this issue Aug 29, 2020 · 2 comments
Closed

Comments

@coderaiser
Copy link
Contributor

coderaiser commented Aug 29, 2020

recast produces invalid code when babel used as a parser for such code, that returns an object:

before:

 const get = (a) => ({
    hello: 'world',
    'x': 'y',
});

after:

 const get = (a) => {
    hello: 'world',
    'x': 'y',
};

Which is invalid because has different meaning without parenthesizes, as a labeled series expressions without an end.

Can be reproduced using v0.20.2 with:

const babel = require('@babel/parser');
const generate = require('@babel/generator').default;
const recast = require('recast');
const traverse = require('@babel/traverse').default;

const source = `
    const get = (a) => ({
        hello: 'world',
        'x': 'y',
    });
`;

const babelAST = recast.parse(source, {
    parser: {
        parse: babel.parse,
    }
});

traverse(babelAST, {
    Identifier(path) {
        if (path.node.name === 'a')
            path.remove();
    }
});

console.log('recast:', recast.print(babelAST));
console.log('babel', generate(babelAST));

Output:

recast: PrintResult {
  code: "\n    const get = () => {\n        hello: 'world',\n        'x': 'y',\n    };\n"
}
babel {
  code: "const get = () => ({\n  hello: 'world',\n  'x': 'y'\n});",
  map: null,
  rawMappings: undefined
}

Can be related to #705
This can be fixed setting createParenthesizedExpressions:

const babelAST = recast.parse(source, {
    parser: {
        parse: () => {
            return babel.parse(source, {
                createParenthesizedExpressions: true
            });
        }
    }
});

But would be amazing if this option can be avoided, because it makes harder to traverse and compare AST nodes, because ParenthesizedExpressions adds an extra noise.

@gnprice
Copy link
Contributor

gnprice commented May 25, 2022

This appears to have been fixed -- the example in the description no longer reproduces.

(Probably fixed by #1068: it looks like #1067 was a duplicate of this issue.)

@eventualbuddha
Copy link
Collaborator

Verified this no longer reproduces. Thanks for the nudge, @gnprice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
3 participants