syn_error_experiment/
lookahead.rs

1use std::cell::RefCell;
2
3use proc_macro2::Span;
4use syn::buffer::Cursor;
5
6use error;
7use parse::Error;
8use token::Token;
9
10/// Support for checking the next token in a stream to decide how to parse.
11///
12/// Use [`ParseStream::lookahead1`] to construct this object.
13///
14/// [`ParseStream::lookahead1`]: struct.ParseBuffer.html#method.lookahead1
15pub struct Lookahead1<'a> {
16    scope: Span,
17    cursor: Cursor<'a>,
18    comparisons: RefCell<Vec<String>>,
19}
20
21impl<'a> Lookahead1<'a> {
22    // Not public API.
23    #[doc(hidden)]
24    pub fn new(scope: Span, cursor: Cursor<'a>) -> Self {
25        Lookahead1 {
26            scope: scope,
27            cursor: cursor,
28            comparisons: RefCell::new(Vec::new()),
29        }
30    }
31
32    pub fn peek<T: Peek>(&self, token: T) -> bool {
33        let _ = token;
34        if T::Token::peek(self) {
35            return true;
36        }
37        self.comparisons.borrow_mut().push(T::Token::display());
38        false
39    }
40
41    pub fn error(self) -> Error {
42        let message = format!("expected one of {:?}", self.comparisons.borrow());
43        error::new_at(self.scope, self.cursor, message)
44    }
45}
46
47/// Types that can be parsed by looking at just one token.
48///
49/// This trait is sealed and cannot be implemented for types outside of Syn.
50pub trait Peek: private::Sealed {
51    // Not public API.
52    #[doc(hidden)]
53    type Token: Token;
54}
55
56impl<F: FnOnce(Span) -> T, T: Token> Peek for F {
57    type Token = T;
58}
59
60// Not public API.
61#[doc(hidden)]
62pub fn is_token(lookahead: &Lookahead1, repr: &'static str) -> bool {
63    if let Some((token, _rest)) = lookahead.cursor.token_tree() {
64        token.to_string() == repr
65    } else {
66        false
67    }
68}
69
70mod private {
71    use super::{Span, Token};
72    pub trait Sealed {}
73    impl<F, T: Token> Sealed for F where F: FnOnce(Span) -> T {}
74}