escodegen
escodegen copied to clipboard
Generate RegExpr from parsed stringified Acorn AST would get [object object]
I've found that if I get a parsed AST from Acorn (supports SpiderMonkey Parser API format), and then JSON.stringify
it to get serialized version, the one would not be handled correctly even after JSON.parse
it.
Example: (Without serialization and de-serialization)
var source = 'var foo = function () {\n var a = b.replace(/(\\/)/, \'/bar\');\n};' // read from file
var output = escodegen.generate(acorn.parse(source))
output // 'var foo = function () {\n var a = b.replace(/(\\/)/, \'/bar\');\n};' // the same
As the same with the original source. In contrast:
var source = 'var foo = function () {\n var a = b.replace(/(\\/)/, \'/bar\');\n};'
var output = escodegen.generate(JSON.parse(JSON.stringify(acorn.parse(source))))
output // 'var foo = function () {\n var a = b.replace([object Object], \'/bar\');\n};' // error...
Unfortunately, I only know the shallow reason why the error happens is because generateRegExp
expects to accept a reg
which would be used as reg.toString
to print the regexpr in string, but if it receive a object (although the object is exactly a "regexp" node as {pattern, flags}), it would only print '[object object]'. It looks like the not serialized AST would have a real RegExp
with the correct toString
method, while serialized one would get rid of it. However, since I have no idea of how the escodegen
handle it deeply, maybe this is not the root cause.
And my Acorn version is"1.0.3", and escodegen is "1.6.1".
meet same issue when using JSON and esprima
escodegen.generate(JSON.parse(JSON.stringify(esprima.parse(code))));
will get [object Object] from regex
any solution now?