Hello Ragel -- 生成状态机的神器

Ragel 是个很 NB 的能生成状态机的编译器,而且支持一堆语言:C、C++、Object-C、C#、D、Java、Go 以及 Ruby。

原来的文本解析器是用正则表达式实现的,随着状态(if-else)越来越多,修改越来越麻烦。。。

安装

Mac OS 安装很简单,直接

brew install Ragel

其他系统没有试过,不过官网提供压缩包 ragel-6.9.tar.gz,里边有个 install.sh,想必是可以完成安装的。

格式

Ragel 通过将状态语句嵌入宿主语言,与宿主语言(Go、Ruby 等)共同组成可执行程序。其基本格式如下:

  • 使用 %%{}%% 包裹多行 Ragel 语句,或使用 %% 表示单行 Ragel 语句
  • 必须使用 machine 定义一个状态机名称(可以继承自其他 .rl 文件)
  • write data 生成数据
  • write init 生成初始化代码
  • write exec 生成执行代码

Hello World

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 输出如下:

console out

对 Ragel 参数感兴趣,可以使用 ragel -h 输出各个参数及其含义。

参考

posted @ 2014-12-24 19:34  山坡上的人们  阅读(1764)  评论(0编辑  收藏  举报