我有一个从 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 theSpirit
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/