這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
前言
parser package 包含了 golang 文法分析相關的資料結構和方法,原始碼位於 <go-src>/src/go/parser
之前大概看了點 PHP 和 Ruby 的原始碼,感歎 go 確實如宣傳的一樣,簡潔如 C,parser.go 代碼總共 幾千行(Ruby 文法規則定義檔案有 1w 多行),使用遞迴下降文法分析方法(感覺 go 語言的文法規則很適合遞迴下降)
example_test.go
parser package 裡面也有一個樣本 example_test.go,如何使用 parser
func ExampleParseFile() { fset := token.NewFileSet() // positions are relative to fset // Parse the file containing this very example // but stop after processing the imports. f, err := parser.ParseFile(fset, "example_test.go", nil, parser.ImportsOnly) if err != nil { fmt.Println(err) return } // Print the imports from the file's AST. for _, s := range f.Imports { fmt.Println(s.Path.Value) } // output: // // "fmt" // "go/parser" // "go/token"}
parser struct
The parser structure holds the parser's internal state.
type parser struct { // 詞法掃描相關欄位 file *token.File errors scanner.ErrorList scanner scanner.Scanner ... pos token.Pos // token position tok token.Token // one token look-ahead lit string // token literal ... // 範圍相關欄位 pkgScope *ast.Scope // pkgScope.Outer == nil topScope *ast.Scope // top-most scope; may be pkgScope unresolved []*ast.Ident // unresolved identifiers imports []*ast.ImportSpec // list of imports ...}
parser 結構體以小寫字母開頭,意味著它是一個僅供內部使用的資料結構,裡面欄位比較多,一時不明白用途關係不大,有個大概印象
總結