【发布时间】:2018-11-09 16:10:19
【问题描述】:
我正在使用一个跳过空格的解析器。在某一时刻,我不想跳过,所以我想使用qi::lexeme。但是,这要么不能编译,要么会弄乱我的结果。我特别无法理解最后一点。 lexeme 的属性是如何处理的?
这是我正在尝试做的一个示例:
#include <iostream>
#include <iomanip>
#include <string>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/vector.hpp>
namespace qi = boost::spirit::qi;
namespace fu = boost::fusion;
struct printer_type
{
void operator() (int i) const
{
std::cout << i << ' ';
}
void operator() (std::string s) const
{
std::cout << '"' << s << '"' << ' ';
}
} printer;
int main() {
for (std::string str : { "1foo 13", "42 bar 13", "13cheese 8", "101pencil13" }) {
auto iter = str.begin(), end = str.end();
qi::rule<std::string::iterator, qi::blank_type, fu::vector<int, std::string, int>()> parser = qi::int_ >> +qi::alpha >> qi::int_;
fu::vector<int, std::string, int> result;
bool r = qi::phrase_parse(iter, end, parser, qi::blank, result);
std::cout << " --- " << std::quoted(str) << " --- ";
if (r) {
std::cout << "parse succeeded: ";
fu::for_each(result, printer);
std::cout << '\n';
} else {
std::cout << "parse failed.\n";
}
if (iter != end) {
std::cout << " Remaining unparsed: " << std::string(iter, str.end()) << '\n';
}
}
}
注意这一行:
qi::rule<std::string::iterator, qi::blank_type, fu::vector<int, std::string, int>()> parser =
qi::int_ >> +qi::alpha >> qi::int_;
好的,所以我们需要一个 int,然后是一个字符串,然后是一个 int。但是,我不想跳过第一个 int 和字符串之间的空格,这里必须没有空格。如果我使用词素,合成的属性就会混乱。
没有lexeme 的运行会给出以下结果:
--- "1foo 13" --- parse succeeded: 1 "foo" 13
--- "42 bar 13" --- parse succeeded: 42 "bar" 13
--- "13cheese 8" --- parse succeeded: 13 "cheese" 8
--- "101pencil13" --- parse succeeded: 101 "pencil" 13
所以一切都解析得很好,这很好。但是,第二个示例 (42 bar 13) 不应该成功解析,所以这里是第一个 int 和字符串 (qi::lexeme[qi::int_ >> +qi::alpha] >> qi::int_;) 周围 lexeme 的结果:
" 0 "1foo 13" --- parse succeeded: 1 "
--- "42 bar 13" --- parse failed.
Remaining unparsed: 42 bar 13
--- "13cheese 8" --- parse succeeded: 13 " 0
" 0 "101pencil13" --- parse succeeded: 101 "
什么!?我不知道发生了什么,我很高兴有任何启发:)
附带问题:我想完全省略 lexeme 并定义一个不跳过的子规则。在这种情况下如何指定属性?
子规则有属性fusion::vector<int, std::string>(),但我仍然希望主规则有fusion::vector<int, std::string, int>()作为属性,而不是fusion::vector<fusion::vector<int, std::string>, int>()(无论如何都不会编译)。
【问题讨论】:
-
这不是完全重复的,但this 显示了类似的问题。在您的示例中,通过使用词位,您拥有
tuple<tuple<int,std::string>,int>的属性,而不是您想要的tuple<int,std::string,int>。您可以通过使用上述问题中的解决方法或使用语义操作自己处理属性来解决它。 -
使用来自this answer 的(未经测试的,可能质量低的)
flatten指令,似乎是give the results you want。
标签: c++ boost boost-spirit