syn/lookahead.rs
1use crate::buffer::Cursor;
2use crate::error::{self, Error};
3use crate::sealed::lookahead::Sealed;
4use crate::span::IntoSpans;
5use crate::token::{CustomToken, Token};
6use alloc::format;
7use alloc::vec::Vec;
8use core::cell::RefCell;
9use core::fmt::{self, Display};
10use proc_macro2::{Delimiter, Span};
11
12/// Support for checking the next token in a stream to decide how to parse.
13///
14/// An important advantage over [`ParseStream::peek`] is that here we
15/// automatically construct an appropriate error message based on the token
16/// alternatives that get peeked. If you are producing your own error message,
17/// go ahead and use `ParseStream::peek` instead.
18///
19/// Use [`ParseStream::lookahead1`] to construct this object.
20///
21/// [`ParseStream::peek`]: crate::parse::ParseBuffer::peek
22/// [`ParseStream::lookahead1`]: crate::parse::ParseBuffer::lookahead1
23///
24/// Consuming tokens from the source stream after constructing a lookahead
25/// object does not also advance the lookahead object.
26///
27/// # Example
28///
29/// ```
30/// use syn::{ConstParam, Ident, Lifetime, LifetimeParam, Result, Token, TypeParam};
31/// use syn::parse::{Parse, ParseStream};
32///
33/// // A generic parameter, a single one of the comma-separated elements inside
34/// // angle brackets in:
35/// //
36/// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
37/// //
38/// // On invalid input, lookahead gives us a reasonable error message.
39/// //
40/// // error: expected one of: identifier, lifetime, `const`
41/// // |
42/// // 5 | fn f<!Sized>() {}
43/// // | ^
44/// enum GenericParam {
45/// Type(TypeParam),
46/// Lifetime(LifetimeParam),
47/// Const(ConstParam),
48/// }
49///
50/// impl Parse for GenericParam {
51/// fn parse(input: ParseStream) -> Result<Self> {
52/// let lookahead = input.lookahead1();
53/// if lookahead.peek(Ident) {
54/// input.parse().map(GenericParam::Type)
55/// } else if lookahead.peek(Lifetime) {
56/// input.parse().map(GenericParam::Lifetime)
57/// } else if lookahead.peek(Token![const]) {
58/// input.parse().map(GenericParam::Const)
59/// } else {
60/// Err(lookahead.error())
61/// }
62/// }
63/// }
64/// ```
65pub struct Lookahead1<'a> {
66 scope: Span,
67 cursor: Cursor<'a>,
68 comparisons: RefCell<Vec<&'static str>>,
69}
70
71pub(crate) fn new(scope: Span, cursor: Cursor) -> Lookahead1 {
72 Lookahead1 {
73 scope,
74 cursor,
75 comparisons: RefCell::new(Vec::new()),
76 }
77}
78
79fn peek_impl(
80 lookahead: &Lookahead1,
81 peek: fn(Cursor) -> bool,
82 display: fn() -> &'static str,
83) -> bool {
84 if peek(lookahead.cursor) {
85 return true;
86 }
87 lookahead.comparisons.borrow_mut().push(display());
88 false
89}
90
91impl<'a> Lookahead1<'a> {
92 /// Looks at the next token in the parse stream to determine whether it
93 /// matches the requested type of token.
94 ///
95 /// # Syntax
96 ///
97 /// Note that this method does not use turbofish syntax. Pass the peek type
98 /// inside of parentheses.
99 ///
100 /// - `input.peek(Token![struct])`
101 /// - `input.peek(Token![==])`
102 /// - `input.peek(Ident)` *(does not accept keywords)*
103 /// - `input.peek(Ident::peek_any)`
104 /// - `input.peek(Lifetime)`
105 /// - `input.peek(token::Brace)`
106 pub fn peek<T: Peek>(&self, token: T) -> bool {
107 let _ = token;
108 peek_impl(self, T::Token::peek, T::Token::display)
109 }
110
111 /// Triggers an error at the current position of the parse stream.
112 ///
113 /// The error message will identify all of the expected token types that
114 /// have been peeked against this lookahead instance.
115 pub fn error(self) -> Error {
116 let mut comparisons = self.comparisons.into_inner();
117 comparisons.retain_mut(|display| {
118 if *display == "`)`" {
119 *display = match self.cursor.scope_delimiter() {
120 Delimiter::Parenthesis => "`)`",
121 Delimiter::Brace => "`}`",
122 Delimiter::Bracket => "`]`",
123 Delimiter::None => return false,
124 }
125 }
126 true
127 });
128 match comparisons.len() {
129 0 => {
130 if self.cursor.eof() {
131 Error::new(self.scope, "unexpected end of input")
132 } else {
133 Error::new(self.cursor.span(), "unexpected token")
134 }
135 }
136 1 => {
137 let message = format!("expected {}", comparisons[0]);
138 error::new_at(self.scope, self.cursor, message)
139 }
140 2 => {
141 let message = format!("expected {} or {}", comparisons[0], comparisons[1]);
142 error::new_at(self.scope, self.cursor, message)
143 }
144 _ => {
145 let message = format!("expected one of: {}", CommaSeparated(&comparisons));
146 error::new_at(self.scope, self.cursor, message)
147 }
148 }
149 }
150}
151
152struct CommaSeparated<'a>(&'a [&'a str]);
153
154impl<'a> Display for CommaSeparated<'a> {
155 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
156 let mut first = true;
157 for &s in self.0 {
158 if !first {
159 f.write_str(", ")?;
160 }
161 f.write_str(s)?;
162 first = false;
163 }
164 Ok(())
165 }
166}
167
168/// Types that can be parsed by looking at just one token.
169///
170/// Use [`ParseStream::peek`] to peek one of these types in a parse stream
171/// without consuming it from the stream.
172///
173/// This trait is sealed and cannot be implemented for types outside of Syn.
174///
175/// [`ParseStream::peek`]: crate::parse::ParseBuffer::peek
176pub trait Peek: Sealed {
177 // Not public API.
178 #[doc(hidden)]
179 type Token: Token;
180}
181
182/// Pseudo-token used for peeking the end of a parse stream.
183///
184/// This type is only useful as an argument to one of the following functions:
185///
186/// - [`ParseStream::peek`][crate::parse::ParseBuffer::peek]
187/// - [`ParseStream::peek2`][crate::parse::ParseBuffer::peek2]
188/// - [`ParseStream::peek3`][crate::parse::ParseBuffer::peek3]
189/// - [`Lookahead1::peek`]
190///
191/// The peek will return `true` if there are no remaining tokens after that
192/// point in the parse stream.
193///
194/// # Example
195///
196/// Suppose we are parsing attributes containing core::fmt inspired formatting
197/// arguments:
198///
199/// - `#[fmt("simple example")]`
200/// - `#[fmt("interpolation e{}ample", self.x)]`
201/// - `#[fmt("interpolation e{x}ample")]`
202///
203/// and we want to recognize the cases where no interpolation occurs so that
204/// more efficient code can be generated.
205///
206/// The following implementation uses `input.peek(Token![,]) &&
207/// input.peek2(End)` to recognize the case of a trailing comma without
208/// consuming the comma from the parse stream, because if it isn't a trailing
209/// comma, that same comma needs to be parsed as part of `args`.
210///
211/// ```
212/// use proc_macro2::TokenStream;
213/// use quote::quote;
214/// use syn::parse::{End, Parse, ParseStream, Result};
215/// use syn::{parse_quote, Attribute, LitStr, Token};
216///
217/// struct FormatArgs {
218/// template: LitStr, // "...{}..."
219/// args: TokenStream, // , self.x
220/// }
221///
222/// impl Parse for FormatArgs {
223/// fn parse(input: ParseStream) -> Result<Self> {
224/// let template: LitStr = input.parse()?;
225///
226/// let args = if input.is_empty()
227/// || input.peek(Token![,]) && input.peek2(End)
228/// {
229/// input.parse::<Option<Token![,]>>()?;
230/// TokenStream::new()
231/// } else {
232/// input.parse()?
233/// };
234///
235/// Ok(FormatArgs {
236/// template,
237/// args,
238/// })
239/// }
240/// }
241///
242/// fn main() -> Result<()> {
243/// let attrs: Vec<Attribute> = parse_quote! {
244/// #[fmt("simple example")]
245/// #[fmt("interpolation e{}ample", self.x)]
246/// #[fmt("interpolation e{x}ample")]
247/// };
248///
249/// for attr in &attrs {
250/// let FormatArgs { template, args } = attr.parse_args()?;
251/// let requires_fmt_machinery =
252/// !args.is_empty() || template.value().contains(['{', '}']);
253/// let out = if requires_fmt_machinery {
254/// quote! {
255/// ::core::write!(__formatter, #template #args)
256/// }
257/// } else {
258/// quote! {
259/// __formatter.write_str(#template)
260/// }
261/// };
262/// println!("{}", out);
263/// }
264/// Ok(())
265/// }
266/// ```
267///
268/// Implementing this parsing logic without `peek2(End)` is more clumsy because
269/// we'd need a parse stream actually advanced past the comma before being able
270/// to find out whether there is anything after it. It would look something
271/// like:
272///
273/// ```
274/// # use proc_macro2::TokenStream;
275/// # use syn::parse::{ParseStream, Result};
276/// # use syn::Token;
277/// #
278/// # fn parse(input: ParseStream) -> Result<()> {
279/// use syn::parse::discouraged::Speculative as _;
280///
281/// let ahead = input.fork();
282/// ahead.parse::<Option<Token![,]>>()?;
283/// let args = if ahead.is_empty() {
284/// input.advance_to(&ahead);
285/// TokenStream::new()
286/// } else {
287/// input.parse()?
288/// };
289/// # Ok(())
290/// # }
291/// ```
292///
293/// or:
294///
295/// ```
296/// # use proc_macro2::TokenStream;
297/// # use syn::parse::{ParseStream, Result};
298/// # use syn::Token;
299/// #
300/// # fn parse(input: ParseStream) -> Result<()> {
301/// use quote::ToTokens as _;
302///
303/// let comma: Option<Token![,]> = input.parse()?;
304/// let mut args = TokenStream::new();
305/// if !input.is_empty() {
306/// comma.to_tokens(&mut args);
307/// input.parse::<TokenStream>()?.to_tokens(&mut args);
308/// }
309/// # Ok(())
310/// # }
311/// ```
312pub struct End;
313
314impl Copy for End {}
315
316impl Clone for End {
317 fn clone(&self) -> Self {
318 *self
319 }
320}
321
322impl Peek for End {
323 type Token = Self;
324}
325
326impl CustomToken for End {
327 fn peek(cursor: Cursor) -> bool {
328 cursor.eof()
329 }
330
331 fn display() -> &'static str {
332 "`)`" // Lookahead1 error message will fill in the expected close delimiter
333 }
334}
335
336impl<F: Copy + FnOnce(TokenMarker) -> T, T: Token> Peek for F {
337 type Token = T;
338}
339
340pub enum TokenMarker {}
341
342impl<S> IntoSpans<S> for TokenMarker {
343 fn into_spans(self) -> S {
344 match self {}
345 }
346}
347
348impl<F: Copy + FnOnce(TokenMarker) -> T, T: Token> Sealed for F {}
349
350impl Sealed for End {}