什么是AST
抽象语法树(Abstract Syntax Tree,AST),或简称语法树(Syntax tree),是源代码语法结构的一种抽象表示。它以树状的形式表现编程语言的语法结构,树上的每个节点都表示源代码中的一种结构。
应用场景
抽象语法树在很多领域有广泛的应用,比如浏览器,智能编辑器,编译器等。在JavaScript中,虽然我们并不会常常与AST直接打交道,但却也会经常的涉及到它。例如使用UglifyJS来压缩代码,bable对代码进行转换,ts类型检查,语法高亮等,实际这背后就是在对JavaScript的抽象语法树进行操作。
解析器 Parser
介绍前,请先打开 astexplorer.net/ 这个网址,这是个在线代码转化成AST工具。 输入简单的一行代码
var name = 'ast';
const names= ['zs', 'ls']
输出结果为
{
"type": "Program",
"body": [
{
"type": "VariableDeclaration",
"declarations": [
{
"type": "VariableDeclarator",
"id": {
"type": "Identifier",
"name": "name"
},
"init": {
"type": "Literal",
"value": "ast",
"raw": "'ast'"
}
}
],
"kind": "var"
},
{
"type": "VariableDeclaration",
"declarations": [
{
"type": "VariableDeclarator",
"id": {
"type": "Identifier",
"name": "names"
},
"init": {
"type": "ArrayExpression",
"elements": [
{
"type": "Literal",
"value": "zs",
"raw": "'zs'"
},
{
"type": "Literal",
"value": "ls",
"raw": "'ls'"
}
]
}
}
],
"kind": "const"
}
],
"sourceType": "module"
}
- type ==> node 类型
- VariableDeclarator ==> 变量声明
- Identifier ==> 标识符,就是我们写 JS 时自定义的名称,如变量名,函数名,属性名,都归为标识符。
- ArrayExpression ==> 数组表达式
- Literal ==> 字面量. 这里的字面量表示值,例如 names= ['zs', 'ls']; 就是zs , ls 不包含[]
- kind 属性表示是什么类型的声明
- id 就是我们自定义的名字
在输入一个函数看看结果
function add(a,b){
return a+b;
}
输出
{
"type": "Program",
"body": [
{
"type": "FunctionDeclaration",
"id": {
"type": "Identifier",
"name": "add"
},
"expression": false,
"generator": false,
"async": false,
"params": [
{
"type": "Identifier",
"name": "a"
},
{
"type": "Identifier",
"name": "b"
}
],
"body": {
"type": "BlockStatement",
"body": [
{
"type": "ReturnStatement",
"argument": {
"type": "BinaryExpression",
"left": {
"type": "Identifier",
"name": "a"
},
"operator": "+",
"right": {
"type": "Identifier",
"name": "b"
}
}
}
]
}
}
],
"sourceType": "module"
}
这个比上面多了些类型
- type ==> node 类型
- FunctionDeclaration ==> 函数声明(非函数表达式)
- BlockStatement ==> Block语句。
- ReturnStatement ==> Return语句
- BinaryExpression ==> 二元操作符表达式
- operator 操作符
- sourceType 源代码数的来源,一种是script脚本,一种是modules模块
本节主要对AST有个大概认识,下节主要讲如何通过babel将代码转成AST在转成js代码。