1 //! Parsing interface for parsing a token stream into a syntax tree node.
2 //!
3 //! Parsing in Syn is built on parser functions that take in a [`ParseStream`]
4 //! and produce a [`Result<T>`] where `T` is some syntax tree node. Underlying
5 //! these parser functions is a lower level mechanism built around the
6 //! [`Cursor`] type. `Cursor` is a cheaply copyable cursor over a range of
7 //! tokens in a token stream.
8 //!
9 //! [`Result<T>`]: Result
10 //! [`Cursor`]: crate::buffer::Cursor
11 //!
12 //! # Example
13 //!
14 //! Here is a snippet of parsing code to get a feel for the style of the
15 //! library. We define data structures for a subset of Rust syntax including
16 //! enums (not shown) and structs, then provide implementations of the [`Parse`]
17 //! trait to parse these syntax tree data structures from a token stream.
18 //!
19 //! Once `Parse` impls have been defined, they can be called conveniently from a
20 //! procedural macro through [`parse_macro_input!`] as shown at the bottom of
21 //! the snippet. If the caller provides syntactically invalid input to the
22 //! procedural macro, they will receive a helpful compiler error message
23 //! pointing out the exact token that triggered the failure to parse.
24 //!
25 //! [`parse_macro_input!`]: crate::parse_macro_input!
26 //!
27 //! ```
28 //! # extern crate proc_macro;
29 //! #
30 //! use proc_macro::TokenStream;
31 //! use syn::{braced, parse_macro_input, token, Field, Ident, Result, Token};
32 //! use syn::parse::{Parse, ParseStream};
33 //! use syn::punctuated::Punctuated;
34 //!
35 //! enum Item {
36 //!     Struct(ItemStruct),
37 //!     Enum(ItemEnum),
38 //! }
39 //!
40 //! struct ItemStruct {
41 //!     struct_token: Token![struct],
42 //!     ident: Ident,
43 //!     brace_token: token::Brace,
44 //!     fields: Punctuated<Field, Token![,]>,
45 //! }
46 //! #
47 //! # enum ItemEnum {}
48 //!
49 //! impl Parse for Item {
50 //!     fn parse(input: ParseStream) -> Result<Self> {
51 //!         let lookahead = input.lookahead1();
52 //!         if lookahead.peek(Token![struct]) {
53 //!             input.parse().map(Item::Struct)
54 //!         } else if lookahead.peek(Token![enum]) {
55 //!             input.parse().map(Item::Enum)
56 //!         } else {
57 //!             Err(lookahead.error())
58 //!         }
59 //!     }
60 //! }
61 //!
62 //! impl Parse for ItemStruct {
63 //!     fn parse(input: ParseStream) -> Result<Self> {
64 //!         let content;
65 //!         Ok(ItemStruct {
66 //!             struct_token: input.parse()?,
67 //!             ident: input.parse()?,
68 //!             brace_token: braced!(content in input),
69 //!             fields: content.parse_terminated(Field::parse_named)?,
70 //!         })
71 //!     }
72 //! }
73 //! #
74 //! # impl Parse for ItemEnum {
75 //! #     fn parse(input: ParseStream) -> Result<Self> {
76 //! #         unimplemented!()
77 //! #     }
78 //! # }
79 //!
80 //! # const IGNORE: &str = stringify! {
81 //! #[proc_macro]
82 //! # };
83 //! pub fn my_macro(tokens: TokenStream) -> TokenStream {
84 //!     let input = parse_macro_input!(tokens as Item);
85 //!
86 //!     /* ... */
87 //! #   "".parse().unwrap()
88 //! }
89 //! ```
90 //!
91 //! # The `syn::parse*` functions
92 //!
93 //! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve
94 //! as an entry point for parsing syntax tree nodes that can be parsed in an
95 //! obvious default way. These functions can return any syntax tree node that
96 //! implements the [`Parse`] trait, which includes most types in Syn.
97 //!
98 //! [`syn::parse`]: crate::parse()
99 //! [`syn::parse2`]: crate::parse2()
100 //! [`syn::parse_str`]: crate::parse_str()
101 //!
102 //! ```
103 //! use syn::Type;
104 //!
105 //! # fn run_parser() -> syn::Result<()> {
106 //! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?;
107 //! #     Ok(())
108 //! # }
109 //! #
110 //! # run_parser().unwrap();
111 //! ```
112 //!
113 //! The [`parse_quote!`] macro also uses this approach.
114 //!
115 //! [`parse_quote!`]: crate::parse_quote!
116 //!
117 //! # The `Parser` trait
118 //!
119 //! Some types can be parsed in several ways depending on context. For example
120 //! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
121 //! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
122 //! may or may not allow trailing punctuation, and parsing it the wrong way
123 //! would either reject valid input or accept invalid input.
124 //!
125 //! [`Attribute`]: crate::Attribute
126 //! [`Punctuated`]: crate::punctuated
127 //!
128 //! The `Parse` trait is not implemented in these cases because there is no good
129 //! behavior to consider the default.
130 //!
131 //! ```compile_fail
132 //! # extern crate proc_macro;
133 //! #
134 //! # use syn::punctuated::Punctuated;
135 //! # use syn::{PathSegment, Result, Token};
136 //! #
137 //! # fn f(tokens: proc_macro::TokenStream) -> Result<()> {
138 //! #
139 //! // Can't parse `Punctuated` without knowing whether trailing punctuation
140 //! // should be allowed in this context.
141 //! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
142 //! #
143 //! #     Ok(())
144 //! # }
145 //! ```
146 //!
147 //! In these cases the types provide a choice of parser functions rather than a
148 //! single `Parse` implementation, and those parser functions can be invoked
149 //! through the [`Parser`] trait.
150 //!
151 //!
152 //! ```
153 //! # extern crate proc_macro;
154 //! #
155 //! use proc_macro::TokenStream;
156 //! use syn::parse::Parser;
157 //! use syn::punctuated::Punctuated;
158 //! use syn::{Attribute, Expr, PathSegment, Result, Token};
159 //!
160 //! fn call_some_parser_methods(input: TokenStream) -> Result<()> {
161 //!     // Parse a nonempty sequence of path segments separated by `::` punctuation
162 //!     // with no trailing punctuation.
163 //!     let tokens = input.clone();
164 //!     let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
165 //!     let _path = parser.parse(tokens)?;
166 //!
167 //!     // Parse a possibly empty sequence of expressions terminated by commas with
168 //!     // an optional trailing punctuation.
169 //!     let tokens = input.clone();
170 //!     let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
171 //!     let _args = parser.parse(tokens)?;
172 //!
173 //!     // Parse zero or more outer attributes but not inner attributes.
174 //!     let tokens = input.clone();
175 //!     let parser = Attribute::parse_outer;
176 //!     let _attrs = parser.parse(tokens)?;
177 //!
178 //!     Ok(())
179 //! }
180 //! ```
181 //!
182 //! ---
183 //!
184 //! *This module is available only if Syn is built with the `"parsing"` feature.*
185 
186 #[path = "discouraged.rs"]
187 pub mod discouraged;
188 
189 use crate::buffer::{Cursor, TokenBuffer};
190 use crate::error;
191 use crate::lookahead;
192 #[cfg(all(
193     not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
194     feature = "proc-macro"
195 ))]
196 use crate::proc_macro;
197 use crate::punctuated::Punctuated;
198 use crate::token::Token;
199 use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree};
200 use std::cell::Cell;
201 use std::fmt::{self, Debug, Display};
202 use std::marker::PhantomData;
203 use std::mem;
204 use std::ops::Deref;
205 use std::rc::Rc;
206 use std::str::FromStr;
207 
208 pub use crate::error::{Error, Result};
209 pub use crate::lookahead::{Lookahead1, Peek};
210 
211 /// Parsing interface implemented by all types that can be parsed in a default
212 /// way from a token stream.
213 ///
214 /// Refer to the [module documentation] for details about implementing and using
215 /// the `Parse` trait.
216 ///
217 /// [module documentation]: self
218 pub trait Parse: Sized {
parse(input: ParseStream) -> Result<Self>219     fn parse(input: ParseStream) -> Result<Self>;
220 }
221 
222 /// Input to a Syn parser function.
223 ///
224 /// See the methods of this type under the documentation of [`ParseBuffer`]. For
225 /// an overview of parsing in Syn, refer to the [module documentation].
226 ///
227 /// [module documentation]: self
228 pub type ParseStream<'a> = &'a ParseBuffer<'a>;
229 
230 /// Cursor position within a buffered token stream.
231 ///
232 /// This type is more commonly used through the type alias [`ParseStream`] which
233 /// is an alias for `&ParseBuffer`.
234 ///
235 /// `ParseStream` is the input type for all parser functions in Syn. They have
236 /// the signature `fn(ParseStream) -> Result<T>`.
237 ///
238 /// ## Calling a parser function
239 ///
240 /// There is no public way to construct a `ParseBuffer`. Instead, if you are
241 /// looking to invoke a parser function that requires `ParseStream` as input,
242 /// you will need to go through one of the public parsing entry points.
243 ///
244 /// - The [`parse_macro_input!`] macro if parsing input of a procedural macro;
245 /// - One of [the `syn::parse*` functions][syn-parse]; or
246 /// - A method of the [`Parser`] trait.
247 ///
248 /// [syn-parse]: self#the-synparse-functions
249 pub struct ParseBuffer<'a> {
250     scope: Span,
251     // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a.
252     // The rest of the code in this module needs to be careful that only a
253     // cursor derived from this `cell` is ever assigned to this `cell`.
254     //
255     // Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a
256     // ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter
257     // than 'a, and then assign a Cursor<'short> into the Cell.
258     //
259     // By extension, it would not be safe to expose an API that accepts a
260     // Cursor<'a> and trusts that it lives as long as the cursor currently in
261     // the cell.
262     cell: Cell<Cursor<'static>>,
263     marker: PhantomData<Cursor<'a>>,
264     unexpected: Cell<Option<Rc<Cell<Unexpected>>>>,
265 }
266 
267 impl<'a> Drop for ParseBuffer<'a> {
drop(&mut self)268     fn drop(&mut self) {
269         if let Some(unexpected_span) = span_of_unexpected_ignoring_nones(self.cursor()) {
270             let (inner, old_span) = inner_unexpected(self);
271             if old_span.is_none() {
272                 inner.set(Unexpected::Some(unexpected_span));
273             }
274         }
275     }
276 }
277 
278 impl<'a> Display for ParseBuffer<'a> {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result279     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
280         Display::fmt(&self.cursor().token_stream(), f)
281     }
282 }
283 
284 impl<'a> Debug for ParseBuffer<'a> {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result285     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
286         Debug::fmt(&self.cursor().token_stream(), f)
287     }
288 }
289 
290 /// Cursor state associated with speculative parsing.
291 ///
292 /// This type is the input of the closure provided to [`ParseStream::step`].
293 ///
294 /// [`ParseStream::step`]: ParseBuffer::step
295 ///
296 /// # Example
297 ///
298 /// ```
299 /// use proc_macro2::TokenTree;
300 /// use syn::Result;
301 /// use syn::parse::ParseStream;
302 ///
303 /// // This function advances the stream past the next occurrence of `@`. If
304 /// // no `@` is present in the stream, the stream position is unchanged and
305 /// // an error is returned.
306 /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
307 ///     input.step(|cursor| {
308 ///         let mut rest = *cursor;
309 ///         while let Some((tt, next)) = rest.token_tree() {
310 ///             match &tt {
311 ///                 TokenTree::Punct(punct) if punct.as_char() == '@' => {
312 ///                     return Ok(((), next));
313 ///                 }
314 ///                 _ => rest = next,
315 ///             }
316 ///         }
317 ///         Err(cursor.error("no `@` was found after this point"))
318 ///     })
319 /// }
320 /// #
321 /// # fn remainder_after_skipping_past_next_at(
322 /// #     input: ParseStream,
323 /// # ) -> Result<proc_macro2::TokenStream> {
324 /// #     skip_past_next_at(input)?;
325 /// #     input.parse()
326 /// # }
327 /// #
328 /// # use syn::parse::Parser;
329 /// # let remainder = remainder_after_skipping_past_next_at
330 /// #     .parse_str("a @ b c")
331 /// #     .unwrap();
332 /// # assert_eq!(remainder.to_string(), "b c");
333 /// ```
334 pub struct StepCursor<'c, 'a> {
335     scope: Span,
336     // This field is covariant in 'c.
337     cursor: Cursor<'c>,
338     // This field is contravariant in 'c. Together these make StepCursor
339     // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a
340     // different lifetime but can upcast into a StepCursor with a shorter
341     // lifetime 'a.
342     //
343     // As long as we only ever construct a StepCursor for which 'c outlives 'a,
344     // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c
345     // outlives 'a.
346     marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
347 }
348 
349 impl<'c, 'a> Deref for StepCursor<'c, 'a> {
350     type Target = Cursor<'c>;
351 
deref(&self) -> &Self::Target352     fn deref(&self) -> &Self::Target {
353         &self.cursor
354     }
355 }
356 
357 impl<'c, 'a> Copy for StepCursor<'c, 'a> {}
358 
359 impl<'c, 'a> Clone for StepCursor<'c, 'a> {
clone(&self) -> Self360     fn clone(&self) -> Self {
361         *self
362     }
363 }
364 
365 impl<'c, 'a> StepCursor<'c, 'a> {
366     /// Triggers an error at the current position of the parse stream.
367     ///
368     /// The `ParseStream::step` invocation will return this same error without
369     /// advancing the stream state.
error<T: Display>(self, message: T) -> Error370     pub fn error<T: Display>(self, message: T) -> Error {
371         error::new_at(self.scope, self.cursor, message)
372     }
373 }
374 
advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a>375 pub(crate) fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
376     // Refer to the comments within the StepCursor definition. We use the
377     // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a.
378     // Cursor is covariant in its lifetime parameter so we can cast a
379     // Cursor<'c> to one with the shorter lifetime Cursor<'a>.
380     let _ = proof;
381     unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
382 }
383 
new_parse_buffer( scope: Span, cursor: Cursor, unexpected: Rc<Cell<Unexpected>>, ) -> ParseBuffer384 pub(crate) fn new_parse_buffer(
385     scope: Span,
386     cursor: Cursor,
387     unexpected: Rc<Cell<Unexpected>>,
388 ) -> ParseBuffer {
389     ParseBuffer {
390         scope,
391         // See comment on `cell` in the struct definition.
392         cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
393         marker: PhantomData,
394         unexpected: Cell::new(Some(unexpected)),
395     }
396 }
397 
398 pub(crate) enum Unexpected {
399     None,
400     Some(Span),
401     Chain(Rc<Cell<Unexpected>>),
402 }
403 
404 impl Default for Unexpected {
default() -> Self405     fn default() -> Self {
406         Unexpected::None
407     }
408 }
409 
410 impl Clone for Unexpected {
clone(&self) -> Self411     fn clone(&self) -> Self {
412         match self {
413             Unexpected::None => Unexpected::None,
414             Unexpected::Some(span) => Unexpected::Some(*span),
415             Unexpected::Chain(next) => Unexpected::Chain(next.clone()),
416         }
417     }
418 }
419 
420 // We call this on Cell<Unexpected> and Cell<Option<T>> where temporarily
421 // swapping in a None is cheap.
cell_clone<T: Default + Clone>(cell: &Cell<T>) -> T422 fn cell_clone<T: Default + Clone>(cell: &Cell<T>) -> T {
423     let prev = cell.take();
424     let ret = prev.clone();
425     cell.set(prev);
426     ret
427 }
428 
inner_unexpected(buffer: &ParseBuffer) -> (Rc<Cell<Unexpected>>, Option<Span>)429 fn inner_unexpected(buffer: &ParseBuffer) -> (Rc<Cell<Unexpected>>, Option<Span>) {
430     let mut unexpected = get_unexpected(buffer);
431     loop {
432         match cell_clone(&unexpected) {
433             Unexpected::None => return (unexpected, None),
434             Unexpected::Some(span) => return (unexpected, Some(span)),
435             Unexpected::Chain(next) => unexpected = next,
436         }
437     }
438 }
439 
get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Unexpected>>440 pub(crate) fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Unexpected>> {
441     cell_clone(&buffer.unexpected).unwrap()
442 }
443 
span_of_unexpected_ignoring_nones(mut cursor: Cursor) -> Option<Span>444 fn span_of_unexpected_ignoring_nones(mut cursor: Cursor) -> Option<Span> {
445     if cursor.eof() {
446         return None;
447     }
448     while let Some((inner, _span, rest)) = cursor.group(Delimiter::None) {
449         if let Some(unexpected) = span_of_unexpected_ignoring_nones(inner) {
450             return Some(unexpected);
451         }
452         cursor = rest;
453     }
454     if cursor.eof() {
455         None
456     } else {
457         Some(cursor.span())
458     }
459 }
460 
461 impl<'a> ParseBuffer<'a> {
462     /// Parses a syntax tree node of type `T`, advancing the position of our
463     /// parse stream past it.
parse<T: Parse>(&self) -> Result<T>464     pub fn parse<T: Parse>(&self) -> Result<T> {
465         T::parse(self)
466     }
467 
468     /// Calls the given parser function to parse a syntax tree node of type `T`
469     /// from this stream.
470     ///
471     /// # Example
472     ///
473     /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
474     /// zero or more outer attributes.
475     ///
476     /// [`Attribute::parse_outer`]: crate::Attribute::parse_outer
477     ///
478     /// ```
479     /// use syn::{Attribute, Ident, Result, Token};
480     /// use syn::parse::{Parse, ParseStream};
481     ///
482     /// // Parses a unit struct with attributes.
483     /// //
484     /// //     #[path = "s.tmpl"]
485     /// //     struct S;
486     /// struct UnitStruct {
487     ///     attrs: Vec<Attribute>,
488     ///     struct_token: Token![struct],
489     ///     name: Ident,
490     ///     semi_token: Token![;],
491     /// }
492     ///
493     /// impl Parse for UnitStruct {
494     ///     fn parse(input: ParseStream) -> Result<Self> {
495     ///         Ok(UnitStruct {
496     ///             attrs: input.call(Attribute::parse_outer)?,
497     ///             struct_token: input.parse()?,
498     ///             name: input.parse()?,
499     ///             semi_token: input.parse()?,
500     ///         })
501     ///     }
502     /// }
503     /// ```
call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T>504     pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
505         function(self)
506     }
507 
508     /// Looks at the next token in the parse stream to determine whether it
509     /// matches the requested type of token.
510     ///
511     /// Does not advance the position of the parse stream.
512     ///
513     /// # Syntax
514     ///
515     /// Note that this method does not use turbofish syntax. Pass the peek type
516     /// inside of parentheses.
517     ///
518     /// - `input.peek(Token![struct])`
519     /// - `input.peek(Token![==])`
520     /// - `input.peek(Ident)`&emsp;*(does not accept keywords)*
521     /// - `input.peek(Ident::peek_any)`
522     /// - `input.peek(Lifetime)`
523     /// - `input.peek(token::Brace)`
524     ///
525     /// # Example
526     ///
527     /// In this example we finish parsing the list of supertraits when the next
528     /// token in the input is either `where` or an opening curly brace.
529     ///
530     /// ```
531     /// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
532     /// use syn::parse::{Parse, ParseStream};
533     /// use syn::punctuated::Punctuated;
534     ///
535     /// // Parses a trait definition containing no associated items.
536     /// //
537     /// //     trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
538     /// struct MarkerTrait {
539     ///     trait_token: Token![trait],
540     ///     ident: Ident,
541     ///     generics: Generics,
542     ///     colon_token: Option<Token![:]>,
543     ///     supertraits: Punctuated<TypeParamBound, Token![+]>,
544     ///     brace_token: token::Brace,
545     /// }
546     ///
547     /// impl Parse for MarkerTrait {
548     ///     fn parse(input: ParseStream) -> Result<Self> {
549     ///         let trait_token: Token![trait] = input.parse()?;
550     ///         let ident: Ident = input.parse()?;
551     ///         let mut generics: Generics = input.parse()?;
552     ///         let colon_token: Option<Token![:]> = input.parse()?;
553     ///
554     ///         let mut supertraits = Punctuated::new();
555     ///         if colon_token.is_some() {
556     ///             loop {
557     ///                 supertraits.push_value(input.parse()?);
558     ///                 if input.peek(Token![where]) || input.peek(token::Brace) {
559     ///                     break;
560     ///                 }
561     ///                 supertraits.push_punct(input.parse()?);
562     ///             }
563     ///         }
564     ///
565     ///         generics.where_clause = input.parse()?;
566     ///         let content;
567     ///         let empty_brace_token = braced!(content in input);
568     ///
569     ///         Ok(MarkerTrait {
570     ///             trait_token,
571     ///             ident,
572     ///             generics,
573     ///             colon_token,
574     ///             supertraits,
575     ///             brace_token: empty_brace_token,
576     ///         })
577     ///     }
578     /// }
579     /// ```
peek<T: Peek>(&self, token: T) -> bool580     pub fn peek<T: Peek>(&self, token: T) -> bool {
581         let _ = token;
582         T::Token::peek(self.cursor())
583     }
584 
585     /// Looks at the second-next token in the parse stream.
586     ///
587     /// This is commonly useful as a way to implement contextual keywords.
588     ///
589     /// # Example
590     ///
591     /// This example needs to use `peek2` because the symbol `union` is not a
592     /// keyword in Rust. We can't use just `peek` and decide to parse a union if
593     /// the very next token is `union`, because someone is free to write a `mod
594     /// union` and a macro invocation that looks like `union::some_macro! { ...
595     /// }`. In other words `union` is a contextual keyword.
596     ///
597     /// ```
598     /// use syn::{Ident, ItemUnion, Macro, Result, Token};
599     /// use syn::parse::{Parse, ParseStream};
600     ///
601     /// // Parses either a union or a macro invocation.
602     /// enum UnionOrMacro {
603     ///     // union MaybeUninit<T> { uninit: (), value: T }
604     ///     Union(ItemUnion),
605     ///     // lazy_static! { ... }
606     ///     Macro(Macro),
607     /// }
608     ///
609     /// impl Parse for UnionOrMacro {
610     ///     fn parse(input: ParseStream) -> Result<Self> {
611     ///         if input.peek(Token![union]) && input.peek2(Ident) {
612     ///             input.parse().map(UnionOrMacro::Union)
613     ///         } else {
614     ///             input.parse().map(UnionOrMacro::Macro)
615     ///         }
616     ///     }
617     /// }
618     /// ```
peek2<T: Peek>(&self, token: T) -> bool619     pub fn peek2<T: Peek>(&self, token: T) -> bool {
620         fn peek2(buffer: &ParseBuffer, peek: fn(Cursor) -> bool) -> bool {
621             if let Some(group) = buffer.cursor().group(Delimiter::None) {
622                 if group.0.skip().map_or(false, peek) {
623                     return true;
624                 }
625             }
626             buffer.cursor().skip().map_or(false, peek)
627         }
628 
629         let _ = token;
630         peek2(self, T::Token::peek)
631     }
632 
633     /// Looks at the third-next token in the parse stream.
peek3<T: Peek>(&self, token: T) -> bool634     pub fn peek3<T: Peek>(&self, token: T) -> bool {
635         fn peek3(buffer: &ParseBuffer, peek: fn(Cursor) -> bool) -> bool {
636             if let Some(group) = buffer.cursor().group(Delimiter::None) {
637                 if group.0.skip().and_then(Cursor::skip).map_or(false, peek) {
638                     return true;
639                 }
640             }
641             buffer
642                 .cursor()
643                 .skip()
644                 .and_then(Cursor::skip)
645                 .map_or(false, peek)
646         }
647 
648         let _ = token;
649         peek3(self, T::Token::peek)
650     }
651 
652     /// Parses zero or more occurrences of `T` separated by punctuation of type
653     /// `P`, with optional trailing punctuation.
654     ///
655     /// Parsing continues until the end of this parse stream. The entire content
656     /// of this parse stream must consist of `T` and `P`.
657     ///
658     /// # Example
659     ///
660     /// ```
661     /// # use quote::quote;
662     /// #
663     /// use syn::{parenthesized, token, Ident, Result, Token, Type};
664     /// use syn::parse::{Parse, ParseStream};
665     /// use syn::punctuated::Punctuated;
666     ///
667     /// // Parse a simplified tuple struct syntax like:
668     /// //
669     /// //     struct S(A, B);
670     /// struct TupleStruct {
671     ///     struct_token: Token![struct],
672     ///     ident: Ident,
673     ///     paren_token: token::Paren,
674     ///     fields: Punctuated<Type, Token![,]>,
675     ///     semi_token: Token![;],
676     /// }
677     ///
678     /// impl Parse for TupleStruct {
679     ///     fn parse(input: ParseStream) -> Result<Self> {
680     ///         let content;
681     ///         Ok(TupleStruct {
682     ///             struct_token: input.parse()?,
683     ///             ident: input.parse()?,
684     ///             paren_token: parenthesized!(content in input),
685     ///             fields: content.parse_terminated(Type::parse)?,
686     ///             semi_token: input.parse()?,
687     ///         })
688     ///     }
689     /// }
690     /// #
691     /// # let input = quote! {
692     /// #     struct S(A, B);
693     /// # };
694     /// # syn::parse2::<TupleStruct>(input).unwrap();
695     /// ```
parse_terminated<T, P: Parse>( &self, parser: fn(ParseStream) -> Result<T>, ) -> Result<Punctuated<T, P>>696     pub fn parse_terminated<T, P: Parse>(
697         &self,
698         parser: fn(ParseStream) -> Result<T>,
699     ) -> Result<Punctuated<T, P>> {
700         Punctuated::parse_terminated_with(self, parser)
701     }
702 
703     /// Returns whether there are tokens remaining in this stream.
704     ///
705     /// This method returns true at the end of the content of a set of
706     /// delimiters, as well as at the very end of the complete macro input.
707     ///
708     /// # Example
709     ///
710     /// ```
711     /// use syn::{braced, token, Ident, Item, Result, Token};
712     /// use syn::parse::{Parse, ParseStream};
713     ///
714     /// // Parses a Rust `mod m { ... }` containing zero or more items.
715     /// struct Mod {
716     ///     mod_token: Token![mod],
717     ///     name: Ident,
718     ///     brace_token: token::Brace,
719     ///     items: Vec<Item>,
720     /// }
721     ///
722     /// impl Parse for Mod {
723     ///     fn parse(input: ParseStream) -> Result<Self> {
724     ///         let content;
725     ///         Ok(Mod {
726     ///             mod_token: input.parse()?,
727     ///             name: input.parse()?,
728     ///             brace_token: braced!(content in input),
729     ///             items: {
730     ///                 let mut items = Vec::new();
731     ///                 while !content.is_empty() {
732     ///                     items.push(content.parse()?);
733     ///                 }
734     ///                 items
735     ///             },
736     ///         })
737     ///     }
738     /// }
739     /// ```
is_empty(&self) -> bool740     pub fn is_empty(&self) -> bool {
741         self.cursor().eof()
742     }
743 
744     /// Constructs a helper for peeking at the next token in this stream and
745     /// building an error message if it is not one of a set of expected tokens.
746     ///
747     /// # Example
748     ///
749     /// ```
750     /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, Token, TypeParam};
751     /// use syn::parse::{Parse, ParseStream};
752     ///
753     /// // A generic parameter, a single one of the comma-separated elements inside
754     /// // angle brackets in:
755     /// //
756     /// //     fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
757     /// //
758     /// // On invalid input, lookahead gives us a reasonable error message.
759     /// //
760     /// //     error: expected one of: identifier, lifetime, `const`
761     /// //       |
762     /// //     5 |     fn f<!Sized>() {}
763     /// //       |          ^
764     /// enum GenericParam {
765     ///     Type(TypeParam),
766     ///     Lifetime(LifetimeDef),
767     ///     Const(ConstParam),
768     /// }
769     ///
770     /// impl Parse for GenericParam {
771     ///     fn parse(input: ParseStream) -> Result<Self> {
772     ///         let lookahead = input.lookahead1();
773     ///         if lookahead.peek(Ident) {
774     ///             input.parse().map(GenericParam::Type)
775     ///         } else if lookahead.peek(Lifetime) {
776     ///             input.parse().map(GenericParam::Lifetime)
777     ///         } else if lookahead.peek(Token![const]) {
778     ///             input.parse().map(GenericParam::Const)
779     ///         } else {
780     ///             Err(lookahead.error())
781     ///         }
782     ///     }
783     /// }
784     /// ```
lookahead1(&self) -> Lookahead1<'a>785     pub fn lookahead1(&self) -> Lookahead1<'a> {
786         lookahead::new(self.scope, self.cursor())
787     }
788 
789     /// Forks a parse stream so that parsing tokens out of either the original
790     /// or the fork does not advance the position of the other.
791     ///
792     /// # Performance
793     ///
794     /// Forking a parse stream is a cheap fixed amount of work and does not
795     /// involve copying token buffers. Where you might hit performance problems
796     /// is if your macro ends up parsing a large amount of content more than
797     /// once.
798     ///
799     /// ```
800     /// # use syn::{Expr, Result};
801     /// # use syn::parse::ParseStream;
802     /// #
803     /// # fn bad(input: ParseStream) -> Result<Expr> {
804     /// // Do not do this.
805     /// if input.fork().parse::<Expr>().is_ok() {
806     ///     return input.parse::<Expr>();
807     /// }
808     /// # unimplemented!()
809     /// # }
810     /// ```
811     ///
812     /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
813     /// parse stream. Only use a fork when the amount of work performed against
814     /// the fork is small and bounded.
815     ///
816     /// When complex speculative parsing against the forked stream is
817     /// unavoidable, use [`parse::discouraged::Speculative`] to advance the
818     /// original stream once the fork's parse is determined to have been
819     /// successful.
820     ///
821     /// For a lower level way to perform speculative parsing at the token level,
822     /// consider using [`ParseStream::step`] instead.
823     ///
824     /// [`parse::discouraged::Speculative`]: discouraged::Speculative
825     /// [`ParseStream::step`]: ParseBuffer::step
826     ///
827     /// # Example
828     ///
829     /// The parse implementation shown here parses possibly restricted `pub`
830     /// visibilities.
831     ///
832     /// - `pub`
833     /// - `pub(crate)`
834     /// - `pub(self)`
835     /// - `pub(super)`
836     /// - `pub(in some::path)`
837     ///
838     /// To handle the case of visibilities inside of tuple structs, the parser
839     /// needs to distinguish parentheses that specify visibility restrictions
840     /// from parentheses that form part of a tuple type.
841     ///
842     /// ```
843     /// # struct A;
844     /// # struct B;
845     /// # struct C;
846     /// #
847     /// struct S(pub(crate) A, pub (B, C));
848     /// ```
849     ///
850     /// In this example input the first tuple struct element of `S` has
851     /// `pub(crate)` visibility while the second tuple struct element has `pub`
852     /// visibility; the parentheses around `(B, C)` are part of the type rather
853     /// than part of a visibility restriction.
854     ///
855     /// The parser uses a forked parse stream to check the first token inside of
856     /// parentheses after the `pub` keyword. This is a small bounded amount of
857     /// work performed against the forked parse stream.
858     ///
859     /// ```
860     /// use syn::{parenthesized, token, Ident, Path, Result, Token};
861     /// use syn::ext::IdentExt;
862     /// use syn::parse::{Parse, ParseStream};
863     ///
864     /// struct PubVisibility {
865     ///     pub_token: Token![pub],
866     ///     restricted: Option<Restricted>,
867     /// }
868     ///
869     /// struct Restricted {
870     ///     paren_token: token::Paren,
871     ///     in_token: Option<Token![in]>,
872     ///     path: Path,
873     /// }
874     ///
875     /// impl Parse for PubVisibility {
876     ///     fn parse(input: ParseStream) -> Result<Self> {
877     ///         let pub_token: Token![pub] = input.parse()?;
878     ///
879     ///         if input.peek(token::Paren) {
880     ///             let ahead = input.fork();
881     ///             let mut content;
882     ///             parenthesized!(content in ahead);
883     ///
884     ///             if content.peek(Token![crate])
885     ///                 || content.peek(Token![self])
886     ///                 || content.peek(Token![super])
887     ///             {
888     ///                 return Ok(PubVisibility {
889     ///                     pub_token,
890     ///                     restricted: Some(Restricted {
891     ///                         paren_token: parenthesized!(content in input),
892     ///                         in_token: None,
893     ///                         path: Path::from(content.call(Ident::parse_any)?),
894     ///                     }),
895     ///                 });
896     ///             } else if content.peek(Token![in]) {
897     ///                 return Ok(PubVisibility {
898     ///                     pub_token,
899     ///                     restricted: Some(Restricted {
900     ///                         paren_token: parenthesized!(content in input),
901     ///                         in_token: Some(content.parse()?),
902     ///                         path: content.call(Path::parse_mod_style)?,
903     ///                     }),
904     ///                 });
905     ///             }
906     ///         }
907     ///
908     ///         Ok(PubVisibility {
909     ///             pub_token,
910     ///             restricted: None,
911     ///         })
912     ///     }
913     /// }
914     /// ```
fork(&self) -> Self915     pub fn fork(&self) -> Self {
916         ParseBuffer {
917             scope: self.scope,
918             cell: self.cell.clone(),
919             marker: PhantomData,
920             // Not the parent's unexpected. Nothing cares whether the clone
921             // parses all the way unless we `advance_to`.
922             unexpected: Cell::new(Some(Rc::new(Cell::new(Unexpected::None)))),
923         }
924     }
925 
926     /// Triggers an error at the current position of the parse stream.
927     ///
928     /// # Example
929     ///
930     /// ```
931     /// use syn::{Expr, Result, Token};
932     /// use syn::parse::{Parse, ParseStream};
933     ///
934     /// // Some kind of loop: `while` or `for` or `loop`.
935     /// struct Loop {
936     ///     expr: Expr,
937     /// }
938     ///
939     /// impl Parse for Loop {
940     ///     fn parse(input: ParseStream) -> Result<Self> {
941     ///         if input.peek(Token![while])
942     ///             || input.peek(Token![for])
943     ///             || input.peek(Token![loop])
944     ///         {
945     ///             Ok(Loop {
946     ///                 expr: input.parse()?,
947     ///             })
948     ///         } else {
949     ///             Err(input.error("expected some kind of loop"))
950     ///         }
951     ///     }
952     /// }
953     /// ```
error<T: Display>(&self, message: T) -> Error954     pub fn error<T: Display>(&self, message: T) -> Error {
955         error::new_at(self.scope, self.cursor(), message)
956     }
957 
958     /// Speculatively parses tokens from this parse stream, advancing the
959     /// position of this stream only if parsing succeeds.
960     ///
961     /// This is a powerful low-level API used for defining the `Parse` impls of
962     /// the basic built-in token types. It is not something that will be used
963     /// widely outside of the Syn codebase.
964     ///
965     /// # Example
966     ///
967     /// ```
968     /// use proc_macro2::TokenTree;
969     /// use syn::Result;
970     /// use syn::parse::ParseStream;
971     ///
972     /// // This function advances the stream past the next occurrence of `@`. If
973     /// // no `@` is present in the stream, the stream position is unchanged and
974     /// // an error is returned.
975     /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
976     ///     input.step(|cursor| {
977     ///         let mut rest = *cursor;
978     ///         while let Some((tt, next)) = rest.token_tree() {
979     ///             match &tt {
980     ///                 TokenTree::Punct(punct) if punct.as_char() == '@' => {
981     ///                     return Ok(((), next));
982     ///                 }
983     ///                 _ => rest = next,
984     ///             }
985     ///         }
986     ///         Err(cursor.error("no `@` was found after this point"))
987     ///     })
988     /// }
989     /// #
990     /// # fn remainder_after_skipping_past_next_at(
991     /// #     input: ParseStream,
992     /// # ) -> Result<proc_macro2::TokenStream> {
993     /// #     skip_past_next_at(input)?;
994     /// #     input.parse()
995     /// # }
996     /// #
997     /// # use syn::parse::Parser;
998     /// # let remainder = remainder_after_skipping_past_next_at
999     /// #     .parse_str("a @ b c")
1000     /// #     .unwrap();
1001     /// # assert_eq!(remainder.to_string(), "b c");
1002     /// ```
step<F, R>(&self, function: F) -> Result<R> where F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,1003     pub fn step<F, R>(&self, function: F) -> Result<R>
1004     where
1005         F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
1006     {
1007         // Since the user's function is required to work for any 'c, we know
1008         // that the Cursor<'c> they return is either derived from the input
1009         // StepCursor<'c, 'a> or from a Cursor<'static>.
1010         //
1011         // It would not be legal to write this function without the invariant
1012         // lifetime 'c in StepCursor<'c, 'a>. If this function were written only
1013         // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to
1014         // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke
1015         // `step` on their ParseBuffer<'short> with a closure that returns
1016         // Cursor<'short>, and we would wrongly write that Cursor<'short> into
1017         // the Cell intended to hold Cursor<'a>.
1018         //
1019         // In some cases it may be necessary for R to contain a Cursor<'a>.
1020         // Within Syn we solve this using `advance_step_cursor` which uses the
1021         // existence of a StepCursor<'c, 'a> as proof that it is safe to cast
1022         // from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it would be
1023         // safe to expose that API as a method on StepCursor.
1024         let (node, rest) = function(StepCursor {
1025             scope: self.scope,
1026             cursor: self.cell.get(),
1027             marker: PhantomData,
1028         })?;
1029         self.cell.set(rest);
1030         Ok(node)
1031     }
1032 
1033     /// Returns the `Span` of the next token in the parse stream, or
1034     /// `Span::call_site()` if this parse stream has completely exhausted its
1035     /// input `TokenStream`.
span(&self) -> Span1036     pub fn span(&self) -> Span {
1037         let cursor = self.cursor();
1038         if cursor.eof() {
1039             self.scope
1040         } else {
1041             crate::buffer::open_span_of_group(cursor)
1042         }
1043     }
1044 
1045     /// Provides low-level access to the token representation underlying this
1046     /// parse stream.
1047     ///
1048     /// Cursors are immutable so no operations you perform against the cursor
1049     /// will affect the state of this parse stream.
cursor(&self) -> Cursor<'a>1050     pub fn cursor(&self) -> Cursor<'a> {
1051         self.cell.get()
1052     }
1053 
check_unexpected(&self) -> Result<()>1054     fn check_unexpected(&self) -> Result<()> {
1055         match inner_unexpected(self).1 {
1056             Some(span) => Err(Error::new(span, "unexpected token")),
1057             None => Ok(()),
1058         }
1059     }
1060 }
1061 
1062 #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
1063 impl<T: Parse> Parse for Box<T> {
parse(input: ParseStream) -> Result<Self>1064     fn parse(input: ParseStream) -> Result<Self> {
1065         input.parse().map(Box::new)
1066     }
1067 }
1068 
1069 #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
1070 impl<T: Parse + Token> Parse for Option<T> {
parse(input: ParseStream) -> Result<Self>1071     fn parse(input: ParseStream) -> Result<Self> {
1072         if T::peek(input.cursor()) {
1073             Ok(Some(input.parse()?))
1074         } else {
1075             Ok(None)
1076         }
1077     }
1078 }
1079 
1080 #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
1081 impl Parse for TokenStream {
parse(input: ParseStream) -> Result<Self>1082     fn parse(input: ParseStream) -> Result<Self> {
1083         input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
1084     }
1085 }
1086 
1087 #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
1088 impl Parse for TokenTree {
parse(input: ParseStream) -> Result<Self>1089     fn parse(input: ParseStream) -> Result<Self> {
1090         input.step(|cursor| match cursor.token_tree() {
1091             Some((tt, rest)) => Ok((tt, rest)),
1092             None => Err(cursor.error("expected token tree")),
1093         })
1094     }
1095 }
1096 
1097 #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
1098 impl Parse for Group {
parse(input: ParseStream) -> Result<Self>1099     fn parse(input: ParseStream) -> Result<Self> {
1100         input.step(|cursor| {
1101             for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
1102                 if let Some((inside, span, rest)) = cursor.group(*delim) {
1103                     let mut group = Group::new(*delim, inside.token_stream());
1104                     group.set_span(span);
1105                     return Ok((group, rest));
1106                 }
1107             }
1108             Err(cursor.error("expected group token"))
1109         })
1110     }
1111 }
1112 
1113 #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
1114 impl Parse for Punct {
parse(input: ParseStream) -> Result<Self>1115     fn parse(input: ParseStream) -> Result<Self> {
1116         input.step(|cursor| match cursor.punct() {
1117             Some((punct, rest)) => Ok((punct, rest)),
1118             None => Err(cursor.error("expected punctuation token")),
1119         })
1120     }
1121 }
1122 
1123 #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
1124 impl Parse for Literal {
parse(input: ParseStream) -> Result<Self>1125     fn parse(input: ParseStream) -> Result<Self> {
1126         input.step(|cursor| match cursor.literal() {
1127             Some((literal, rest)) => Ok((literal, rest)),
1128             None => Err(cursor.error("expected literal token")),
1129         })
1130     }
1131 }
1132 
1133 /// Parser that can parse Rust tokens into a particular syntax tree node.
1134 ///
1135 /// Refer to the [module documentation] for details about parsing in Syn.
1136 ///
1137 /// [module documentation]: self
1138 ///
1139 /// *This trait is available only if Syn is built with the `"parsing"` feature.*
1140 pub trait Parser: Sized {
1141     type Output;
1142 
1143     /// Parse a proc-macro2 token stream into the chosen syntax tree node.
1144     ///
1145     /// This function will check that the input is fully parsed. If there are
1146     /// any unparsed tokens at the end of the stream, an error is returned.
parse2(self, tokens: TokenStream) -> Result<Self::Output>1147     fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
1148 
1149     /// Parse tokens of source code into the chosen syntax tree node.
1150     ///
1151     /// This function will check that the input is fully parsed. If there are
1152     /// any unparsed tokens at the end of the stream, an error is returned.
1153     ///
1154     /// *This method is available only if Syn is built with both the `"parsing"` and
1155     /// `"proc-macro"` features.*
1156     #[cfg(all(
1157         not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
1158         feature = "proc-macro"
1159     ))]
parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output>1160     fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
1161         self.parse2(proc_macro2::TokenStream::from(tokens))
1162     }
1163 
1164     /// Parse a string of Rust code into the chosen syntax tree node.
1165     ///
1166     /// This function will check that the input is fully parsed. If there are
1167     /// any unparsed tokens at the end of the string, an error is returned.
1168     ///
1169     /// # Hygiene
1170     ///
1171     /// Every span in the resulting syntax tree will be set to resolve at the
1172     /// macro call site.
parse_str(self, s: &str) -> Result<Self::Output>1173     fn parse_str(self, s: &str) -> Result<Self::Output> {
1174         self.parse2(proc_macro2::TokenStream::from_str(s)?)
1175     }
1176 
1177     // Not public API.
1178     #[doc(hidden)]
1179     #[cfg(any(feature = "full", feature = "derive"))]
__parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output>1180     fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> {
1181         let _ = scope;
1182         self.parse2(tokens)
1183     }
1184 
1185     // Not public API.
1186     #[doc(hidden)]
1187     #[cfg(any(feature = "full", feature = "derive"))]
__parse_stream(self, input: ParseStream) -> Result<Self::Output>1188     fn __parse_stream(self, input: ParseStream) -> Result<Self::Output> {
1189         input.parse().and_then(|tokens| self.parse2(tokens))
1190     }
1191 }
1192 
tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer1193 fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
1194     let scope = Span::call_site();
1195     let cursor = tokens.begin();
1196     let unexpected = Rc::new(Cell::new(Unexpected::None));
1197     new_parse_buffer(scope, cursor, unexpected)
1198 }
1199 
1200 impl<F, T> Parser for F
1201 where
1202     F: FnOnce(ParseStream) -> Result<T>,
1203 {
1204     type Output = T;
1205 
parse2(self, tokens: TokenStream) -> Result<T>1206     fn parse2(self, tokens: TokenStream) -> Result<T> {
1207         let buf = TokenBuffer::new2(tokens);
1208         let state = tokens_to_parse_buffer(&buf);
1209         let node = self(&state)?;
1210         state.check_unexpected()?;
1211         if let Some(unexpected_span) = span_of_unexpected_ignoring_nones(state.cursor()) {
1212             Err(Error::new(unexpected_span, "unexpected token"))
1213         } else {
1214             Ok(node)
1215         }
1216     }
1217 
1218     #[doc(hidden)]
1219     #[cfg(any(feature = "full", feature = "derive"))]
__parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output>1220     fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> {
1221         let buf = TokenBuffer::new2(tokens);
1222         let cursor = buf.begin();
1223         let unexpected = Rc::new(Cell::new(Unexpected::None));
1224         let state = new_parse_buffer(scope, cursor, unexpected);
1225         let node = self(&state)?;
1226         state.check_unexpected()?;
1227         if let Some(unexpected_span) = span_of_unexpected_ignoring_nones(state.cursor()) {
1228             Err(Error::new(unexpected_span, "unexpected token"))
1229         } else {
1230             Ok(node)
1231         }
1232     }
1233 
1234     #[doc(hidden)]
1235     #[cfg(any(feature = "full", feature = "derive"))]
__parse_stream(self, input: ParseStream) -> Result<Self::Output>1236     fn __parse_stream(self, input: ParseStream) -> Result<Self::Output> {
1237         self(input)
1238     }
1239 }
1240 
1241 #[cfg(any(feature = "full", feature = "derive"))]
parse_scoped<F: Parser>(f: F, scope: Span, tokens: TokenStream) -> Result<F::Output>1242 pub(crate) fn parse_scoped<F: Parser>(f: F, scope: Span, tokens: TokenStream) -> Result<F::Output> {
1243     f.__parse_scoped(scope, tokens)
1244 }
1245 
1246 #[cfg(any(feature = "full", feature = "derive"))]
parse_stream<F: Parser>(f: F, input: ParseStream) -> Result<F::Output>1247 pub(crate) fn parse_stream<F: Parser>(f: F, input: ParseStream) -> Result<F::Output> {
1248     f.__parse_stream(input)
1249 }
1250 
1251 /// An empty syntax tree node that consumes no tokens when parsed.
1252 ///
1253 /// This is useful for attribute macros that want to ensure they are not
1254 /// provided any attribute args.
1255 ///
1256 /// ```
1257 /// # extern crate proc_macro;
1258 /// #
1259 /// use proc_macro::TokenStream;
1260 /// use syn::parse_macro_input;
1261 /// use syn::parse::Nothing;
1262 ///
1263 /// # const IGNORE: &str = stringify! {
1264 /// #[proc_macro_attribute]
1265 /// # };
1266 /// pub fn my_attr(args: TokenStream, input: TokenStream) -> TokenStream {
1267 ///     parse_macro_input!(args as Nothing);
1268 ///
1269 ///     /* ... */
1270 /// #   "".parse().unwrap()
1271 /// }
1272 /// ```
1273 ///
1274 /// ```text
1275 /// error: unexpected token
1276 ///  --> src/main.rs:3:19
1277 ///   |
1278 /// 3 | #[my_attr(asdf)]
1279 ///   |           ^^^^
1280 /// ```
1281 pub struct Nothing;
1282 
1283 impl Parse for Nothing {
parse(_input: ParseStream) -> Result<Self>1284     fn parse(_input: ParseStream) -> Result<Self> {
1285         Ok(Nothing)
1286     }
1287 }
1288