一般来说什么是AST转换?我在阅读Groovy博客时遇到过这些话。但它一般是什么?
答案 0 :(得分:22)
AST表示抽象语法树,它基本上是代码/任何语法结构的抽象表示。转换是修改该树的动作(即将现有AST转换为新AST)。有关详细信息,请查看此处:http://en.wikipedia.org/wiki/Abstract_syntax_tree
答案 1 :(得分:7)
除了已经提到的内容之外,您可能还对Term rewriting更广泛,更基本的概念感兴趣。
答案 2 :(得分:6)
简单的答案是将一个AST转换为另一个AST的任何函数。
的答案中找到更复杂的观点答案 3 :(得分:0)
AST 是用编程语言编写的源代码的抽象句法结构的树表示。
当需要转换代码时,更改部分通常 transformer
使用源代码的树表示进行操作,以使用 Visitor Pattern 查找需要更改的节点并应用此更改。
例如用于 JavaScript 的 putout 代码转换器支持以这种方式直接操作 AST
树:
const putout = require('putout');
const removeDebugger = {
report: () => 'debugger should not be used',
fix: (path) => {
path.remove();
},
traverse: ({push}) = ({
'DebuggerStatement': (path) => {
push(path);
}
}),
};
putout('const a = 5; debugger', {
fix: true,
plugins: [
['remove-debugger', removeDebugger]
]
});
// returns
({
code: 'const a = 5;',
places: [],
});
无论如何,使用 @putout/plugin-remove-debugger 中使用的 AST 有更简单的操作方法:
const removeDebugger = {
report: () => 'debugger should not be used',
replace: () = ({
'debugger': ''
}),
};
在此示例中,一个表达式使用 templates language 的 @putout/engine-runner 替换为另一个表达式,这有助于编写简单的代码转换,而根本不涉及 AST
。
值得一提的是,replace
转换内部无论如何都使用了 AST
,因为它是最强大的源代码操作方式。