Go 1.8RC3 Source Code Learning: Parser

Source: Internet
Author: User
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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.