?
本文檔使用 php中文網(wǎng)手冊 發(fā)布
import "go/parser"
Overview
Index
Examples
Package parser為Go源文件實現(xiàn)解析器。輸入可以以各種形式提供(參見各種Parse *函數(shù)); 輸出是表示Go源的抽象語法樹(AST)。解析器是通過一個Parse *函數(shù)調(diào)用的。
解析器接受比Go規(guī)范在語法上允許的語言更大的語言,以簡化語法錯誤,并提高語法錯誤的健壯性。例如,在方法聲明中,接收器被看作是一個普通的參數(shù)列表,因此可能包含多個條目,其中規(guī)范只允許一個。因此,AST(ast.FuncDecl.Recv)字段中的對應(yīng)字段不限于一個條目。
func ParseDir(fset *token.FileSet, path string, filter func(os.FileInfo) bool, mode Mode) (pkgs map[string]*ast.Package, first error)
func ParseExpr(x string) (ast.Expr, error)
func ParseExprFrom(fset *token.FileSet, filename string, src interface{}, mode Mode) (ast.Expr, error)
func ParseFile(fset *token.FileSet, filename string, src interface{}, mode Mode) (f *ast.File, err error)
type Mode
ParseFile
interface.go parser.go
func ParseDir(fset *token.FileSet, path string, filter func(os.FileInfo) bool, mode Mode) (pkgs map[string]*ast.Package, first error)
ParseDir針對path指定的目錄中名稱以“.go”結(jié)尾的所有文件調(diào)用ParseFile,并返回包名 - > AST包與所有找到的包。
如果filter!= nil,則只考慮os.FileInfo條目通過過濾器(以“.go”結(jié)尾)的文件。模式位不變地傳遞給ParseFile。位置信息記錄在fset中,不能為零。
如果無法讀取目錄,則返回零映射和相應(yīng)的錯誤。如果發(fā)生分析錯誤,則返回一個非零但不完整的映射和遇到的第一個錯誤。
func ParseExpr(x string) (ast.Expr, error)
ParseExpr是獲取表達(dá)式x的AST的便捷函數(shù)。記錄在AST中的位置信息是未定義的。錯誤消息中使用的文件名是空字符串。
func ParseExprFrom(fset *token.FileSet, filename string, src interface{}, mode Mode) (ast.Expr, error)
ParseExprFrom是一個用于解析表達(dá)式的便捷函數(shù)。參數(shù)的含義與ParseFile相同,但源必須是有效的Go(類型或值)表達(dá)式。具體而言,fset不能為零。
func ParseFile(fset *token.FileSet, filename string, src interface{}, mode Mode) (f *ast.File, err error)
ParseFile解析單個Go源文件的源代碼并返回相應(yīng)的ast.File節(jié)點。源代碼可以通過源文件的文件名或通過src參數(shù)提供。
如果src!= nil,ParseFile解析來自src的源文件并且文件名僅在記錄位置信息時使用。src參數(shù)的參數(shù)類型必須是string,[] byte或io.Reader。如果src == nil,ParseFile解析由filename指定的文件。
mode參數(shù)控制解析的源文本的數(shù)量和其他可選的解析器功能。位置信息記錄在文件集fset中,該文件集不能為零。
如果源無法讀取,則返回的AST為零,并且錯誤指示特定故障。如果源被讀取但發(fā)現(xiàn)語法錯誤,則結(jié)果是部分AST(ast.Bad *節(jié)點代表錯誤源代碼的片段)。多個錯誤通過一個scanner.ErrorList按文件位置排序返回。
package mainimport ("fmt""go/parser""go/token")func main() { fset := token.NewFileSet() // positions are relative to fset src := `package foo import ( "fmt" "time" ) func bar() { fmt.Println(time.Now()) }`// Parse src but stop after processing the imports. f, err := parser.ParseFile(fset, "", src, 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)}}
Mode值是一組標(biāo)志(或0)。它們控制解析的源代碼量和其他可選的解析器功能。
type Mode uint
const ( PackageClauseOnly Mode = 1 << iota // stop parsing after package clause ImportsOnly // stop parsing after import declarations ParseComments // parse comments and add them to AST Trace // print a trace of parsed productions DeclarationErrors // report declaration errors SpuriousErrors // same as AllErrors, for backward-compatibility AllErrors = SpuriousErrors // report all errors (not just the first 10 on different lines))