davidbonnet / astring

🌳 Tiny and fast JavaScript code generator from an ESTree-compliant AST.

Home Page:https://david.bonnet.cc/astring/demo/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Uncaught TypeError: Do not know how to serialize a BigInt if `raw` field missing

samuelgruetter opened this issue · comments

<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <script src="node_modules/astring/dist/astring.min.js"></script>
    <script>
        // obtained with acorn:
        const a = { 
            bigint: "0", 
            end: 81, 
            raw: "0n", 
            start: 79, 
            type: "Literal", 
            value: 0n
        };

        console.log(astring.generate(a));
        // works

        delete a.raw;
        console.log(a);
        console.log(astring.generate(a));
        // Uncaught TypeError: Do not know how to serialize a BigInt

    </script>
</head>

<body>
</body>

</html>

astring version: 1.4.3

Actual behavior:

The second invocation of astring.generate throws an error.

Desired behavior:

The second invocation of astring.generate should return "0n", like the first invocation.

Motivation:

I'm generating ASTs containing bigint literals, and it would be convenient if I didn't have to set the raw field. Looking at the source code, it seems that it intends to work even if raw is absent:

astring/src/astring.js

Lines 944 to 952 in 92ad965

Literal(node, state) {
if (node.raw != null) {
state.write(node.raw, node)
} else if (node.regex != null) {
this.RegExpLiteral(node, state)
} else {
state.write(stringify(node.value), node)
}
},

but JSON.stringify does not support serializing bigint literals, hence the exception.

Thanks @samuelgruetter for reporting this.

Fixed in d061997.