[英]How can I transform a custom AST into JS code
I am currently generating a custom AST from a new language specification I have designed.我目前正在根据我设计的新语言规范生成自定义 AST。 This custom AST contains different nodes that I have designed with all the information I need in order to now generate JavaScript code.
这个自定义 AST 包含我设计的不同节点,其中包含我现在生成 JavaScript 代码所需的所有信息。 For example:
例如:
Say I have a customExpressionNode which I wish to translate into a JavaScript function which contains a couple of if conditions.假设我有一个 customExpressionNode,我希望将其转换为一个包含几个 if 条件的 JavaScript 函数。
I am currently looking into libraries like Babylon and Esprima for generating a new Javascript AST from my Custom AST, but from what I've seen there is quite a lot of complexity in the AST that these libraries use.我目前正在研究像 Babylon 和 Esprima 这样的库,以从我的自定义 AST 生成新的 Javascript AST,但据我所知,这些库使用的 AST 非常复杂。 I would also like to avoid printing js code into a few files and then parsing and compiling them, so my question is:
我还想避免将 js 代码打印到几个文件中然后解析和编译它们,所以我的问题是:
Is there a better way of generating programmatically a JavaScript compliant AST that I can use to generate JavaScript code?有没有更好的方式以编程方式生成符合 JavaScript 的 AST,我可以用它来生成 JavaScript 代码?
Something like this?像这样的东西? https://github.com/estools/escodegen
https://github.com/estools/escodegen
A simple example: the program
一个简单的例子:程序
escodegen.generate({
type: 'BinaryExpression',
operator: '+',
left: { type: 'Literal', value: 40 },
right: { type: 'Literal', value: 2 }
})
produces the string '40 + 2'
.产生字符串
'40 + 2'
。
npm install --save-dev @babel/generator
const { default: generate } = require("@babel/generator");
Identifier(path) {
console.log(generate(path.node).code); // code string
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.