AST
AST
AST
6 views
Oct 15, 2024
AST
定义:抽象语法树,源代码语法结构的一种抽象表示
以树状的形式表现编程语言的语法结构,树上的每个节点都表示源代码中的一种结构
n * n;
[
{ type: { ... }, value: "n", loc: { ... } },
{ type: { ... }, value: "*", loc: { ... } },
{ type: { ... }, value: "n", loc: { ... } },
...
]
每个type有一组属性来描述该令牌
{
type: {
label: 'name',
keyword: undefined,
beforeExpr: false,
startsExpr: true,
rightAssociative: false,
isLoop: false,
isAssign: false,
prefix: false,
postfix: false,
binop: null,
updateContext: null
},
...
}
举例
function square(n) {
return n * n;
}
转换为如下的抽象语法树
- FunctionDeclaration:
- id:
- Identifier:
- name: square
- params [1]
- Identifier
- name: n
- body:
- BlockStatement
- body [1]
- ReturnStatement
- argument
- BinaryExpression
- operator: *
- left
- Identifier
- name: n
- right
- Identifier
- name: n
或是如下的JavaScript对象
{
type: "FunctionDeclaration", // 类型 一个函数
id: {
type: "Identifier",
name: "square"
},
params: [{ // 参数
type: "Identifier",
name: "n"
}],
body: {
type: "BlockStatement",
body: [{
type: "ReturnStatement",
argument: {
type: "BinaryExpression",
operator: "*",
left: {
type: "Identifier",
name: "n"
},
right: {
type: "Identifier",
name: "n"
}
}
}]
}
}
ast
的每一层都有相同的结构,比如type
或者其他的