c++ - 如何使用 boost::spirit::lex 实现包含指令?

标签 c++ boost boost-spirit boost-spirit-lex

我有一个从 spirit::lex 和 spirit::qi 构建的简单配置文件解析器。当词法分析器到达模式 include "path" 时,我希望包含文件的文本。你可能知道,spirit::lexer::begin() 启动扫描过程:

// Read file contents into a std::string
...

// _first and _last are const char*
_first = _contents.c_str();
_last  = &_first[_input.size()];

// _token is a lexer::iterator_type for the current token
_token = _lexer.begin(_first, _last);

我的想法是有一个堆栈来存储表示为结构的词法分析器状态:

struct LexerState
{
    const char* first;
    const char* last;
    std::string contents;
};

词法分析器将识别include "path" 的模式,并在语义操作中提取包含文件的路径。然后,将当前词法分析器状态压入堆栈,将文件内容加载到字符串中,并使用 lexer::begin() 如上所述初始化新状态。

当词法分析器找到 EOF 字符时,弹出堆栈并使用先前的词法分析器状态变量调用 lexer::begin()。

像这样重复调用 lexer::begin() 可以吗?如何让 lex::lexer 识别 include "path" 模式和 EOF 字符而不向 qi 解析器返回标记?

最后,是否有任何替代或更好的方法来实现这一目标?

最佳答案

看看如何 Boost Wave 做事:

The Wave C++ preprocessor library uses the Spirit parser construction library to implement a C++ lexer with ISO/ANSI Standards conformant preprocessing capabilities. It exposes an iterator interface, which returns the current preprocessed token from the input stream. This preprocessed token is generated on the fly while iterating over the preprocessor iterator sequence (in the terminology of the STL these iterators are forward iterators).

关于功能:

The C++ preprocessor provides four separate facilities that you can use as you see fit:

  • Inclusion of header files
  • Macro expansion
  • Conditional compilation
  • Line control

他们的 Quick Start Sample展示了您将如何使用 Boost Wave 的词法分析器界面。

关于c++ - 如何使用 boost::spirit::lex 实现包含指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10525216/

相关文章:

c++ - 逐行遍历char数组的最佳方法

c++ - 如何绕过匹配的 Boost Variant 返回类型?

c++ - Boost.Spirit X3 解析器 "no type named type in(...)"

c++ - 正则表达式替换:到 ":"等

c++ - Boost 图形库 C++/幂律

c++ - 什么时候我应该选择 boost spirit attr_cast 而不是语义 Action

c++ - 具有相同简单改编结构属性的 boost::spirit::qi 规则会产生编译错误

c++ - 列表迭代器删除 "Debug assertion failed"

c++ - 将一个txt文件读入一个字符串

c++ - 在 cocos2d-x ios 的 UITestFieldTest 中使用未声明的标识符