pub struct LexerBuilder<'r, 't, T: 't> { /* private fields */ }
Expand description
Builder struct for Lexer.
Implementations§
Source§impl<'r, 't, T: 't> LexerBuilder<'r, 't, T>
impl<'r, 't, T: 't> LexerBuilder<'r, 't, T>
Sourcepub fn new() -> Self
pub fn new() -> Self
Create a new LexerBuilder.
Sourcepub fn token<F>(self, re: &'r str, f: F) -> Self
pub fn token<F>(self, re: &'r str, f: F) -> Self
Add a new token that matches the regular expression re
.
This uses the same syntax as the regex crate.
If re
gives the longest match, then f
is called on the matched string.
- If
f
returnsSome(tok)
, emit the tokentok
. - Otherwise, skip this token and emit nothing.
#[derive(Debug, PartialEq, Eq)]
enum Token {
Num(usize),
// ...
}
let lexer = regex_lexer_lalrpop::LexerBuilder::new()
.token(r"[0-9]*", |_, num, _| Some(Token::Num(num.parse().unwrap())))
.token(r"\s+", |_, _, _| None) // skip whitespace
// ...
.build()?;
assert_eq!(
lexer.tokens("1 2 3").collect::<Vec<_>>(),
vec![Ok(Token::Num(1)), Ok(Token::Num(2)), Ok(Token::Num(3))],
);
If multiple regexes all have the same longest match, then whichever is defined last is given priority.
#[derive(Debug, PartialEq, Eq)]
enum Token<'t> {
Ident(&'t str),
Then,
// ...
}
let lexer = regex_lexer_lalrpop::LexerBuilder::new()
.token(r"[a-zA-Z_][a-zA-Z0-9_]*", |_, id, _| Some(Token::Ident(id)))
.token(r"then", |_, _, _| Some(Token::Then))
// ...
.build()?;
assert_eq!(lexer.tokens("then").next(), Some(Ok(Token::Then)));
assert_eq!(lexer.tokens("then_perish").next(), Some(Ok(Token::Ident("then_perish"))));
Trait Implementations§
Source§impl<'r, 't, T: 't> Debug for LexerBuilder<'r, 't, T>
impl<'r, 't, T: 't> Debug for LexerBuilder<'r, 't, T>
Auto Trait Implementations§
impl<'r, 't, T> Freeze for LexerBuilder<'r, 't, T>
impl<'r, 't, T> !RefUnwindSafe for LexerBuilder<'r, 't, T>
impl<'r, 't, T> !Send for LexerBuilder<'r, 't, T>
impl<'r, 't, T> !Sync for LexerBuilder<'r, 't, T>
impl<'r, 't, T> Unpin for LexerBuilder<'r, 't, T>
impl<'r, 't, T> !UnwindSafe for LexerBuilder<'r, 't, T>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more