AST

410 阅读1分钟

什么是ast

ast就是把一段代码,然后转换成一颗语法树。

ast 如何工作

1, 词法分析

image.png
2,句法分析
image.png
最后转换成如下结果
image.png

ast 使用流程

1,code 转ast 2,修改ast 3,ast转code

ast 各种定义

1 VariableDeclaration

定义: 是指一段声明,type 表示声明,kind 表示类型,declarations 表示变量的具体定义

interface VariableDeclaration <: Declaration {
    type: "VariableDeclaration";
    declarations: [ VariableDeclarator ];
    kind: "var";
}

例子:

image.png

2 VariableDeclarator

定义:表示变量的定义,id 表示变量名称,init表示初始值 interface VariableDeclarator <: Node { type: "VariableDeclarator"; id: Pattern; init: Expression | null; } 例子:

var a = 1;

转换后

image.png

##3 Identifier 定义:标识符,name为名称

interface Identifier <: Expression, Pattern {
   type: "Identifier";
   name: string;
}

例子:

let a = 1;

a的Identifier 如下所示:

image.png

##3 BinaryExpression 二元操作符。 #babel ast ##Paths

{
  type: "FunctionDeclaration",
  id: {
    type: "Identifier",
    name: "square"
  },
  ...
}

如果这里的Identifier被视为path,则可以把上面的结构理解为一下结构

{
  "parent": {
    "type": "FunctionDeclaration",
    "id": {...},
    ....
  },
  "node": {
    "type": "Identifier",
    "name": "square"
  }
}

##Paths in Visitors

a + b + c;

转换后ast树如下:

image.png
如果遍历ast树的时候,可以通过path来访问

const MyVisitor = {
  Identifier(path) {
    console.log("Visiting: " + path.node.name);
  }
};

结果如下 ··· Visiting: a Visiting: b Visiting: c ··· ##Bindings Bindings就是一个变量或者其它的作用域范围

function scopeOnce() {
  var ref = "This is a binding";

  ref; // This is a reference to a binding

  function scopeTwo() {
    ref; // This is a reference to a binding from a lower scope
  }
}

比如这里的ref的表示如下:

{
  identifier: node,
  scope: scope,
  path: path,
  kind: 'var',

  referenced: true,
  references: 3,
  referencePaths: [path, path, path],

  constant: false,
  constantViolations: [path]
}

通过一些标识符表示被引用了几次,在哪里被引用,是不是常量等有关属性。