Go 1.8rc3 原始碼學習:parser

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

前言

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 結構體以小寫字母開頭,意味著它是一個僅供內部使用的資料結構,裡面欄位比較多,一時不明白用途關係不大,有個大概印象

總結

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.