xref: /linux/rust/syn/parse.rs (revision 784faa8eca8270671e0ed6d9d21f04bbb80fc5f7)
1*69942c0aSMiguel Ojeda // SPDX-License-Identifier: Apache-2.0 OR MIT
2*69942c0aSMiguel Ojeda 
3808c999fSMiguel Ojeda //! Parsing interface for parsing a token stream into a syntax tree node.
4808c999fSMiguel Ojeda //!
5808c999fSMiguel Ojeda //! Parsing in Syn is built on parser functions that take in a [`ParseStream`]
6808c999fSMiguel Ojeda //! and produce a [`Result<T>`] where `T` is some syntax tree node. Underlying
7808c999fSMiguel Ojeda //! these parser functions is a lower level mechanism built around the
8808c999fSMiguel Ojeda //! [`Cursor`] type. `Cursor` is a cheaply copyable cursor over a range of
9808c999fSMiguel Ojeda //! tokens in a token stream.
10808c999fSMiguel Ojeda //!
11808c999fSMiguel Ojeda //! [`Result<T>`]: Result
12808c999fSMiguel Ojeda //! [`Cursor`]: crate::buffer::Cursor
13808c999fSMiguel Ojeda //!
14808c999fSMiguel Ojeda //! # Example
15808c999fSMiguel Ojeda //!
16808c999fSMiguel Ojeda //! Here is a snippet of parsing code to get a feel for the style of the
17808c999fSMiguel Ojeda //! library. We define data structures for a subset of Rust syntax including
18808c999fSMiguel Ojeda //! enums (not shown) and structs, then provide implementations of the [`Parse`]
19808c999fSMiguel Ojeda //! trait to parse these syntax tree data structures from a token stream.
20808c999fSMiguel Ojeda //!
21808c999fSMiguel Ojeda //! Once `Parse` impls have been defined, they can be called conveniently from a
22808c999fSMiguel Ojeda //! procedural macro through [`parse_macro_input!`] as shown at the bottom of
23808c999fSMiguel Ojeda //! the snippet. If the caller provides syntactically invalid input to the
24808c999fSMiguel Ojeda //! procedural macro, they will receive a helpful compiler error message
25808c999fSMiguel Ojeda //! pointing out the exact token that triggered the failure to parse.
26808c999fSMiguel Ojeda //!
27808c999fSMiguel Ojeda //! [`parse_macro_input!`]: crate::parse_macro_input!
28808c999fSMiguel Ojeda //!
29808c999fSMiguel Ojeda //! ```
30808c999fSMiguel Ojeda //! # extern crate proc_macro;
31808c999fSMiguel Ojeda //! #
32808c999fSMiguel Ojeda //! use proc_macro::TokenStream;
33808c999fSMiguel Ojeda //! use syn::{braced, parse_macro_input, token, Field, Ident, Result, Token};
34808c999fSMiguel Ojeda //! use syn::parse::{Parse, ParseStream};
35808c999fSMiguel Ojeda //! use syn::punctuated::Punctuated;
36808c999fSMiguel Ojeda //!
37808c999fSMiguel Ojeda //! enum Item {
38808c999fSMiguel Ojeda //!     Struct(ItemStruct),
39808c999fSMiguel Ojeda //!     Enum(ItemEnum),
40808c999fSMiguel Ojeda //! }
41808c999fSMiguel Ojeda //!
42808c999fSMiguel Ojeda //! struct ItemStruct {
43808c999fSMiguel Ojeda //!     struct_token: Token![struct],
44808c999fSMiguel Ojeda //!     ident: Ident,
45808c999fSMiguel Ojeda //!     brace_token: token::Brace,
46808c999fSMiguel Ojeda //!     fields: Punctuated<Field, Token![,]>,
47808c999fSMiguel Ojeda //! }
48808c999fSMiguel Ojeda //! #
49808c999fSMiguel Ojeda //! # enum ItemEnum {}
50808c999fSMiguel Ojeda //!
51808c999fSMiguel Ojeda //! impl Parse for Item {
52808c999fSMiguel Ojeda //!     fn parse(input: ParseStream) -> Result<Self> {
53808c999fSMiguel Ojeda //!         let lookahead = input.lookahead1();
54808c999fSMiguel Ojeda //!         if lookahead.peek(Token![struct]) {
55808c999fSMiguel Ojeda //!             input.parse().map(Item::Struct)
56808c999fSMiguel Ojeda //!         } else if lookahead.peek(Token![enum]) {
57808c999fSMiguel Ojeda //!             input.parse().map(Item::Enum)
58808c999fSMiguel Ojeda //!         } else {
59808c999fSMiguel Ojeda //!             Err(lookahead.error())
60808c999fSMiguel Ojeda //!         }
61808c999fSMiguel Ojeda //!     }
62808c999fSMiguel Ojeda //! }
63808c999fSMiguel Ojeda //!
64808c999fSMiguel Ojeda //! impl Parse for ItemStruct {
65808c999fSMiguel Ojeda //!     fn parse(input: ParseStream) -> Result<Self> {
66808c999fSMiguel Ojeda //!         let content;
67808c999fSMiguel Ojeda //!         Ok(ItemStruct {
68808c999fSMiguel Ojeda //!             struct_token: input.parse()?,
69808c999fSMiguel Ojeda //!             ident: input.parse()?,
70808c999fSMiguel Ojeda //!             brace_token: braced!(content in input),
71808c999fSMiguel Ojeda //!             fields: content.parse_terminated(Field::parse_named, Token![,])?,
72808c999fSMiguel Ojeda //!         })
73808c999fSMiguel Ojeda //!     }
74808c999fSMiguel Ojeda //! }
75808c999fSMiguel Ojeda //! #
76808c999fSMiguel Ojeda //! # impl Parse for ItemEnum {
77808c999fSMiguel Ojeda //! #     fn parse(input: ParseStream) -> Result<Self> {
78808c999fSMiguel Ojeda //! #         unimplemented!()
79808c999fSMiguel Ojeda //! #     }
80808c999fSMiguel Ojeda //! # }
81808c999fSMiguel Ojeda //!
82808c999fSMiguel Ojeda //! # const IGNORE: &str = stringify! {
83808c999fSMiguel Ojeda //! #[proc_macro]
84808c999fSMiguel Ojeda //! # };
85808c999fSMiguel Ojeda //! pub fn my_macro(tokens: TokenStream) -> TokenStream {
86808c999fSMiguel Ojeda //!     let input = parse_macro_input!(tokens as Item);
87808c999fSMiguel Ojeda //!
88808c999fSMiguel Ojeda //!     /* ... */
89808c999fSMiguel Ojeda //! #   TokenStream::new()
90808c999fSMiguel Ojeda //! }
91808c999fSMiguel Ojeda //! ```
92808c999fSMiguel Ojeda //!
93808c999fSMiguel Ojeda //! # The `syn::parse*` functions
94808c999fSMiguel Ojeda //!
95808c999fSMiguel Ojeda //! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve
96808c999fSMiguel Ojeda //! as an entry point for parsing syntax tree nodes that can be parsed in an
97808c999fSMiguel Ojeda //! obvious default way. These functions can return any syntax tree node that
98808c999fSMiguel Ojeda //! implements the [`Parse`] trait, which includes most types in Syn.
99808c999fSMiguel Ojeda //!
100808c999fSMiguel Ojeda //! [`syn::parse`]: crate::parse()
101808c999fSMiguel Ojeda //! [`syn::parse2`]: crate::parse2()
102808c999fSMiguel Ojeda //! [`syn::parse_str`]: crate::parse_str()
103808c999fSMiguel Ojeda //!
104808c999fSMiguel Ojeda //! ```
105808c999fSMiguel Ojeda //! use syn::Type;
106808c999fSMiguel Ojeda //!
107808c999fSMiguel Ojeda //! # fn run_parser() -> syn::Result<()> {
108808c999fSMiguel Ojeda //! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?;
109808c999fSMiguel Ojeda //! #     Ok(())
110808c999fSMiguel Ojeda //! # }
111808c999fSMiguel Ojeda //! #
112808c999fSMiguel Ojeda //! # run_parser().unwrap();
113808c999fSMiguel Ojeda //! ```
114808c999fSMiguel Ojeda //!
115808c999fSMiguel Ojeda //! The [`parse_quote!`] macro also uses this approach.
116808c999fSMiguel Ojeda //!
117808c999fSMiguel Ojeda //! [`parse_quote!`]: crate::parse_quote!
118808c999fSMiguel Ojeda //!
119808c999fSMiguel Ojeda //! # The `Parser` trait
120808c999fSMiguel Ojeda //!
121808c999fSMiguel Ojeda //! Some types can be parsed in several ways depending on context. For example
122808c999fSMiguel Ojeda //! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
123808c999fSMiguel Ojeda //! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
124808c999fSMiguel Ojeda //! may or may not allow trailing punctuation, and parsing it the wrong way
125808c999fSMiguel Ojeda //! would either reject valid input or accept invalid input.
126808c999fSMiguel Ojeda //!
127808c999fSMiguel Ojeda //! [`Attribute`]: crate::Attribute
128808c999fSMiguel Ojeda //! [`Punctuated`]: crate::punctuated
129808c999fSMiguel Ojeda //!
130808c999fSMiguel Ojeda //! The `Parse` trait is not implemented in these cases because there is no good
131808c999fSMiguel Ojeda //! behavior to consider the default.
132808c999fSMiguel Ojeda //!
133808c999fSMiguel Ojeda //! ```compile_fail
134808c999fSMiguel Ojeda //! # extern crate proc_macro;
135808c999fSMiguel Ojeda //! #
136808c999fSMiguel Ojeda //! # use syn::punctuated::Punctuated;
137808c999fSMiguel Ojeda //! # use syn::{PathSegment, Result, Token};
138808c999fSMiguel Ojeda //! #
139808c999fSMiguel Ojeda //! # fn f(tokens: proc_macro::TokenStream) -> Result<()> {
140808c999fSMiguel Ojeda //! #
141808c999fSMiguel Ojeda //! // Can't parse `Punctuated` without knowing whether trailing punctuation
142808c999fSMiguel Ojeda //! // should be allowed in this context.
143808c999fSMiguel Ojeda //! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
144808c999fSMiguel Ojeda //! #
145808c999fSMiguel Ojeda //! #     Ok(())
146808c999fSMiguel Ojeda //! # }
147808c999fSMiguel Ojeda //! ```
148808c999fSMiguel Ojeda //!
149808c999fSMiguel Ojeda //! In these cases the types provide a choice of parser functions rather than a
150808c999fSMiguel Ojeda //! single `Parse` implementation, and those parser functions can be invoked
151808c999fSMiguel Ojeda //! through the [`Parser`] trait.
152808c999fSMiguel Ojeda //!
153808c999fSMiguel Ojeda //!
154808c999fSMiguel Ojeda //! ```
155808c999fSMiguel Ojeda //! # extern crate proc_macro;
156808c999fSMiguel Ojeda //! #
157808c999fSMiguel Ojeda //! use proc_macro::TokenStream;
158808c999fSMiguel Ojeda //! use syn::parse::Parser;
159808c999fSMiguel Ojeda //! use syn::punctuated::Punctuated;
160808c999fSMiguel Ojeda //! use syn::{Attribute, Expr, PathSegment, Result, Token};
161808c999fSMiguel Ojeda //!
162808c999fSMiguel Ojeda //! fn call_some_parser_methods(input: TokenStream) -> Result<()> {
163808c999fSMiguel Ojeda //!     // Parse a nonempty sequence of path segments separated by `::` punctuation
164808c999fSMiguel Ojeda //!     // with no trailing punctuation.
165808c999fSMiguel Ojeda //!     let tokens = input.clone();
166808c999fSMiguel Ojeda //!     let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
167808c999fSMiguel Ojeda //!     let _path = parser.parse(tokens)?;
168808c999fSMiguel Ojeda //!
169808c999fSMiguel Ojeda //!     // Parse a possibly empty sequence of expressions terminated by commas with
170808c999fSMiguel Ojeda //!     // an optional trailing punctuation.
171808c999fSMiguel Ojeda //!     let tokens = input.clone();
172808c999fSMiguel Ojeda //!     let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
173808c999fSMiguel Ojeda //!     let _args = parser.parse(tokens)?;
174808c999fSMiguel Ojeda //!
175808c999fSMiguel Ojeda //!     // Parse zero or more outer attributes but not inner attributes.
176808c999fSMiguel Ojeda //!     let tokens = input.clone();
177808c999fSMiguel Ojeda //!     let parser = Attribute::parse_outer;
178808c999fSMiguel Ojeda //!     let _attrs = parser.parse(tokens)?;
179808c999fSMiguel Ojeda //!
180808c999fSMiguel Ojeda //!     Ok(())
181808c999fSMiguel Ojeda //! }
182808c999fSMiguel Ojeda //! ```
183808c999fSMiguel Ojeda 
184808c999fSMiguel Ojeda #[path = "discouraged.rs"]
185808c999fSMiguel Ojeda pub mod discouraged;
186808c999fSMiguel Ojeda 
187808c999fSMiguel Ojeda use crate::buffer::{Cursor, TokenBuffer};
188808c999fSMiguel Ojeda use crate::error;
189808c999fSMiguel Ojeda use crate::lookahead;
190808c999fSMiguel Ojeda use crate::punctuated::Punctuated;
191808c999fSMiguel Ojeda use crate::token::Token;
192808c999fSMiguel Ojeda use proc_macro2::{Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree};
193808c999fSMiguel Ojeda #[cfg(feature = "printing")]
194808c999fSMiguel Ojeda use quote::ToTokens;
195808c999fSMiguel Ojeda use std::cell::Cell;
196808c999fSMiguel Ojeda use std::fmt::{self, Debug, Display};
197808c999fSMiguel Ojeda #[cfg(feature = "extra-traits")]
198808c999fSMiguel Ojeda use std::hash::{Hash, Hasher};
199808c999fSMiguel Ojeda use std::marker::PhantomData;
200808c999fSMiguel Ojeda use std::mem;
201808c999fSMiguel Ojeda use std::ops::Deref;
202808c999fSMiguel Ojeda use std::panic::{RefUnwindSafe, UnwindSafe};
203808c999fSMiguel Ojeda use std::rc::Rc;
204808c999fSMiguel Ojeda use std::str::FromStr;
205808c999fSMiguel Ojeda 
206808c999fSMiguel Ojeda pub use crate::error::{Error, Result};
207808c999fSMiguel Ojeda pub use crate::lookahead::{End, Lookahead1, Peek};
208808c999fSMiguel Ojeda 
209808c999fSMiguel Ojeda /// Parsing interface implemented by all types that can be parsed in a default
210808c999fSMiguel Ojeda /// way from a token stream.
211808c999fSMiguel Ojeda ///
212808c999fSMiguel Ojeda /// Refer to the [module documentation] for details about implementing and using
213808c999fSMiguel Ojeda /// the `Parse` trait.
214808c999fSMiguel Ojeda ///
215808c999fSMiguel Ojeda /// [module documentation]: self
216808c999fSMiguel Ojeda pub trait Parse: Sized {
parse(input: ParseStream) -> Result<Self>217808c999fSMiguel Ojeda     fn parse(input: ParseStream) -> Result<Self>;
218808c999fSMiguel Ojeda }
219808c999fSMiguel Ojeda 
220808c999fSMiguel Ojeda /// Input to a Syn parser function.
221808c999fSMiguel Ojeda ///
222808c999fSMiguel Ojeda /// See the methods of this type under the documentation of [`ParseBuffer`]. For
223808c999fSMiguel Ojeda /// an overview of parsing in Syn, refer to the [module documentation].
224808c999fSMiguel Ojeda ///
225808c999fSMiguel Ojeda /// [module documentation]: self
226808c999fSMiguel Ojeda pub type ParseStream<'a> = &'a ParseBuffer<'a>;
227808c999fSMiguel Ojeda 
228808c999fSMiguel Ojeda /// Cursor position within a buffered token stream.
229808c999fSMiguel Ojeda ///
230808c999fSMiguel Ojeda /// This type is more commonly used through the type alias [`ParseStream`] which
231808c999fSMiguel Ojeda /// is an alias for `&ParseBuffer`.
232808c999fSMiguel Ojeda ///
233808c999fSMiguel Ojeda /// `ParseStream` is the input type for all parser functions in Syn. They have
234808c999fSMiguel Ojeda /// the signature `fn(ParseStream) -> Result<T>`.
235808c999fSMiguel Ojeda ///
236808c999fSMiguel Ojeda /// ## Calling a parser function
237808c999fSMiguel Ojeda ///
238808c999fSMiguel Ojeda /// There is no public way to construct a `ParseBuffer`. Instead, if you are
239808c999fSMiguel Ojeda /// looking to invoke a parser function that requires `ParseStream` as input,
240808c999fSMiguel Ojeda /// you will need to go through one of the public parsing entry points.
241808c999fSMiguel Ojeda ///
242808c999fSMiguel Ojeda /// - The [`parse_macro_input!`] macro if parsing input of a procedural macro;
243808c999fSMiguel Ojeda /// - One of [the `syn::parse*` functions][syn-parse]; or
244808c999fSMiguel Ojeda /// - A method of the [`Parser`] trait.
245808c999fSMiguel Ojeda ///
246808c999fSMiguel Ojeda /// [`parse_macro_input!`]: crate::parse_macro_input!
247808c999fSMiguel Ojeda /// [syn-parse]: self#the-synparse-functions
248808c999fSMiguel Ojeda pub struct ParseBuffer<'a> {
249808c999fSMiguel Ojeda     scope: Span,
250808c999fSMiguel Ojeda     // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a.
251808c999fSMiguel Ojeda     // The rest of the code in this module needs to be careful that only a
252808c999fSMiguel Ojeda     // cursor derived from this `cell` is ever assigned to this `cell`.
253808c999fSMiguel Ojeda     //
254808c999fSMiguel Ojeda     // Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a
255808c999fSMiguel Ojeda     // ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter
256808c999fSMiguel Ojeda     // than 'a, and then assign a Cursor<'short> into the Cell.
257808c999fSMiguel Ojeda     //
258808c999fSMiguel Ojeda     // By extension, it would not be safe to expose an API that accepts a
259808c999fSMiguel Ojeda     // Cursor<'a> and trusts that it lives as long as the cursor currently in
260808c999fSMiguel Ojeda     // the cell.
261808c999fSMiguel Ojeda     cell: Cell<Cursor<'static>>,
262808c999fSMiguel Ojeda     marker: PhantomData<Cursor<'a>>,
263808c999fSMiguel Ojeda     unexpected: Cell<Option<Rc<Cell<Unexpected>>>>,
264808c999fSMiguel Ojeda }
265808c999fSMiguel Ojeda 
266808c999fSMiguel Ojeda impl<'a> Drop for ParseBuffer<'a> {
drop(&mut self)267808c999fSMiguel Ojeda     fn drop(&mut self) {
268808c999fSMiguel Ojeda         if let Some((unexpected_span, delimiter)) = span_of_unexpected_ignoring_nones(self.cursor())
269808c999fSMiguel Ojeda         {
270808c999fSMiguel Ojeda             let (inner, old_span) = inner_unexpected(self);
271808c999fSMiguel Ojeda             if old_span.is_none() {
272808c999fSMiguel Ojeda                 inner.set(Unexpected::Some(unexpected_span, delimiter));
273808c999fSMiguel Ojeda             }
274808c999fSMiguel Ojeda         }
275808c999fSMiguel Ojeda     }
276808c999fSMiguel Ojeda }
277808c999fSMiguel Ojeda 
278808c999fSMiguel Ojeda impl<'a> Display for ParseBuffer<'a> {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result279808c999fSMiguel Ojeda     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
280808c999fSMiguel Ojeda         Display::fmt(&self.cursor().token_stream(), f)
281808c999fSMiguel Ojeda     }
282808c999fSMiguel Ojeda }
283808c999fSMiguel Ojeda 
284808c999fSMiguel Ojeda impl<'a> Debug for ParseBuffer<'a> {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result285808c999fSMiguel Ojeda     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
286808c999fSMiguel Ojeda         Debug::fmt(&self.cursor().token_stream(), f)
287808c999fSMiguel Ojeda     }
288808c999fSMiguel Ojeda }
289808c999fSMiguel Ojeda 
290808c999fSMiguel Ojeda impl<'a> UnwindSafe for ParseBuffer<'a> {}
291808c999fSMiguel Ojeda impl<'a> RefUnwindSafe for ParseBuffer<'a> {}
292808c999fSMiguel Ojeda 
293808c999fSMiguel Ojeda /// Cursor state associated with speculative parsing.
294808c999fSMiguel Ojeda ///
295808c999fSMiguel Ojeda /// This type is the input of the closure provided to [`ParseStream::step`].
296808c999fSMiguel Ojeda ///
297808c999fSMiguel Ojeda /// [`ParseStream::step`]: ParseBuffer::step
298808c999fSMiguel Ojeda ///
299808c999fSMiguel Ojeda /// # Example
300808c999fSMiguel Ojeda ///
301808c999fSMiguel Ojeda /// ```
302808c999fSMiguel Ojeda /// use proc_macro2::TokenTree;
303808c999fSMiguel Ojeda /// use syn::Result;
304808c999fSMiguel Ojeda /// use syn::parse::ParseStream;
305808c999fSMiguel Ojeda ///
306808c999fSMiguel Ojeda /// // This function advances the stream past the next occurrence of `@`. If
307808c999fSMiguel Ojeda /// // no `@` is present in the stream, the stream position is unchanged and
308808c999fSMiguel Ojeda /// // an error is returned.
309808c999fSMiguel Ojeda /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
310808c999fSMiguel Ojeda ///     input.step(|cursor| {
311808c999fSMiguel Ojeda ///         let mut rest = *cursor;
312808c999fSMiguel Ojeda ///         while let Some((tt, next)) = rest.token_tree() {
313808c999fSMiguel Ojeda ///             match &tt {
314808c999fSMiguel Ojeda ///                 TokenTree::Punct(punct) if punct.as_char() == '@' => {
315808c999fSMiguel Ojeda ///                     return Ok(((), next));
316808c999fSMiguel Ojeda ///                 }
317808c999fSMiguel Ojeda ///                 _ => rest = next,
318808c999fSMiguel Ojeda ///             }
319808c999fSMiguel Ojeda ///         }
320808c999fSMiguel Ojeda ///         Err(cursor.error("no `@` was found after this point"))
321808c999fSMiguel Ojeda ///     })
322808c999fSMiguel Ojeda /// }
323808c999fSMiguel Ojeda /// #
324808c999fSMiguel Ojeda /// # fn remainder_after_skipping_past_next_at(
325808c999fSMiguel Ojeda /// #     input: ParseStream,
326808c999fSMiguel Ojeda /// # ) -> Result<proc_macro2::TokenStream> {
327808c999fSMiguel Ojeda /// #     skip_past_next_at(input)?;
328808c999fSMiguel Ojeda /// #     input.parse()
329808c999fSMiguel Ojeda /// # }
330808c999fSMiguel Ojeda /// #
331808c999fSMiguel Ojeda /// # use syn::parse::Parser;
332808c999fSMiguel Ojeda /// # let remainder = remainder_after_skipping_past_next_at
333808c999fSMiguel Ojeda /// #     .parse_str("a @ b c")
334808c999fSMiguel Ojeda /// #     .unwrap();
335808c999fSMiguel Ojeda /// # assert_eq!(remainder.to_string(), "b c");
336808c999fSMiguel Ojeda /// ```
337808c999fSMiguel Ojeda pub struct StepCursor<'c, 'a> {
338808c999fSMiguel Ojeda     scope: Span,
339808c999fSMiguel Ojeda     // This field is covariant in 'c.
340808c999fSMiguel Ojeda     cursor: Cursor<'c>,
341808c999fSMiguel Ojeda     // This field is contravariant in 'c. Together these make StepCursor
342808c999fSMiguel Ojeda     // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a
343808c999fSMiguel Ojeda     // different lifetime but can upcast into a StepCursor with a shorter
344808c999fSMiguel Ojeda     // lifetime 'a.
345808c999fSMiguel Ojeda     //
346808c999fSMiguel Ojeda     // As long as we only ever construct a StepCursor for which 'c outlives 'a,
347808c999fSMiguel Ojeda     // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c
348808c999fSMiguel Ojeda     // outlives 'a.
349808c999fSMiguel Ojeda     marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
350808c999fSMiguel Ojeda }
351808c999fSMiguel Ojeda 
352808c999fSMiguel Ojeda impl<'c, 'a> Deref for StepCursor<'c, 'a> {
353808c999fSMiguel Ojeda     type Target = Cursor<'c>;
354808c999fSMiguel Ojeda 
deref(&self) -> &Self::Target355808c999fSMiguel Ojeda     fn deref(&self) -> &Self::Target {
356808c999fSMiguel Ojeda         &self.cursor
357808c999fSMiguel Ojeda     }
358808c999fSMiguel Ojeda }
359808c999fSMiguel Ojeda 
360808c999fSMiguel Ojeda impl<'c, 'a> Copy for StepCursor<'c, 'a> {}
361808c999fSMiguel Ojeda 
362808c999fSMiguel Ojeda impl<'c, 'a> Clone for StepCursor<'c, 'a> {
clone(&self) -> Self363808c999fSMiguel Ojeda     fn clone(&self) -> Self {
364808c999fSMiguel Ojeda         *self
365808c999fSMiguel Ojeda     }
366808c999fSMiguel Ojeda }
367808c999fSMiguel Ojeda 
368808c999fSMiguel Ojeda impl<'c, 'a> StepCursor<'c, 'a> {
369808c999fSMiguel Ojeda     /// Triggers an error at the current position of the parse stream.
370808c999fSMiguel Ojeda     ///
371808c999fSMiguel Ojeda     /// The `ParseStream::step` invocation will return this same error without
372808c999fSMiguel Ojeda     /// advancing the stream state.
error<T: Display>(self, message: T) -> Error373808c999fSMiguel Ojeda     pub fn error<T: Display>(self, message: T) -> Error {
374808c999fSMiguel Ojeda         error::new_at(self.scope, self.cursor, message)
375808c999fSMiguel Ojeda     }
376808c999fSMiguel Ojeda }
377808c999fSMiguel Ojeda 
advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a>378808c999fSMiguel Ojeda pub(crate) fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
379808c999fSMiguel Ojeda     // Refer to the comments within the StepCursor definition. We use the
380808c999fSMiguel Ojeda     // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a.
381808c999fSMiguel Ojeda     // Cursor is covariant in its lifetime parameter so we can cast a
382808c999fSMiguel Ojeda     // Cursor<'c> to one with the shorter lifetime Cursor<'a>.
383808c999fSMiguel Ojeda     let _ = proof;
384808c999fSMiguel Ojeda     unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
385808c999fSMiguel Ojeda }
386808c999fSMiguel Ojeda 
new_parse_buffer( scope: Span, cursor: Cursor, unexpected: Rc<Cell<Unexpected>>, ) -> ParseBuffer387808c999fSMiguel Ojeda pub(crate) fn new_parse_buffer(
388808c999fSMiguel Ojeda     scope: Span,
389808c999fSMiguel Ojeda     cursor: Cursor,
390808c999fSMiguel Ojeda     unexpected: Rc<Cell<Unexpected>>,
391808c999fSMiguel Ojeda ) -> ParseBuffer {
392808c999fSMiguel Ojeda     ParseBuffer {
393808c999fSMiguel Ojeda         scope,
394808c999fSMiguel Ojeda         // See comment on `cell` in the struct definition.
395808c999fSMiguel Ojeda         cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }),
396808c999fSMiguel Ojeda         marker: PhantomData,
397808c999fSMiguel Ojeda         unexpected: Cell::new(Some(unexpected)),
398808c999fSMiguel Ojeda     }
399808c999fSMiguel Ojeda }
400808c999fSMiguel Ojeda 
401808c999fSMiguel Ojeda pub(crate) enum Unexpected {
402808c999fSMiguel Ojeda     None,
403808c999fSMiguel Ojeda     Some(Span, Delimiter),
404808c999fSMiguel Ojeda     Chain(Rc<Cell<Unexpected>>),
405808c999fSMiguel Ojeda }
406808c999fSMiguel Ojeda 
407808c999fSMiguel Ojeda impl Default for Unexpected {
default() -> Self408808c999fSMiguel Ojeda     fn default() -> Self {
409808c999fSMiguel Ojeda         Unexpected::None
410808c999fSMiguel Ojeda     }
411808c999fSMiguel Ojeda }
412808c999fSMiguel Ojeda 
413808c999fSMiguel Ojeda impl Clone for Unexpected {
clone(&self) -> Self414808c999fSMiguel Ojeda     fn clone(&self) -> Self {
415808c999fSMiguel Ojeda         match self {
416808c999fSMiguel Ojeda             Unexpected::None => Unexpected::None,
417808c999fSMiguel Ojeda             Unexpected::Some(span, delimiter) => Unexpected::Some(*span, *delimiter),
418808c999fSMiguel Ojeda             Unexpected::Chain(next) => Unexpected::Chain(next.clone()),
419808c999fSMiguel Ojeda         }
420808c999fSMiguel Ojeda     }
421808c999fSMiguel Ojeda }
422808c999fSMiguel Ojeda 
423808c999fSMiguel Ojeda // We call this on Cell<Unexpected> and Cell<Option<T>> where temporarily
424808c999fSMiguel Ojeda // swapping in a None is cheap.
cell_clone<T: Default + Clone>(cell: &Cell<T>) -> T425808c999fSMiguel Ojeda fn cell_clone<T: Default + Clone>(cell: &Cell<T>) -> T {
426808c999fSMiguel Ojeda     let prev = cell.take();
427808c999fSMiguel Ojeda     let ret = prev.clone();
428808c999fSMiguel Ojeda     cell.set(prev);
429808c999fSMiguel Ojeda     ret
430808c999fSMiguel Ojeda }
431808c999fSMiguel Ojeda 
inner_unexpected(buffer: &ParseBuffer) -> (Rc<Cell<Unexpected>>, Option<(Span, Delimiter)>)432808c999fSMiguel Ojeda fn inner_unexpected(buffer: &ParseBuffer) -> (Rc<Cell<Unexpected>>, Option<(Span, Delimiter)>) {
433808c999fSMiguel Ojeda     let mut unexpected = get_unexpected(buffer);
434808c999fSMiguel Ojeda     loop {
435808c999fSMiguel Ojeda         match cell_clone(&unexpected) {
436808c999fSMiguel Ojeda             Unexpected::None => return (unexpected, None),
437808c999fSMiguel Ojeda             Unexpected::Some(span, delimiter) => return (unexpected, Some((span, delimiter))),
438808c999fSMiguel Ojeda             Unexpected::Chain(next) => unexpected = next,
439808c999fSMiguel Ojeda         }
440808c999fSMiguel Ojeda     }
441808c999fSMiguel Ojeda }
442808c999fSMiguel Ojeda 
get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Unexpected>>443808c999fSMiguel Ojeda pub(crate) fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Unexpected>> {
444808c999fSMiguel Ojeda     cell_clone(&buffer.unexpected).unwrap()
445808c999fSMiguel Ojeda }
446808c999fSMiguel Ojeda 
span_of_unexpected_ignoring_nones(mut cursor: Cursor) -> Option<(Span, Delimiter)>447808c999fSMiguel Ojeda fn span_of_unexpected_ignoring_nones(mut cursor: Cursor) -> Option<(Span, Delimiter)> {
448808c999fSMiguel Ojeda     if cursor.eof() {
449808c999fSMiguel Ojeda         return None;
450808c999fSMiguel Ojeda     }
451808c999fSMiguel Ojeda     while let Some((inner, _span, rest)) = cursor.group(Delimiter::None) {
452808c999fSMiguel Ojeda         if let Some(unexpected) = span_of_unexpected_ignoring_nones(inner) {
453808c999fSMiguel Ojeda             return Some(unexpected);
454808c999fSMiguel Ojeda         }
455808c999fSMiguel Ojeda         cursor = rest;
456808c999fSMiguel Ojeda     }
457808c999fSMiguel Ojeda     if cursor.eof() {
458808c999fSMiguel Ojeda         None
459808c999fSMiguel Ojeda     } else {
460808c999fSMiguel Ojeda         Some((cursor.span(), cursor.scope_delimiter()))
461808c999fSMiguel Ojeda     }
462808c999fSMiguel Ojeda }
463808c999fSMiguel Ojeda 
464808c999fSMiguel Ojeda impl<'a> ParseBuffer<'a> {
465808c999fSMiguel Ojeda     /// Parses a syntax tree node of type `T`, advancing the position of our
466808c999fSMiguel Ojeda     /// parse stream past it.
parse<T: Parse>(&self) -> Result<T>467808c999fSMiguel Ojeda     pub fn parse<T: Parse>(&self) -> Result<T> {
468808c999fSMiguel Ojeda         T::parse(self)
469808c999fSMiguel Ojeda     }
470808c999fSMiguel Ojeda 
471808c999fSMiguel Ojeda     /// Calls the given parser function to parse a syntax tree node of type `T`
472808c999fSMiguel Ojeda     /// from this stream.
473808c999fSMiguel Ojeda     ///
474808c999fSMiguel Ojeda     /// # Example
475808c999fSMiguel Ojeda     ///
476808c999fSMiguel Ojeda     /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of
477808c999fSMiguel Ojeda     /// zero or more outer attributes.
478808c999fSMiguel Ojeda     ///
479808c999fSMiguel Ojeda     /// [`Attribute::parse_outer`]: crate::Attribute::parse_outer
480808c999fSMiguel Ojeda     ///
481808c999fSMiguel Ojeda     /// ```
482808c999fSMiguel Ojeda     /// use syn::{Attribute, Ident, Result, Token};
483808c999fSMiguel Ojeda     /// use syn::parse::{Parse, ParseStream};
484808c999fSMiguel Ojeda     ///
485808c999fSMiguel Ojeda     /// // Parses a unit struct with attributes.
486808c999fSMiguel Ojeda     /// //
487808c999fSMiguel Ojeda     /// //     #[path = "s.tmpl"]
488808c999fSMiguel Ojeda     /// //     struct S;
489808c999fSMiguel Ojeda     /// struct UnitStruct {
490808c999fSMiguel Ojeda     ///     attrs: Vec<Attribute>,
491808c999fSMiguel Ojeda     ///     struct_token: Token![struct],
492808c999fSMiguel Ojeda     ///     name: Ident,
493808c999fSMiguel Ojeda     ///     semi_token: Token![;],
494808c999fSMiguel Ojeda     /// }
495808c999fSMiguel Ojeda     ///
496808c999fSMiguel Ojeda     /// impl Parse for UnitStruct {
497808c999fSMiguel Ojeda     ///     fn parse(input: ParseStream) -> Result<Self> {
498808c999fSMiguel Ojeda     ///         Ok(UnitStruct {
499808c999fSMiguel Ojeda     ///             attrs: input.call(Attribute::parse_outer)?,
500808c999fSMiguel Ojeda     ///             struct_token: input.parse()?,
501808c999fSMiguel Ojeda     ///             name: input.parse()?,
502808c999fSMiguel Ojeda     ///             semi_token: input.parse()?,
503808c999fSMiguel Ojeda     ///         })
504808c999fSMiguel Ojeda     ///     }
505808c999fSMiguel Ojeda     /// }
506808c999fSMiguel Ojeda     /// ```
call<T>(&'a self, function: fn(ParseStream<'a>) -> Result<T>) -> Result<T>507808c999fSMiguel Ojeda     pub fn call<T>(&'a self, function: fn(ParseStream<'a>) -> Result<T>) -> Result<T> {
508808c999fSMiguel Ojeda         function(self)
509808c999fSMiguel Ojeda     }
510808c999fSMiguel Ojeda 
511808c999fSMiguel Ojeda     /// Looks at the next token in the parse stream to determine whether it
512808c999fSMiguel Ojeda     /// matches the requested type of token.
513808c999fSMiguel Ojeda     ///
514808c999fSMiguel Ojeda     /// Does not advance the position of the parse stream.
515808c999fSMiguel Ojeda     ///
516808c999fSMiguel Ojeda     /// # Syntax
517808c999fSMiguel Ojeda     ///
518808c999fSMiguel Ojeda     /// Note that this method does not use turbofish syntax. Pass the peek type
519808c999fSMiguel Ojeda     /// inside of parentheses.
520808c999fSMiguel Ojeda     ///
521808c999fSMiguel Ojeda     /// - `input.peek(Token![struct])`
522808c999fSMiguel Ojeda     /// - `input.peek(Token![==])`
523808c999fSMiguel Ojeda     /// - `input.peek(syn::Ident)`&emsp;*(does not accept keywords)*
524808c999fSMiguel Ojeda     /// - `input.peek(syn::Ident::peek_any)`
525808c999fSMiguel Ojeda     /// - `input.peek(Lifetime)`
526808c999fSMiguel Ojeda     /// - `input.peek(token::Brace)`
527808c999fSMiguel Ojeda     ///
528808c999fSMiguel Ojeda     /// # Example
529808c999fSMiguel Ojeda     ///
530808c999fSMiguel Ojeda     /// In this example we finish parsing the list of supertraits when the next
531808c999fSMiguel Ojeda     /// token in the input is either `where` or an opening curly brace.
532808c999fSMiguel Ojeda     ///
533808c999fSMiguel Ojeda     /// ```
534808c999fSMiguel Ojeda     /// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
535808c999fSMiguel Ojeda     /// use syn::parse::{Parse, ParseStream};
536808c999fSMiguel Ojeda     /// use syn::punctuated::Punctuated;
537808c999fSMiguel Ojeda     ///
538808c999fSMiguel Ojeda     /// // Parses a trait definition containing no associated items.
539808c999fSMiguel Ojeda     /// //
540808c999fSMiguel Ojeda     /// //     trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
541808c999fSMiguel Ojeda     /// struct MarkerTrait {
542808c999fSMiguel Ojeda     ///     trait_token: Token![trait],
543808c999fSMiguel Ojeda     ///     ident: Ident,
544808c999fSMiguel Ojeda     ///     generics: Generics,
545808c999fSMiguel Ojeda     ///     colon_token: Option<Token![:]>,
546808c999fSMiguel Ojeda     ///     supertraits: Punctuated<TypeParamBound, Token![+]>,
547808c999fSMiguel Ojeda     ///     brace_token: token::Brace,
548808c999fSMiguel Ojeda     /// }
549808c999fSMiguel Ojeda     ///
550808c999fSMiguel Ojeda     /// impl Parse for MarkerTrait {
551808c999fSMiguel Ojeda     ///     fn parse(input: ParseStream) -> Result<Self> {
552808c999fSMiguel Ojeda     ///         let trait_token: Token![trait] = input.parse()?;
553808c999fSMiguel Ojeda     ///         let ident: Ident = input.parse()?;
554808c999fSMiguel Ojeda     ///         let mut generics: Generics = input.parse()?;
555808c999fSMiguel Ojeda     ///         let colon_token: Option<Token![:]> = input.parse()?;
556808c999fSMiguel Ojeda     ///
557808c999fSMiguel Ojeda     ///         let mut supertraits = Punctuated::new();
558808c999fSMiguel Ojeda     ///         if colon_token.is_some() {
559808c999fSMiguel Ojeda     ///             loop {
560808c999fSMiguel Ojeda     ///                 supertraits.push_value(input.parse()?);
561808c999fSMiguel Ojeda     ///                 if input.peek(Token![where]) || input.peek(token::Brace) {
562808c999fSMiguel Ojeda     ///                     break;
563808c999fSMiguel Ojeda     ///                 }
564808c999fSMiguel Ojeda     ///                 supertraits.push_punct(input.parse()?);
565808c999fSMiguel Ojeda     ///             }
566808c999fSMiguel Ojeda     ///         }
567808c999fSMiguel Ojeda     ///
568808c999fSMiguel Ojeda     ///         generics.where_clause = input.parse()?;
569808c999fSMiguel Ojeda     ///         let content;
570808c999fSMiguel Ojeda     ///         let empty_brace_token = braced!(content in input);
571808c999fSMiguel Ojeda     ///
572808c999fSMiguel Ojeda     ///         Ok(MarkerTrait {
573808c999fSMiguel Ojeda     ///             trait_token,
574808c999fSMiguel Ojeda     ///             ident,
575808c999fSMiguel Ojeda     ///             generics,
576808c999fSMiguel Ojeda     ///             colon_token,
577808c999fSMiguel Ojeda     ///             supertraits,
578808c999fSMiguel Ojeda     ///             brace_token: empty_brace_token,
579808c999fSMiguel Ojeda     ///         })
580808c999fSMiguel Ojeda     ///     }
581808c999fSMiguel Ojeda     /// }
582808c999fSMiguel Ojeda     /// ```
peek<T: Peek>(&self, token: T) -> bool583808c999fSMiguel Ojeda     pub fn peek<T: Peek>(&self, token: T) -> bool {
584808c999fSMiguel Ojeda         let _ = token;
585808c999fSMiguel Ojeda         T::Token::peek(self.cursor())
586808c999fSMiguel Ojeda     }
587808c999fSMiguel Ojeda 
588808c999fSMiguel Ojeda     /// Looks at the second-next token in the parse stream.
589808c999fSMiguel Ojeda     ///
590808c999fSMiguel Ojeda     /// This is commonly useful as a way to implement contextual keywords.
591808c999fSMiguel Ojeda     ///
592808c999fSMiguel Ojeda     /// # Example
593808c999fSMiguel Ojeda     ///
594808c999fSMiguel Ojeda     /// This example needs to use `peek2` because the symbol `union` is not a
595808c999fSMiguel Ojeda     /// keyword in Rust. We can't use just `peek` and decide to parse a union if
596808c999fSMiguel Ojeda     /// the very next token is `union`, because someone is free to write a `mod
597808c999fSMiguel Ojeda     /// union` and a macro invocation that looks like `union::some_macro! { ...
598808c999fSMiguel Ojeda     /// }`. In other words `union` is a contextual keyword.
599808c999fSMiguel Ojeda     ///
600808c999fSMiguel Ojeda     /// ```
601808c999fSMiguel Ojeda     /// use syn::{Ident, ItemUnion, Macro, Result, Token};
602808c999fSMiguel Ojeda     /// use syn::parse::{Parse, ParseStream};
603808c999fSMiguel Ojeda     ///
604808c999fSMiguel Ojeda     /// // Parses either a union or a macro invocation.
605808c999fSMiguel Ojeda     /// enum UnionOrMacro {
606808c999fSMiguel Ojeda     ///     // union MaybeUninit<T> { uninit: (), value: T }
607808c999fSMiguel Ojeda     ///     Union(ItemUnion),
608808c999fSMiguel Ojeda     ///     // lazy_static! { ... }
609808c999fSMiguel Ojeda     ///     Macro(Macro),
610808c999fSMiguel Ojeda     /// }
611808c999fSMiguel Ojeda     ///
612808c999fSMiguel Ojeda     /// impl Parse for UnionOrMacro {
613808c999fSMiguel Ojeda     ///     fn parse(input: ParseStream) -> Result<Self> {
614808c999fSMiguel Ojeda     ///         if input.peek(Token![union]) && input.peek2(Ident) {
615808c999fSMiguel Ojeda     ///             input.parse().map(UnionOrMacro::Union)
616808c999fSMiguel Ojeda     ///         } else {
617808c999fSMiguel Ojeda     ///             input.parse().map(UnionOrMacro::Macro)
618808c999fSMiguel Ojeda     ///         }
619808c999fSMiguel Ojeda     ///     }
620808c999fSMiguel Ojeda     /// }
621808c999fSMiguel Ojeda     /// ```
peek2<T: Peek>(&self, token: T) -> bool622808c999fSMiguel Ojeda     pub fn peek2<T: Peek>(&self, token: T) -> bool {
623808c999fSMiguel Ojeda         fn peek2(buffer: &ParseBuffer, peek: fn(Cursor) -> bool) -> bool {
624808c999fSMiguel Ojeda             buffer.cursor().skip().map_or(false, peek)
625808c999fSMiguel Ojeda         }
626808c999fSMiguel Ojeda 
627808c999fSMiguel Ojeda         let _ = token;
628808c999fSMiguel Ojeda         peek2(self, T::Token::peek)
629808c999fSMiguel Ojeda     }
630808c999fSMiguel Ojeda 
631808c999fSMiguel Ojeda     /// Looks at the third-next token in the parse stream.
peek3<T: Peek>(&self, token: T) -> bool632808c999fSMiguel Ojeda     pub fn peek3<T: Peek>(&self, token: T) -> bool {
633808c999fSMiguel Ojeda         fn peek3(buffer: &ParseBuffer, peek: fn(Cursor) -> bool) -> bool {
634808c999fSMiguel Ojeda             buffer
635808c999fSMiguel Ojeda                 .cursor()
636808c999fSMiguel Ojeda                 .skip()
637808c999fSMiguel Ojeda                 .and_then(Cursor::skip)
638808c999fSMiguel Ojeda                 .map_or(false, peek)
639808c999fSMiguel Ojeda         }
640808c999fSMiguel Ojeda 
641808c999fSMiguel Ojeda         let _ = token;
642808c999fSMiguel Ojeda         peek3(self, T::Token::peek)
643808c999fSMiguel Ojeda     }
644808c999fSMiguel Ojeda 
645808c999fSMiguel Ojeda     /// Parses zero or more occurrences of `T` separated by punctuation of type
646808c999fSMiguel Ojeda     /// `P`, with optional trailing punctuation.
647808c999fSMiguel Ojeda     ///
648808c999fSMiguel Ojeda     /// Parsing continues until the end of this parse stream. The entire content
649808c999fSMiguel Ojeda     /// of this parse stream must consist of `T` and `P`.
650808c999fSMiguel Ojeda     ///
651808c999fSMiguel Ojeda     /// # Example
652808c999fSMiguel Ojeda     ///
653808c999fSMiguel Ojeda     /// ```
654808c999fSMiguel Ojeda     /// # use quote::quote;
655808c999fSMiguel Ojeda     /// #
656808c999fSMiguel Ojeda     /// use syn::{parenthesized, token, Ident, Result, Token, Type};
657808c999fSMiguel Ojeda     /// use syn::parse::{Parse, ParseStream};
658808c999fSMiguel Ojeda     /// use syn::punctuated::Punctuated;
659808c999fSMiguel Ojeda     ///
660808c999fSMiguel Ojeda     /// // Parse a simplified tuple struct syntax like:
661808c999fSMiguel Ojeda     /// //
662808c999fSMiguel Ojeda     /// //     struct S(A, B);
663808c999fSMiguel Ojeda     /// struct TupleStruct {
664808c999fSMiguel Ojeda     ///     struct_token: Token![struct],
665808c999fSMiguel Ojeda     ///     ident: Ident,
666808c999fSMiguel Ojeda     ///     paren_token: token::Paren,
667808c999fSMiguel Ojeda     ///     fields: Punctuated<Type, Token![,]>,
668808c999fSMiguel Ojeda     ///     semi_token: Token![;],
669808c999fSMiguel Ojeda     /// }
670808c999fSMiguel Ojeda     ///
671808c999fSMiguel Ojeda     /// impl Parse for TupleStruct {
672808c999fSMiguel Ojeda     ///     fn parse(input: ParseStream) -> Result<Self> {
673808c999fSMiguel Ojeda     ///         let content;
674808c999fSMiguel Ojeda     ///         Ok(TupleStruct {
675808c999fSMiguel Ojeda     ///             struct_token: input.parse()?,
676808c999fSMiguel Ojeda     ///             ident: input.parse()?,
677808c999fSMiguel Ojeda     ///             paren_token: parenthesized!(content in input),
678808c999fSMiguel Ojeda     ///             fields: content.parse_terminated(Type::parse, Token![,])?,
679808c999fSMiguel Ojeda     ///             semi_token: input.parse()?,
680808c999fSMiguel Ojeda     ///         })
681808c999fSMiguel Ojeda     ///     }
682808c999fSMiguel Ojeda     /// }
683808c999fSMiguel Ojeda     /// #
684808c999fSMiguel Ojeda     /// # let input = quote! {
685808c999fSMiguel Ojeda     /// #     struct S(A, B);
686808c999fSMiguel Ojeda     /// # };
687808c999fSMiguel Ojeda     /// # syn::parse2::<TupleStruct>(input).unwrap();
688808c999fSMiguel Ojeda     /// ```
689808c999fSMiguel Ojeda     ///
690808c999fSMiguel Ojeda     /// # See also
691808c999fSMiguel Ojeda     ///
692808c999fSMiguel Ojeda     /// If your separator is anything more complicated than an invocation of the
693808c999fSMiguel Ojeda     /// `Token!` macro, this method won't be applicable and you can instead
694808c999fSMiguel Ojeda     /// directly use `Punctuated`'s parser functions: [`parse_terminated`],
695808c999fSMiguel Ojeda     /// [`parse_separated_nonempty`] etc.
696808c999fSMiguel Ojeda     ///
697808c999fSMiguel Ojeda     /// [`parse_terminated`]: Punctuated::parse_terminated
698808c999fSMiguel Ojeda     /// [`parse_separated_nonempty`]: Punctuated::parse_separated_nonempty
699808c999fSMiguel Ojeda     ///
700808c999fSMiguel Ojeda     /// ```
701808c999fSMiguel Ojeda     /// use syn::{custom_keyword, Expr, Result, Token};
702808c999fSMiguel Ojeda     /// use syn::parse::{Parse, ParseStream};
703808c999fSMiguel Ojeda     /// use syn::punctuated::Punctuated;
704808c999fSMiguel Ojeda     ///
705808c999fSMiguel Ojeda     /// mod kw {
706808c999fSMiguel Ojeda     ///     syn::custom_keyword!(fin);
707808c999fSMiguel Ojeda     /// }
708808c999fSMiguel Ojeda     ///
709808c999fSMiguel Ojeda     /// struct Fin(kw::fin, Token![;]);
710808c999fSMiguel Ojeda     ///
711808c999fSMiguel Ojeda     /// impl Parse for Fin {
712808c999fSMiguel Ojeda     ///     fn parse(input: ParseStream) -> Result<Self> {
713808c999fSMiguel Ojeda     ///         Ok(Self(input.parse()?, input.parse()?))
714808c999fSMiguel Ojeda     ///     }
715808c999fSMiguel Ojeda     /// }
716808c999fSMiguel Ojeda     ///
717808c999fSMiguel Ojeda     /// struct Thing {
718808c999fSMiguel Ojeda     ///     steps: Punctuated<Expr, Fin>,
719808c999fSMiguel Ojeda     /// }
720808c999fSMiguel Ojeda     ///
721808c999fSMiguel Ojeda     /// impl Parse for Thing {
722808c999fSMiguel Ojeda     ///     fn parse(input: ParseStream) -> Result<Self> {
723808c999fSMiguel Ojeda     /// # if true {
724808c999fSMiguel Ojeda     ///         Ok(Thing {
725808c999fSMiguel Ojeda     ///             steps: Punctuated::parse_terminated(input)?,
726808c999fSMiguel Ojeda     ///         })
727808c999fSMiguel Ojeda     /// # } else {
728808c999fSMiguel Ojeda     ///         // or equivalently, this means the same thing:
729808c999fSMiguel Ojeda     /// #       Ok(Thing {
730808c999fSMiguel Ojeda     ///             steps: input.call(Punctuated::parse_terminated)?,
731808c999fSMiguel Ojeda     /// #       })
732808c999fSMiguel Ojeda     /// # }
733808c999fSMiguel Ojeda     ///     }
734808c999fSMiguel Ojeda     /// }
735808c999fSMiguel Ojeda     /// ```
parse_terminated<T, P>( &'a self, parser: fn(ParseStream<'a>) -> Result<T>, separator: P, ) -> Result<Punctuated<T, P::Token>> where P: Peek, P::Token: Parse,736808c999fSMiguel Ojeda     pub fn parse_terminated<T, P>(
737808c999fSMiguel Ojeda         &'a self,
738808c999fSMiguel Ojeda         parser: fn(ParseStream<'a>) -> Result<T>,
739808c999fSMiguel Ojeda         separator: P,
740808c999fSMiguel Ojeda     ) -> Result<Punctuated<T, P::Token>>
741808c999fSMiguel Ojeda     where
742808c999fSMiguel Ojeda         P: Peek,
743808c999fSMiguel Ojeda         P::Token: Parse,
744808c999fSMiguel Ojeda     {
745808c999fSMiguel Ojeda         let _ = separator;
746808c999fSMiguel Ojeda         Punctuated::parse_terminated_with(self, parser)
747808c999fSMiguel Ojeda     }
748808c999fSMiguel Ojeda 
749808c999fSMiguel Ojeda     /// Returns whether there are no more tokens remaining to be parsed from
750808c999fSMiguel Ojeda     /// this stream.
751808c999fSMiguel Ojeda     ///
752808c999fSMiguel Ojeda     /// This method returns true upon reaching the end of the content within a
753808c999fSMiguel Ojeda     /// set of delimiters, as well as at the end of the tokens provided to the
754808c999fSMiguel Ojeda     /// outermost parsing entry point.
755808c999fSMiguel Ojeda     ///
756808c999fSMiguel Ojeda     /// This is equivalent to
757808c999fSMiguel Ojeda     /// <code>.<a href="#method.peek">peek</a>(<a href="struct.End.html">syn::parse::End</a>)</code>.
758808c999fSMiguel Ojeda     /// Use `.peek2(End)` or `.peek3(End)` to look for the end of a parse stream
759808c999fSMiguel Ojeda     /// further ahead than the current position.
760808c999fSMiguel Ojeda     ///
761808c999fSMiguel Ojeda     /// # Example
762808c999fSMiguel Ojeda     ///
763808c999fSMiguel Ojeda     /// ```
764808c999fSMiguel Ojeda     /// use syn::{braced, token, Ident, Item, Result, Token};
765808c999fSMiguel Ojeda     /// use syn::parse::{Parse, ParseStream};
766808c999fSMiguel Ojeda     ///
767808c999fSMiguel Ojeda     /// // Parses a Rust `mod m { ... }` containing zero or more items.
768808c999fSMiguel Ojeda     /// struct Mod {
769808c999fSMiguel Ojeda     ///     mod_token: Token![mod],
770808c999fSMiguel Ojeda     ///     name: Ident,
771808c999fSMiguel Ojeda     ///     brace_token: token::Brace,
772808c999fSMiguel Ojeda     ///     items: Vec<Item>,
773808c999fSMiguel Ojeda     /// }
774808c999fSMiguel Ojeda     ///
775808c999fSMiguel Ojeda     /// impl Parse for Mod {
776808c999fSMiguel Ojeda     ///     fn parse(input: ParseStream) -> Result<Self> {
777808c999fSMiguel Ojeda     ///         let content;
778808c999fSMiguel Ojeda     ///         Ok(Mod {
779808c999fSMiguel Ojeda     ///             mod_token: input.parse()?,
780808c999fSMiguel Ojeda     ///             name: input.parse()?,
781808c999fSMiguel Ojeda     ///             brace_token: braced!(content in input),
782808c999fSMiguel Ojeda     ///             items: {
783808c999fSMiguel Ojeda     ///                 let mut items = Vec::new();
784808c999fSMiguel Ojeda     ///                 while !content.is_empty() {
785808c999fSMiguel Ojeda     ///                     items.push(content.parse()?);
786808c999fSMiguel Ojeda     ///                 }
787808c999fSMiguel Ojeda     ///                 items
788808c999fSMiguel Ojeda     ///             },
789808c999fSMiguel Ojeda     ///         })
790808c999fSMiguel Ojeda     ///     }
791808c999fSMiguel Ojeda     /// }
792808c999fSMiguel Ojeda     /// ```
is_empty(&self) -> bool793808c999fSMiguel Ojeda     pub fn is_empty(&self) -> bool {
794808c999fSMiguel Ojeda         self.cursor().eof()
795808c999fSMiguel Ojeda     }
796808c999fSMiguel Ojeda 
797808c999fSMiguel Ojeda     /// Constructs a helper for peeking at the next token in this stream and
798808c999fSMiguel Ojeda     /// building an error message if it is not one of a set of expected tokens.
799808c999fSMiguel Ojeda     ///
800808c999fSMiguel Ojeda     /// # Example
801808c999fSMiguel Ojeda     ///
802808c999fSMiguel Ojeda     /// ```
803808c999fSMiguel Ojeda     /// use syn::{ConstParam, Ident, Lifetime, LifetimeParam, Result, Token, TypeParam};
804808c999fSMiguel Ojeda     /// use syn::parse::{Parse, ParseStream};
805808c999fSMiguel Ojeda     ///
806808c999fSMiguel Ojeda     /// // A generic parameter, a single one of the comma-separated elements inside
807808c999fSMiguel Ojeda     /// // angle brackets in:
808808c999fSMiguel Ojeda     /// //
809808c999fSMiguel Ojeda     /// //     fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
810808c999fSMiguel Ojeda     /// //
811808c999fSMiguel Ojeda     /// // On invalid input, lookahead gives us a reasonable error message.
812808c999fSMiguel Ojeda     /// //
813808c999fSMiguel Ojeda     /// //     error: expected one of: identifier, lifetime, `const`
814808c999fSMiguel Ojeda     /// //       |
815808c999fSMiguel Ojeda     /// //     5 |     fn f<!Sized>() {}
816808c999fSMiguel Ojeda     /// //       |          ^
817808c999fSMiguel Ojeda     /// enum GenericParam {
818808c999fSMiguel Ojeda     ///     Type(TypeParam),
819808c999fSMiguel Ojeda     ///     Lifetime(LifetimeParam),
820808c999fSMiguel Ojeda     ///     Const(ConstParam),
821808c999fSMiguel Ojeda     /// }
822808c999fSMiguel Ojeda     ///
823808c999fSMiguel Ojeda     /// impl Parse for GenericParam {
824808c999fSMiguel Ojeda     ///     fn parse(input: ParseStream) -> Result<Self> {
825808c999fSMiguel Ojeda     ///         let lookahead = input.lookahead1();
826808c999fSMiguel Ojeda     ///         if lookahead.peek(Ident) {
827808c999fSMiguel Ojeda     ///             input.parse().map(GenericParam::Type)
828808c999fSMiguel Ojeda     ///         } else if lookahead.peek(Lifetime) {
829808c999fSMiguel Ojeda     ///             input.parse().map(GenericParam::Lifetime)
830808c999fSMiguel Ojeda     ///         } else if lookahead.peek(Token![const]) {
831808c999fSMiguel Ojeda     ///             input.parse().map(GenericParam::Const)
832808c999fSMiguel Ojeda     ///         } else {
833808c999fSMiguel Ojeda     ///             Err(lookahead.error())
834808c999fSMiguel Ojeda     ///         }
835808c999fSMiguel Ojeda     ///     }
836808c999fSMiguel Ojeda     /// }
837808c999fSMiguel Ojeda     /// ```
lookahead1(&self) -> Lookahead1<'a>838808c999fSMiguel Ojeda     pub fn lookahead1(&self) -> Lookahead1<'a> {
839808c999fSMiguel Ojeda         lookahead::new(self.scope, self.cursor())
840808c999fSMiguel Ojeda     }
841808c999fSMiguel Ojeda 
842808c999fSMiguel Ojeda     /// Forks a parse stream so that parsing tokens out of either the original
843808c999fSMiguel Ojeda     /// or the fork does not advance the position of the other.
844808c999fSMiguel Ojeda     ///
845808c999fSMiguel Ojeda     /// # Performance
846808c999fSMiguel Ojeda     ///
847808c999fSMiguel Ojeda     /// Forking a parse stream is a cheap fixed amount of work and does not
848808c999fSMiguel Ojeda     /// involve copying token buffers. Where you might hit performance problems
849808c999fSMiguel Ojeda     /// is if your macro ends up parsing a large amount of content more than
850808c999fSMiguel Ojeda     /// once.
851808c999fSMiguel Ojeda     ///
852808c999fSMiguel Ojeda     /// ```
853808c999fSMiguel Ojeda     /// # use syn::{Expr, Result};
854808c999fSMiguel Ojeda     /// # use syn::parse::ParseStream;
855808c999fSMiguel Ojeda     /// #
856808c999fSMiguel Ojeda     /// # fn bad(input: ParseStream) -> Result<Expr> {
857808c999fSMiguel Ojeda     /// // Do not do this.
858808c999fSMiguel Ojeda     /// if input.fork().parse::<Expr>().is_ok() {
859808c999fSMiguel Ojeda     ///     return input.parse::<Expr>();
860808c999fSMiguel Ojeda     /// }
861808c999fSMiguel Ojeda     /// # unimplemented!()
862808c999fSMiguel Ojeda     /// # }
863808c999fSMiguel Ojeda     /// ```
864808c999fSMiguel Ojeda     ///
865808c999fSMiguel Ojeda     /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
866808c999fSMiguel Ojeda     /// parse stream. Only use a fork when the amount of work performed against
867808c999fSMiguel Ojeda     /// the fork is small and bounded.
868808c999fSMiguel Ojeda     ///
869808c999fSMiguel Ojeda     /// When complex speculative parsing against the forked stream is
870808c999fSMiguel Ojeda     /// unavoidable, use [`parse::discouraged::Speculative`] to advance the
871808c999fSMiguel Ojeda     /// original stream once the fork's parse is determined to have been
872808c999fSMiguel Ojeda     /// successful.
873808c999fSMiguel Ojeda     ///
874808c999fSMiguel Ojeda     /// For a lower level way to perform speculative parsing at the token level,
875808c999fSMiguel Ojeda     /// consider using [`ParseStream::step`] instead.
876808c999fSMiguel Ojeda     ///
877808c999fSMiguel Ojeda     /// [`parse::discouraged::Speculative`]: discouraged::Speculative
878808c999fSMiguel Ojeda     /// [`ParseStream::step`]: ParseBuffer::step
879808c999fSMiguel Ojeda     ///
880808c999fSMiguel Ojeda     /// # Example
881808c999fSMiguel Ojeda     ///
882808c999fSMiguel Ojeda     /// The parse implementation shown here parses possibly restricted `pub`
883808c999fSMiguel Ojeda     /// visibilities.
884808c999fSMiguel Ojeda     ///
885808c999fSMiguel Ojeda     /// - `pub`
886808c999fSMiguel Ojeda     /// - `pub(crate)`
887808c999fSMiguel Ojeda     /// - `pub(self)`
888808c999fSMiguel Ojeda     /// - `pub(super)`
889808c999fSMiguel Ojeda     /// - `pub(in some::path)`
890808c999fSMiguel Ojeda     ///
891808c999fSMiguel Ojeda     /// To handle the case of visibilities inside of tuple structs, the parser
892808c999fSMiguel Ojeda     /// needs to distinguish parentheses that specify visibility restrictions
893808c999fSMiguel Ojeda     /// from parentheses that form part of a tuple type.
894808c999fSMiguel Ojeda     ///
895808c999fSMiguel Ojeda     /// ```
896808c999fSMiguel Ojeda     /// # struct A;
897808c999fSMiguel Ojeda     /// # struct B;
898808c999fSMiguel Ojeda     /// # struct C;
899808c999fSMiguel Ojeda     /// #
900808c999fSMiguel Ojeda     /// struct S(pub(crate) A, pub (B, C));
901808c999fSMiguel Ojeda     /// ```
902808c999fSMiguel Ojeda     ///
903808c999fSMiguel Ojeda     /// In this example input the first tuple struct element of `S` has
904808c999fSMiguel Ojeda     /// `pub(crate)` visibility while the second tuple struct element has `pub`
905808c999fSMiguel Ojeda     /// visibility; the parentheses around `(B, C)` are part of the type rather
906808c999fSMiguel Ojeda     /// than part of a visibility restriction.
907808c999fSMiguel Ojeda     ///
908808c999fSMiguel Ojeda     /// The parser uses a forked parse stream to check the first token inside of
909808c999fSMiguel Ojeda     /// parentheses after the `pub` keyword. This is a small bounded amount of
910808c999fSMiguel Ojeda     /// work performed against the forked parse stream.
911808c999fSMiguel Ojeda     ///
912808c999fSMiguel Ojeda     /// ```
913808c999fSMiguel Ojeda     /// use syn::{parenthesized, token, Ident, Path, Result, Token};
914808c999fSMiguel Ojeda     /// use syn::ext::IdentExt;
915808c999fSMiguel Ojeda     /// use syn::parse::{Parse, ParseStream};
916808c999fSMiguel Ojeda     ///
917808c999fSMiguel Ojeda     /// struct PubVisibility {
918808c999fSMiguel Ojeda     ///     pub_token: Token![pub],
919808c999fSMiguel Ojeda     ///     restricted: Option<Restricted>,
920808c999fSMiguel Ojeda     /// }
921808c999fSMiguel Ojeda     ///
922808c999fSMiguel Ojeda     /// struct Restricted {
923808c999fSMiguel Ojeda     ///     paren_token: token::Paren,
924808c999fSMiguel Ojeda     ///     in_token: Option<Token![in]>,
925808c999fSMiguel Ojeda     ///     path: Path,
926808c999fSMiguel Ojeda     /// }
927808c999fSMiguel Ojeda     ///
928808c999fSMiguel Ojeda     /// impl Parse for PubVisibility {
929808c999fSMiguel Ojeda     ///     fn parse(input: ParseStream) -> Result<Self> {
930808c999fSMiguel Ojeda     ///         let pub_token: Token![pub] = input.parse()?;
931808c999fSMiguel Ojeda     ///
932808c999fSMiguel Ojeda     ///         if input.peek(token::Paren) {
933808c999fSMiguel Ojeda     ///             let ahead = input.fork();
934808c999fSMiguel Ojeda     ///             let mut content;
935808c999fSMiguel Ojeda     ///             parenthesized!(content in ahead);
936808c999fSMiguel Ojeda     ///
937808c999fSMiguel Ojeda     ///             if content.peek(Token![crate])
938808c999fSMiguel Ojeda     ///                 || content.peek(Token![self])
939808c999fSMiguel Ojeda     ///                 || content.peek(Token![super])
940808c999fSMiguel Ojeda     ///             {
941808c999fSMiguel Ojeda     ///                 return Ok(PubVisibility {
942808c999fSMiguel Ojeda     ///                     pub_token,
943808c999fSMiguel Ojeda     ///                     restricted: Some(Restricted {
944808c999fSMiguel Ojeda     ///                         paren_token: parenthesized!(content in input),
945808c999fSMiguel Ojeda     ///                         in_token: None,
946808c999fSMiguel Ojeda     ///                         path: Path::from(content.call(Ident::parse_any)?),
947808c999fSMiguel Ojeda     ///                     }),
948808c999fSMiguel Ojeda     ///                 });
949808c999fSMiguel Ojeda     ///             } else if content.peek(Token![in]) {
950808c999fSMiguel Ojeda     ///                 return Ok(PubVisibility {
951808c999fSMiguel Ojeda     ///                     pub_token,
952808c999fSMiguel Ojeda     ///                     restricted: Some(Restricted {
953808c999fSMiguel Ojeda     ///                         paren_token: parenthesized!(content in input),
954808c999fSMiguel Ojeda     ///                         in_token: Some(content.parse()?),
955808c999fSMiguel Ojeda     ///                         path: content.call(Path::parse_mod_style)?,
956808c999fSMiguel Ojeda     ///                     }),
957808c999fSMiguel Ojeda     ///                 });
958808c999fSMiguel Ojeda     ///             }
959808c999fSMiguel Ojeda     ///         }
960808c999fSMiguel Ojeda     ///
961808c999fSMiguel Ojeda     ///         Ok(PubVisibility {
962808c999fSMiguel Ojeda     ///             pub_token,
963808c999fSMiguel Ojeda     ///             restricted: None,
964808c999fSMiguel Ojeda     ///         })
965808c999fSMiguel Ojeda     ///     }
966808c999fSMiguel Ojeda     /// }
967808c999fSMiguel Ojeda     /// ```
fork(&self) -> Self968808c999fSMiguel Ojeda     pub fn fork(&self) -> Self {
969808c999fSMiguel Ojeda         ParseBuffer {
970808c999fSMiguel Ojeda             scope: self.scope,
971808c999fSMiguel Ojeda             cell: self.cell.clone(),
972808c999fSMiguel Ojeda             marker: PhantomData,
973808c999fSMiguel Ojeda             // Not the parent's unexpected. Nothing cares whether the clone
974808c999fSMiguel Ojeda             // parses all the way unless we `advance_to`.
975808c999fSMiguel Ojeda             unexpected: Cell::new(Some(Rc::new(Cell::new(Unexpected::None)))),
976808c999fSMiguel Ojeda         }
977808c999fSMiguel Ojeda     }
978808c999fSMiguel Ojeda 
979808c999fSMiguel Ojeda     /// Triggers an error at the current position of the parse stream.
980808c999fSMiguel Ojeda     ///
981808c999fSMiguel Ojeda     /// # Example
982808c999fSMiguel Ojeda     ///
983808c999fSMiguel Ojeda     /// ```
984808c999fSMiguel Ojeda     /// use syn::{Expr, Result, Token};
985808c999fSMiguel Ojeda     /// use syn::parse::{Parse, ParseStream};
986808c999fSMiguel Ojeda     ///
987808c999fSMiguel Ojeda     /// // Some kind of loop: `while` or `for` or `loop`.
988808c999fSMiguel Ojeda     /// struct Loop {
989808c999fSMiguel Ojeda     ///     expr: Expr,
990808c999fSMiguel Ojeda     /// }
991808c999fSMiguel Ojeda     ///
992808c999fSMiguel Ojeda     /// impl Parse for Loop {
993808c999fSMiguel Ojeda     ///     fn parse(input: ParseStream) -> Result<Self> {
994808c999fSMiguel Ojeda     ///         if input.peek(Token![while])
995808c999fSMiguel Ojeda     ///             || input.peek(Token![for])
996808c999fSMiguel Ojeda     ///             || input.peek(Token![loop])
997808c999fSMiguel Ojeda     ///         {
998808c999fSMiguel Ojeda     ///             Ok(Loop {
999808c999fSMiguel Ojeda     ///                 expr: input.parse()?,
1000808c999fSMiguel Ojeda     ///             })
1001808c999fSMiguel Ojeda     ///         } else {
1002808c999fSMiguel Ojeda     ///             Err(input.error("expected some kind of loop"))
1003808c999fSMiguel Ojeda     ///         }
1004808c999fSMiguel Ojeda     ///     }
1005808c999fSMiguel Ojeda     /// }
1006808c999fSMiguel Ojeda     /// ```
error<T: Display>(&self, message: T) -> Error1007808c999fSMiguel Ojeda     pub fn error<T: Display>(&self, message: T) -> Error {
1008808c999fSMiguel Ojeda         error::new_at(self.scope, self.cursor(), message)
1009808c999fSMiguel Ojeda     }
1010808c999fSMiguel Ojeda 
1011808c999fSMiguel Ojeda     /// Speculatively parses tokens from this parse stream, advancing the
1012808c999fSMiguel Ojeda     /// position of this stream only if parsing succeeds.
1013808c999fSMiguel Ojeda     ///
1014808c999fSMiguel Ojeda     /// This is a powerful low-level API used for defining the `Parse` impls of
1015808c999fSMiguel Ojeda     /// the basic built-in token types. It is not something that will be used
1016808c999fSMiguel Ojeda     /// widely outside of the Syn codebase.
1017808c999fSMiguel Ojeda     ///
1018808c999fSMiguel Ojeda     /// # Example
1019808c999fSMiguel Ojeda     ///
1020808c999fSMiguel Ojeda     /// ```
1021808c999fSMiguel Ojeda     /// use proc_macro2::TokenTree;
1022808c999fSMiguel Ojeda     /// use syn::Result;
1023808c999fSMiguel Ojeda     /// use syn::parse::ParseStream;
1024808c999fSMiguel Ojeda     ///
1025808c999fSMiguel Ojeda     /// // This function advances the stream past the next occurrence of `@`. If
1026808c999fSMiguel Ojeda     /// // no `@` is present in the stream, the stream position is unchanged and
1027808c999fSMiguel Ojeda     /// // an error is returned.
1028808c999fSMiguel Ojeda     /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
1029808c999fSMiguel Ojeda     ///     input.step(|cursor| {
1030808c999fSMiguel Ojeda     ///         let mut rest = *cursor;
1031808c999fSMiguel Ojeda     ///         while let Some((tt, next)) = rest.token_tree() {
1032808c999fSMiguel Ojeda     ///             match &tt {
1033808c999fSMiguel Ojeda     ///                 TokenTree::Punct(punct) if punct.as_char() == '@' => {
1034808c999fSMiguel Ojeda     ///                     return Ok(((), next));
1035808c999fSMiguel Ojeda     ///                 }
1036808c999fSMiguel Ojeda     ///                 _ => rest = next,
1037808c999fSMiguel Ojeda     ///             }
1038808c999fSMiguel Ojeda     ///         }
1039808c999fSMiguel Ojeda     ///         Err(cursor.error("no `@` was found after this point"))
1040808c999fSMiguel Ojeda     ///     })
1041808c999fSMiguel Ojeda     /// }
1042808c999fSMiguel Ojeda     /// #
1043808c999fSMiguel Ojeda     /// # fn remainder_after_skipping_past_next_at(
1044808c999fSMiguel Ojeda     /// #     input: ParseStream,
1045808c999fSMiguel Ojeda     /// # ) -> Result<proc_macro2::TokenStream> {
1046808c999fSMiguel Ojeda     /// #     skip_past_next_at(input)?;
1047808c999fSMiguel Ojeda     /// #     input.parse()
1048808c999fSMiguel Ojeda     /// # }
1049808c999fSMiguel Ojeda     /// #
1050808c999fSMiguel Ojeda     /// # use syn::parse::Parser;
1051808c999fSMiguel Ojeda     /// # let remainder = remainder_after_skipping_past_next_at
1052808c999fSMiguel Ojeda     /// #     .parse_str("a @ b c")
1053808c999fSMiguel Ojeda     /// #     .unwrap();
1054808c999fSMiguel Ojeda     /// # assert_eq!(remainder.to_string(), "b c");
1055808c999fSMiguel Ojeda     /// ```
step<F, R>(&self, function: F) -> Result<R> where F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,1056808c999fSMiguel Ojeda     pub fn step<F, R>(&self, function: F) -> Result<R>
1057808c999fSMiguel Ojeda     where
1058808c999fSMiguel Ojeda         F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
1059808c999fSMiguel Ojeda     {
1060808c999fSMiguel Ojeda         // Since the user's function is required to work for any 'c, we know
1061808c999fSMiguel Ojeda         // that the Cursor<'c> they return is either derived from the input
1062808c999fSMiguel Ojeda         // StepCursor<'c, 'a> or from a Cursor<'static>.
1063808c999fSMiguel Ojeda         //
1064808c999fSMiguel Ojeda         // It would not be legal to write this function without the invariant
1065808c999fSMiguel Ojeda         // lifetime 'c in StepCursor<'c, 'a>. If this function were written only
1066808c999fSMiguel Ojeda         // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to
1067808c999fSMiguel Ojeda         // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke
1068808c999fSMiguel Ojeda         // `step` on their ParseBuffer<'short> with a closure that returns
1069808c999fSMiguel Ojeda         // Cursor<'short>, and we would wrongly write that Cursor<'short> into
1070808c999fSMiguel Ojeda         // the Cell intended to hold Cursor<'a>.
1071808c999fSMiguel Ojeda         //
1072808c999fSMiguel Ojeda         // In some cases it may be necessary for R to contain a Cursor<'a>.
1073808c999fSMiguel Ojeda         // Within Syn we solve this using `advance_step_cursor` which uses the
1074808c999fSMiguel Ojeda         // existence of a StepCursor<'c, 'a> as proof that it is safe to cast
1075808c999fSMiguel Ojeda         // from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it would be
1076808c999fSMiguel Ojeda         // safe to expose that API as a method on StepCursor.
1077808c999fSMiguel Ojeda         let (node, rest) = function(StepCursor {
1078808c999fSMiguel Ojeda             scope: self.scope,
1079808c999fSMiguel Ojeda             cursor: self.cell.get(),
1080808c999fSMiguel Ojeda             marker: PhantomData,
1081808c999fSMiguel Ojeda         })?;
1082808c999fSMiguel Ojeda         self.cell.set(rest);
1083808c999fSMiguel Ojeda         Ok(node)
1084808c999fSMiguel Ojeda     }
1085808c999fSMiguel Ojeda 
1086808c999fSMiguel Ojeda     /// Returns the `Span` of the next token in the parse stream, or
1087808c999fSMiguel Ojeda     /// `Span::call_site()` if this parse stream has completely exhausted its
1088808c999fSMiguel Ojeda     /// input `TokenStream`.
span(&self) -> Span1089808c999fSMiguel Ojeda     pub fn span(&self) -> Span {
1090808c999fSMiguel Ojeda         let cursor = self.cursor();
1091808c999fSMiguel Ojeda         if cursor.eof() {
1092808c999fSMiguel Ojeda             self.scope
1093808c999fSMiguel Ojeda         } else {
1094808c999fSMiguel Ojeda             crate::buffer::open_span_of_group(cursor)
1095808c999fSMiguel Ojeda         }
1096808c999fSMiguel Ojeda     }
1097808c999fSMiguel Ojeda 
1098808c999fSMiguel Ojeda     /// Provides low-level access to the token representation underlying this
1099808c999fSMiguel Ojeda     /// parse stream.
1100808c999fSMiguel Ojeda     ///
1101808c999fSMiguel Ojeda     /// Cursors are immutable so no operations you perform against the cursor
1102808c999fSMiguel Ojeda     /// will affect the state of this parse stream.
1103808c999fSMiguel Ojeda     ///
1104808c999fSMiguel Ojeda     /// # Example
1105808c999fSMiguel Ojeda     ///
1106808c999fSMiguel Ojeda     /// ```
1107808c999fSMiguel Ojeda     /// use proc_macro2::TokenStream;
1108808c999fSMiguel Ojeda     /// use syn::buffer::Cursor;
1109808c999fSMiguel Ojeda     /// use syn::parse::{ParseStream, Result};
1110808c999fSMiguel Ojeda     ///
1111808c999fSMiguel Ojeda     /// // Run a parser that returns T, but get its output as TokenStream instead of T.
1112808c999fSMiguel Ojeda     /// // This works without T needing to implement ToTokens.
1113808c999fSMiguel Ojeda     /// fn recognize_token_stream<T>(
1114808c999fSMiguel Ojeda     ///     recognizer: fn(ParseStream) -> Result<T>,
1115808c999fSMiguel Ojeda     /// ) -> impl Fn(ParseStream) -> Result<TokenStream> {
1116808c999fSMiguel Ojeda     ///     move |input| {
1117808c999fSMiguel Ojeda     ///         let begin = input.cursor();
1118808c999fSMiguel Ojeda     ///         recognizer(input)?;
1119808c999fSMiguel Ojeda     ///         let end = input.cursor();
1120808c999fSMiguel Ojeda     ///         Ok(tokens_between(begin, end))
1121808c999fSMiguel Ojeda     ///     }
1122808c999fSMiguel Ojeda     /// }
1123808c999fSMiguel Ojeda     ///
1124808c999fSMiguel Ojeda     /// // Collect tokens between two cursors as a TokenStream.
1125808c999fSMiguel Ojeda     /// fn tokens_between(begin: Cursor, end: Cursor) -> TokenStream {
1126808c999fSMiguel Ojeda     ///     assert!(begin <= end);
1127808c999fSMiguel Ojeda     ///
1128808c999fSMiguel Ojeda     ///     let mut cursor = begin;
1129808c999fSMiguel Ojeda     ///     let mut tokens = TokenStream::new();
1130808c999fSMiguel Ojeda     ///     while cursor < end {
1131808c999fSMiguel Ojeda     ///         let (token, next) = cursor.token_tree().unwrap();
1132808c999fSMiguel Ojeda     ///         tokens.extend(std::iter::once(token));
1133808c999fSMiguel Ojeda     ///         cursor = next;
1134808c999fSMiguel Ojeda     ///     }
1135808c999fSMiguel Ojeda     ///     tokens
1136808c999fSMiguel Ojeda     /// }
1137808c999fSMiguel Ojeda     ///
1138808c999fSMiguel Ojeda     /// fn main() {
1139808c999fSMiguel Ojeda     ///     use quote::quote;
1140808c999fSMiguel Ojeda     ///     use syn::parse::{Parse, Parser};
1141808c999fSMiguel Ojeda     ///     use syn::Token;
1142808c999fSMiguel Ojeda     ///
1143808c999fSMiguel Ojeda     ///     // Parse syn::Type as a TokenStream, surrounded by angle brackets.
1144808c999fSMiguel Ojeda     ///     fn example(input: ParseStream) -> Result<TokenStream> {
1145808c999fSMiguel Ojeda     ///         let _langle: Token![<] = input.parse()?;
1146808c999fSMiguel Ojeda     ///         let ty = recognize_token_stream(syn::Type::parse)(input)?;
1147808c999fSMiguel Ojeda     ///         let _rangle: Token![>] = input.parse()?;
1148808c999fSMiguel Ojeda     ///         Ok(ty)
1149808c999fSMiguel Ojeda     ///     }
1150808c999fSMiguel Ojeda     ///
1151808c999fSMiguel Ojeda     ///     let tokens = quote! { <fn() -> u8> };
1152808c999fSMiguel Ojeda     ///     println!("{}", example.parse2(tokens).unwrap());
1153808c999fSMiguel Ojeda     /// }
1154808c999fSMiguel Ojeda     /// ```
cursor(&self) -> Cursor<'a>1155808c999fSMiguel Ojeda     pub fn cursor(&self) -> Cursor<'a> {
1156808c999fSMiguel Ojeda         self.cell.get()
1157808c999fSMiguel Ojeda     }
1158808c999fSMiguel Ojeda 
check_unexpected(&self) -> Result<()>1159808c999fSMiguel Ojeda     fn check_unexpected(&self) -> Result<()> {
1160808c999fSMiguel Ojeda         match inner_unexpected(self).1 {
1161808c999fSMiguel Ojeda             Some((span, delimiter)) => Err(err_unexpected_token(span, delimiter)),
1162808c999fSMiguel Ojeda             None => Ok(()),
1163808c999fSMiguel Ojeda         }
1164808c999fSMiguel Ojeda     }
1165808c999fSMiguel Ojeda }
1166808c999fSMiguel Ojeda 
1167808c999fSMiguel Ojeda #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1168808c999fSMiguel Ojeda impl<T: Parse> Parse for Box<T> {
parse(input: ParseStream) -> Result<Self>1169808c999fSMiguel Ojeda     fn parse(input: ParseStream) -> Result<Self> {
1170808c999fSMiguel Ojeda         input.parse().map(Box::new)
1171808c999fSMiguel Ojeda     }
1172808c999fSMiguel Ojeda }
1173808c999fSMiguel Ojeda 
1174808c999fSMiguel Ojeda #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1175808c999fSMiguel Ojeda impl<T: Parse + Token> Parse for Option<T> {
parse(input: ParseStream) -> Result<Self>1176808c999fSMiguel Ojeda     fn parse(input: ParseStream) -> Result<Self> {
1177808c999fSMiguel Ojeda         if T::peek(input.cursor()) {
1178808c999fSMiguel Ojeda             Ok(Some(input.parse()?))
1179808c999fSMiguel Ojeda         } else {
1180808c999fSMiguel Ojeda             Ok(None)
1181808c999fSMiguel Ojeda         }
1182808c999fSMiguel Ojeda     }
1183808c999fSMiguel Ojeda }
1184808c999fSMiguel Ojeda 
1185808c999fSMiguel Ojeda #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1186808c999fSMiguel Ojeda impl Parse for TokenStream {
parse(input: ParseStream) -> Result<Self>1187808c999fSMiguel Ojeda     fn parse(input: ParseStream) -> Result<Self> {
1188808c999fSMiguel Ojeda         input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
1189808c999fSMiguel Ojeda     }
1190808c999fSMiguel Ojeda }
1191808c999fSMiguel Ojeda 
1192808c999fSMiguel Ojeda #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1193808c999fSMiguel Ojeda impl Parse for TokenTree {
parse(input: ParseStream) -> Result<Self>1194808c999fSMiguel Ojeda     fn parse(input: ParseStream) -> Result<Self> {
1195808c999fSMiguel Ojeda         input.step(|cursor| match cursor.token_tree() {
1196808c999fSMiguel Ojeda             Some((tt, rest)) => Ok((tt, rest)),
1197808c999fSMiguel Ojeda             None => Err(cursor.error("expected token tree")),
1198808c999fSMiguel Ojeda         })
1199808c999fSMiguel Ojeda     }
1200808c999fSMiguel Ojeda }
1201808c999fSMiguel Ojeda 
1202808c999fSMiguel Ojeda #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1203808c999fSMiguel Ojeda impl Parse for Group {
parse(input: ParseStream) -> Result<Self>1204808c999fSMiguel Ojeda     fn parse(input: ParseStream) -> Result<Self> {
1205808c999fSMiguel Ojeda         input.step(|cursor| {
1206808c999fSMiguel Ojeda             if let Some((group, rest)) = cursor.any_group_token() {
1207808c999fSMiguel Ojeda                 if group.delimiter() != Delimiter::None {
1208808c999fSMiguel Ojeda                     return Ok((group, rest));
1209808c999fSMiguel Ojeda                 }
1210808c999fSMiguel Ojeda             }
1211808c999fSMiguel Ojeda             Err(cursor.error("expected group token"))
1212808c999fSMiguel Ojeda         })
1213808c999fSMiguel Ojeda     }
1214808c999fSMiguel Ojeda }
1215808c999fSMiguel Ojeda 
1216808c999fSMiguel Ojeda #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1217808c999fSMiguel Ojeda impl Parse for Punct {
parse(input: ParseStream) -> Result<Self>1218808c999fSMiguel Ojeda     fn parse(input: ParseStream) -> Result<Self> {
1219808c999fSMiguel Ojeda         input.step(|cursor| match cursor.punct() {
1220808c999fSMiguel Ojeda             Some((punct, rest)) => Ok((punct, rest)),
1221808c999fSMiguel Ojeda             None => Err(cursor.error("expected punctuation token")),
1222808c999fSMiguel Ojeda         })
1223808c999fSMiguel Ojeda     }
1224808c999fSMiguel Ojeda }
1225808c999fSMiguel Ojeda 
1226808c999fSMiguel Ojeda #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1227808c999fSMiguel Ojeda impl Parse for Literal {
parse(input: ParseStream) -> Result<Self>1228808c999fSMiguel Ojeda     fn parse(input: ParseStream) -> Result<Self> {
1229808c999fSMiguel Ojeda         input.step(|cursor| match cursor.literal() {
1230808c999fSMiguel Ojeda             Some((literal, rest)) => Ok((literal, rest)),
1231808c999fSMiguel Ojeda             None => Err(cursor.error("expected literal token")),
1232808c999fSMiguel Ojeda         })
1233808c999fSMiguel Ojeda     }
1234808c999fSMiguel Ojeda }
1235808c999fSMiguel Ojeda 
1236808c999fSMiguel Ojeda /// Parser that can parse Rust tokens into a particular syntax tree node.
1237808c999fSMiguel Ojeda ///
1238808c999fSMiguel Ojeda /// Refer to the [module documentation] for details about parsing in Syn.
1239808c999fSMiguel Ojeda ///
1240808c999fSMiguel Ojeda /// [module documentation]: self
1241808c999fSMiguel Ojeda pub trait Parser: Sized {
1242808c999fSMiguel Ojeda     type Output;
1243808c999fSMiguel Ojeda 
1244808c999fSMiguel Ojeda     /// Parse a proc-macro2 token stream into the chosen syntax tree node.
1245808c999fSMiguel Ojeda     ///
1246808c999fSMiguel Ojeda     /// This function enforces that the input is fully parsed. If there are any
1247808c999fSMiguel Ojeda     /// unparsed tokens at the end of the stream, an error is returned.
parse2(self, tokens: TokenStream) -> Result<Self::Output>1248808c999fSMiguel Ojeda     fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
1249808c999fSMiguel Ojeda 
1250808c999fSMiguel Ojeda     /// Parse tokens of source code into the chosen syntax tree node.
1251808c999fSMiguel Ojeda     ///
1252808c999fSMiguel Ojeda     /// This function enforces that the input is fully parsed. If there are any
1253808c999fSMiguel Ojeda     /// unparsed tokens at the end of the stream, an error is returned.
1254808c999fSMiguel Ojeda     #[cfg(feature = "proc-macro")]
1255808c999fSMiguel Ojeda     #[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))]
parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output>1256808c999fSMiguel Ojeda     fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
1257808c999fSMiguel Ojeda         self.parse2(proc_macro2::TokenStream::from(tokens))
1258808c999fSMiguel Ojeda     }
1259808c999fSMiguel Ojeda 
1260808c999fSMiguel Ojeda     /// Parse a string of Rust code into the chosen syntax tree node.
1261808c999fSMiguel Ojeda     ///
1262808c999fSMiguel Ojeda     /// This function enforces that the input is fully parsed. If there are any
1263808c999fSMiguel Ojeda     /// unparsed tokens at the end of the string, an error is returned.
1264808c999fSMiguel Ojeda     ///
1265808c999fSMiguel Ojeda     /// # Hygiene
1266808c999fSMiguel Ojeda     ///
1267808c999fSMiguel Ojeda     /// Every span in the resulting syntax tree will be set to resolve at the
1268808c999fSMiguel Ojeda     /// macro call site.
parse_str(self, s: &str) -> Result<Self::Output>1269808c999fSMiguel Ojeda     fn parse_str(self, s: &str) -> Result<Self::Output> {
1270808c999fSMiguel Ojeda         self.parse2(proc_macro2::TokenStream::from_str(s)?)
1271808c999fSMiguel Ojeda     }
1272808c999fSMiguel Ojeda 
1273808c999fSMiguel Ojeda     // Not public API.
1274808c999fSMiguel Ojeda     #[doc(hidden)]
__parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output>1275808c999fSMiguel Ojeda     fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> {
1276808c999fSMiguel Ojeda         let _ = scope;
1277808c999fSMiguel Ojeda         self.parse2(tokens)
1278808c999fSMiguel Ojeda     }
1279808c999fSMiguel Ojeda }
1280808c999fSMiguel Ojeda 
tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer1281808c999fSMiguel Ojeda fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
1282808c999fSMiguel Ojeda     let scope = Span::call_site();
1283808c999fSMiguel Ojeda     let cursor = tokens.begin();
1284808c999fSMiguel Ojeda     let unexpected = Rc::new(Cell::new(Unexpected::None));
1285808c999fSMiguel Ojeda     new_parse_buffer(scope, cursor, unexpected)
1286808c999fSMiguel Ojeda }
1287808c999fSMiguel Ojeda 
1288808c999fSMiguel Ojeda impl<F, T> Parser for F
1289808c999fSMiguel Ojeda where
1290808c999fSMiguel Ojeda     F: FnOnce(ParseStream) -> Result<T>,
1291808c999fSMiguel Ojeda {
1292808c999fSMiguel Ojeda     type Output = T;
1293808c999fSMiguel Ojeda 
parse2(self, tokens: TokenStream) -> Result<T>1294808c999fSMiguel Ojeda     fn parse2(self, tokens: TokenStream) -> Result<T> {
1295808c999fSMiguel Ojeda         let buf = TokenBuffer::new2(tokens);
1296808c999fSMiguel Ojeda         let state = tokens_to_parse_buffer(&buf);
1297808c999fSMiguel Ojeda         let node = self(&state)?;
1298808c999fSMiguel Ojeda         state.check_unexpected()?;
1299808c999fSMiguel Ojeda         if let Some((unexpected_span, delimiter)) =
1300808c999fSMiguel Ojeda             span_of_unexpected_ignoring_nones(state.cursor())
1301808c999fSMiguel Ojeda         {
1302808c999fSMiguel Ojeda             Err(err_unexpected_token(unexpected_span, delimiter))
1303808c999fSMiguel Ojeda         } else {
1304808c999fSMiguel Ojeda             Ok(node)
1305808c999fSMiguel Ojeda         }
1306808c999fSMiguel Ojeda     }
1307808c999fSMiguel Ojeda 
__parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output>1308808c999fSMiguel Ojeda     fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> {
1309808c999fSMiguel Ojeda         let buf = TokenBuffer::new2(tokens);
1310808c999fSMiguel Ojeda         let cursor = buf.begin();
1311808c999fSMiguel Ojeda         let unexpected = Rc::new(Cell::new(Unexpected::None));
1312808c999fSMiguel Ojeda         let state = new_parse_buffer(scope, cursor, unexpected);
1313808c999fSMiguel Ojeda         let node = self(&state)?;
1314808c999fSMiguel Ojeda         state.check_unexpected()?;
1315808c999fSMiguel Ojeda         if let Some((unexpected_span, delimiter)) =
1316808c999fSMiguel Ojeda             span_of_unexpected_ignoring_nones(state.cursor())
1317808c999fSMiguel Ojeda         {
1318808c999fSMiguel Ojeda             Err(err_unexpected_token(unexpected_span, delimiter))
1319808c999fSMiguel Ojeda         } else {
1320808c999fSMiguel Ojeda             Ok(node)
1321808c999fSMiguel Ojeda         }
1322808c999fSMiguel Ojeda     }
1323808c999fSMiguel Ojeda }
1324808c999fSMiguel Ojeda 
parse_scoped<F: Parser>(f: F, scope: Span, tokens: TokenStream) -> Result<F::Output>1325808c999fSMiguel Ojeda pub(crate) fn parse_scoped<F: Parser>(f: F, scope: Span, tokens: TokenStream) -> Result<F::Output> {
1326808c999fSMiguel Ojeda     f.__parse_scoped(scope, tokens)
1327808c999fSMiguel Ojeda }
1328808c999fSMiguel Ojeda 
err_unexpected_token(span: Span, delimiter: Delimiter) -> Error1329808c999fSMiguel Ojeda fn err_unexpected_token(span: Span, delimiter: Delimiter) -> Error {
1330808c999fSMiguel Ojeda     let msg = match delimiter {
1331808c999fSMiguel Ojeda         Delimiter::Parenthesis => "unexpected token, expected `)`",
1332808c999fSMiguel Ojeda         Delimiter::Brace => "unexpected token, expected `}`",
1333808c999fSMiguel Ojeda         Delimiter::Bracket => "unexpected token, expected `]`",
1334808c999fSMiguel Ojeda         Delimiter::None => "unexpected token",
1335808c999fSMiguel Ojeda     };
1336808c999fSMiguel Ojeda     Error::new(span, msg)
1337808c999fSMiguel Ojeda }
1338808c999fSMiguel Ojeda 
1339808c999fSMiguel Ojeda /// An empty syntax tree node that consumes no tokens when parsed.
1340808c999fSMiguel Ojeda ///
1341808c999fSMiguel Ojeda /// This is useful for attribute macros that want to ensure they are not
1342808c999fSMiguel Ojeda /// provided any attribute args.
1343808c999fSMiguel Ojeda ///
1344808c999fSMiguel Ojeda /// ```
1345808c999fSMiguel Ojeda /// # extern crate proc_macro;
1346808c999fSMiguel Ojeda /// #
1347808c999fSMiguel Ojeda /// use proc_macro::TokenStream;
1348808c999fSMiguel Ojeda /// use syn::parse_macro_input;
1349808c999fSMiguel Ojeda /// use syn::parse::Nothing;
1350808c999fSMiguel Ojeda ///
1351808c999fSMiguel Ojeda /// # const IGNORE: &str = stringify! {
1352808c999fSMiguel Ojeda /// #[proc_macro_attribute]
1353808c999fSMiguel Ojeda /// # };
1354808c999fSMiguel Ojeda /// pub fn my_attr(args: TokenStream, input: TokenStream) -> TokenStream {
1355808c999fSMiguel Ojeda ///     parse_macro_input!(args as Nothing);
1356808c999fSMiguel Ojeda ///
1357808c999fSMiguel Ojeda ///     /* ... */
1358808c999fSMiguel Ojeda /// #   TokenStream::new()
1359808c999fSMiguel Ojeda /// }
1360808c999fSMiguel Ojeda /// ```
1361808c999fSMiguel Ojeda ///
1362808c999fSMiguel Ojeda /// ```text
1363808c999fSMiguel Ojeda /// error: unexpected token
1364808c999fSMiguel Ojeda ///  --> src/main.rs:3:19
1365808c999fSMiguel Ojeda ///   |
1366808c999fSMiguel Ojeda /// 3 | #[my_attr(asdf)]
1367808c999fSMiguel Ojeda ///   |           ^^^^
1368808c999fSMiguel Ojeda /// ```
1369808c999fSMiguel Ojeda pub struct Nothing;
1370808c999fSMiguel Ojeda 
1371808c999fSMiguel Ojeda impl Parse for Nothing {
parse(_input: ParseStream) -> Result<Self>1372808c999fSMiguel Ojeda     fn parse(_input: ParseStream) -> Result<Self> {
1373808c999fSMiguel Ojeda         Ok(Nothing)
1374808c999fSMiguel Ojeda     }
1375808c999fSMiguel Ojeda }
1376808c999fSMiguel Ojeda 
1377808c999fSMiguel Ojeda #[cfg(feature = "printing")]
1378808c999fSMiguel Ojeda #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
1379808c999fSMiguel Ojeda impl ToTokens for Nothing {
to_tokens(&self, tokens: &mut TokenStream)1380808c999fSMiguel Ojeda     fn to_tokens(&self, tokens: &mut TokenStream) {
1381808c999fSMiguel Ojeda         let _ = tokens;
1382808c999fSMiguel Ojeda     }
1383808c999fSMiguel Ojeda }
1384808c999fSMiguel Ojeda 
1385808c999fSMiguel Ojeda #[cfg(feature = "clone-impls")]
1386808c999fSMiguel Ojeda #[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))]
1387808c999fSMiguel Ojeda impl Clone for Nothing {
clone(&self) -> Self1388808c999fSMiguel Ojeda     fn clone(&self) -> Self {
1389808c999fSMiguel Ojeda         *self
1390808c999fSMiguel Ojeda     }
1391808c999fSMiguel Ojeda }
1392808c999fSMiguel Ojeda 
1393808c999fSMiguel Ojeda #[cfg(feature = "clone-impls")]
1394808c999fSMiguel Ojeda #[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))]
1395808c999fSMiguel Ojeda impl Copy for Nothing {}
1396808c999fSMiguel Ojeda 
1397808c999fSMiguel Ojeda #[cfg(feature = "extra-traits")]
1398808c999fSMiguel Ojeda #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))]
1399808c999fSMiguel Ojeda impl Debug for Nothing {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result1400808c999fSMiguel Ojeda     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1401808c999fSMiguel Ojeda         f.write_str("Nothing")
1402808c999fSMiguel Ojeda     }
1403808c999fSMiguel Ojeda }
1404808c999fSMiguel Ojeda 
1405808c999fSMiguel Ojeda #[cfg(feature = "extra-traits")]
1406808c999fSMiguel Ojeda #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))]
1407808c999fSMiguel Ojeda impl Eq for Nothing {}
1408808c999fSMiguel Ojeda 
1409808c999fSMiguel Ojeda #[cfg(feature = "extra-traits")]
1410808c999fSMiguel Ojeda #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))]
1411808c999fSMiguel Ojeda impl PartialEq for Nothing {
eq(&self, _other: &Self) -> bool1412808c999fSMiguel Ojeda     fn eq(&self, _other: &Self) -> bool {
1413808c999fSMiguel Ojeda         true
1414808c999fSMiguel Ojeda     }
1415808c999fSMiguel Ojeda }
1416808c999fSMiguel Ojeda 
1417808c999fSMiguel Ojeda #[cfg(feature = "extra-traits")]
1418808c999fSMiguel Ojeda #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))]
1419808c999fSMiguel Ojeda impl Hash for Nothing {
hash<H: Hasher>(&self, _state: &mut H)1420808c999fSMiguel Ojeda     fn hash<H: Hasher>(&self, _state: &mut H) {}
1421808c999fSMiguel Ojeda }
1422