Skip to content

AST 节点类型遍历表

estree git

在 JavaScript 的抽象语法树(AST)中,节点类型(type)定义了代码结构的分类。不同解析器(如 Acorn、Babel、Esprima)遵循 ESTree 规范,但可能有扩展。以下是常见类型分类及示例:


一、核心类型

类型描述代码示例
Program整个程序的根节点const a = 1;
Identifier标识符(变量名/函数名)const a = 1;
Literal字面量值const a = 1;
ExpressionStatement表达式语句a = 5;
BlockStatement代码块({} 包裹){ console.log(a); }

二、声明与作用域

类型描述代码示例
VariableDeclaration变量声明 (var/let/const)const a = 1;
FunctionDeclaration函数声明function foo() {}
ClassDeclaration类声明class Foo {}
ImportDeclarationES6 导入import fs from 'fs';
ExportDefaultDeclaration默认导出export default foo;

三、表达式

类型描述代码示例
CallExpression函数调用foo()
MemberExpression成员访问 (obj.prop/obj['prop'])obj.prop
BinaryExpression二元运算 (+, >, === 等)a + b
UnaryExpression一元运算 (!, -, typeof)!true
ArrowFunctionExpression箭头函数() => {}
TemplateLiteral模板字符串`Hello ${name}`
LogicalExpression逻辑运算 (&&/`

四、控制流

类型描述代码示例
IfStatementif 语句if (a) { ... }
ForStatementfor 循环for (let i=0; i<5; i++)
WhileStatementwhile 循环while (true) { ... }
SwitchStatementswitch 语句switch (a) { ... }
ReturnStatementreturn 语句return a;
ThrowStatementthrow 语句throw new Error();
TryStatementtry/catchtry { ... } catch(e) {}

五、其他常见类型

类型描述代码示例
ObjectExpression对象字面量{ name: 'Alice' }
ArrayExpression数组字面量[1, 2, 3]
AssignmentExpression赋值操作 (=, += 等)a = 10
NewExpressionnew 实例化new Date()
ThisExpressionthis 关键字this.name
SpreadElement展开运算符 (...)[...arr]

六、工具与扩展

  1. 查看完整类型列表
  2. 解析器差异
    • Babel:支持实验性语法(如装饰器)。
    • Acorn:轻量级,符合 ESTree。
    • TypeScript 解析器:额外支持类型注解节点(如 TSTypeAnnotation)。

示例 AST 片段

json5
// 代码: const sum = (a, b) => a + b;
{
    type: "Program",
    body: [
        {
            type: "VariableDeclaration",
            declarations: [
                {
                    type: "VariableDeclarator",
                    id: {
                        type: "Identifier",
                        name: "sum"
                    },
                    init: {
                        type: "ArrowFunctionExpression",
                        params: [
                            {
                                type: "Identifier",
                                name: "a"
                            },
                            {
                                type: "Identifier",
                                name: "b"
                            }
                        ],
                        body: {
                            type: "BinaryExpression",
                            operator: "+",
                            left: {
                                type: "Identifier",
                                name: "a"
                            },
                            right: {
                                type: "Identifier",
                                name: "b"
                            }
                        }
                    }
                }
            ]
        }
    ]
}