blob: cbaa68e1af5c3f3f8fc6514e947dd8a64176a554 [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
David Tolnay2b687b02018-08-24 13:36:36 -040071impl<F: FnOnce(TokenMarker) -> T, T: Token> Peek for F {
David Tolnay18c754c2018-08-21 23:26:58 -040072 type Token = T;
73}
74
David Tolnay2b687b02018-08-24 13:36:36 -040075pub enum TokenMarker {}
76
David Tolnay18c754c2018-08-21 23:26:58 -040077// Not public API.
78#[doc(hidden)]
79pub fn is_token(lookahead: &Lookahead1, repr: &'static str) -> bool {
80 if let Some((token, _rest)) = lookahead.cursor.token_tree() {
81 token.to_string() == repr
82 } else {
83 false
84 }
85}
86
87mod private {
David Tolnay2b687b02018-08-24 13:36:36 -040088 use super::{Token, TokenMarker};
David Tolnay18c754c2018-08-21 23:26:58 -040089 pub trait Sealed {}
David Tolnay2b687b02018-08-24 13:36:36 -040090 impl<F: FnOnce(TokenMarker) -> T, T: Token> Sealed for F {}
David Tolnay18c754c2018-08-21 23:26:58 -040091}