This is a creation in Article, where the information may have evolved or changed.
Objective
The parser package contains data structures and methods related to Golang parsing, where the source code is located <go-src>/src/go/parser
Before probably read the source code of PHP and Ruby, exclamation go really as advertised, concise such as C,parser.go code total thousands of lines (Ruby syntax rule definition file has more than 1w lines), using recursive descent parsing method (feel that the grammar rules of the Go language is suitable for recursive descent)
Example_test.go
Parser package also has an example example_test.go, how to use 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 ...}
The parser structure begins with a lowercase letter, which means it is a data structure for internal use only, with more fields in it, and a little bit of a sense of purpose.
Summarize