Ragel 是個很 NB 的能生成狀態機的編譯器,並且支持一堆語言:C、C++、Object-C、C#、D、Java、Go 以及 Ruby。html
原來的文本解析器是用正則表達式實現的,隨着狀態(if-else)愈來愈多,修改愈來愈麻煩。。。正則表達式
Mac OS 安裝很簡單,直接ruby
brew install Ragel
其餘系統沒有試過,不過官網提供壓縮包 ragel-6.9.tar.gz,裏邊有個 install.sh
,想必是能夠完成安裝的。.net
Ragel 經過將狀態語句嵌入宿主語言,與宿主語言(Go、Ruby 等)共同組成可執行程序。其基本格式以下:code
%%{}%%
包裹多行 Ragel 語句,或使用 %%
表示單行 Ragel 語句machine
定義一個狀態機名稱(能夠繼承自其餘 .rl 文件)write data
生成數據write init
生成初始化代碼write exec
生成執行代碼package main import ( "fmt" ) %%{ machine hello; write data; }%% func main(){ run_machine("h") run_machine("w") } func run_machine(data string){ cs, p, pe := 0, 0, len(data) fmt.Println("Running the state machine with input ",data) %%{ exp1 = "h"; exp2 = "w"; main:=(exp1 @ {fmt.Println("Hello world")} | exp2 @ {fmt.Println("welcome")}); write init; write exec; }%% fmt.Println("Finished. The state of the machine is: ",cs) fmt.Println("p: ",p," pe: ",pe) }
保存爲 hello.rl
而後執行 ragel -Z hello.rl
則生成 hello.go,執行 go run hello.go
輸出以下:htm
對 Ragel 參數感興趣,可使用 ragel -h
輸出各個參數及其含義。blog