Macro esparse::eat [] [src]

macro_rules! eat {
    (@collect $lexer:expr => $id:tt $all:tt, { $($($p:pat)|+ if $c:expr => $e:expr ,)* }, _ => $else:expr $(,)*) => { ... };
    (@collect $lexer:expr => $id:tt $all:tt, { $($($p:pat)|+ if $c:expr => $e:expr ,)* }, $($q:pat)|+ => $f:expr, $($t:tt)+) => { ... };
    (@collect $lexer:expr => $id:tt $all:tt, { $($($p:pat)|+ if $c:expr => $e:expr ,)* }, $($q:pat)|+ if $d:expr => $f:expr, $($t:tt)+) => { ... };
    ($lexer:expr => $id:tt { $($all:tt)* }, $($t:tt)+) => { ... };
    ($lexer:expr => $id:tt, $($t:tt)+) => { ... };
    ($lexer:expr, $($t:tt)+) => { ... };
}

Consumes a token from the given lexer if it matches one of the patterns given.

Syntax

This example is not tested
eat!(lexer => tok { all_cases },
    pat1_1 | pat1_2 | ... if guard1 => expr1,
    pat2_1 | pat2_2 | ... if guard2 => expr2,
    _ => else_expr,
)

Each pattern is matched against lexer's current token type (Tt), and, if it matches, lexer is advanced, all_cases is evaluated, and finally the corresponding expression is evaluated. tok is an identifier to which the consumed token is bound.

{ all_cases } can be omitted, as can the entire => tok { all_cases } block.

Examples

Conditionally accept a token:

#[macro_use]
extern crate esparse;
use esparse::lex::{self, Tt};

let mut lexer = lex::Lexer::new_unnamed("foo = 1");
eat!(lexer,
    Tt::Id(name) => println!("the name is: {}", name),
    _ => panic!("expected identifier"),
);

Parse a token stream while outputting source code to a string:

#[macro_use]
extern crate esparse;
use esparse::lex::{self, Tt};
use std::fmt::Write;

let mut lexer = lex::Lexer::new_unnamed("/* example */ foo = 1");
let mut output = String::new();

eat!(lexer => tok { write!(output, "{}{}", tok.ws_before, tok.tt).unwrap() },
    Tt::Id(name) => println!("the name is: {}", name),
    _ => panic!("expected identifier"),
);

assert_eq!(output, "/* example */ foo");