在 C++ 代码库中使用 Ragel 解析字符串的原因是什么?

What are the reasons for using Ragel to parse strings in a C++ codebase?

我继承了一个使用Ragel进行字符串解析的C++项目

这是我第一次看到这样做,我想了解为什么有人会使用 Ragel 而不是 C++ 来解析字符串?

parser generators (improperly called "compiler-compilers") are very handsome to use and produce reliable and efficient C++ or C code (notably because parsing理论很好理解)。

一般来说,使用源代码生成器可能是明智之举。有时,特别是在大型项目中,编写自己的代码生成器是明智的(阅读 metaprogramming, notably SICP and even J.Pitrat's blog). Good build automation tools like GNU make or ninja 可以轻松配置为 运行 C 或 C++ 代码生成器并在构建时使用它们。

阅读 Ragel intro. Look also into flex, bison, ANTLR, rpcgen, Qt moc, swig, gperf 作为 C 或 C++ 生成器的常见示例。

在某些程序中,您甚至可以使用一些 JIT compilation library (such as libgccjit or LLVM) to dynamically generate code at run time and use it. On POSIX systems you could also generate at runtime a temporary C or C++ file, compile it as a plugin, and load that temporary plugin using dlopen & dlsym. Having a good culture about compilers and interpreters (e.g. thru the Dragon Book) 是值得的。

在您的应用程序中嵌入一些解​​释器(如 lua or guile)也是一种有趣的方法。但这是一个强有力的架构决策。

在很多情况下,生成源代码比手写更容易。当然这并不总是可能的。

PS。在阅读您的问题之前,我从未听说过 Ragel!