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