1 use crate::buffer::Cursor;
2 use crate::error::{self, Error};
3 use crate::sealed::lookahead::Sealed;
4 use crate::span::IntoSpans;
5 use crate::token::Token;
6 use proc_macro2::{Delimiter, Span};
7 use std::cell::RefCell;
8 
9 /// Support for checking the next token in a stream to decide how to parse.
10 ///
11 /// An important advantage over [`ParseStream::peek`] is that here we
12 /// automatically construct an appropriate error message based on the token
13 /// alternatives that get peeked. If you are producing your own error message,
14 /// go ahead and use `ParseStream::peek` instead.
15 ///
16 /// Use [`ParseStream::lookahead1`] to construct this object.
17 ///
18 /// [`ParseStream::peek`]: crate::parse::ParseBuffer::peek
19 /// [`ParseStream::lookahead1`]: crate::parse::ParseBuffer::lookahead1
20 ///
21 /// # Example
22 ///
23 /// ```
24 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, Token, TypeParam};
25 /// use syn::parse::{Parse, ParseStream};
26 ///
27 /// // A generic parameter, a single one of the comma-separated elements inside
28 /// // angle brackets in:
29 /// //
30 /// //     fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
31 /// //
32 /// // On invalid input, lookahead gives us a reasonable error message.
33 /// //
34 /// //     error: expected one of: identifier, lifetime, `const`
35 /// //       |
36 /// //     5 |     fn f<!Sized>() {}
37 /// //       |          ^
38 /// enum GenericParam {
39 ///     Type(TypeParam),
40 ///     Lifetime(LifetimeDef),
41 ///     Const(ConstParam),
42 /// }
43 ///
44 /// impl Parse for GenericParam {
45 ///     fn parse(input: ParseStream) -> Result<Self> {
46 ///         let lookahead = input.lookahead1();
47 ///         if lookahead.peek(Ident) {
48 ///             input.parse().map(GenericParam::Type)
49 ///         } else if lookahead.peek(Lifetime) {
50 ///             input.parse().map(GenericParam::Lifetime)
51 ///         } else if lookahead.peek(Token![const]) {
52 ///             input.parse().map(GenericParam::Const)
53 ///         } else {
54 ///             Err(lookahead.error())
55 ///         }
56 ///     }
57 /// }
58 /// ```
59 pub struct Lookahead1<'a> {
60     scope: Span,
61     cursor: Cursor<'a>,
62     comparisons: RefCell<Vec<&'static str>>,
63 }
64 
new(scope: Span, cursor: Cursor) -> Lookahead165 pub fn new(scope: Span, cursor: Cursor) -> Lookahead1 {
66     Lookahead1 {
67         scope,
68         cursor,
69         comparisons: RefCell::new(Vec::new()),
70     }
71 }
72 
peek_impl( lookahead: &Lookahead1, peek: fn(Cursor) -> bool, display: fn() -> &'static str, ) -> bool73 fn peek_impl(
74     lookahead: &Lookahead1,
75     peek: fn(Cursor) -> bool,
76     display: fn() -> &'static str,
77 ) -> bool {
78     if peek(lookahead.cursor) {
79         return true;
80     }
81     lookahead.comparisons.borrow_mut().push(display());
82     false
83 }
84 
85 impl<'a> Lookahead1<'a> {
86     /// Looks at the next token in the parse stream to determine whether it
87     /// matches the requested type of token.
88     ///
89     /// # Syntax
90     ///
91     /// Note that this method does not use turbofish syntax. Pass the peek type
92     /// inside of parentheses.
93     ///
94     /// - `input.peek(Token![struct])`
95     /// - `input.peek(Token![==])`
96     /// - `input.peek(Ident)`&emsp;*(does not accept keywords)*
97     /// - `input.peek(Ident::peek_any)`
98     /// - `input.peek(Lifetime)`
99     /// - `input.peek(token::Brace)`
peek<T: Peek>(&self, token: T) -> bool100     pub fn peek<T: Peek>(&self, token: T) -> bool {
101         let _ = token;
102         peek_impl(self, T::Token::peek, T::Token::display)
103     }
104 
105     /// Triggers an error at the current position of the parse stream.
106     ///
107     /// The error message will identify all of the expected token types that
108     /// have been peeked against this lookahead instance.
error(self) -> Error109     pub fn error(self) -> Error {
110         let comparisons = self.comparisons.borrow();
111         match comparisons.len() {
112             0 => {
113                 if self.cursor.eof() {
114                     Error::new(self.scope, "unexpected end of input")
115                 } else {
116                     Error::new(self.cursor.span(), "unexpected token")
117                 }
118             }
119             1 => {
120                 let message = format!("expected {}", comparisons[0]);
121                 error::new_at(self.scope, self.cursor, message)
122             }
123             2 => {
124                 let message = format!("expected {} or {}", comparisons[0], comparisons[1]);
125                 error::new_at(self.scope, self.cursor, message)
126             }
127             _ => {
128                 let join = comparisons.join(", ");
129                 let message = format!("expected one of: {}", join);
130                 error::new_at(self.scope, self.cursor, message)
131             }
132         }
133     }
134 }
135 
136 /// Types that can be parsed by looking at just one token.
137 ///
138 /// Use [`ParseStream::peek`] to peek one of these types in a parse stream
139 /// without consuming it from the stream.
140 ///
141 /// This trait is sealed and cannot be implemented for types outside of Syn.
142 ///
143 /// [`ParseStream::peek`]: crate::parse::ParseBuffer::peek
144 pub trait Peek: Sealed {
145     // Not public API.
146     #[doc(hidden)]
147     type Token: Token;
148 }
149 
150 impl<F: Copy + FnOnce(TokenMarker) -> T, T: Token> Peek for F {
151     type Token = T;
152 }
153 
154 pub enum TokenMarker {}
155 
156 impl<S> IntoSpans<S> for TokenMarker {
into_spans(self) -> S157     fn into_spans(self) -> S {
158         match self {}
159     }
160 }
161 
is_delimiter(cursor: Cursor, delimiter: Delimiter) -> bool162 pub fn is_delimiter(cursor: Cursor, delimiter: Delimiter) -> bool {
163     cursor.group(delimiter).is_some()
164 }
165 
166 impl<F: Copy + FnOnce(TokenMarker) -> T, T: Token> Sealed for F {}
167