全文基于 https://astexplorer.net/ 网站, 选用 acorn 做 parse
通过逐个扫描全文字符串 code, 进行关键字匹配
上面代码转成语法树结构就是, 显而易见的是, 上面是从右到左依次解析.
{
"type": "Program",
"start": 0,
"end": 7,
"body": [
{
"type": "ExpressionStatement", 表达式
"start": 0,
"end": 7,
"expression": {
"type": "BinaryExpression",
"start": 0,
"end": 7,
"left": {
"type": "BinaryExpression",
"start": 0,
"end": 5,
"left": {
"type": "BinaryExpression", // 二项式运算
"start": 0,
"end": 3,
"left": {
"type": "Literal",
"start": 0,
"end": 1,
"value": 1,
"raw": "1"
},
"operator": "+",
"right": {
"type": "Literal",
"start": 2,
"end": 3,
"value": 2,
"raw": "2"
}
},
"operator": "+",
"right": {
"type": "Literal", // 字面量
"start": 4,
"end": 5,
"value": 3,
"raw": "3"
}
},
"operator": "+",
"right": {
"type": "Literal", // 字面量
"start": 6,
"end": 7,
"value": 4,
"raw": "4"
}
}
}
],
"sourceType": "module"
}
{
"type": "Program",
"start": 0,
"end": 18,
"body": [
{
"type": "VariableDeclaration", // const 变量声明表达式
"start": 0,
"end": 18,
"declarations": [
{
"type": "VariableDeclarator",
"start": 6,
"end": 17,
"id": {
"type": "Identifier",
"start": 6,
"end": 8,
"name": "fn"
},
"init": {
"type": "ArrowFunctionExpression",
"start": 11,
"end": 17,
"id": null,
"expression": true,
"generator": false,
"async": false,
"params": [
{
"type": "Identifier",
"start": 11,
"end": 12,
"name": "a"
}
],
"body": {
"type": "Identifier",
"start": 16,
"end": 17,
"name": "a"
}
}
}
],
"kind": "const"
}
],
"sourceType": "module"
}