周世铁,微医前端技术部医疗支撑组前端架构师
本文将通过以下几个方面对AST进行学习
基础知识
实战小例子
总结
AST是什么
在计算机科学中,抽象语法树(abstract syntax tree 或者缩写为 AST),或者语法树(syntax tree),是源代码的抽象语法结构的树状表现形式,这里特指编程语言的源代码。
var tree = 'this is tree'
{
\"type\": \"Program\",
\"start\": 0,
\"end\": 25,
\"body\": [
{
\"type\": \"VariableDeclaration\",
\"start\": 0,
\"end\": 25,
\"declarations\": [
{
\"type\": \"VariableDeclarator\",
\"start\": 4,
\"end\": 25,
\"id\": {
\"type\": \"Identifier\",
\"start\": 4,
\"end\": 8,
\"name\": \"tree\"
},
\"init\": {
\"type\": \"Literal\",
\"start\": 11,
\"end\": 25,
\"value\": \"this is tree\",
\"raw\": \"'this is tree'\"
}
}
],
\"kind\": \"var\"
}
],
\"sourceType\": \"module\"
}
至于有哪些词法单元可点击查看AST 对象文档 或者 参考掘金大佬的文章高级前端基础-JavaScript 抽象语法树 AST里面列举了语法树节点与解释。
例子 1:去 debugger
function fn() {
console.log('debugger')
debugger;
}
const parser = require('@babel/parser');
const traverse = require(\"@babel/traverse\");
const generator = require(\"@babel/generator\");
// 源代码
const code = `
function fn() {
console.log('debugger')
debugger;
}
`;
// 1. 源代码解析成 ast
const ast = parser.parse(code);
// 2. 转换
const visitor = {
// traverse 会遍历树节点,只要节点的 type 在 visitor 对象中出现,变化调用该方法
DebuggerStatement(path) {
// 删除该抽象语法树节点
path.remove();
}
}
traverse.default(ast, visitor);
// 3. 生成
const result = generator.default(ast, {}, code);
console.log(result.code)
// 4. 日志输出
// function fn() {
// console.log('debugger');
// }
function funA() {
console.log(1)
}
// 转换成
function funA() {
console.log('from function funA:', 1)
}
const visitor = {
CallExpression(path) {
// console.log(path)
}
const visitor = {
// 当遍历到 CallExpression 时候触发
CallExpression(path) {
const callee = path.node.callee;
// 判断当前当前执行的函数是否是组合表达式
if (types.isMemberExpression(callee)) {
const { object, property } = callee;
if (types.isIdentifier(object, { name: 'console' }) && types.isIdentifier(property, { name: 'log' })) {
// 查找最接近的父函数或程序
const parent = path.getFunctionParent();
const parentFunName = parent.node.id.name;
path.node.arguments.unshift(types.stringLiteral(`from function ${parentFunName}`))
}
}
}
}
标签: ast