Using Boost.Spirit X3, I want to parse a comma-separated list of ranges and individual numbers (e.g. 1-4, 6, 7, 9-12) into a single std::vector<int>
. Here's what I've come up with:
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] ) % ',' );
}
Given the input
"1,2,3,4,6,7,9,10,11,12", // individually enumerated
"1-4,6-7,9-12", // short-hand: using three ranges
this is successfully parsed as ( 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,
Question: I think I understand that applying the semantic action expand
to the range
part is necessary, but why do I also have to apply the semantic action push
to the number
part? Without it (i.e. with a plain ( -(range [expand] | number) % ',')
rule for expr
, the individual numbers don't get propagated into the AST ( Live On Coliru ):
OK! Parsed:
OK! Parsed: 1, 2, 3, 4, 6, 7, 9, 10, 11, 12,
Bonus Question: do I even need semantic actions at all to do this? The Spirit X3 documentation seems to discourage them.