go-lexer-詞法分析

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

詞法分析一般是編譯器的第一部分,而且詞法分析很簡單,就是一個有限狀態機器.
開始詞法分析的過程就是把源檔案轉換成一組預先定義好的token的過程.
這一組被統一表現的token之後會被送入文法分析器進行文法解析,這裡我們主要關注如何進行詞法分析.

做詞法分析就幾種方法:

  1. 直接使用工具比如lex.
  2. 使用更低一層的Regex.
  3. 使用狀態動作,構造一個狀態機器.

而真正實現一個語言的話,使用工具沒有什麼錯,但是問題是,很難獲得正確的錯誤提示.
工具產生的錯誤處理很弱.而且需要學習另一門規則或特定的文法.產生的程式碼可能效能不好,難以最佳化,但是用工具可以非常簡單實現詞法分析.
早期編譯器的設計階段都會使用lex來做詞法分析器,比如gcc和Go都是這麼做的,但是到了後期一個真正生產化的語言可能不能依賴產生的程式碼,而需要做自己特定的修改和最佳化,所以自己實現一個詞法分析器就顯得比較重要了.

正則表達被人詬病的一個話題就是效率問題,比如perl擁有功能最強大的Regex,但是整個Regex引擎的效率卻很低,Go在這方面犧牲了一些Regex的特性來保證Regex的效率不至於過低,但是Regex對於大量文本處理體現的弱勢卻是很明顯的.因為可能我們要處理的狀態其實不需要一個繁重的正則表達來解決.

其實實現一個詞法分析器很簡單,而且這種技能是基本不會變的,如果寫過一次,以後都是同樣的實現方式.

先看一下Go的實現,在Go的源碼下面go/token/token.go目錄裡面是這麼定義token的.

// Token is the set of lexical tokens of the Go programming language.type Token int

其實就是個枚舉類型,對於每種類型的字面值都有對應的token.
實際上這個只能算是一個token的類型.

// The list of tokens.const (        // Special tokens        ILLEGAL Token = iota        EOF        COMMENT        literal_beg        // Identifiers and basic type literals        // (these tokens stand for classes of literals)        IDENT  // main        INT    // 12345        FLOAT  // 123.45        IMAG   // 123.45i        CHAR   // 'a'        STRING // "abc"    // 省略)

枚舉所有可以碰到的token類型.

go/token/position.go 當中是關於token位置相關的定義.

// -----------------------------------------------------------------------------// Positions// Position describes an arbitrary source position// including the file, line, and column location.// A Position is valid if the line number is > 0.//type Position struct {        Filename string // filename, if any        Offset   int    // offset, starting at 0         Line     int    // line number, starting at 1           Column   int    // column number, starting at 1 (byte count)}

這個很簡單就是標示在檔案中的位置,比較有意思的是Pos的定義type Pos int,這是位置標示的緊湊表示.接下來看看Pos和Position之間是如何轉換的.

首先定義了一個FileSet,可以理解為把File的內容位元組按順序存放的一個大數組,而某個檔案則屬於數組的一個區間[base,base+size]中,base是檔案的第一個位元組在大數組中的位置,size是這個檔案的大小,某個檔案中的Pos是在[base,base+size]這個區間裡的一個小標.

所以最後Pos能夠壓縮成一個整數來表示一個檔案當中的位置,當需要使用的使用再從FileSet中轉換出完整的Position對象.

go/token/serialize.go 是對FileSet序列化,這裡就略過了.

所以整個go/token包只是對token的一些定義和轉化,詞法分析的部分在go/scanner當中.

scan的主流程如下,主體是一個switch case表示的狀態機器,
比如碰到字元那麼掃描到不為字元為止就作為一個標識符,比如碰到數字那麼可能按照掃描數字,然後向後看一次小數字再掃描數字,直到沒有數字為止.
scan每次會返回一個被掃描的token,壓縮表示的位置,和字面值的字串,這樣就能夠把一個源檔案轉化成一個token的記號流,也就是tokenize或者lexical analysis的過程.

func (s *Scanner) Scan() (pos token.Pos, tok token.Token, lit string) {scanAgain:        s.skipWhitespace()         // current token start        pos = s.file.Pos(s.offset)        // determine token value        insertSemi := false        switch ch := s.ch; {    /* 字元開頭,開始掃描標識符 */        case isLetter(ch):                lit = s.scanIdentifier()                if len(lit) > 1 {                        // keywords are longer than one letter - avoid lookup otherwise                        tok = token.Lookup(lit)                        switch tok {                        case token.IDENT, token.BREAK, token.CONTINUE, token.FALLTHROUGH, token.RETURN:                                insertSemi = true                        }                } else {                        insertSemi = true                        tok = token.IDENT                }     /* 數字開頭,掃描數字 */        case '0' <= ch && ch <= '9':                insertSemi = true                tok, lit = s.scanNumber(false)        default:

看一下例子的結果.

func ExampleScanner_Scan() {        // src is the input that we want to tokenize.    // 需要記號化的源檔案        src := []byte("cos(x) + 1i*sin(x) // Euler")        // Initialize the scanner.        var s scanner.Scanner        fset := token.NewFileSet()                      // positions are relative to fset    // 添加到檔案集合中        file := fset.AddFile("", fset.Base(), len(src)) // register input "file"    // 初始化scanner        s.Init(file, src, nil /* no error handler */, scanner.ScanComments)        // Repeated calls to Scan yield the token sequence found in the input.        for {                pos, tok, lit := s.Scan()                if tok == token.EOF {                        break                }                fmt.Printf("%s\t%s\t%q\n", fset.Position(pos), tok, lit)        }    // 不斷掃描就能得到如下結果    // 詞法分析就是做這樣一件事情.        // output:        // 1:1  IDENT   "cos"        // 1:4  (       ""        // 1:5  IDENT   "x"        // 1:6  )       ""        // 1:8  +       ""        // 1:10 IMAG    "1i"        // 1:12 *       ""        // 1:13 IDENT   "sin"        // 1:16 (       ""        // 1:17 IDENT   "x"        // 1:18 )       ""        // 1:20 ;       "\n"        // 1:20 COMMENT "// Euler"}

我在我的資料結構字元畫產生工具[1]裡面就實現了一個詞法分析器,方便我用簡單的文法構造一個字元畫,然後插入到注釋中輔助解釋.
唯一的不同的是,我使用了channel讀取token記號,來增加並發,而go本身的記號化是串列的,當然,這點區別其實沒有多大,而且這個設計
在Go的模板包裡面使用了,Rob Pike也有過相關的演講[2].

  1. https://github.com/ggaaooppeenngg/cpic/blob/master/lex.go
  2. http://cuddle.googlecode.com/hg/talk/lex.html#landing-slide

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.