13 #ifndef WIBBLE_PARSE_H
14 #define WIBBLE_PARSE_H
28 template<
typename _Id >
51 template<
typename X,
typename Y >
52 inline std::ostream &operator<<( std::ostream &o, const std::pair< X, Y > &x ) {
53 return o <<
"(" << x.first <<
", " << x.second <<
")";
64 template<
typename Token,
typename Stream >
75 std::string r =
stream.remove();
76 std::copy( r.begin(), r.end(), std::back_inserter(
_window ) );
86 static_cast< void >( valid );
89 return std::string( b, e );
99 for(
int i = 0; i < n; ++i ) {
127 template<
typename I >
131 return std::equal( begin, end,
_window.begin() );
135 if (
match( data.begin(), data.end() ) )
136 return keep(
id, data );
140 unsigned n = 1, max = 0;
167 void match(
const std::string &from,
const std::string &to,
typename Token::Id id ) {
168 if ( !
match( from.begin(), from.end() ) )
172 int n = from.length();
178 if ( std::equal( to.begin(), to.end(), where ) )
186 while ( !
eof() && isspace(
window( 1 )[ 0 ] ) )
200 template<
typename Token,
typename Stream >
235 failures = std::priority_queue< Fail >();
238 void error( std::ostream &o, std::string prefix,
const Fail &fail ) {
240 switch ( fail.
type ) {
246 <<
", but seen " << Token::tokenName[ t.
id ] <<
" '" << t.
data <<
"'"
275 o <<
" error in context " <<
name <<
": ";
277 o <<
failures.size() <<
" rightmost alternatives:" << std::endl;
291 }
while ( t.
id == Token::Comment );
317 template<
typename Token,
typename Stream >
344 void fail(
const char *what,
FailType type = FailType::Syntax ) __attribute__((noreturn))
355 if ( t.
id == Token::Punctuation && t.
data ==
";" )
364 if ( t.
id == Token::Punctuation && t.
data ==
":" )
376 fail( Token::tokenName[
id].c_str() );
380 #if __cplusplus >= 201103L
381 template<
typename F >
382 void either(
void (F::*f)() ) {
383 (
static_cast< F*
>( this )->*f)();
386 template<
typename F,
typename... Args >
387 void either( F f, Args... args ) {
393 template<
typename F,
typename G >
397 (
static_cast< G*
>( this )->*g)();
402 #if __cplusplus >= 201103L
403 template<
typename F,
typename... Args >
404 bool maybe( F f, Args... args ) {
407 return maybe( args... );
411 template<
typename F,
typename G >
419 template<
typename F,
typename G,
typename H >
430 template<
typename F >
434 (
static_cast< F*
>( this )->*f)();
453 template<
typename T,
typename I >
465 #if __cplusplus >= 201103L
466 template<
typename F >
467 bool arbitrary( F f ) {
471 template<
typename F,
typename... Args >
472 bool arbitrary( F f, Args... args ) {
473 bool retval = arbitrary( args... );
474 retval |=
maybe( f );
475 retval |= arbitrary( args... );
480 template<
typename T,
typename I >
484 }
while (
next( sep ) );
487 template<
typename T,
typename I,
typename F >
488 void list( I i,
void (F::*sep)() ) {
494 (
static_cast< F*
>( this )->*sep)();
501 template<
typename T,
typename I >
511 if ( _fail && !t.
valid() ) {
513 fail(
"valid token" );