zoukankan      html  css  js  c++  java
  • 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 输出各个参数及其含义。

    参考

  • 相关阅读:
    堆内存内部结构
    JVM 总体结构
    HTTP的工作原理
    HTTP协议简介
    服务器硬件资源_I/O
    maven常用命令行总结
    java enum—枚举的应用
    JAVA闰年的判断
    JAVA数据结构与算法——求最大公约数!!
    ThinkPHP 分页
  • 原文地址:https://www.cnblogs.com/shanpow/p/4183215.html
Copyright © 2011-2022 走看看