抽象语法树(abstract syntax tree, AST)

Abstract syntax tree

In computer science, an abstract syntax tree (AST), or just syntax tree, is a tree representation of the abstract syntactic structure of source code written in a programming language. Each node of the tree denotes a construct occurring in the source code.

抽象语法树(AST)就是由代码本身解析得到的一个树形结构

直接盗用 wikipedia 的图

1
2
3
4
5
6
while b ≠ 0
if a > b
a := a − b
else
b := b − a
return a

Abstract_syntax_tree_for_Euclidean_algorithm
图片来源

编译原理

至于为什么会有这么一个东西以及怎么来的就要祭出我们的编译原理了:

compile_process
图片来源

高级语言需要经过以上步骤才能被计算机识别并执行,ast 就是前端(编译原理上的“前端”)的产物,解释型语言的后端往往被虚拟机替代了,不会直接生成二进制文件。ast 包含了代码的全部信息,按一定规则解析 ast 就可以得到目标程序,可以说 ast 就是“结构化”后的代码。

javascript_ast
图片来源

js 与 ts 的区别

没啥区别

不能说十分相似只能说完全一样!

1
2
3
function add(a, b) {
return a + b;
}

add-ast

然而 ts 多了类型系统,所以在 ast 上也会有相应的结点来体现,比如

1
2
3
function add(a: number, b: number) {
return a + b;
}

ts-ast

这里 ts 的 ast 是基于 ts 本身编译器的 compile api 来实现的,所以结构上和 js 的会有些不同。(这里 js 用的 babel 的 parser,基于acorn)

当然也可以用 js 来处理 ts 的项目,毕竟本质上就是一些字符串而已,但是 ts 提供了独立的编译 api,可以更方便地处理文件(懒得搞 js)

前端应用

  1. es6 转 es5(不完全可以)

  2. 偷懒语法转换(babel-plugin-import 这类)

  3. 引用分析

  4. 小程序热更新

示例:BigInt babel 插件

https://github.com/dreamhuan/bigint

开源的完整版

见代码

手动简陋版

见代码

小工具:静态引用分析

https://github.com/dreamhuan/next-analysis

目的

  1. 找出项目中没有被引用的文件
  2. 找出页面的组件引用情况
  3. 找出组件的被引用情况

架构

next-analysis

常用链接 & 参考文章