一个抽象语法树AST的生成需要经过下面的处理步骤:

  1. 使用词法分析器对源文件进行词法分析,生成Token。
  2. 将Token传给语法分析器,来生成AST

Golang官方提供了几个包,可以帮助我们进行AST分析:

  • go/scanner:词法分析,将源代码分割成一个个token
  • go/token:token类型及相关结构体定义
  • go/ast:ast的结构定义
  • go/parser:语法分析,读取token流生成ast

Golang的AST主要由三种节点构成:

  • 表达式和类型节点(Expr)
  • 语句节点(Stmt)
  • 声明节点(Decl)

其接口定义如下:

// All node types implement the Node interface.
type Node interface {
    Pos() token.Pos // position of first character belonging to the node
    End() token.Pos // position of first character immediately after the node
}
 
// All expression nodes implement the Expr interface.
type Expr interface {
    Node
    exprNode()
}
 
// All statement nodes implement the Stmt interface.
type Stmt interface {
    Node
    stmtNode()
}
 
// All declaration nodes implement the Decl interface.
type Decl interface {
    Node
    declNode()
}

Expr,Stmt和Decl都实现了Node接口