2

Kind of a hard-to-word title but I wanna parse something like this:

int_ >> repeat(N)[double_]

But I'd like N to be equal to whatever int_ parses out to

How does one do this using Boost.Spirit.X3?

Justin
  • 24,288
  • 12
  • 92
  • 142
ExBigBoss
  • 43
  • 6
  • 2
    https://stackoverflow.com/questions/33624149/boost-spirit-x3-cannot-compile-repeat-directive-with-variable-factor – llonesmiz Aug 15 '18 at 19:18

1 Answers1

1

It's easier to validate this after parsing. That is, just parse without restricting the count, then verify afterwards:

auto const p = x3::int_ >> *x3::double_;

// ...
std::pair<int, std::vector<double>> result;

if (x3::phrase_parse(begin, end, p, x3::space, result)) {
    if (result.first != result.second.size()) {
        // invalid
    }
}

If you really want to validate this while parsing, it's possible with semantic actions:

int size;
auto const store_size = [&size](auto& ctx) { size = _attr(ctx); };
auto const validate_size = [&size](auto& ctx) {
    if (size >= 0 && static_cast<std::size_t>(size) != _attr(ctx).size()) {
        _pass(ctx) = false;
    }
};
auto const p = x3::int_[store_size] >> (*x3::double_)[validate_size];
Justin
  • 24,288
  • 12
  • 92
  • 142