macro_rules! one_of {
($tokens:ident; $( $e:expr ),+ $(,)?) => { ... };
($alias:ident from $tokens:expr; $( $e:expr ),+ $(,)?) => { ... };
}Expand description
Pass the provided tokens into each expression, one after the other. All of the
expressions provided must return something implementing [crate::one_of::IsMatch],
ie Option<T> or bool. It will try each expression until a match is found,
consuming no tokens for any expressions that to not match.
- If expressions return
Option<T>, thenSome(T)denotes that we’ve found a match and can return it, andNonemeans that one_of should try the next expression. - If expressions return
bool, then returning true denotes that we’ve found a match and returningfalsemeans to try the next expression.
§Examples
A basic example:
use yap::{ Tokens, IntoTokens };
let mut tokens = "hello world".into_tokens();
// The macro expects a mutable reference to your tokens:
let ts = &mut tokens;
let res = yap::one_of!(ts;
ts.tokens("bye".chars()).then(|| 1),
ts.tokens("hi".chars()).then(|| 2),
ts.tokens("hello".chars()).then(|| 3),
ts.tokens("world".chars()).then(|| 4),
);
assert_eq!(res, Some(3));
assert_eq!(tokens.remaining(), " world");You can declare an alias from some expression that’s passed in, too. Handy for abbreviating, or in this case, adding the required mut reference:
use yap::{ Tokens, IntoTokens };
let mut tokens = "hello world".into_tokens();
let res = yap::one_of!(ts from &mut tokens;
ts.tokens("bye".chars()).then(|| 1),
ts.tokens("hi".chars()).then(|| 2),
ts.tokens("hello".chars()).then(|| 3),
ts.tokens("world".chars()).then(|| 4),
);
assert_eq!(res, Some(3));
assert_eq!(tokens.remaining(), " world");We can return bools too, for when we want to find out whether something matches but don’t care what exactly has been matched:
use yap::{ Tokens, IntoTokens };
let mut tokens = "hello world".into_tokens();
let res: bool = yap::one_of!(ts from &mut tokens;
ts.tokens("howdy".chars()),
ts.tokens("bye".chars()),
ts.tokens("hello".chars()),
);
assert_eq!(res, true);
assert_eq!(tokens.remaining(), " world");Expressions can return Results inside the Option too (or anything else that they wish),
allowing for parsers to propagate errors out through this macro however you prefer.