Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

foldr_start_with_parser

Synopsis

template <class P, class StateP, class BackwardOp>
struct foldr_start_with_parser;

This is a parser combinator.

Table 29. Arguments

Name

Type

P

parser

StateP

parser

BackwardOp

template metafunction class taking two arguments


Description

The same as foldr, but after folding it applies a parser, StateP on the input. If StateP fails, foldr_start_with_parser fails. If it succeeds, the result of parsing is equivalent to boost::reverse_fold<Sequence, State, BackwardOp>, where Sequence is the sequence of the results of the applications of P and State is the result StateP returned after the repeated application of P on the input.

Here is a diagram showing how foldr_start_with_parser works by example:

using int_token = token<int_>;
using plus_token = token<lit_c<'+'>>;
using int_plus = first_of<int_token, plus_token>;
using sum_op = mpl::lambda<mpl::plus<mpl::_1, mpl::_2>>::type;

Further details can be found in the Introducing foldr_start_with_parser section of the User Manual.

Header

#include <boost/metaparse/foldr_start_with_parser.hpp>

Expression semantics

For any p parser, pt class, f metafunction class taking two arguments, s compile-time string and pos source position let pos_ be the position where the repeated application of p on s fails for the first time. Let s_ be the postfix of s starting at that position.

foldr_start_with_parser<p, pt, f>::apply<s, pos>

is equivalent to

pt::apply<s_, pos_>

when the above expression returns a parsing error. It is

return_<
  foldr<p, get_result<pt::apply<s_, pos_>>::type, f>::apply<s, pos>
>::apply<
  get_remaining<pt::apply<s_, pos_>>::type,
  get_position<pt::apply<s_, pos_>>::type
>

otherwise.

Example

#include <boost/metaparse/foldr_start_with_parser.hpp>
#include <boost/metaparse/lit_c.hpp>
#include <boost/metaparse/first_of.hpp>
#include <boost/metaparse/token.hpp>
#include <boost/metaparse/int_.hpp>
#include <boost/metaparse/string.hpp>
#include <boost/metaparse/start.hpp>
#include <boost/metaparse/get_result.hpp>
#include <boost/metaparse/is_error.hpp>

#include <boost/mpl/lambda.hpp>
#include <boost/mpl/plus.hpp>

using namespace boost::metaparse;

using int_token = token<int_>;
using plus_token = token<lit_c<'+'>>;
using int_plus = first_of<int_token, plus_token>;
using sum_op =
  boost::mpl::lambda<boost::mpl::plus<boost::mpl::_1, boost::mpl::_2>>::type;

using ints = foldr_start_with_parser<int_plus, int_token, sum_op>;

static_assert(
  get_result<
    ints::apply<BOOST_METAPARSE_STRING("11 + 13 + 3 + 21"), start>
  >::type::value == 48,
  "ints should sum the numbers"
);

static_assert(
  is_error<ints::apply<BOOST_METAPARSE_STRING(""), start>>::type::value,
  "when no numbers are provided, it should be an error"
);

PrevUpHomeNext