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