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