在Spirit Qi中使用可选的解析器 [英] Use of optional parser in spirit qi
问题描述
我试图解析形式为"A + C"或"A"的加法表达式.经过几次测试,我意识到问题显然出在我对可选解析器的使用上,因此可以举例说明:
I'm trying to parse either an additive expression of the form "A+C", or "A" alone. After a few tests I realized that the problem is apparently my use of the optional parser, so to exemplify:
qi::rule<string::iterator, string()> Test;
Test =
(
qi::string("A")[qi::_val= qi::_1]
>> -(
qi::string("B")[qi::_val += qi::_1]
>> qi::string("C")[qi::_val += qi::_1]
)
)
;
string s1, s2;
s1 = "AB";
bool a= qi::parse(s1.begin(), s1.end(), Test, s2);
这个想法是解析"A"或"ABC",但是如果s1值为"AB"而没有"C",则a的值为true.我相信,尽管我将括号放在运算符-"之后,然后使用">>"运算符,但"C"部分被认为是可选的,而不是整个B >> C.有什么想法吗?
The idea is to parse 'A' or "ABC", but if the s1 value is "AB" without 'C', the value of a is true. I believe that although I put parenthesis after the operator '-' and then I use the ">>" operator, the 'C' part is considered optional, and not the B>>C as a whole. Any ideas?
推荐答案
容器属性未回溯.
这是一种性能选择.您需要使用例如来明确控制传播 qi :: hold
:
That's a performance choice. You need to explicitly control propagation using e.g. qi::hold
:
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;
int main() {
using It = std::string::const_iterator;
qi::rule<It, std::string()> Test;
Test =
(
qi::char_('A')
>> -qi::hold [
qi::char_('B')
>> qi::char_('C')
]
)
;
for (std::string const input : { "A", "AB", "ABC" })
{
std::cout << "-------------------------\nTesting '" << input << "'\n";
It f = input.begin(), l = input.end();
std::string parsed;
bool ok = qi::parse(f, l, Test, parsed);
if (ok)
std::cout << "Parsed success: " << parsed << "\n";
else
std::cout << "Parsed failed\n";
if (f != l)
std::cout << "Remaining unparsed: '" << std::string(f,l) << "'\n";
}
}
打印:
-------------------------
Testing 'A'
Parsed success: A
-------------------------
Testing 'AB'
Parsed success: A
Remaining unparsed: 'B'
-------------------------
Testing 'ABC'
Parsed success: ABC
请注意,我已经做了很多简化.
Note I have made a number of simplifications.
另请参阅:
这篇关于在Spirit Qi中使用可选的解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!