简体   繁体   English

如何通过javascript(esprima)将一个节点插入到抽象语法树中

[英]How to insert one node into an abstract syntax tree by javascript (esprima)

there is a question about esprima and inserting an ast node.有一个关于 esprima 和插入 ast 节点的问题。

I try to generate one ast node to replace other node with new node , (node = newNode) , but It does't work.我尝试生成一个 ast 节点以用新节点 (node = newNode) 替换其他节点,但它不起作用。

    estraverse.traverse(tree, {
enter(node, parent) {
try {
    if (node.type === "ExpressionStatement") {
        if(node.expression.right.type == "FunctionExpression"){
            // the id attribution can be replaced
            node.expression.right.id = node.expression.left;
            // but node can not be replaced
            node = node.expression.right;
            node.type = "FunctionDeclaration";
        }
    }
} catch (error) {

}
},});

Based on the code snippet you shared, you are using estraverse to parse through the AST.根据您共享的代码片段,您正在使用 estraverse 来解析 AST。 For replacing a node, you need to use the estraverse.replace API.要替换节点,您需要使用 estraverse.replace API。 You can check the details in the documentation for estraverse.replace, but in general when you find the node to replace (Ex. if(node=='Expression Statement'){ .... }) you need to return the new node to this function which will replace the current node.您可以在 estraverse.replace 的文档中查看详细信息,但通常当您找到要替换的节点时 (Ex. if(node=='Expression Statement'){ .... }) 您需要返回新节点此函数将替换当前节点。

//node is replaced by Newnode //节点被新节点替换

result = estraverse.replace(AST, {
    leave: function (node) {
        if (node.type == 'Expression Statement')
            return Newnode;
    }
});

One point you need to take care is to make sure the Newnode does not break the AST syntax in anyway.您需要注意的一点是确保 Newnode 无论如何都不会破坏 AST 语法。 Best way I found was to get the Newnode by converting a code snippet into AST and then grabbing the respective node out of it.我发现的最好方法是通过将代码片段转换为 AST 来获取 Newnode,然后从中获取相应的节点。 This makes sure the structure remains ecmascript compliant.这确保结构保持 ecmascript 兼容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM