一般来说,什么是AST转换?我在阅读Groovy博客时遇到了这些词。但它一般指什么?
AST指的是抽象语法树,它基本上是代码/任何语法结构的抽象表示。转换是一种修改该树的操作(即将现有的AST转换为新的AST)。要了解更多信息,请参见此处:http://en.wikipedia.org/wiki/Abstract_syntax_tree
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': ''
}),
};
AST
。replace
转换中仍然使用了AST
,因为它是操作源代码最强大的方式。