为什么这个解析器离开'b'
在属性中,即使选项不匹配?
using namespace boost::spirit::qi;
std::string str = "abc";
auto a = char_("a");
auto b = char_("b");
qi::rule<std::string::iterator, std::string()> expr;
expr = +a >> -(b >> +a);
std::string res;
bool r = qi::parse(
str.begin(),
str.end(),
expr >> lit("bc"),
res
);
解析成功,但是res是"ab"
.
如果解析"abac"
单独使用 expr,选项被匹配并且属性是"aba"
.
与相同"aac"
,选项没有开始匹配并且属性是"aa"
.
但与"ab"
,属性为"ab"
,即使 b 被回溯,并且如示例所示,与下一个解析器匹配。
UPD
With expr.name("expr");
and debug(expr);
I got
<expr>
<try>abc</try>
<success>bc</success>
<attributes>[[a, b]]</attributes>
</expr>
Firstly, it's UB to use the auto
variables to keep the expression templates, because they hold references to the temporaries "a"
and "b"
[1].
而是写
expr = +qi::char_("a") >> -(qi::char_("b") >> +qi::char_("a"));
或者,如果您坚持:
auto a = boost::proto::deep_copy(qi::char_("a"));
auto b = boost::proto::deep_copy(qi::char_("b"));
expr = +a >> -(b >> +a);
现在注意到>> lit("bc")
部分隐藏在parse
调用,表明您可能希望在解析失败时回溯到成功匹配的标记。
但这并没有发生:Spirit 生成 PEG 语法,并且总是贪婪地从左到右匹配。
对于给出的样本,ab
结果,即使回溯does发生时,对属性的影响不会回滚,除非qi::hold
: 住在科里鲁
容器属性通过 ref 传递,先前(成功)表达式的效果是not回滚,除非你也告诉精灵。这样,您就可以“为您使用的内容付费”(因为一直复制临时文件的成本很高)。
参见例如
- boost::spirit::qi 对输出进行重复解析
- 理解 Boost.spirit 的字符串解析器
- 提升精神恢复解析
<a>
<try>abc</try>
<success>bc</success>
<attributes>[a]</attributes>
</a>
<a>
<try>bc</try>
<fail/>
</a>
<b>
<try>bc</try>
<success>c</success>
<attributes>[b]</attributes>
</b>
<a>
<try>c</try>
<fail/>
</a>
<bc>
<try>bc</try>
<success></success>
<attributes>[]</attributes>
</bc>
Success: 'ab'
[1] see here:
- 将解析器分配给自动变量
- 从替代解析器表达式的可变参数列表生成 Spirit 解析器表达式
- boost Spirit V2 qi 与优化级别相关的错误
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)