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