进行从基于的典型标识符解析器中提取字符串的语义动作的最简单方法是什么boost::spirit::x3::lexeme
?
我认为可能可以绕开需要解压缩属性的过程,而仅在输入流中使用迭代器,但显然x3::_where
并没有达到我的想法。
以下产量output
为空。我希望它包含“ foobar_hello”。
namespace x3 = boost::spirit::x3;
using x3::_where;
using x3::lexeme;
using x3::alpha;
auto ctx_to_string = [&](auto& ctx) {
_val(ctx) = std::string(_where(ctx).begin(), _where(ctx).end());
};
x3::rule<class identifier_rule_, std::string> const identifier_rule = "identifier_rule";
auto const identifier_rule_def = lexeme[(x3::alpha | '_') >> *(x3::alnum | '_')][ctx_to_string];
BOOST_SPIRIT_DEFINE(identifier_rule);
int main()
{
std::string input = "foobar_hello";
std::string output;
auto result = x3::parse(input.begin(), input.end(), identifier_rule, output);
}
我是否需要以某种方式从boost :: fusion对象中提取字符串,x3::_attr(ctx)
或者我做错了什么?
您可以简单地使用自动属性传播,这意味着您不需要语义动作(1)
#include <iostream>
#include <iomanip>
#define BOOST_SPIRIT_X3_DEBUG
#include <boost/spirit/home/x3.hpp>
namespace x3 = boost::spirit::x3;
namespace P {
x3::rule<class identifier_rule_, std::string> const identifier_rule = "identifier_rule";
auto const identifier_rule_def = x3::lexeme[(x3::alpha | x3::char_('_')) >> *(x3::alnum | x3::char_('_'))];
BOOST_SPIRIT_DEFINE(identifier_rule)
}
int main() {
std::string const input = "foobar_hello";
std::string output;
auto result = x3::parse(input.begin(), input.end(), P::identifier_rule, output);
}
版画
<identifier_rule>
<try>foobar_hello</try>
<success></success>
<attributes>[f, o, o, b, a, r, _, h, e, l, l, o]</attributes>
</identifier_rule>
注意我已更改
'_'
为x3::char_('_')
捕获下划线(x3::lit
不捕获匹配的内容)
如果你坚持语义动作,
rule<..., std::string, true>
到也迫使自动attrobute传播_where
您的希望是指向:http : //coliru.stacked-crooked.com/a/336c057dabc86a84用于x3::raw[]
公开受控的源迭代器范围(http://coliru.stacked-crooked.com/a/80a69ae9b99a4c61)
auto ctx_to_string = [](auto& ctx) {
std::cout << "\nSA: '" << _attr(ctx) << "'" << std::endl;
_val(ctx) = std::string(_attr(ctx).begin(), _attr(ctx).end());
};
x3::rule<class identifier_rule_, std::string> const identifier_rule = "identifier_rule";
auto const identifier_rule_def = x3::raw[ lexeme[(x3::alpha | '_') >> *(x3::alnum | '_')] ] [ctx_to_string];
BOOST_SPIRIT_DEFINE(identifier_rule)
请注意,现在
char_('_')
不再起作用了
考虑使用内置的属性帮助器:http : //coliru.stacked-crooked.com/a/3e3861330494e7c9
auto ctx_to_string = [](auto& ctx) {
using x3::traits::move_to;
move_to(_attr(ctx), _val(ctx));
};
请注意,这比内置属性传播的方式近似,尽管它比让Spirit管理它的灵活性要差得多
(1)强制链接:Boost Spirit:“语义行为是邪恶的”?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句