Boost.Spirit X3を使用して、範囲と個々の数字 (例: 1-4、6、7、9-12) のカンマ区切りのリストを単一の に解析したいと考えていますstd::vector<int>
。これが私が思いついたものです:
namespace ast {
struct range
{
int first_, last_;
};
using expr = std::vector<int>;
}
namespace parser {
template<typename T>
auto as_rule = [](auto p) { return x3::rule<struct _, T>{} = x3::as_parser(p); };
auto const push = [](auto& ctx) {
x3::_val(ctx).push_back(x3::_attr(ctx));
};
auto const expand = [](auto& ctx) {
for (auto i = x3::_attr(ctx).first_; i <= x3::_attr(ctx).last_; ++i)
x3::_val(ctx).push_back(i);
};
auto const number = x3::uint_;
auto const range = as_rule<ast::range> (number >> '-' >> number );
auto const expr = as_rule<ast::expr> ( -(range [expand] | number [push] ) % ',' );
}
入力を考えると
"1,2,3,4,6,7,9,10,11,12", // individually enumerated
"1-4,6-7,9-12", // short-hand: using three ranges
Live On Coliruこれは ( )として正常に解析されます。
OK! Parsed: 1, 2, 3, 4, 6, 7, 9, 10, 11, 12,
OK! Parsed: 1, 2, 3, 4, 6, 7, 9, 10, 11, 12,
質問expand
: セマンティック アクションをパーツに適用する必要があることは理解していると思いますrange
が、なぜパーツにもセマンティック アクションを適用する必要があるpush
のnumber
ですか? それがなければ (つまり、 の単純な( -(range [expand] | number) % ',')
ルールでexpr
は、個々の数値は AST ( ) に伝播されませんLive On Coliru:
OK! Parsed:
OK! Parsed: 1, 2, 3, 4, 6, 7, 9, 10, 11, 12,
おまけの質問: これを行うにはセマンティック アクションが必要ですか? Spirit X3 のドキュメントは彼らを思いとどまらせているようです。