blob: b73d8b26a3dbcd81fd6895cdd0b67a22b99a01b0 [file] [log] [blame]
David Tolnay18c754c2018-08-21 23:26:58 -04001use 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 {
David Tolnayda1dc7c2018-08-24 11:57:28 -040042 let comparisons = self.comparisons.borrow();
43 match comparisons.len() {
44 0 => if self.cursor.eof() {
45 Error::new(self.scope, "unexpected end of input")
46 } else {
47 Error::new(self.cursor.span(), "unexpected token")
48 },
49 1 => {
50 let message = format!("expected {}", comparisons[0]);
51 error::new_at(self.scope, self.cursor, message)
52 }
53 _ => {
David Tolnayc6e86c72018-08-24 12:28:40 -040054 let join = comparisons.join(", ");
55 let message = format!("expected one of: {}", join);
David Tolnayda1dc7c2018-08-24 11:57:28 -040056 error::new_at(self.scope, self.cursor, message)
57 }
58 }
David Tolnay18c754c2018-08-21 23:26:58 -040059 }
60}
61
62/// Types that can be parsed by looking at just one token.
63///
64/// This trait is sealed and cannot be implemented for types outside of Syn.
65pub trait Peek: private::Sealed {
66 // Not public API.
67 #[doc(hidden)]
68 type Token: Token;
69}
70
71impl<F: FnOnce(Span) -> T, T: Token> Peek for F {
72 type Token = T;
73}
74
75// Not public API.
76#[doc(hidden)]
77pub fn is_token(lookahead: &Lookahead1, repr: &'static str) -> bool {
78 if let Some((token, _rest)) = lookahead.cursor.token_tree() {
79 token.to_string() == repr
80 } else {
81 false
82 }
83}
84
85mod private {
86 use super::{Span, Token};
87 pub trait Sealed {}
88 impl<F, T: Token> Sealed for F where F: FnOnce(Span) -> T {}
89}