1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
//! A utility for checking the type of the next token.
use crate::error::Error;
use crate::token::Token;
use crate::ParseBuffer;
use crate::Peek;
use std::cell::RefCell;
use std::collections::HashSet;
/// A type for peeking at the next token, and generating a helpful error if it
/// isn't an expected type.
pub struct Lookahead<'a> {
stream: ParseBuffer<'a>,
comparisons: RefCell<HashSet<String>>,
}
impl<'a> Lookahead<'a> {
pub(crate) fn new(stream: ParseBuffer<'a>) -> Lookahead<'a> {
Lookahead {
stream,
comparisons: RefCell::new(HashSet::new()),
}
}
/// Returns true if the next token is the given type.
pub fn peek<T: Peek>(&self, token: T) -> bool {
if self.stream.peek::<T>(token) {
true
} else {
self.comparisons.borrow_mut().insert(T::Token::display());
false
}
}
/// Generates an error based on the peek attempts.
pub fn error(self) -> Error {
self.stream.unexpected_token(self.comparisons.into_inner())
}
}