syn/
item.rs

1use crate::attr::Attribute;
2use crate::data::{Fields, FieldsNamed, Variant};
3use crate::derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput};
4use crate::expr::Expr;
5use crate::generics::{Generics, TypeParamBound};
6use crate::ident::Ident;
7use crate::lifetime::Lifetime;
8use crate::mac::Macro;
9use crate::pat::{Pat, PatType};
10use crate::path::Path;
11use crate::punctuated::Punctuated;
12use crate::restriction::Visibility;
13use crate::stmt::Block;
14use crate::token;
15use crate::ty::{Abi, ReturnType, Type};
16use proc_macro2::TokenStream;
17#[cfg(feature = "parsing")]
18use std::mem;
19
20ast_enum_of_structs! {
21    /// Things that can appear directly inside of a module or scope.
22    ///
23    /// # Syntax tree enum
24    ///
25    /// This type is a [syntax tree enum].
26    ///
27    /// [syntax tree enum]: crate::expr::Expr#syntax-tree-enums
28    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
29    #[non_exhaustive]
30    pub enum Item {
31        /// A constant item: `const MAX: u16 = 65535`.
32        Const(ItemConst),
33
34        /// An enum definition: `enum Foo<A, B> { A(A), B(B) }`.
35        Enum(ItemEnum),
36
37        /// An `extern crate` item: `extern crate serde`.
38        ExternCrate(ItemExternCrate),
39
40        /// A free-standing function: `fn process(n: usize) -> Result<()> { ...
41        /// }`.
42        Fn(ItemFn),
43
44        /// A block of foreign items: `extern "C" { ... }`.
45        ForeignMod(ItemForeignMod),
46
47        /// An impl block providing trait or associated items: `impl<A> Trait
48        /// for Data<A> { ... }`.
49        Impl(ItemImpl),
50
51        /// A macro invocation, which includes `macro_rules!` definitions.
52        Macro(ItemMacro),
53
54        /// A module or module declaration: `mod m` or `mod m { ... }`.
55        Mod(ItemMod),
56
57        /// A static item: `static BIKE: Shed = Shed(42)`.
58        Static(ItemStatic),
59
60        /// A struct definition: `struct Foo<A> { x: A }`.
61        Struct(ItemStruct),
62
63        /// A trait definition: `pub trait Iterator { ... }`.
64        Trait(ItemTrait),
65
66        /// A trait alias: `pub trait SharableIterator = Iterator + Sync`.
67        TraitAlias(ItemTraitAlias),
68
69        /// A type alias: `type Result<T> = std::result::Result<T, MyError>`.
70        Type(ItemType),
71
72        /// A union definition: `union Foo<A, B> { x: A, y: B }`.
73        Union(ItemUnion),
74
75        /// A use declaration: `use std::collections::HashMap`.
76        Use(ItemUse),
77
78        /// Tokens forming an item not interpreted by Syn.
79        Verbatim(TokenStream),
80
81        // For testing exhaustiveness in downstream code, use the following idiom:
82        //
83        //     match item {
84        //         #![cfg_attr(test, deny(non_exhaustive_omitted_patterns))]
85        //
86        //         Item::Const(item) => {...}
87        //         Item::Enum(item) => {...}
88        //         ...
89        //         Item::Verbatim(item) => {...}
90        //
91        //         _ => { /* some sane fallback */ }
92        //     }
93        //
94        // This way we fail your tests but don't break your library when adding
95        // a variant. You will be notified by a test failure when a variant is
96        // added, so that you can add code to handle it, but your library will
97        // continue to compile and work for downstream users in the interim.
98    }
99}
100
101ast_struct! {
102    /// A constant item: `const MAX: u16 = 65535`.
103    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
104    pub struct ItemConst {
105        pub attrs: Vec<Attribute>,
106        pub vis: Visibility,
107        pub const_token: Token![const],
108        pub ident: Ident,
109        pub generics: Generics,
110        pub colon_token: Token![:],
111        pub ty: Box<Type>,
112        pub eq_token: Token![=],
113        pub expr: Box<Expr>,
114        pub semi_token: Token![;],
115    }
116}
117
118ast_struct! {
119    /// An enum definition: `enum Foo<A, B> { A(A), B(B) }`.
120    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
121    pub struct ItemEnum {
122        pub attrs: Vec<Attribute>,
123        pub vis: Visibility,
124        pub enum_token: Token![enum],
125        pub ident: Ident,
126        pub generics: Generics,
127        pub brace_token: token::Brace,
128        pub variants: Punctuated<Variant, Token![,]>,
129    }
130}
131
132ast_struct! {
133    /// An `extern crate` item: `extern crate serde`.
134    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
135    pub struct ItemExternCrate {
136        pub attrs: Vec<Attribute>,
137        pub vis: Visibility,
138        pub extern_token: Token![extern],
139        pub crate_token: Token![crate],
140        pub ident: Ident,
141        pub rename: Option<(Token![as], Ident)>,
142        pub semi_token: Token![;],
143    }
144}
145
146ast_struct! {
147    /// A free-standing function: `fn process(n: usize) -> Result<()> { ... }`.
148    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
149    pub struct ItemFn {
150        pub attrs: Vec<Attribute>,
151        pub vis: Visibility,
152        pub sig: Signature,
153        pub block: Box<Block>,
154    }
155}
156
157ast_struct! {
158    /// A block of foreign items: `extern "C" { ... }`.
159    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
160    pub struct ItemForeignMod {
161        pub attrs: Vec<Attribute>,
162        pub unsafety: Option<Token![unsafe]>,
163        pub abi: Abi,
164        pub brace_token: token::Brace,
165        pub items: Vec<ForeignItem>,
166    }
167}
168
169ast_struct! {
170    /// An impl block providing trait or associated items: `impl<A> Trait
171    /// for Data<A> { ... }`.
172    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
173    pub struct ItemImpl {
174        pub attrs: Vec<Attribute>,
175        pub defaultness: Option<Token![default]>,
176        pub unsafety: Option<Token![unsafe]>,
177        pub impl_token: Token![impl],
178        pub generics: Generics,
179        /// Trait this impl implements.
180        pub trait_: Option<(Option<Token![!]>, Path, Token![for])>,
181        /// The Self type of the impl.
182        pub self_ty: Box<Type>,
183        pub brace_token: token::Brace,
184        pub items: Vec<ImplItem>,
185    }
186}
187
188ast_struct! {
189    /// A macro invocation, which includes `macro_rules!` definitions.
190    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
191    pub struct ItemMacro {
192        pub attrs: Vec<Attribute>,
193        /// The `example` in `macro_rules! example { ... }`.
194        pub ident: Option<Ident>,
195        pub mac: Macro,
196        pub semi_token: Option<Token![;]>,
197    }
198}
199
200ast_struct! {
201    /// A module or module declaration: `mod m` or `mod m { ... }`.
202    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
203    pub struct ItemMod {
204        pub attrs: Vec<Attribute>,
205        pub vis: Visibility,
206        pub unsafety: Option<Token![unsafe]>,
207        pub mod_token: Token![mod],
208        pub ident: Ident,
209        pub content: Option<(token::Brace, Vec<Item>)>,
210        pub semi: Option<Token![;]>,
211    }
212}
213
214ast_struct! {
215    /// A static item: `static BIKE: Shed = Shed(42)`.
216    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
217    pub struct ItemStatic {
218        pub attrs: Vec<Attribute>,
219        pub vis: Visibility,
220        pub static_token: Token![static],
221        pub mutability: StaticMutability,
222        pub ident: Ident,
223        pub colon_token: Token![:],
224        pub ty: Box<Type>,
225        pub eq_token: Token![=],
226        pub expr: Box<Expr>,
227        pub semi_token: Token![;],
228    }
229}
230
231ast_struct! {
232    /// A struct definition: `struct Foo<A> { x: A }`.
233    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
234    pub struct ItemStruct {
235        pub attrs: Vec<Attribute>,
236        pub vis: Visibility,
237        pub struct_token: Token![struct],
238        pub ident: Ident,
239        pub generics: Generics,
240        pub fields: Fields,
241        pub semi_token: Option<Token![;]>,
242    }
243}
244
245ast_struct! {
246    /// A trait definition: `pub trait Iterator { ... }`.
247    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
248    pub struct ItemTrait {
249        pub attrs: Vec<Attribute>,
250        pub vis: Visibility,
251        pub unsafety: Option<Token![unsafe]>,
252        pub auto_token: Option<Token![auto]>,
253        pub restriction: Option<ImplRestriction>,
254        pub trait_token: Token![trait],
255        pub ident: Ident,
256        pub generics: Generics,
257        pub colon_token: Option<Token![:]>,
258        pub supertraits: Punctuated<TypeParamBound, Token![+]>,
259        pub brace_token: token::Brace,
260        pub items: Vec<TraitItem>,
261    }
262}
263
264ast_struct! {
265    /// A trait alias: `pub trait SharableIterator = Iterator + Sync`.
266    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
267    pub struct ItemTraitAlias {
268        pub attrs: Vec<Attribute>,
269        pub vis: Visibility,
270        pub trait_token: Token![trait],
271        pub ident: Ident,
272        pub generics: Generics,
273        pub eq_token: Token![=],
274        pub bounds: Punctuated<TypeParamBound, Token![+]>,
275        pub semi_token: Token![;],
276    }
277}
278
279ast_struct! {
280    /// A type alias: `type Result<T> = std::result::Result<T, MyError>`.
281    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
282    pub struct ItemType {
283        pub attrs: Vec<Attribute>,
284        pub vis: Visibility,
285        pub type_token: Token![type],
286        pub ident: Ident,
287        pub generics: Generics,
288        pub eq_token: Token![=],
289        pub ty: Box<Type>,
290        pub semi_token: Token![;],
291    }
292}
293
294ast_struct! {
295    /// A union definition: `union Foo<A, B> { x: A, y: B }`.
296    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
297    pub struct ItemUnion {
298        pub attrs: Vec<Attribute>,
299        pub vis: Visibility,
300        pub union_token: Token![union],
301        pub ident: Ident,
302        pub generics: Generics,
303        pub fields: FieldsNamed,
304    }
305}
306
307ast_struct! {
308    /// A use declaration: `use std::collections::HashMap`.
309    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
310    pub struct ItemUse {
311        pub attrs: Vec<Attribute>,
312        pub vis: Visibility,
313        pub use_token: Token![use],
314        pub leading_colon: Option<Token![::]>,
315        pub tree: UseTree,
316        pub semi_token: Token![;],
317    }
318}
319
320impl Item {
321    #[cfg(feature = "parsing")]
322    pub(crate) fn replace_attrs(&mut self, new: Vec<Attribute>) -> Vec<Attribute> {
323        match self {
324            Item::Const(ItemConst { attrs, .. })
325            | Item::Enum(ItemEnum { attrs, .. })
326            | Item::ExternCrate(ItemExternCrate { attrs, .. })
327            | Item::Fn(ItemFn { attrs, .. })
328            | Item::ForeignMod(ItemForeignMod { attrs, .. })
329            | Item::Impl(ItemImpl { attrs, .. })
330            | Item::Macro(ItemMacro { attrs, .. })
331            | Item::Mod(ItemMod { attrs, .. })
332            | Item::Static(ItemStatic { attrs, .. })
333            | Item::Struct(ItemStruct { attrs, .. })
334            | Item::Trait(ItemTrait { attrs, .. })
335            | Item::TraitAlias(ItemTraitAlias { attrs, .. })
336            | Item::Type(ItemType { attrs, .. })
337            | Item::Union(ItemUnion { attrs, .. })
338            | Item::Use(ItemUse { attrs, .. }) => mem::replace(attrs, new),
339            Item::Verbatim(_) => Vec::new(),
340        }
341    }
342}
343
344impl From<DeriveInput> for Item {
345    fn from(input: DeriveInput) -> Item {
346        match input.data {
347            Data::Struct(data) => Item::Struct(ItemStruct {
348                attrs: input.attrs,
349                vis: input.vis,
350                struct_token: data.struct_token,
351                ident: input.ident,
352                generics: input.generics,
353                fields: data.fields,
354                semi_token: data.semi_token,
355            }),
356            Data::Enum(data) => Item::Enum(ItemEnum {
357                attrs: input.attrs,
358                vis: input.vis,
359                enum_token: data.enum_token,
360                ident: input.ident,
361                generics: input.generics,
362                brace_token: data.brace_token,
363                variants: data.variants,
364            }),
365            Data::Union(data) => Item::Union(ItemUnion {
366                attrs: input.attrs,
367                vis: input.vis,
368                union_token: data.union_token,
369                ident: input.ident,
370                generics: input.generics,
371                fields: data.fields,
372            }),
373        }
374    }
375}
376
377impl From<ItemStruct> for DeriveInput {
378    fn from(input: ItemStruct) -> DeriveInput {
379        DeriveInput {
380            attrs: input.attrs,
381            vis: input.vis,
382            ident: input.ident,
383            generics: input.generics,
384            data: Data::Struct(DataStruct {
385                struct_token: input.struct_token,
386                fields: input.fields,
387                semi_token: input.semi_token,
388            }),
389        }
390    }
391}
392
393impl From<ItemEnum> for DeriveInput {
394    fn from(input: ItemEnum) -> DeriveInput {
395        DeriveInput {
396            attrs: input.attrs,
397            vis: input.vis,
398            ident: input.ident,
399            generics: input.generics,
400            data: Data::Enum(DataEnum {
401                enum_token: input.enum_token,
402                brace_token: input.brace_token,
403                variants: input.variants,
404            }),
405        }
406    }
407}
408
409impl From<ItemUnion> for DeriveInput {
410    fn from(input: ItemUnion) -> DeriveInput {
411        DeriveInput {
412            attrs: input.attrs,
413            vis: input.vis,
414            ident: input.ident,
415            generics: input.generics,
416            data: Data::Union(DataUnion {
417                union_token: input.union_token,
418                fields: input.fields,
419            }),
420        }
421    }
422}
423
424ast_enum_of_structs! {
425    /// A suffix of an import tree in a `use` item: `Type as Renamed` or `*`.
426    ///
427    /// # Syntax tree enum
428    ///
429    /// This type is a [syntax tree enum].
430    ///
431    /// [syntax tree enum]: crate::expr::Expr#syntax-tree-enums
432    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
433    pub enum UseTree {
434        /// A path prefix of imports in a `use` item: `std::...`.
435        Path(UsePath),
436
437        /// An identifier imported by a `use` item: `HashMap`.
438        Name(UseName),
439
440        /// An renamed identifier imported by a `use` item: `HashMap as Map`.
441        Rename(UseRename),
442
443        /// A glob import in a `use` item: `*`.
444        Glob(UseGlob),
445
446        /// A braced group of imports in a `use` item: `{A, B, C}`.
447        Group(UseGroup),
448    }
449}
450
451ast_struct! {
452    /// A path prefix of imports in a `use` item: `std::...`.
453    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
454    pub struct UsePath {
455        pub ident: Ident,
456        pub colon2_token: Token![::],
457        pub tree: Box<UseTree>,
458    }
459}
460
461ast_struct! {
462    /// An identifier imported by a `use` item: `HashMap`.
463    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
464    pub struct UseName {
465        pub ident: Ident,
466    }
467}
468
469ast_struct! {
470    /// An renamed identifier imported by a `use` item: `HashMap as Map`.
471    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
472    pub struct UseRename {
473        pub ident: Ident,
474        pub as_token: Token![as],
475        pub rename: Ident,
476    }
477}
478
479ast_struct! {
480    /// A glob import in a `use` item: `*`.
481    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
482    pub struct UseGlob {
483        pub star_token: Token![*],
484    }
485}
486
487ast_struct! {
488    /// A braced group of imports in a `use` item: `{A, B, C}`.
489    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
490    pub struct UseGroup {
491        pub brace_token: token::Brace,
492        pub items: Punctuated<UseTree, Token![,]>,
493    }
494}
495
496ast_enum_of_structs! {
497    /// An item within an `extern` block.
498    ///
499    /// # Syntax tree enum
500    ///
501    /// This type is a [syntax tree enum].
502    ///
503    /// [syntax tree enum]: crate::expr::Expr#syntax-tree-enums
504    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
505    #[non_exhaustive]
506    pub enum ForeignItem {
507        /// A foreign function in an `extern` block.
508        Fn(ForeignItemFn),
509
510        /// A foreign static item in an `extern` block: `static ext: u8`.
511        Static(ForeignItemStatic),
512
513        /// A foreign type in an `extern` block: `type void`.
514        Type(ForeignItemType),
515
516        /// A macro invocation within an extern block.
517        Macro(ForeignItemMacro),
518
519        /// Tokens in an `extern` block not interpreted by Syn.
520        Verbatim(TokenStream),
521
522        // For testing exhaustiveness in downstream code, use the following idiom:
523        //
524        //     match item {
525        //         #![cfg_attr(test, deny(non_exhaustive_omitted_patterns))]
526        //
527        //         ForeignItem::Fn(item) => {...}
528        //         ForeignItem::Static(item) => {...}
529        //         ...
530        //         ForeignItem::Verbatim(item) => {...}
531        //
532        //         _ => { /* some sane fallback */ }
533        //     }
534        //
535        // This way we fail your tests but don't break your library when adding
536        // a variant. You will be notified by a test failure when a variant is
537        // added, so that you can add code to handle it, but your library will
538        // continue to compile and work for downstream users in the interim.
539    }
540}
541
542ast_struct! {
543    /// A foreign function in an `extern` block.
544    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
545    pub struct ForeignItemFn {
546        pub attrs: Vec<Attribute>,
547        pub vis: Visibility,
548        pub sig: Signature,
549        pub semi_token: Token![;],
550    }
551}
552
553ast_struct! {
554    /// A foreign static item in an `extern` block: `static ext: u8`.
555    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
556    pub struct ForeignItemStatic {
557        pub attrs: Vec<Attribute>,
558        pub vis: Visibility,
559        pub static_token: Token![static],
560        pub mutability: StaticMutability,
561        pub ident: Ident,
562        pub colon_token: Token![:],
563        pub ty: Box<Type>,
564        pub semi_token: Token![;],
565    }
566}
567
568ast_struct! {
569    /// A foreign type in an `extern` block: `type void`.
570    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
571    pub struct ForeignItemType {
572        pub attrs: Vec<Attribute>,
573        pub vis: Visibility,
574        pub type_token: Token![type],
575        pub ident: Ident,
576        pub generics: Generics,
577        pub semi_token: Token![;],
578    }
579}
580
581ast_struct! {
582    /// A macro invocation within an extern block.
583    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
584    pub struct ForeignItemMacro {
585        pub attrs: Vec<Attribute>,
586        pub mac: Macro,
587        pub semi_token: Option<Token![;]>,
588    }
589}
590
591ast_enum_of_structs! {
592    /// An item declaration within the definition of a trait.
593    ///
594    /// # Syntax tree enum
595    ///
596    /// This type is a [syntax tree enum].
597    ///
598    /// [syntax tree enum]: crate::expr::Expr#syntax-tree-enums
599    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
600    #[non_exhaustive]
601    pub enum TraitItem {
602        /// An associated constant within the definition of a trait.
603        Const(TraitItemConst),
604
605        /// An associated function within the definition of a trait.
606        Fn(TraitItemFn),
607
608        /// An associated type within the definition of a trait.
609        Type(TraitItemType),
610
611        /// A macro invocation within the definition of a trait.
612        Macro(TraitItemMacro),
613
614        /// Tokens within the definition of a trait not interpreted by Syn.
615        Verbatim(TokenStream),
616
617        // For testing exhaustiveness in downstream code, use the following idiom:
618        //
619        //     match item {
620        //         #![cfg_attr(test, deny(non_exhaustive_omitted_patterns))]
621        //
622        //         TraitItem::Const(item) => {...}
623        //         TraitItem::Fn(item) => {...}
624        //         ...
625        //         TraitItem::Verbatim(item) => {...}
626        //
627        //         _ => { /* some sane fallback */ }
628        //     }
629        //
630        // This way we fail your tests but don't break your library when adding
631        // a variant. You will be notified by a test failure when a variant is
632        // added, so that you can add code to handle it, but your library will
633        // continue to compile and work for downstream users in the interim.
634    }
635}
636
637ast_struct! {
638    /// An associated constant within the definition of a trait.
639    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
640    pub struct TraitItemConst {
641        pub attrs: Vec<Attribute>,
642        pub const_token: Token![const],
643        pub ident: Ident,
644        pub generics: Generics,
645        pub colon_token: Token![:],
646        pub ty: Type,
647        pub default: Option<(Token![=], Expr)>,
648        pub semi_token: Token![;],
649    }
650}
651
652ast_struct! {
653    /// An associated function within the definition of a trait.
654    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
655    pub struct TraitItemFn {
656        pub attrs: Vec<Attribute>,
657        pub sig: Signature,
658        pub default: Option<Block>,
659        pub semi_token: Option<Token![;]>,
660    }
661}
662
663ast_struct! {
664    /// An associated type within the definition of a trait.
665    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
666    pub struct TraitItemType {
667        pub attrs: Vec<Attribute>,
668        pub type_token: Token![type],
669        pub ident: Ident,
670        pub generics: Generics,
671        pub colon_token: Option<Token![:]>,
672        pub bounds: Punctuated<TypeParamBound, Token![+]>,
673        pub default: Option<(Token![=], Type)>,
674        pub semi_token: Token![;],
675    }
676}
677
678ast_struct! {
679    /// A macro invocation within the definition of a trait.
680    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
681    pub struct TraitItemMacro {
682        pub attrs: Vec<Attribute>,
683        pub mac: Macro,
684        pub semi_token: Option<Token![;]>,
685    }
686}
687
688ast_enum_of_structs! {
689    /// An item within an impl block.
690    ///
691    /// # Syntax tree enum
692    ///
693    /// This type is a [syntax tree enum].
694    ///
695    /// [syntax tree enum]: crate::expr::Expr#syntax-tree-enums
696    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
697    #[non_exhaustive]
698    pub enum ImplItem {
699        /// An associated constant within an impl block.
700        Const(ImplItemConst),
701
702        /// An associated function within an impl block.
703        Fn(ImplItemFn),
704
705        /// An associated type within an impl block.
706        Type(ImplItemType),
707
708        /// A macro invocation within an impl block.
709        Macro(ImplItemMacro),
710
711        /// Tokens within an impl block not interpreted by Syn.
712        Verbatim(TokenStream),
713
714        // For testing exhaustiveness in downstream code, use the following idiom:
715        //
716        //     match item {
717        //         #![cfg_attr(test, deny(non_exhaustive_omitted_patterns))]
718        //
719        //         ImplItem::Const(item) => {...}
720        //         ImplItem::Fn(item) => {...}
721        //         ...
722        //         ImplItem::Verbatim(item) => {...}
723        //
724        //         _ => { /* some sane fallback */ }
725        //     }
726        //
727        // This way we fail your tests but don't break your library when adding
728        // a variant. You will be notified by a test failure when a variant is
729        // added, so that you can add code to handle it, but your library will
730        // continue to compile and work for downstream users in the interim.
731    }
732}
733
734ast_struct! {
735    /// An associated constant within an impl block.
736    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
737    pub struct ImplItemConst {
738        pub attrs: Vec<Attribute>,
739        pub vis: Visibility,
740        pub defaultness: Option<Token![default]>,
741        pub const_token: Token![const],
742        pub ident: Ident,
743        pub generics: Generics,
744        pub colon_token: Token![:],
745        pub ty: Type,
746        pub eq_token: Token![=],
747        pub expr: Expr,
748        pub semi_token: Token![;],
749    }
750}
751
752ast_struct! {
753    /// An associated function within an impl block.
754    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
755    pub struct ImplItemFn {
756        pub attrs: Vec<Attribute>,
757        pub vis: Visibility,
758        pub defaultness: Option<Token![default]>,
759        pub sig: Signature,
760        pub block: Block,
761    }
762}
763
764ast_struct! {
765    /// An associated type within an impl block.
766    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
767    pub struct ImplItemType {
768        pub attrs: Vec<Attribute>,
769        pub vis: Visibility,
770        pub defaultness: Option<Token![default]>,
771        pub type_token: Token![type],
772        pub ident: Ident,
773        pub generics: Generics,
774        pub eq_token: Token![=],
775        pub ty: Type,
776        pub semi_token: Token![;],
777    }
778}
779
780ast_struct! {
781    /// A macro invocation within an impl block.
782    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
783    pub struct ImplItemMacro {
784        pub attrs: Vec<Attribute>,
785        pub mac: Macro,
786        pub semi_token: Option<Token![;]>,
787    }
788}
789
790ast_struct! {
791    /// A function signature in a trait or implementation: `unsafe fn
792    /// initialize(&self)`.
793    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
794    pub struct Signature {
795        pub constness: Option<Token![const]>,
796        pub asyncness: Option<Token![async]>,
797        pub unsafety: Option<Token![unsafe]>,
798        pub abi: Option<Abi>,
799        pub fn_token: Token![fn],
800        pub ident: Ident,
801        pub generics: Generics,
802        pub paren_token: token::Paren,
803        pub inputs: Punctuated<FnArg, Token![,]>,
804        pub variadic: Option<Variadic>,
805        pub output: ReturnType,
806    }
807}
808
809impl Signature {
810    /// A method's `self` receiver, such as `&self` or `self: Box<Self>`.
811    pub fn receiver(&self) -> Option<&Receiver> {
812        let arg = self.inputs.first()?;
813        match arg {
814            FnArg::Receiver(receiver) => Some(receiver),
815            FnArg::Typed(_) => None,
816        }
817    }
818}
819
820ast_enum_of_structs! {
821    /// An argument in a function signature: the `n: usize` in `fn f(n: usize)`.
822    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
823    pub enum FnArg {
824        /// The `self` argument of an associated method.
825        Receiver(Receiver),
826
827        /// A function argument accepted by pattern and type.
828        Typed(PatType),
829    }
830}
831
832ast_struct! {
833    /// The `self` argument of an associated method.
834    ///
835    /// If `colon_token` is present, the receiver is written with an explicit
836    /// type such as `self: Box<Self>`. If `colon_token` is absent, the receiver
837    /// is written in shorthand such as `self` or `&self` or `&mut self`. In the
838    /// shorthand case, the type in `ty` is reconstructed as one of `Self`,
839    /// `&Self`, or `&mut Self`.
840    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
841    pub struct Receiver {
842        pub attrs: Vec<Attribute>,
843        pub reference: Option<(Token![&], Option<Lifetime>)>,
844        pub mutability: Option<Token![mut]>,
845        pub self_token: Token![self],
846        pub colon_token: Option<Token![:]>,
847        pub ty: Box<Type>,
848    }
849}
850
851impl Receiver {
852    pub fn lifetime(&self) -> Option<&Lifetime> {
853        self.reference.as_ref()?.1.as_ref()
854    }
855}
856
857ast_struct! {
858    /// The variadic argument of a foreign function.
859    ///
860    /// ```rust
861    /// # struct c_char;
862    /// # struct c_int;
863    /// #
864    /// extern "C" {
865    ///     fn printf(format: *const c_char, ...) -> c_int;
866    ///     //                               ^^^
867    /// }
868    /// ```
869    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
870    pub struct Variadic {
871        pub attrs: Vec<Attribute>,
872        pub pat: Option<(Box<Pat>, Token![:])>,
873        pub dots: Token![...],
874        pub comma: Option<Token![,]>,
875    }
876}
877
878ast_enum! {
879    /// The mutability of an `Item::Static` or `ForeignItem::Static`.
880    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
881    #[non_exhaustive]
882    pub enum StaticMutability {
883        Mut(Token![mut]),
884        None,
885    }
886}
887
888ast_enum! {
889    /// Unused, but reserved for RFC 3323 restrictions.
890    #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
891    #[non_exhaustive]
892    pub enum ImplRestriction {}
893
894
895    // TODO: https://rust-lang.github.io/rfcs/3323-restrictions.html
896    //
897    // pub struct ImplRestriction {
898    //     pub impl_token: Token![impl],
899    //     pub paren_token: token::Paren,
900    //     pub in_token: Option<Token![in]>,
901    //     pub path: Box<Path>,
902    // }
903}
904
905#[cfg(feature = "parsing")]
906pub(crate) mod parsing {
907    use crate::attr::{self, Attribute};
908    use crate::derive;
909    use crate::error::{Error, Result};
910    use crate::expr::Expr;
911    use crate::ext::IdentExt as _;
912    use crate::generics::{Generics, TypeParamBound};
913    use crate::ident::Ident;
914    use crate::item::{
915        FnArg, ForeignItem, ForeignItemFn, ForeignItemMacro, ForeignItemStatic, ForeignItemType,
916        ImplItem, ImplItemConst, ImplItemFn, ImplItemMacro, ImplItemType, Item, ItemConst,
917        ItemEnum, ItemExternCrate, ItemFn, ItemForeignMod, ItemImpl, ItemMacro, ItemMod,
918        ItemStatic, ItemStruct, ItemTrait, ItemTraitAlias, ItemType, ItemUnion, ItemUse, Receiver,
919        Signature, StaticMutability, TraitItem, TraitItemConst, TraitItemFn, TraitItemMacro,
920        TraitItemType, UseGlob, UseGroup, UseName, UsePath, UseRename, UseTree, Variadic,
921    };
922    use crate::lifetime::Lifetime;
923    use crate::lit::LitStr;
924    use crate::mac::{self, Macro};
925    use crate::parse::discouraged::Speculative as _;
926    use crate::parse::{Parse, ParseBuffer, ParseStream};
927    use crate::pat::{Pat, PatType, PatWild};
928    use crate::path::Path;
929    use crate::punctuated::Punctuated;
930    use crate::restriction::Visibility;
931    use crate::stmt::Block;
932    use crate::token;
933    use crate::ty::{Abi, ReturnType, Type, TypePath, TypeReference};
934    use crate::verbatim;
935    use proc_macro2::TokenStream;
936
937    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
938    impl Parse for Item {
939        fn parse(input: ParseStream) -> Result<Self> {
940            let begin = input.fork();
941            let attrs = input.call(Attribute::parse_outer)?;
942            parse_rest_of_item(begin, attrs, input)
943        }
944    }
945
946    pub(crate) fn parse_rest_of_item(
947        begin: ParseBuffer,
948        mut attrs: Vec<Attribute>,
949        input: ParseStream,
950    ) -> Result<Item> {
951        let ahead = input.fork();
952        let vis: Visibility = ahead.parse()?;
953
954        let lookahead = ahead.lookahead1();
955        let allow_safe = false;
956        let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead, allow_safe) {
957            let vis: Visibility = input.parse()?;
958            let sig: Signature = input.parse()?;
959            if input.peek(Token![;]) {
960                input.parse::<Token![;]>()?;
961                Ok(Item::Verbatim(verbatim::between(&begin, input)))
962            } else {
963                parse_rest_of_fn(input, Vec::new(), vis, sig).map(Item::Fn)
964            }
965        } else if lookahead.peek(Token![extern]) {
966            ahead.parse::<Token![extern]>()?;
967            let lookahead = ahead.lookahead1();
968            if lookahead.peek(Token![crate]) {
969                input.parse().map(Item::ExternCrate)
970            } else if lookahead.peek(token::Brace) {
971                input.parse().map(Item::ForeignMod)
972            } else if lookahead.peek(LitStr) {
973                ahead.parse::<LitStr>()?;
974                let lookahead = ahead.lookahead1();
975                if lookahead.peek(token::Brace) {
976                    input.parse().map(Item::ForeignMod)
977                } else {
978                    Err(lookahead.error())
979                }
980            } else {
981                Err(lookahead.error())
982            }
983        } else if lookahead.peek(Token![use]) {
984            let allow_crate_root_in_path = true;
985            match parse_item_use(input, allow_crate_root_in_path)? {
986                Some(item_use) => Ok(Item::Use(item_use)),
987                None => Ok(Item::Verbatim(verbatim::between(&begin, input))),
988            }
989        } else if lookahead.peek(Token![static]) {
990            let vis = input.parse()?;
991            let static_token = input.parse()?;
992            let mutability = input.parse()?;
993            let ident = input.parse()?;
994            if input.peek(Token![=]) {
995                input.parse::<Token![=]>()?;
996                input.parse::<Expr>()?;
997                input.parse::<Token![;]>()?;
998                Ok(Item::Verbatim(verbatim::between(&begin, input)))
999            } else {
1000                let colon_token = input.parse()?;
1001                let ty = input.parse()?;
1002                if input.peek(Token![;]) {
1003                    input.parse::<Token![;]>()?;
1004                    Ok(Item::Verbatim(verbatim::between(&begin, input)))
1005                } else {
1006                    Ok(Item::Static(ItemStatic {
1007                        attrs: Vec::new(),
1008                        vis,
1009                        static_token,
1010                        mutability,
1011                        ident,
1012                        colon_token,
1013                        ty,
1014                        eq_token: input.parse()?,
1015                        expr: input.parse()?,
1016                        semi_token: input.parse()?,
1017                    }))
1018                }
1019            }
1020        } else if lookahead.peek(Token![const]) {
1021            let vis = input.parse()?;
1022            let const_token: Token![const] = input.parse()?;
1023            let lookahead = input.lookahead1();
1024            let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
1025                input.call(Ident::parse_any)?
1026            } else {
1027                return Err(lookahead.error());
1028            };
1029            let mut generics: Generics = input.parse()?;
1030            let colon_token = input.parse()?;
1031            let ty = input.parse()?;
1032            let value = if let Some(eq_token) = input.parse::<Option<Token![=]>>()? {
1033                let expr: Expr = input.parse()?;
1034                Some((eq_token, expr))
1035            } else {
1036                None
1037            };
1038            generics.where_clause = input.parse()?;
1039            let semi_token: Token![;] = input.parse()?;
1040            match value {
1041                Some((eq_token, expr))
1042                    if generics.lt_token.is_none() && generics.where_clause.is_none() =>
1043                {
1044                    Ok(Item::Const(ItemConst {
1045                        attrs: Vec::new(),
1046                        vis,
1047                        const_token,
1048                        ident,
1049                        generics,
1050                        colon_token,
1051                        ty,
1052                        eq_token,
1053                        expr: Box::new(expr),
1054                        semi_token,
1055                    }))
1056                }
1057                _ => Ok(Item::Verbatim(verbatim::between(&begin, input))),
1058            }
1059        } else if lookahead.peek(Token![unsafe]) {
1060            ahead.parse::<Token![unsafe]>()?;
1061            let lookahead = ahead.lookahead1();
1062            if lookahead.peek(Token![trait])
1063                || lookahead.peek(Token![auto]) && ahead.peek2(Token![trait])
1064            {
1065                input.parse().map(Item::Trait)
1066            } else if lookahead.peek(Token![impl]) {
1067                let allow_verbatim_impl = true;
1068                if let Some(item) = parse_impl(input, allow_verbatim_impl)? {
1069                    Ok(Item::Impl(item))
1070                } else {
1071                    Ok(Item::Verbatim(verbatim::between(&begin, input)))
1072                }
1073            } else if lookahead.peek(Token![extern]) {
1074                input.parse().map(Item::ForeignMod)
1075            } else if lookahead.peek(Token![mod]) {
1076                input.parse().map(Item::Mod)
1077            } else {
1078                Err(lookahead.error())
1079            }
1080        } else if lookahead.peek(Token![mod]) {
1081            input.parse().map(Item::Mod)
1082        } else if lookahead.peek(Token![type]) {
1083            parse_item_type(begin, input)
1084        } else if lookahead.peek(Token![struct]) {
1085            input.parse().map(Item::Struct)
1086        } else if lookahead.peek(Token![enum]) {
1087            input.parse().map(Item::Enum)
1088        } else if lookahead.peek(Token![union]) && ahead.peek2(Ident) {
1089            input.parse().map(Item::Union)
1090        } else if lookahead.peek(Token![trait]) {
1091            input.call(parse_trait_or_trait_alias)
1092        } else if lookahead.peek(Token![auto]) && ahead.peek2(Token![trait]) {
1093            input.parse().map(Item::Trait)
1094        } else if lookahead.peek(Token![impl])
1095            || lookahead.peek(Token![default]) && !ahead.peek2(Token![!])
1096        {
1097            let allow_verbatim_impl = true;
1098            if let Some(item) = parse_impl(input, allow_verbatim_impl)? {
1099                Ok(Item::Impl(item))
1100            } else {
1101                Ok(Item::Verbatim(verbatim::between(&begin, input)))
1102            }
1103        } else if lookahead.peek(Token![macro]) {
1104            input.advance_to(&ahead);
1105            parse_macro2(begin, vis, input)
1106        } else if vis.is_inherited()
1107            && (lookahead.peek(Ident)
1108                || lookahead.peek(Token![self])
1109                || lookahead.peek(Token![super])
1110                || lookahead.peek(Token![crate])
1111                || lookahead.peek(Token![::]))
1112        {
1113            input.parse().map(Item::Macro)
1114        } else {
1115            Err(lookahead.error())
1116        }?;
1117
1118        attrs.extend(item.replace_attrs(Vec::new()));
1119        item.replace_attrs(attrs);
1120        Ok(item)
1121    }
1122
1123    struct FlexibleItemType {
1124        vis: Visibility,
1125        defaultness: Option<Token![default]>,
1126        type_token: Token![type],
1127        ident: Ident,
1128        generics: Generics,
1129        colon_token: Option<Token![:]>,
1130        bounds: Punctuated<TypeParamBound, Token![+]>,
1131        ty: Option<(Token![=], Type)>,
1132        semi_token: Token![;],
1133    }
1134
1135    enum TypeDefaultness {
1136        Optional,
1137        Disallowed,
1138    }
1139
1140    enum WhereClauseLocation {
1141        // type Ty<T> where T: 'static = T;
1142        BeforeEq,
1143        // type Ty<T> = T where T: 'static;
1144        AfterEq,
1145        // TODO: goes away once the migration period on rust-lang/rust#89122 is over
1146        Both,
1147    }
1148
1149    impl FlexibleItemType {
1150        fn parse(
1151            input: ParseStream,
1152            allow_defaultness: TypeDefaultness,
1153            where_clause_location: WhereClauseLocation,
1154        ) -> Result<Self> {
1155            let vis: Visibility = input.parse()?;
1156            let defaultness: Option<Token![default]> = match allow_defaultness {
1157                TypeDefaultness::Optional => input.parse()?,
1158                TypeDefaultness::Disallowed => None,
1159            };
1160            let type_token: Token![type] = input.parse()?;
1161            let ident: Ident = input.parse()?;
1162            let mut generics: Generics = input.parse()?;
1163            let (colon_token, bounds) = Self::parse_optional_bounds(input)?;
1164
1165            match where_clause_location {
1166                WhereClauseLocation::BeforeEq | WhereClauseLocation::Both => {
1167                    generics.where_clause = input.parse()?;
1168                }
1169                WhereClauseLocation::AfterEq => {}
1170            }
1171
1172            let ty = Self::parse_optional_definition(input)?;
1173
1174            match where_clause_location {
1175                WhereClauseLocation::AfterEq | WhereClauseLocation::Both
1176                    if generics.where_clause.is_none() =>
1177                {
1178                    generics.where_clause = input.parse()?;
1179                }
1180                _ => {}
1181            }
1182
1183            let semi_token: Token![;] = input.parse()?;
1184
1185            Ok(FlexibleItemType {
1186                vis,
1187                defaultness,
1188                type_token,
1189                ident,
1190                generics,
1191                colon_token,
1192                bounds,
1193                ty,
1194                semi_token,
1195            })
1196        }
1197
1198        fn parse_optional_bounds(
1199            input: ParseStream,
1200        ) -> Result<(Option<Token![:]>, Punctuated<TypeParamBound, Token![+]>)> {
1201            let colon_token: Option<Token![:]> = input.parse()?;
1202
1203            let mut bounds = Punctuated::new();
1204            if colon_token.is_some() {
1205                loop {
1206                    if input.peek(Token![where]) || input.peek(Token![=]) || input.peek(Token![;]) {
1207                        break;
1208                    }
1209                    bounds.push_value({
1210                        let allow_precise_capture = false;
1211                        let allow_tilde_const = true;
1212                        TypeParamBound::parse_single(
1213                            input,
1214                            allow_precise_capture,
1215                            allow_tilde_const,
1216                        )?
1217                    });
1218                    if input.peek(Token![where]) || input.peek(Token![=]) || input.peek(Token![;]) {
1219                        break;
1220                    }
1221                    bounds.push_punct(input.parse::<Token![+]>()?);
1222                }
1223            }
1224
1225            Ok((colon_token, bounds))
1226        }
1227
1228        fn parse_optional_definition(input: ParseStream) -> Result<Option<(Token![=], Type)>> {
1229            let eq_token: Option<Token![=]> = input.parse()?;
1230            if let Some(eq_token) = eq_token {
1231                let definition: Type = input.parse()?;
1232                Ok(Some((eq_token, definition)))
1233            } else {
1234                Ok(None)
1235            }
1236        }
1237    }
1238
1239    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1240    impl Parse for ItemMacro {
1241        fn parse(input: ParseStream) -> Result<Self> {
1242            let attrs = input.call(Attribute::parse_outer)?;
1243            let path = input.call(Path::parse_mod_style)?;
1244            let bang_token: Token![!] = input.parse()?;
1245            let ident: Option<Ident> = if input.peek(Token![try]) {
1246                input.call(Ident::parse_any).map(Some)
1247            } else {
1248                input.parse()
1249            }?;
1250            let (delimiter, tokens) = input.call(mac::parse_delimiter)?;
1251            let semi_token: Option<Token![;]> = if !delimiter.is_brace() {
1252                Some(input.parse()?)
1253            } else {
1254                None
1255            };
1256            Ok(ItemMacro {
1257                attrs,
1258                ident,
1259                mac: Macro {
1260                    path,
1261                    bang_token,
1262                    delimiter,
1263                    tokens,
1264                },
1265                semi_token,
1266            })
1267        }
1268    }
1269
1270    fn parse_macro2(begin: ParseBuffer, _vis: Visibility, input: ParseStream) -> Result<Item> {
1271        input.parse::<Token![macro]>()?;
1272        input.parse::<Ident>()?;
1273
1274        let mut lookahead = input.lookahead1();
1275        if lookahead.peek(token::Paren) {
1276            let paren_content;
1277            parenthesized!(paren_content in input);
1278            paren_content.parse::<TokenStream>()?;
1279            lookahead = input.lookahead1();
1280        }
1281
1282        if lookahead.peek(token::Brace) {
1283            let brace_content;
1284            braced!(brace_content in input);
1285            brace_content.parse::<TokenStream>()?;
1286        } else {
1287            return Err(lookahead.error());
1288        }
1289
1290        Ok(Item::Verbatim(verbatim::between(&begin, input)))
1291    }
1292
1293    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1294    impl Parse for ItemExternCrate {
1295        fn parse(input: ParseStream) -> Result<Self> {
1296            Ok(ItemExternCrate {
1297                attrs: input.call(Attribute::parse_outer)?,
1298                vis: input.parse()?,
1299                extern_token: input.parse()?,
1300                crate_token: input.parse()?,
1301                ident: {
1302                    if input.peek(Token![self]) {
1303                        input.call(Ident::parse_any)?
1304                    } else {
1305                        input.parse()?
1306                    }
1307                },
1308                rename: {
1309                    if input.peek(Token![as]) {
1310                        let as_token: Token![as] = input.parse()?;
1311                        let rename: Ident = if input.peek(Token![_]) {
1312                            Ident::from(input.parse::<Token![_]>()?)
1313                        } else {
1314                            input.parse()?
1315                        };
1316                        Some((as_token, rename))
1317                    } else {
1318                        None
1319                    }
1320                },
1321                semi_token: input.parse()?,
1322            })
1323        }
1324    }
1325
1326    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1327    impl Parse for ItemUse {
1328        fn parse(input: ParseStream) -> Result<Self> {
1329            let allow_crate_root_in_path = false;
1330            parse_item_use(input, allow_crate_root_in_path).map(Option::unwrap)
1331        }
1332    }
1333
1334    fn parse_item_use(
1335        input: ParseStream,
1336        allow_crate_root_in_path: bool,
1337    ) -> Result<Option<ItemUse>> {
1338        let attrs = input.call(Attribute::parse_outer)?;
1339        let vis: Visibility = input.parse()?;
1340        let use_token: Token![use] = input.parse()?;
1341        let leading_colon: Option<Token![::]> = input.parse()?;
1342        let tree = parse_use_tree(input, allow_crate_root_in_path && leading_colon.is_none())?;
1343        let semi_token: Token![;] = input.parse()?;
1344
1345        let tree = match tree {
1346            Some(tree) => tree,
1347            None => return Ok(None),
1348        };
1349
1350        Ok(Some(ItemUse {
1351            attrs,
1352            vis,
1353            use_token,
1354            leading_colon,
1355            tree,
1356            semi_token,
1357        }))
1358    }
1359
1360    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1361    impl Parse for UseTree {
1362        fn parse(input: ParseStream) -> Result<UseTree> {
1363            let allow_crate_root_in_path = false;
1364            parse_use_tree(input, allow_crate_root_in_path).map(Option::unwrap)
1365        }
1366    }
1367
1368    fn parse_use_tree(
1369        input: ParseStream,
1370        allow_crate_root_in_path: bool,
1371    ) -> Result<Option<UseTree>> {
1372        let lookahead = input.lookahead1();
1373        if lookahead.peek(Ident)
1374            || lookahead.peek(Token![self])
1375            || lookahead.peek(Token![super])
1376            || lookahead.peek(Token![crate])
1377            || lookahead.peek(Token![try])
1378        {
1379            let ident = input.call(Ident::parse_any)?;
1380            if input.peek(Token![::]) {
1381                Ok(Some(UseTree::Path(UsePath {
1382                    ident,
1383                    colon2_token: input.parse()?,
1384                    tree: Box::new(input.parse()?),
1385                })))
1386            } else if input.peek(Token![as]) {
1387                Ok(Some(UseTree::Rename(UseRename {
1388                    ident,
1389                    as_token: input.parse()?,
1390                    rename: {
1391                        if input.peek(Ident) {
1392                            input.parse()?
1393                        } else if input.peek(Token![_]) {
1394                            Ident::from(input.parse::<Token![_]>()?)
1395                        } else {
1396                            return Err(input.error("expected identifier or underscore"));
1397                        }
1398                    },
1399                })))
1400            } else {
1401                Ok(Some(UseTree::Name(UseName { ident })))
1402            }
1403        } else if lookahead.peek(Token![*]) {
1404            Ok(Some(UseTree::Glob(UseGlob {
1405                star_token: input.parse()?,
1406            })))
1407        } else if lookahead.peek(token::Brace) {
1408            let content;
1409            let brace_token = braced!(content in input);
1410            let mut items = Punctuated::new();
1411            let mut has_any_crate_root_in_path = false;
1412            loop {
1413                if content.is_empty() {
1414                    break;
1415                }
1416                let this_tree_starts_with_crate_root =
1417                    allow_crate_root_in_path && content.parse::<Option<Token![::]>>()?.is_some();
1418                has_any_crate_root_in_path |= this_tree_starts_with_crate_root;
1419                match parse_use_tree(
1420                    &content,
1421                    allow_crate_root_in_path && !this_tree_starts_with_crate_root,
1422                )? {
1423                    Some(tree) if !has_any_crate_root_in_path => items.push_value(tree),
1424                    _ => has_any_crate_root_in_path = true,
1425                }
1426                if content.is_empty() {
1427                    break;
1428                }
1429                let comma: Token![,] = content.parse()?;
1430                if !has_any_crate_root_in_path {
1431                    items.push_punct(comma);
1432                }
1433            }
1434            if has_any_crate_root_in_path {
1435                Ok(None)
1436            } else {
1437                Ok(Some(UseTree::Group(UseGroup { brace_token, items })))
1438            }
1439        } else {
1440            Err(lookahead.error())
1441        }
1442    }
1443
1444    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1445    impl Parse for ItemStatic {
1446        fn parse(input: ParseStream) -> Result<Self> {
1447            Ok(ItemStatic {
1448                attrs: input.call(Attribute::parse_outer)?,
1449                vis: input.parse()?,
1450                static_token: input.parse()?,
1451                mutability: input.parse()?,
1452                ident: input.parse()?,
1453                colon_token: input.parse()?,
1454                ty: input.parse()?,
1455                eq_token: input.parse()?,
1456                expr: input.parse()?,
1457                semi_token: input.parse()?,
1458            })
1459        }
1460    }
1461
1462    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1463    impl Parse for ItemConst {
1464        fn parse(input: ParseStream) -> Result<Self> {
1465            let attrs = input.call(Attribute::parse_outer)?;
1466            let vis: Visibility = input.parse()?;
1467            let const_token: Token![const] = input.parse()?;
1468
1469            let lookahead = input.lookahead1();
1470            let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
1471                input.call(Ident::parse_any)?
1472            } else {
1473                return Err(lookahead.error());
1474            };
1475
1476            let colon_token: Token![:] = input.parse()?;
1477            let ty: Type = input.parse()?;
1478            let eq_token: Token![=] = input.parse()?;
1479            let expr: Expr = input.parse()?;
1480            let semi_token: Token![;] = input.parse()?;
1481
1482            Ok(ItemConst {
1483                attrs,
1484                vis,
1485                const_token,
1486                ident,
1487                generics: Generics::default(),
1488                colon_token,
1489                ty: Box::new(ty),
1490                eq_token,
1491                expr: Box::new(expr),
1492                semi_token,
1493            })
1494        }
1495    }
1496
1497    fn peek_signature(input: ParseStream, allow_safe: bool) -> bool {
1498        let fork = input.fork();
1499        fork.parse::<Option<Token![const]>>().is_ok()
1500            && fork.parse::<Option<Token![async]>>().is_ok()
1501            && ((allow_safe
1502                && token::parsing::peek_keyword(fork.cursor(), "safe")
1503                && token::parsing::keyword(&fork, "safe").is_ok())
1504                || fork.parse::<Option<Token![unsafe]>>().is_ok())
1505            && fork.parse::<Option<Abi>>().is_ok()
1506            && fork.peek(Token![fn])
1507    }
1508
1509    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1510    impl Parse for Signature {
1511        fn parse(input: ParseStream) -> Result<Self> {
1512            let allow_safe = false;
1513            parse_signature(input, allow_safe).map(Option::unwrap)
1514        }
1515    }
1516
1517    fn parse_signature(input: ParseStream, allow_safe: bool) -> Result<Option<Signature>> {
1518        let constness: Option<Token![const]> = input.parse()?;
1519        let asyncness: Option<Token![async]> = input.parse()?;
1520        let unsafety: Option<Token![unsafe]> = input.parse()?;
1521        let safe = allow_safe
1522            && unsafety.is_none()
1523            && token::parsing::peek_keyword(input.cursor(), "safe");
1524        if safe {
1525            token::parsing::keyword(input, "safe")?;
1526        }
1527        let abi: Option<Abi> = input.parse()?;
1528        let fn_token: Token![fn] = input.parse()?;
1529        let ident: Ident = input.parse()?;
1530        let mut generics: Generics = input.parse()?;
1531
1532        let content;
1533        let paren_token = parenthesized!(content in input);
1534        let (inputs, variadic) = parse_fn_args(&content)?;
1535
1536        let output: ReturnType = input.parse()?;
1537        generics.where_clause = input.parse()?;
1538
1539        Ok(if safe {
1540            None
1541        } else {
1542            Some(Signature {
1543                constness,
1544                asyncness,
1545                unsafety,
1546                abi,
1547                fn_token,
1548                ident,
1549                generics,
1550                paren_token,
1551                inputs,
1552                variadic,
1553                output,
1554            })
1555        })
1556    }
1557
1558    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1559    impl Parse for ItemFn {
1560        fn parse(input: ParseStream) -> Result<Self> {
1561            let outer_attrs = input.call(Attribute::parse_outer)?;
1562            let vis: Visibility = input.parse()?;
1563            let sig: Signature = input.parse()?;
1564            parse_rest_of_fn(input, outer_attrs, vis, sig)
1565        }
1566    }
1567
1568    fn parse_rest_of_fn(
1569        input: ParseStream,
1570        mut attrs: Vec<Attribute>,
1571        vis: Visibility,
1572        sig: Signature,
1573    ) -> Result<ItemFn> {
1574        let content;
1575        let brace_token = braced!(content in input);
1576        attr::parsing::parse_inner(&content, &mut attrs)?;
1577        let stmts = content.call(Block::parse_within)?;
1578
1579        Ok(ItemFn {
1580            attrs,
1581            vis,
1582            sig,
1583            block: Box::new(Block { brace_token, stmts }),
1584        })
1585    }
1586
1587    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1588    impl Parse for FnArg {
1589        fn parse(input: ParseStream) -> Result<Self> {
1590            let allow_variadic = false;
1591            let attrs = input.call(Attribute::parse_outer)?;
1592            match parse_fn_arg_or_variadic(input, attrs, allow_variadic)? {
1593                FnArgOrVariadic::FnArg(arg) => Ok(arg),
1594                FnArgOrVariadic::Variadic(_) => unreachable!(),
1595            }
1596        }
1597    }
1598
1599    enum FnArgOrVariadic {
1600        FnArg(FnArg),
1601        Variadic(Variadic),
1602    }
1603
1604    fn parse_fn_arg_or_variadic(
1605        input: ParseStream,
1606        attrs: Vec<Attribute>,
1607        allow_variadic: bool,
1608    ) -> Result<FnArgOrVariadic> {
1609        let ahead = input.fork();
1610        if let Ok(mut receiver) = ahead.parse::<Receiver>() {
1611            input.advance_to(&ahead);
1612            receiver.attrs = attrs;
1613            return Ok(FnArgOrVariadic::FnArg(FnArg::Receiver(receiver)));
1614        }
1615
1616        // Hack to parse pre-2018 syntax in
1617        // test/ui/rfc-2565-param-attrs/param-attrs-pretty.rs
1618        // because the rest of the test case is valuable.
1619        if input.peek(Ident) && input.peek2(Token![<]) {
1620            let span = input.fork().parse::<Ident>()?.span();
1621            return Ok(FnArgOrVariadic::FnArg(FnArg::Typed(PatType {
1622                attrs,
1623                pat: Box::new(Pat::Wild(PatWild {
1624                    attrs: Vec::new(),
1625                    underscore_token: Token![_](span),
1626                })),
1627                colon_token: Token![:](span),
1628                ty: input.parse()?,
1629            })));
1630        }
1631
1632        let pat = Box::new(Pat::parse_single(input)?);
1633        let colon_token: Token![:] = input.parse()?;
1634
1635        if allow_variadic {
1636            if let Some(dots) = input.parse::<Option<Token![...]>>()? {
1637                return Ok(FnArgOrVariadic::Variadic(Variadic {
1638                    attrs,
1639                    pat: Some((pat, colon_token)),
1640                    dots,
1641                    comma: None,
1642                }));
1643            }
1644        }
1645
1646        Ok(FnArgOrVariadic::FnArg(FnArg::Typed(PatType {
1647            attrs,
1648            pat,
1649            colon_token,
1650            ty: input.parse()?,
1651        })))
1652    }
1653
1654    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1655    impl Parse for Receiver {
1656        fn parse(input: ParseStream) -> Result<Self> {
1657            let reference = if input.peek(Token![&]) {
1658                let ampersand: Token![&] = input.parse()?;
1659                let lifetime: Option<Lifetime> = input.parse()?;
1660                Some((ampersand, lifetime))
1661            } else {
1662                None
1663            };
1664            let mutability: Option<Token![mut]> = input.parse()?;
1665            let self_token: Token![self] = input.parse()?;
1666            let colon_token: Option<Token![:]> = if reference.is_some() {
1667                None
1668            } else {
1669                input.parse()?
1670            };
1671            let ty: Type = if colon_token.is_some() {
1672                input.parse()?
1673            } else {
1674                let mut ty = Type::Path(TypePath {
1675                    qself: None,
1676                    path: Path::from(Ident::new("Self", self_token.span)),
1677                });
1678                if let Some((ampersand, lifetime)) = reference.as_ref() {
1679                    ty = Type::Reference(TypeReference {
1680                        and_token: Token![&](ampersand.span),
1681                        lifetime: lifetime.clone(),
1682                        mutability: mutability.as_ref().map(|m| Token![mut](m.span)),
1683                        elem: Box::new(ty),
1684                    });
1685                }
1686                ty
1687            };
1688            Ok(Receiver {
1689                attrs: Vec::new(),
1690                reference,
1691                mutability,
1692                self_token,
1693                colon_token,
1694                ty: Box::new(ty),
1695            })
1696        }
1697    }
1698
1699    fn parse_fn_args(
1700        input: ParseStream,
1701    ) -> Result<(Punctuated<FnArg, Token![,]>, Option<Variadic>)> {
1702        let mut args = Punctuated::new();
1703        let mut variadic = None;
1704        let mut has_receiver = false;
1705
1706        while !input.is_empty() {
1707            let attrs = input.call(Attribute::parse_outer)?;
1708
1709            if let Some(dots) = input.parse::<Option<Token![...]>>()? {
1710                variadic = Some(Variadic {
1711                    attrs,
1712                    pat: None,
1713                    dots,
1714                    comma: if input.is_empty() {
1715                        None
1716                    } else {
1717                        Some(input.parse()?)
1718                    },
1719                });
1720                break;
1721            }
1722
1723            let allow_variadic = true;
1724            let arg = match parse_fn_arg_or_variadic(input, attrs, allow_variadic)? {
1725                FnArgOrVariadic::FnArg(arg) => arg,
1726                FnArgOrVariadic::Variadic(arg) => {
1727                    variadic = Some(Variadic {
1728                        comma: if input.is_empty() {
1729                            None
1730                        } else {
1731                            Some(input.parse()?)
1732                        },
1733                        ..arg
1734                    });
1735                    break;
1736                }
1737            };
1738
1739            match &arg {
1740                FnArg::Receiver(receiver) if has_receiver => {
1741                    return Err(Error::new(
1742                        receiver.self_token.span,
1743                        "unexpected second method receiver",
1744                    ));
1745                }
1746                FnArg::Receiver(receiver) if !args.is_empty() => {
1747                    return Err(Error::new(
1748                        receiver.self_token.span,
1749                        "unexpected method receiver",
1750                    ));
1751                }
1752                FnArg::Receiver(_) => has_receiver = true,
1753                FnArg::Typed(_) => {}
1754            }
1755            args.push_value(arg);
1756
1757            if input.is_empty() {
1758                break;
1759            }
1760
1761            let comma: Token![,] = input.parse()?;
1762            args.push_punct(comma);
1763        }
1764
1765        Ok((args, variadic))
1766    }
1767
1768    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1769    impl Parse for ItemMod {
1770        fn parse(input: ParseStream) -> Result<Self> {
1771            let mut attrs = input.call(Attribute::parse_outer)?;
1772            let vis: Visibility = input.parse()?;
1773            let unsafety: Option<Token![unsafe]> = input.parse()?;
1774            let mod_token: Token![mod] = input.parse()?;
1775            let ident: Ident = if input.peek(Token![try]) {
1776                input.call(Ident::parse_any)
1777            } else {
1778                input.parse()
1779            }?;
1780
1781            let lookahead = input.lookahead1();
1782            if lookahead.peek(Token![;]) {
1783                Ok(ItemMod {
1784                    attrs,
1785                    vis,
1786                    unsafety,
1787                    mod_token,
1788                    ident,
1789                    content: None,
1790                    semi: Some(input.parse()?),
1791                })
1792            } else if lookahead.peek(token::Brace) {
1793                let content;
1794                let brace_token = braced!(content in input);
1795                attr::parsing::parse_inner(&content, &mut attrs)?;
1796
1797                let mut items = Vec::new();
1798                while !content.is_empty() {
1799                    items.push(content.parse()?);
1800                }
1801
1802                Ok(ItemMod {
1803                    attrs,
1804                    vis,
1805                    unsafety,
1806                    mod_token,
1807                    ident,
1808                    content: Some((brace_token, items)),
1809                    semi: None,
1810                })
1811            } else {
1812                Err(lookahead.error())
1813            }
1814        }
1815    }
1816
1817    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1818    impl Parse for ItemForeignMod {
1819        fn parse(input: ParseStream) -> Result<Self> {
1820            let mut attrs = input.call(Attribute::parse_outer)?;
1821            let unsafety: Option<Token![unsafe]> = input.parse()?;
1822            let abi: Abi = input.parse()?;
1823
1824            let content;
1825            let brace_token = braced!(content in input);
1826            attr::parsing::parse_inner(&content, &mut attrs)?;
1827            let mut items = Vec::new();
1828            while !content.is_empty() {
1829                items.push(content.parse()?);
1830            }
1831
1832            Ok(ItemForeignMod {
1833                attrs,
1834                unsafety,
1835                abi,
1836                brace_token,
1837                items,
1838            })
1839        }
1840    }
1841
1842    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1843    impl Parse for ForeignItem {
1844        fn parse(input: ParseStream) -> Result<Self> {
1845            let begin = input.fork();
1846            let mut attrs = input.call(Attribute::parse_outer)?;
1847            let ahead = input.fork();
1848            let vis: Visibility = ahead.parse()?;
1849
1850            let lookahead = ahead.lookahead1();
1851            let allow_safe = true;
1852            let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead, allow_safe) {
1853                let vis: Visibility = input.parse()?;
1854                let sig = parse_signature(input, allow_safe)?;
1855                let has_safe = sig.is_none();
1856                let has_body = input.peek(token::Brace);
1857                let semi_token: Option<Token![;]> = if has_body {
1858                    let content;
1859                    braced!(content in input);
1860                    content.call(Attribute::parse_inner)?;
1861                    content.call(Block::parse_within)?;
1862                    None
1863                } else {
1864                    Some(input.parse()?)
1865                };
1866                if has_safe || has_body {
1867                    Ok(ForeignItem::Verbatim(verbatim::between(&begin, input)))
1868                } else {
1869                    Ok(ForeignItem::Fn(ForeignItemFn {
1870                        attrs: Vec::new(),
1871                        vis,
1872                        sig: sig.unwrap(),
1873                        semi_token: semi_token.unwrap(),
1874                    }))
1875                }
1876            } else if lookahead.peek(Token![static])
1877                || ((ahead.peek(Token![unsafe])
1878                    || token::parsing::peek_keyword(ahead.cursor(), "safe"))
1879                    && ahead.peek2(Token![static]))
1880            {
1881                let vis = input.parse()?;
1882                let unsafety: Option<Token![unsafe]> = input.parse()?;
1883                let safe =
1884                    unsafety.is_none() && token::parsing::peek_keyword(input.cursor(), "safe");
1885                if safe {
1886                    token::parsing::keyword(input, "safe")?;
1887                }
1888                let static_token = input.parse()?;
1889                let mutability = input.parse()?;
1890                let ident = input.parse()?;
1891                let colon_token = input.parse()?;
1892                let ty = input.parse()?;
1893                let has_value = input.peek(Token![=]);
1894                if has_value {
1895                    input.parse::<Token![=]>()?;
1896                    input.parse::<Expr>()?;
1897                }
1898                let semi_token: Token![;] = input.parse()?;
1899                if unsafety.is_some() || safe || has_value {
1900                    Ok(ForeignItem::Verbatim(verbatim::between(&begin, input)))
1901                } else {
1902                    Ok(ForeignItem::Static(ForeignItemStatic {
1903                        attrs: Vec::new(),
1904                        vis,
1905                        static_token,
1906                        mutability,
1907                        ident,
1908                        colon_token,
1909                        ty,
1910                        semi_token,
1911                    }))
1912                }
1913            } else if lookahead.peek(Token![type]) {
1914                parse_foreign_item_type(begin, input)
1915            } else if vis.is_inherited()
1916                && (lookahead.peek(Ident)
1917                    || lookahead.peek(Token![self])
1918                    || lookahead.peek(Token![super])
1919                    || lookahead.peek(Token![crate])
1920                    || lookahead.peek(Token![::]))
1921            {
1922                input.parse().map(ForeignItem::Macro)
1923            } else {
1924                Err(lookahead.error())
1925            }?;
1926
1927            let item_attrs = match &mut item {
1928                ForeignItem::Fn(item) => &mut item.attrs,
1929                ForeignItem::Static(item) => &mut item.attrs,
1930                ForeignItem::Type(item) => &mut item.attrs,
1931                ForeignItem::Macro(item) => &mut item.attrs,
1932                ForeignItem::Verbatim(_) => return Ok(item),
1933            };
1934            attrs.append(item_attrs);
1935            *item_attrs = attrs;
1936
1937            Ok(item)
1938        }
1939    }
1940
1941    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1942    impl Parse for ForeignItemFn {
1943        fn parse(input: ParseStream) -> Result<Self> {
1944            let attrs = input.call(Attribute::parse_outer)?;
1945            let vis: Visibility = input.parse()?;
1946            let sig: Signature = input.parse()?;
1947            let semi_token: Token![;] = input.parse()?;
1948            Ok(ForeignItemFn {
1949                attrs,
1950                vis,
1951                sig,
1952                semi_token,
1953            })
1954        }
1955    }
1956
1957    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1958    impl Parse for ForeignItemStatic {
1959        fn parse(input: ParseStream) -> Result<Self> {
1960            Ok(ForeignItemStatic {
1961                attrs: input.call(Attribute::parse_outer)?,
1962                vis: input.parse()?,
1963                static_token: input.parse()?,
1964                mutability: input.parse()?,
1965                ident: input.parse()?,
1966                colon_token: input.parse()?,
1967                ty: input.parse()?,
1968                semi_token: input.parse()?,
1969            })
1970        }
1971    }
1972
1973    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1974    impl Parse for ForeignItemType {
1975        fn parse(input: ParseStream) -> Result<Self> {
1976            Ok(ForeignItemType {
1977                attrs: input.call(Attribute::parse_outer)?,
1978                vis: input.parse()?,
1979                type_token: input.parse()?,
1980                ident: input.parse()?,
1981                generics: {
1982                    let mut generics: Generics = input.parse()?;
1983                    generics.where_clause = input.parse()?;
1984                    generics
1985                },
1986                semi_token: input.parse()?,
1987            })
1988        }
1989    }
1990
1991    fn parse_foreign_item_type(begin: ParseBuffer, input: ParseStream) -> Result<ForeignItem> {
1992        let FlexibleItemType {
1993            vis,
1994            defaultness: _,
1995            type_token,
1996            ident,
1997            generics,
1998            colon_token,
1999            bounds: _,
2000            ty,
2001            semi_token,
2002        } = FlexibleItemType::parse(
2003            input,
2004            TypeDefaultness::Disallowed,
2005            WhereClauseLocation::Both,
2006        )?;
2007
2008        if colon_token.is_some() || ty.is_some() {
2009            Ok(ForeignItem::Verbatim(verbatim::between(&begin, input)))
2010        } else {
2011            Ok(ForeignItem::Type(ForeignItemType {
2012                attrs: Vec::new(),
2013                vis,
2014                type_token,
2015                ident,
2016                generics,
2017                semi_token,
2018            }))
2019        }
2020    }
2021
2022    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2023    impl Parse for ForeignItemMacro {
2024        fn parse(input: ParseStream) -> Result<Self> {
2025            let attrs = input.call(Attribute::parse_outer)?;
2026            let mac: Macro = input.parse()?;
2027            let semi_token: Option<Token![;]> = if mac.delimiter.is_brace() {
2028                None
2029            } else {
2030                Some(input.parse()?)
2031            };
2032            Ok(ForeignItemMacro {
2033                attrs,
2034                mac,
2035                semi_token,
2036            })
2037        }
2038    }
2039
2040    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2041    impl Parse for ItemType {
2042        fn parse(input: ParseStream) -> Result<Self> {
2043            Ok(ItemType {
2044                attrs: input.call(Attribute::parse_outer)?,
2045                vis: input.parse()?,
2046                type_token: input.parse()?,
2047                ident: input.parse()?,
2048                generics: {
2049                    let mut generics: Generics = input.parse()?;
2050                    generics.where_clause = input.parse()?;
2051                    generics
2052                },
2053                eq_token: input.parse()?,
2054                ty: input.parse()?,
2055                semi_token: input.parse()?,
2056            })
2057        }
2058    }
2059
2060    fn parse_item_type(begin: ParseBuffer, input: ParseStream) -> Result<Item> {
2061        let FlexibleItemType {
2062            vis,
2063            defaultness: _,
2064            type_token,
2065            ident,
2066            generics,
2067            colon_token,
2068            bounds: _,
2069            ty,
2070            semi_token,
2071        } = FlexibleItemType::parse(
2072            input,
2073            TypeDefaultness::Disallowed,
2074            WhereClauseLocation::BeforeEq,
2075        )?;
2076
2077        let (eq_token, ty) = match ty {
2078            Some(ty) if colon_token.is_none() => ty,
2079            _ => return Ok(Item::Verbatim(verbatim::between(&begin, input))),
2080        };
2081
2082        Ok(Item::Type(ItemType {
2083            attrs: Vec::new(),
2084            vis,
2085            type_token,
2086            ident,
2087            generics,
2088            eq_token,
2089            ty: Box::new(ty),
2090            semi_token,
2091        }))
2092    }
2093
2094    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2095    impl Parse for ItemStruct {
2096        fn parse(input: ParseStream) -> Result<Self> {
2097            let attrs = input.call(Attribute::parse_outer)?;
2098            let vis = input.parse::<Visibility>()?;
2099            let struct_token = input.parse::<Token![struct]>()?;
2100            let ident = input.parse::<Ident>()?;
2101            let generics = input.parse::<Generics>()?;
2102            let (where_clause, fields, semi_token) = derive::parsing::data_struct(input)?;
2103            Ok(ItemStruct {
2104                attrs,
2105                vis,
2106                struct_token,
2107                ident,
2108                generics: Generics {
2109                    where_clause,
2110                    ..generics
2111                },
2112                fields,
2113                semi_token,
2114            })
2115        }
2116    }
2117
2118    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2119    impl Parse for ItemEnum {
2120        fn parse(input: ParseStream) -> Result<Self> {
2121            let attrs = input.call(Attribute::parse_outer)?;
2122            let vis = input.parse::<Visibility>()?;
2123            let enum_token = input.parse::<Token![enum]>()?;
2124            let ident = input.parse::<Ident>()?;
2125            let generics = input.parse::<Generics>()?;
2126            let (where_clause, brace_token, variants) = derive::parsing::data_enum(input)?;
2127            Ok(ItemEnum {
2128                attrs,
2129                vis,
2130                enum_token,
2131                ident,
2132                generics: Generics {
2133                    where_clause,
2134                    ..generics
2135                },
2136                brace_token,
2137                variants,
2138            })
2139        }
2140    }
2141
2142    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2143    impl Parse for ItemUnion {
2144        fn parse(input: ParseStream) -> Result<Self> {
2145            let attrs = input.call(Attribute::parse_outer)?;
2146            let vis = input.parse::<Visibility>()?;
2147            let union_token = input.parse::<Token![union]>()?;
2148            let ident = input.parse::<Ident>()?;
2149            let generics = input.parse::<Generics>()?;
2150            let (where_clause, fields) = derive::parsing::data_union(input)?;
2151            Ok(ItemUnion {
2152                attrs,
2153                vis,
2154                union_token,
2155                ident,
2156                generics: Generics {
2157                    where_clause,
2158                    ..generics
2159                },
2160                fields,
2161            })
2162        }
2163    }
2164
2165    fn parse_trait_or_trait_alias(input: ParseStream) -> Result<Item> {
2166        let (attrs, vis, trait_token, ident, generics) = parse_start_of_trait_alias(input)?;
2167        let lookahead = input.lookahead1();
2168        if lookahead.peek(token::Brace)
2169            || lookahead.peek(Token![:])
2170            || lookahead.peek(Token![where])
2171        {
2172            let unsafety = None;
2173            let auto_token = None;
2174            parse_rest_of_trait(
2175                input,
2176                attrs,
2177                vis,
2178                unsafety,
2179                auto_token,
2180                trait_token,
2181                ident,
2182                generics,
2183            )
2184            .map(Item::Trait)
2185        } else if lookahead.peek(Token![=]) {
2186            parse_rest_of_trait_alias(input, attrs, vis, trait_token, ident, generics)
2187                .map(Item::TraitAlias)
2188        } else {
2189            Err(lookahead.error())
2190        }
2191    }
2192
2193    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2194    impl Parse for ItemTrait {
2195        fn parse(input: ParseStream) -> Result<Self> {
2196            let outer_attrs = input.call(Attribute::parse_outer)?;
2197            let vis: Visibility = input.parse()?;
2198            let unsafety: Option<Token![unsafe]> = input.parse()?;
2199            let auto_token: Option<Token![auto]> = input.parse()?;
2200            let trait_token: Token![trait] = input.parse()?;
2201            let ident: Ident = input.parse()?;
2202            let generics: Generics = input.parse()?;
2203            parse_rest_of_trait(
2204                input,
2205                outer_attrs,
2206                vis,
2207                unsafety,
2208                auto_token,
2209                trait_token,
2210                ident,
2211                generics,
2212            )
2213        }
2214    }
2215
2216    fn parse_rest_of_trait(
2217        input: ParseStream,
2218        mut attrs: Vec<Attribute>,
2219        vis: Visibility,
2220        unsafety: Option<Token![unsafe]>,
2221        auto_token: Option<Token![auto]>,
2222        trait_token: Token![trait],
2223        ident: Ident,
2224        mut generics: Generics,
2225    ) -> Result<ItemTrait> {
2226        let colon_token: Option<Token![:]> = input.parse()?;
2227
2228        let mut supertraits = Punctuated::new();
2229        if colon_token.is_some() {
2230            loop {
2231                if input.peek(Token![where]) || input.peek(token::Brace) {
2232                    break;
2233                }
2234                supertraits.push_value({
2235                    let allow_precise_capture = false;
2236                    let allow_tilde_const = true;
2237                    TypeParamBound::parse_single(input, allow_precise_capture, allow_tilde_const)?
2238                });
2239                if input.peek(Token![where]) || input.peek(token::Brace) {
2240                    break;
2241                }
2242                supertraits.push_punct(input.parse()?);
2243            }
2244        }
2245
2246        generics.where_clause = input.parse()?;
2247
2248        let content;
2249        let brace_token = braced!(content in input);
2250        attr::parsing::parse_inner(&content, &mut attrs)?;
2251        let mut items = Vec::new();
2252        while !content.is_empty() {
2253            items.push(content.parse()?);
2254        }
2255
2256        Ok(ItemTrait {
2257            attrs,
2258            vis,
2259            unsafety,
2260            auto_token,
2261            restriction: None,
2262            trait_token,
2263            ident,
2264            generics,
2265            colon_token,
2266            supertraits,
2267            brace_token,
2268            items,
2269        })
2270    }
2271
2272    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2273    impl Parse for ItemTraitAlias {
2274        fn parse(input: ParseStream) -> Result<Self> {
2275            let (attrs, vis, trait_token, ident, generics) = parse_start_of_trait_alias(input)?;
2276            parse_rest_of_trait_alias(input, attrs, vis, trait_token, ident, generics)
2277        }
2278    }
2279
2280    fn parse_start_of_trait_alias(
2281        input: ParseStream,
2282    ) -> Result<(Vec<Attribute>, Visibility, Token![trait], Ident, Generics)> {
2283        let attrs = input.call(Attribute::parse_outer)?;
2284        let vis: Visibility = input.parse()?;
2285        let trait_token: Token![trait] = input.parse()?;
2286        let ident: Ident = input.parse()?;
2287        let generics: Generics = input.parse()?;
2288        Ok((attrs, vis, trait_token, ident, generics))
2289    }
2290
2291    fn parse_rest_of_trait_alias(
2292        input: ParseStream,
2293        attrs: Vec<Attribute>,
2294        vis: Visibility,
2295        trait_token: Token![trait],
2296        ident: Ident,
2297        mut generics: Generics,
2298    ) -> Result<ItemTraitAlias> {
2299        let eq_token: Token![=] = input.parse()?;
2300
2301        let mut bounds = Punctuated::new();
2302        loop {
2303            if input.peek(Token![where]) || input.peek(Token![;]) {
2304                break;
2305            }
2306            bounds.push_value({
2307                let allow_precise_capture = false;
2308                let allow_tilde_const = false;
2309                TypeParamBound::parse_single(input, allow_precise_capture, allow_tilde_const)?
2310            });
2311            if input.peek(Token![where]) || input.peek(Token![;]) {
2312                break;
2313            }
2314            bounds.push_punct(input.parse()?);
2315        }
2316
2317        generics.where_clause = input.parse()?;
2318        let semi_token: Token![;] = input.parse()?;
2319
2320        Ok(ItemTraitAlias {
2321            attrs,
2322            vis,
2323            trait_token,
2324            ident,
2325            generics,
2326            eq_token,
2327            bounds,
2328            semi_token,
2329        })
2330    }
2331
2332    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2333    impl Parse for TraitItem {
2334        fn parse(input: ParseStream) -> Result<Self> {
2335            let begin = input.fork();
2336            let mut attrs = input.call(Attribute::parse_outer)?;
2337            let vis: Visibility = input.parse()?;
2338            let defaultness: Option<Token![default]> = input.parse()?;
2339            let ahead = input.fork();
2340
2341            let lookahead = ahead.lookahead1();
2342            let allow_safe = false;
2343            let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead, allow_safe) {
2344                input.parse().map(TraitItem::Fn)
2345            } else if lookahead.peek(Token![const]) {
2346                let const_token: Token![const] = ahead.parse()?;
2347                let lookahead = ahead.lookahead1();
2348                if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
2349                    input.advance_to(&ahead);
2350                    let ident = input.call(Ident::parse_any)?;
2351                    let mut generics: Generics = input.parse()?;
2352                    let colon_token: Token![:] = input.parse()?;
2353                    let ty: Type = input.parse()?;
2354                    let default = if let Some(eq_token) = input.parse::<Option<Token![=]>>()? {
2355                        let expr: Expr = input.parse()?;
2356                        Some((eq_token, expr))
2357                    } else {
2358                        None
2359                    };
2360                    generics.where_clause = input.parse()?;
2361                    let semi_token: Token![;] = input.parse()?;
2362                    if generics.lt_token.is_none() && generics.where_clause.is_none() {
2363                        Ok(TraitItem::Const(TraitItemConst {
2364                            attrs: Vec::new(),
2365                            const_token,
2366                            ident,
2367                            generics,
2368                            colon_token,
2369                            ty,
2370                            default,
2371                            semi_token,
2372                        }))
2373                    } else {
2374                        return Ok(TraitItem::Verbatim(verbatim::between(&begin, input)));
2375                    }
2376                } else if lookahead.peek(Token![async])
2377                    || lookahead.peek(Token![unsafe])
2378                    || lookahead.peek(Token![extern])
2379                    || lookahead.peek(Token![fn])
2380                {
2381                    input.parse().map(TraitItem::Fn)
2382                } else {
2383                    Err(lookahead.error())
2384                }
2385            } else if lookahead.peek(Token![type]) {
2386                parse_trait_item_type(begin.fork(), input)
2387            } else if vis.is_inherited()
2388                && defaultness.is_none()
2389                && (lookahead.peek(Ident)
2390                    || lookahead.peek(Token![self])
2391                    || lookahead.peek(Token![super])
2392                    || lookahead.peek(Token![crate])
2393                    || lookahead.peek(Token![::]))
2394            {
2395                input.parse().map(TraitItem::Macro)
2396            } else {
2397                Err(lookahead.error())
2398            }?;
2399
2400            match (vis, defaultness) {
2401                (Visibility::Inherited, None) => {}
2402                _ => return Ok(TraitItem::Verbatim(verbatim::between(&begin, input))),
2403            }
2404
2405            let item_attrs = match &mut item {
2406                TraitItem::Const(item) => &mut item.attrs,
2407                TraitItem::Fn(item) => &mut item.attrs,
2408                TraitItem::Type(item) => &mut item.attrs,
2409                TraitItem::Macro(item) => &mut item.attrs,
2410                TraitItem::Verbatim(_) => unreachable!(),
2411            };
2412            attrs.append(item_attrs);
2413            *item_attrs = attrs;
2414            Ok(item)
2415        }
2416    }
2417
2418    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2419    impl Parse for TraitItemConst {
2420        fn parse(input: ParseStream) -> Result<Self> {
2421            let attrs = input.call(Attribute::parse_outer)?;
2422            let const_token: Token![const] = input.parse()?;
2423
2424            let lookahead = input.lookahead1();
2425            let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
2426                input.call(Ident::parse_any)?
2427            } else {
2428                return Err(lookahead.error());
2429            };
2430
2431            let colon_token: Token![:] = input.parse()?;
2432            let ty: Type = input.parse()?;
2433            let default = if input.peek(Token![=]) {
2434                let eq_token: Token![=] = input.parse()?;
2435                let default: Expr = input.parse()?;
2436                Some((eq_token, default))
2437            } else {
2438                None
2439            };
2440            let semi_token: Token![;] = input.parse()?;
2441
2442            Ok(TraitItemConst {
2443                attrs,
2444                const_token,
2445                ident,
2446                generics: Generics::default(),
2447                colon_token,
2448                ty,
2449                default,
2450                semi_token,
2451            })
2452        }
2453    }
2454
2455    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2456    impl Parse for TraitItemFn {
2457        fn parse(input: ParseStream) -> Result<Self> {
2458            let mut attrs = input.call(Attribute::parse_outer)?;
2459            let sig: Signature = input.parse()?;
2460
2461            let lookahead = input.lookahead1();
2462            let (brace_token, stmts, semi_token) = if lookahead.peek(token::Brace) {
2463                let content;
2464                let brace_token = braced!(content in input);
2465                attr::parsing::parse_inner(&content, &mut attrs)?;
2466                let stmts = content.call(Block::parse_within)?;
2467                (Some(brace_token), stmts, None)
2468            } else if lookahead.peek(Token![;]) {
2469                let semi_token: Token![;] = input.parse()?;
2470                (None, Vec::new(), Some(semi_token))
2471            } else {
2472                return Err(lookahead.error());
2473            };
2474
2475            Ok(TraitItemFn {
2476                attrs,
2477                sig,
2478                default: brace_token.map(|brace_token| Block { brace_token, stmts }),
2479                semi_token,
2480            })
2481        }
2482    }
2483
2484    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2485    impl Parse for TraitItemType {
2486        fn parse(input: ParseStream) -> Result<Self> {
2487            let attrs = input.call(Attribute::parse_outer)?;
2488            let type_token: Token![type] = input.parse()?;
2489            let ident: Ident = input.parse()?;
2490            let mut generics: Generics = input.parse()?;
2491            let (colon_token, bounds) = FlexibleItemType::parse_optional_bounds(input)?;
2492            let default = FlexibleItemType::parse_optional_definition(input)?;
2493            generics.where_clause = input.parse()?;
2494            let semi_token: Token![;] = input.parse()?;
2495            Ok(TraitItemType {
2496                attrs,
2497                type_token,
2498                ident,
2499                generics,
2500                colon_token,
2501                bounds,
2502                default,
2503                semi_token,
2504            })
2505        }
2506    }
2507
2508    fn parse_trait_item_type(begin: ParseBuffer, input: ParseStream) -> Result<TraitItem> {
2509        let FlexibleItemType {
2510            vis,
2511            defaultness: _,
2512            type_token,
2513            ident,
2514            generics,
2515            colon_token,
2516            bounds,
2517            ty,
2518            semi_token,
2519        } = FlexibleItemType::parse(
2520            input,
2521            TypeDefaultness::Disallowed,
2522            WhereClauseLocation::AfterEq,
2523        )?;
2524
2525        if vis.is_some() {
2526            Ok(TraitItem::Verbatim(verbatim::between(&begin, input)))
2527        } else {
2528            Ok(TraitItem::Type(TraitItemType {
2529                attrs: Vec::new(),
2530                type_token,
2531                ident,
2532                generics,
2533                colon_token,
2534                bounds,
2535                default: ty,
2536                semi_token,
2537            }))
2538        }
2539    }
2540
2541    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2542    impl Parse for TraitItemMacro {
2543        fn parse(input: ParseStream) -> Result<Self> {
2544            let attrs = input.call(Attribute::parse_outer)?;
2545            let mac: Macro = input.parse()?;
2546            let semi_token: Option<Token![;]> = if mac.delimiter.is_brace() {
2547                None
2548            } else {
2549                Some(input.parse()?)
2550            };
2551            Ok(TraitItemMacro {
2552                attrs,
2553                mac,
2554                semi_token,
2555            })
2556        }
2557    }
2558
2559    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2560    impl Parse for ItemImpl {
2561        fn parse(input: ParseStream) -> Result<Self> {
2562            let allow_verbatim_impl = false;
2563            parse_impl(input, allow_verbatim_impl).map(Option::unwrap)
2564        }
2565    }
2566
2567    fn parse_impl(input: ParseStream, allow_verbatim_impl: bool) -> Result<Option<ItemImpl>> {
2568        let mut attrs = input.call(Attribute::parse_outer)?;
2569        let has_visibility = allow_verbatim_impl && input.parse::<Visibility>()?.is_some();
2570        let defaultness: Option<Token![default]> = input.parse()?;
2571        let unsafety: Option<Token![unsafe]> = input.parse()?;
2572        let impl_token: Token![impl] = input.parse()?;
2573
2574        let has_generics = input.peek(Token![<])
2575            && (input.peek2(Token![>])
2576                || input.peek2(Token![#])
2577                || (input.peek2(Ident) || input.peek2(Lifetime))
2578                    && (input.peek3(Token![:])
2579                        || input.peek3(Token![,])
2580                        || input.peek3(Token![>])
2581                        || input.peek3(Token![=]))
2582                || input.peek2(Token![const]));
2583        let mut generics: Generics = if has_generics {
2584            input.parse()?
2585        } else {
2586            Generics::default()
2587        };
2588
2589        let is_const_impl = allow_verbatim_impl
2590            && (input.peek(Token![const]) || input.peek(Token![?]) && input.peek2(Token![const]));
2591        if is_const_impl {
2592            input.parse::<Option<Token![?]>>()?;
2593            input.parse::<Token![const]>()?;
2594        }
2595
2596        let begin = input.fork();
2597        let polarity = if input.peek(Token![!]) && !input.peek2(token::Brace) {
2598            Some(input.parse::<Token![!]>()?)
2599        } else {
2600            None
2601        };
2602
2603        #[cfg(not(feature = "printing"))]
2604        let first_ty_span = input.span();
2605        let mut first_ty: Type = input.parse()?;
2606        let self_ty: Type;
2607        let trait_;
2608
2609        let is_impl_for = input.peek(Token![for]);
2610        if is_impl_for {
2611            let for_token: Token![for] = input.parse()?;
2612            let mut first_ty_ref = &first_ty;
2613            while let Type::Group(ty) = first_ty_ref {
2614                first_ty_ref = &ty.elem;
2615            }
2616            if let Type::Path(TypePath { qself: None, .. }) = first_ty_ref {
2617                while let Type::Group(ty) = first_ty {
2618                    first_ty = *ty.elem;
2619                }
2620                if let Type::Path(TypePath { qself: None, path }) = first_ty {
2621                    trait_ = Some((polarity, path, for_token));
2622                } else {
2623                    unreachable!();
2624                }
2625            } else if !allow_verbatim_impl {
2626                #[cfg(feature = "printing")]
2627                return Err(Error::new_spanned(first_ty_ref, "expected trait path"));
2628                #[cfg(not(feature = "printing"))]
2629                return Err(Error::new(first_ty_span, "expected trait path"));
2630            } else {
2631                trait_ = None;
2632            }
2633            self_ty = input.parse()?;
2634        } else {
2635            trait_ = None;
2636            self_ty = if polarity.is_none() {
2637                first_ty
2638            } else {
2639                Type::Verbatim(verbatim::between(&begin, input))
2640            };
2641        }
2642
2643        generics.where_clause = input.parse()?;
2644
2645        let content;
2646        let brace_token = braced!(content in input);
2647        attr::parsing::parse_inner(&content, &mut attrs)?;
2648
2649        let mut items = Vec::new();
2650        while !content.is_empty() {
2651            items.push(content.parse()?);
2652        }
2653
2654        if has_visibility || is_const_impl || is_impl_for && trait_.is_none() {
2655            Ok(None)
2656        } else {
2657            Ok(Some(ItemImpl {
2658                attrs,
2659                defaultness,
2660                unsafety,
2661                impl_token,
2662                generics,
2663                trait_,
2664                self_ty: Box::new(self_ty),
2665                brace_token,
2666                items,
2667            }))
2668        }
2669    }
2670
2671    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2672    impl Parse for ImplItem {
2673        fn parse(input: ParseStream) -> Result<Self> {
2674            let begin = input.fork();
2675            let mut attrs = input.call(Attribute::parse_outer)?;
2676            let ahead = input.fork();
2677            let vis: Visibility = ahead.parse()?;
2678
2679            let mut lookahead = ahead.lookahead1();
2680            let defaultness = if lookahead.peek(Token![default]) && !ahead.peek2(Token![!]) {
2681                let defaultness: Token![default] = ahead.parse()?;
2682                lookahead = ahead.lookahead1();
2683                Some(defaultness)
2684            } else {
2685                None
2686            };
2687
2688            let allow_safe = false;
2689            let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead, allow_safe) {
2690                let allow_omitted_body = true;
2691                if let Some(item) = parse_impl_item_fn(input, allow_omitted_body)? {
2692                    Ok(ImplItem::Fn(item))
2693                } else {
2694                    Ok(ImplItem::Verbatim(verbatim::between(&begin, input)))
2695                }
2696            } else if lookahead.peek(Token![const]) {
2697                input.advance_to(&ahead);
2698                let const_token: Token![const] = input.parse()?;
2699                let lookahead = input.lookahead1();
2700                let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
2701                    input.call(Ident::parse_any)?
2702                } else {
2703                    return Err(lookahead.error());
2704                };
2705                let mut generics: Generics = input.parse()?;
2706                let colon_token: Token![:] = input.parse()?;
2707                let ty: Type = input.parse()?;
2708                let value = if let Some(eq_token) = input.parse::<Option<Token![=]>>()? {
2709                    let expr: Expr = input.parse()?;
2710                    Some((eq_token, expr))
2711                } else {
2712                    None
2713                };
2714                generics.where_clause = input.parse()?;
2715                let semi_token: Token![;] = input.parse()?;
2716                return match value {
2717                    Some((eq_token, expr))
2718                        if generics.lt_token.is_none() && generics.where_clause.is_none() =>
2719                    {
2720                        Ok(ImplItem::Const(ImplItemConst {
2721                            attrs,
2722                            vis,
2723                            defaultness,
2724                            const_token,
2725                            ident,
2726                            generics,
2727                            colon_token,
2728                            ty,
2729                            eq_token,
2730                            expr,
2731                            semi_token,
2732                        }))
2733                    }
2734                    _ => Ok(ImplItem::Verbatim(verbatim::between(&begin, input))),
2735                };
2736            } else if lookahead.peek(Token![type]) {
2737                parse_impl_item_type(begin, input)
2738            } else if vis.is_inherited()
2739                && defaultness.is_none()
2740                && (lookahead.peek(Ident)
2741                    || lookahead.peek(Token![self])
2742                    || lookahead.peek(Token![super])
2743                    || lookahead.peek(Token![crate])
2744                    || lookahead.peek(Token![::]))
2745            {
2746                input.parse().map(ImplItem::Macro)
2747            } else {
2748                Err(lookahead.error())
2749            }?;
2750
2751            {
2752                let item_attrs = match &mut item {
2753                    ImplItem::Const(item) => &mut item.attrs,
2754                    ImplItem::Fn(item) => &mut item.attrs,
2755                    ImplItem::Type(item) => &mut item.attrs,
2756                    ImplItem::Macro(item) => &mut item.attrs,
2757                    ImplItem::Verbatim(_) => return Ok(item),
2758                };
2759                attrs.append(item_attrs);
2760                *item_attrs = attrs;
2761            }
2762
2763            Ok(item)
2764        }
2765    }
2766
2767    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2768    impl Parse for ImplItemConst {
2769        fn parse(input: ParseStream) -> Result<Self> {
2770            let attrs = input.call(Attribute::parse_outer)?;
2771            let vis: Visibility = input.parse()?;
2772            let defaultness: Option<Token![default]> = input.parse()?;
2773            let const_token: Token![const] = input.parse()?;
2774
2775            let lookahead = input.lookahead1();
2776            let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
2777                input.call(Ident::parse_any)?
2778            } else {
2779                return Err(lookahead.error());
2780            };
2781
2782            let colon_token: Token![:] = input.parse()?;
2783            let ty: Type = input.parse()?;
2784            let eq_token: Token![=] = input.parse()?;
2785            let expr: Expr = input.parse()?;
2786            let semi_token: Token![;] = input.parse()?;
2787
2788            Ok(ImplItemConst {
2789                attrs,
2790                vis,
2791                defaultness,
2792                const_token,
2793                ident,
2794                generics: Generics::default(),
2795                colon_token,
2796                ty,
2797                eq_token,
2798                expr,
2799                semi_token,
2800            })
2801        }
2802    }
2803
2804    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2805    impl Parse for ImplItemFn {
2806        fn parse(input: ParseStream) -> Result<Self> {
2807            let allow_omitted_body = false;
2808            parse_impl_item_fn(input, allow_omitted_body).map(Option::unwrap)
2809        }
2810    }
2811
2812    fn parse_impl_item_fn(
2813        input: ParseStream,
2814        allow_omitted_body: bool,
2815    ) -> Result<Option<ImplItemFn>> {
2816        let mut attrs = input.call(Attribute::parse_outer)?;
2817        let vis: Visibility = input.parse()?;
2818        let defaultness: Option<Token![default]> = input.parse()?;
2819        let sig: Signature = input.parse()?;
2820
2821        // Accept functions without a body in an impl block because rustc's
2822        // *parser* does not reject them (the compilation error is emitted later
2823        // than parsing) and it can be useful for macro DSLs.
2824        if allow_omitted_body && input.parse::<Option<Token![;]>>()?.is_some() {
2825            return Ok(None);
2826        }
2827
2828        let content;
2829        let brace_token = braced!(content in input);
2830        attrs.extend(content.call(Attribute::parse_inner)?);
2831        let block = Block {
2832            brace_token,
2833            stmts: content.call(Block::parse_within)?,
2834        };
2835
2836        Ok(Some(ImplItemFn {
2837            attrs,
2838            vis,
2839            defaultness,
2840            sig,
2841            block,
2842        }))
2843    }
2844
2845    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2846    impl Parse for ImplItemType {
2847        fn parse(input: ParseStream) -> Result<Self> {
2848            let attrs = input.call(Attribute::parse_outer)?;
2849            let vis: Visibility = input.parse()?;
2850            let defaultness: Option<Token![default]> = input.parse()?;
2851            let type_token: Token![type] = input.parse()?;
2852            let ident: Ident = input.parse()?;
2853            let mut generics: Generics = input.parse()?;
2854            let eq_token: Token![=] = input.parse()?;
2855            let ty: Type = input.parse()?;
2856            generics.where_clause = input.parse()?;
2857            let semi_token: Token![;] = input.parse()?;
2858            Ok(ImplItemType {
2859                attrs,
2860                vis,
2861                defaultness,
2862                type_token,
2863                ident,
2864                generics,
2865                eq_token,
2866                ty,
2867                semi_token,
2868            })
2869        }
2870    }
2871
2872    fn parse_impl_item_type(begin: ParseBuffer, input: ParseStream) -> Result<ImplItem> {
2873        let FlexibleItemType {
2874            vis,
2875            defaultness,
2876            type_token,
2877            ident,
2878            generics,
2879            colon_token,
2880            bounds: _,
2881            ty,
2882            semi_token,
2883        } = FlexibleItemType::parse(
2884            input,
2885            TypeDefaultness::Optional,
2886            WhereClauseLocation::AfterEq,
2887        )?;
2888
2889        let (eq_token, ty) = match ty {
2890            Some(ty) if colon_token.is_none() => ty,
2891            _ => return Ok(ImplItem::Verbatim(verbatim::between(&begin, input))),
2892        };
2893
2894        Ok(ImplItem::Type(ImplItemType {
2895            attrs: Vec::new(),
2896            vis,
2897            defaultness,
2898            type_token,
2899            ident,
2900            generics,
2901            eq_token,
2902            ty,
2903            semi_token,
2904        }))
2905    }
2906
2907    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2908    impl Parse for ImplItemMacro {
2909        fn parse(input: ParseStream) -> Result<Self> {
2910            let attrs = input.call(Attribute::parse_outer)?;
2911            let mac: Macro = input.parse()?;
2912            let semi_token: Option<Token![;]> = if mac.delimiter.is_brace() {
2913                None
2914            } else {
2915                Some(input.parse()?)
2916            };
2917            Ok(ImplItemMacro {
2918                attrs,
2919                mac,
2920                semi_token,
2921            })
2922        }
2923    }
2924
2925    impl Visibility {
2926        fn is_inherited(&self) -> bool {
2927            match self {
2928                Visibility::Inherited => true,
2929                _ => false,
2930            }
2931        }
2932    }
2933
2934    #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2935    impl Parse for StaticMutability {
2936        fn parse(input: ParseStream) -> Result<Self> {
2937            let mut_token: Option<Token![mut]> = input.parse()?;
2938            Ok(mut_token.map_or(StaticMutability::None, StaticMutability::Mut))
2939        }
2940    }
2941}
2942
2943#[cfg(feature = "printing")]
2944mod printing {
2945    use crate::attr::FilterAttrs;
2946    use crate::data::Fields;
2947    use crate::item::{
2948        ForeignItemFn, ForeignItemMacro, ForeignItemStatic, ForeignItemType, ImplItemConst,
2949        ImplItemFn, ImplItemMacro, ImplItemType, ItemConst, ItemEnum, ItemExternCrate, ItemFn,
2950        ItemForeignMod, ItemImpl, ItemMacro, ItemMod, ItemStatic, ItemStruct, ItemTrait,
2951        ItemTraitAlias, ItemType, ItemUnion, ItemUse, Receiver, Signature, StaticMutability,
2952        TraitItemConst, TraitItemFn, TraitItemMacro, TraitItemType, UseGlob, UseGroup, UseName,
2953        UsePath, UseRename, Variadic,
2954    };
2955    use crate::mac::MacroDelimiter;
2956    use crate::path;
2957    use crate::path::printing::PathStyle;
2958    use crate::print::TokensOrDefault;
2959    use crate::ty::Type;
2960    use proc_macro2::TokenStream;
2961    use quote::{ToTokens, TokenStreamExt};
2962
2963    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
2964    impl ToTokens for ItemExternCrate {
2965        fn to_tokens(&self, tokens: &mut TokenStream) {
2966            tokens.append_all(self.attrs.outer());
2967            self.vis.to_tokens(tokens);
2968            self.extern_token.to_tokens(tokens);
2969            self.crate_token.to_tokens(tokens);
2970            self.ident.to_tokens(tokens);
2971            if let Some((as_token, rename)) = &self.rename {
2972                as_token.to_tokens(tokens);
2973                rename.to_tokens(tokens);
2974            }
2975            self.semi_token.to_tokens(tokens);
2976        }
2977    }
2978
2979    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
2980    impl ToTokens for ItemUse {
2981        fn to_tokens(&self, tokens: &mut TokenStream) {
2982            tokens.append_all(self.attrs.outer());
2983            self.vis.to_tokens(tokens);
2984            self.use_token.to_tokens(tokens);
2985            self.leading_colon.to_tokens(tokens);
2986            self.tree.to_tokens(tokens);
2987            self.semi_token.to_tokens(tokens);
2988        }
2989    }
2990
2991    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
2992    impl ToTokens for ItemStatic {
2993        fn to_tokens(&self, tokens: &mut TokenStream) {
2994            tokens.append_all(self.attrs.outer());
2995            self.vis.to_tokens(tokens);
2996            self.static_token.to_tokens(tokens);
2997            self.mutability.to_tokens(tokens);
2998            self.ident.to_tokens(tokens);
2999            self.colon_token.to_tokens(tokens);
3000            self.ty.to_tokens(tokens);
3001            self.eq_token.to_tokens(tokens);
3002            self.expr.to_tokens(tokens);
3003            self.semi_token.to_tokens(tokens);
3004        }
3005    }
3006
3007    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3008    impl ToTokens for ItemConst {
3009        fn to_tokens(&self, tokens: &mut TokenStream) {
3010            tokens.append_all(self.attrs.outer());
3011            self.vis.to_tokens(tokens);
3012            self.const_token.to_tokens(tokens);
3013            self.ident.to_tokens(tokens);
3014            self.colon_token.to_tokens(tokens);
3015            self.ty.to_tokens(tokens);
3016            self.eq_token.to_tokens(tokens);
3017            self.expr.to_tokens(tokens);
3018            self.semi_token.to_tokens(tokens);
3019        }
3020    }
3021
3022    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3023    impl ToTokens for ItemFn {
3024        fn to_tokens(&self, tokens: &mut TokenStream) {
3025            tokens.append_all(self.attrs.outer());
3026            self.vis.to_tokens(tokens);
3027            self.sig.to_tokens(tokens);
3028            self.block.brace_token.surround(tokens, |tokens| {
3029                tokens.append_all(self.attrs.inner());
3030                tokens.append_all(&self.block.stmts);
3031            });
3032        }
3033    }
3034
3035    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3036    impl ToTokens for ItemMod {
3037        fn to_tokens(&self, tokens: &mut TokenStream) {
3038            tokens.append_all(self.attrs.outer());
3039            self.vis.to_tokens(tokens);
3040            self.unsafety.to_tokens(tokens);
3041            self.mod_token.to_tokens(tokens);
3042            self.ident.to_tokens(tokens);
3043            if let Some((brace, items)) = &self.content {
3044                brace.surround(tokens, |tokens| {
3045                    tokens.append_all(self.attrs.inner());
3046                    tokens.append_all(items);
3047                });
3048            } else {
3049                TokensOrDefault(&self.semi).to_tokens(tokens);
3050            }
3051        }
3052    }
3053
3054    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3055    impl ToTokens for ItemForeignMod {
3056        fn to_tokens(&self, tokens: &mut TokenStream) {
3057            tokens.append_all(self.attrs.outer());
3058            self.unsafety.to_tokens(tokens);
3059            self.abi.to_tokens(tokens);
3060            self.brace_token.surround(tokens, |tokens| {
3061                tokens.append_all(self.attrs.inner());
3062                tokens.append_all(&self.items);
3063            });
3064        }
3065    }
3066
3067    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3068    impl ToTokens for ItemType {
3069        fn to_tokens(&self, tokens: &mut TokenStream) {
3070            tokens.append_all(self.attrs.outer());
3071            self.vis.to_tokens(tokens);
3072            self.type_token.to_tokens(tokens);
3073            self.ident.to_tokens(tokens);
3074            self.generics.to_tokens(tokens);
3075            self.generics.where_clause.to_tokens(tokens);
3076            self.eq_token.to_tokens(tokens);
3077            self.ty.to_tokens(tokens);
3078            self.semi_token.to_tokens(tokens);
3079        }
3080    }
3081
3082    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3083    impl ToTokens for ItemEnum {
3084        fn to_tokens(&self, tokens: &mut TokenStream) {
3085            tokens.append_all(self.attrs.outer());
3086            self.vis.to_tokens(tokens);
3087            self.enum_token.to_tokens(tokens);
3088            self.ident.to_tokens(tokens);
3089            self.generics.to_tokens(tokens);
3090            self.generics.where_clause.to_tokens(tokens);
3091            self.brace_token.surround(tokens, |tokens| {
3092                self.variants.to_tokens(tokens);
3093            });
3094        }
3095    }
3096
3097    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3098    impl ToTokens for ItemStruct {
3099        fn to_tokens(&self, tokens: &mut TokenStream) {
3100            tokens.append_all(self.attrs.outer());
3101            self.vis.to_tokens(tokens);
3102            self.struct_token.to_tokens(tokens);
3103            self.ident.to_tokens(tokens);
3104            self.generics.to_tokens(tokens);
3105            match &self.fields {
3106                Fields::Named(fields) => {
3107                    self.generics.where_clause.to_tokens(tokens);
3108                    fields.to_tokens(tokens);
3109                }
3110                Fields::Unnamed(fields) => {
3111                    fields.to_tokens(tokens);
3112                    self.generics.where_clause.to_tokens(tokens);
3113                    TokensOrDefault(&self.semi_token).to_tokens(tokens);
3114                }
3115                Fields::Unit => {
3116                    self.generics.where_clause.to_tokens(tokens);
3117                    TokensOrDefault(&self.semi_token).to_tokens(tokens);
3118                }
3119            }
3120        }
3121    }
3122
3123    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3124    impl ToTokens for ItemUnion {
3125        fn to_tokens(&self, tokens: &mut TokenStream) {
3126            tokens.append_all(self.attrs.outer());
3127            self.vis.to_tokens(tokens);
3128            self.union_token.to_tokens(tokens);
3129            self.ident.to_tokens(tokens);
3130            self.generics.to_tokens(tokens);
3131            self.generics.where_clause.to_tokens(tokens);
3132            self.fields.to_tokens(tokens);
3133        }
3134    }
3135
3136    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3137    impl ToTokens for ItemTrait {
3138        fn to_tokens(&self, tokens: &mut TokenStream) {
3139            tokens.append_all(self.attrs.outer());
3140            self.vis.to_tokens(tokens);
3141            self.unsafety.to_tokens(tokens);
3142            self.auto_token.to_tokens(tokens);
3143            self.trait_token.to_tokens(tokens);
3144            self.ident.to_tokens(tokens);
3145            self.generics.to_tokens(tokens);
3146            if !self.supertraits.is_empty() {
3147                TokensOrDefault(&self.colon_token).to_tokens(tokens);
3148                self.supertraits.to_tokens(tokens);
3149            }
3150            self.generics.where_clause.to_tokens(tokens);
3151            self.brace_token.surround(tokens, |tokens| {
3152                tokens.append_all(self.attrs.inner());
3153                tokens.append_all(&self.items);
3154            });
3155        }
3156    }
3157
3158    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3159    impl ToTokens for ItemTraitAlias {
3160        fn to_tokens(&self, tokens: &mut TokenStream) {
3161            tokens.append_all(self.attrs.outer());
3162            self.vis.to_tokens(tokens);
3163            self.trait_token.to_tokens(tokens);
3164            self.ident.to_tokens(tokens);
3165            self.generics.to_tokens(tokens);
3166            self.eq_token.to_tokens(tokens);
3167            self.bounds.to_tokens(tokens);
3168            self.generics.where_clause.to_tokens(tokens);
3169            self.semi_token.to_tokens(tokens);
3170        }
3171    }
3172
3173    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3174    impl ToTokens for ItemImpl {
3175        fn to_tokens(&self, tokens: &mut TokenStream) {
3176            tokens.append_all(self.attrs.outer());
3177            self.defaultness.to_tokens(tokens);
3178            self.unsafety.to_tokens(tokens);
3179            self.impl_token.to_tokens(tokens);
3180            self.generics.to_tokens(tokens);
3181            if let Some((polarity, path, for_token)) = &self.trait_ {
3182                polarity.to_tokens(tokens);
3183                path.to_tokens(tokens);
3184                for_token.to_tokens(tokens);
3185            }
3186            self.self_ty.to_tokens(tokens);
3187            self.generics.where_clause.to_tokens(tokens);
3188            self.brace_token.surround(tokens, |tokens| {
3189                tokens.append_all(self.attrs.inner());
3190                tokens.append_all(&self.items);
3191            });
3192        }
3193    }
3194
3195    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3196    impl ToTokens for ItemMacro {
3197        fn to_tokens(&self, tokens: &mut TokenStream) {
3198            tokens.append_all(self.attrs.outer());
3199            path::printing::print_path(tokens, &self.mac.path, PathStyle::Mod);
3200            self.mac.bang_token.to_tokens(tokens);
3201            self.ident.to_tokens(tokens);
3202            match &self.mac.delimiter {
3203                MacroDelimiter::Paren(paren) => {
3204                    paren.surround(tokens, |tokens| self.mac.tokens.to_tokens(tokens));
3205                }
3206                MacroDelimiter::Brace(brace) => {
3207                    brace.surround(tokens, |tokens| self.mac.tokens.to_tokens(tokens));
3208                }
3209                MacroDelimiter::Bracket(bracket) => {
3210                    bracket.surround(tokens, |tokens| self.mac.tokens.to_tokens(tokens));
3211                }
3212            }
3213            self.semi_token.to_tokens(tokens);
3214        }
3215    }
3216
3217    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3218    impl ToTokens for UsePath {
3219        fn to_tokens(&self, tokens: &mut TokenStream) {
3220            self.ident.to_tokens(tokens);
3221            self.colon2_token.to_tokens(tokens);
3222            self.tree.to_tokens(tokens);
3223        }
3224    }
3225
3226    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3227    impl ToTokens for UseName {
3228        fn to_tokens(&self, tokens: &mut TokenStream) {
3229            self.ident.to_tokens(tokens);
3230        }
3231    }
3232
3233    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3234    impl ToTokens for UseRename {
3235        fn to_tokens(&self, tokens: &mut TokenStream) {
3236            self.ident.to_tokens(tokens);
3237            self.as_token.to_tokens(tokens);
3238            self.rename.to_tokens(tokens);
3239        }
3240    }
3241
3242    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3243    impl ToTokens for UseGlob {
3244        fn to_tokens(&self, tokens: &mut TokenStream) {
3245            self.star_token.to_tokens(tokens);
3246        }
3247    }
3248
3249    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3250    impl ToTokens for UseGroup {
3251        fn to_tokens(&self, tokens: &mut TokenStream) {
3252            self.brace_token.surround(tokens, |tokens| {
3253                self.items.to_tokens(tokens);
3254            });
3255        }
3256    }
3257
3258    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3259    impl ToTokens for TraitItemConst {
3260        fn to_tokens(&self, tokens: &mut TokenStream) {
3261            tokens.append_all(self.attrs.outer());
3262            self.const_token.to_tokens(tokens);
3263            self.ident.to_tokens(tokens);
3264            self.colon_token.to_tokens(tokens);
3265            self.ty.to_tokens(tokens);
3266            if let Some((eq_token, default)) = &self.default {
3267                eq_token.to_tokens(tokens);
3268                default.to_tokens(tokens);
3269            }
3270            self.semi_token.to_tokens(tokens);
3271        }
3272    }
3273
3274    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3275    impl ToTokens for TraitItemFn {
3276        fn to_tokens(&self, tokens: &mut TokenStream) {
3277            tokens.append_all(self.attrs.outer());
3278            self.sig.to_tokens(tokens);
3279            match &self.default {
3280                Some(block) => {
3281                    block.brace_token.surround(tokens, |tokens| {
3282                        tokens.append_all(self.attrs.inner());
3283                        tokens.append_all(&block.stmts);
3284                    });
3285                }
3286                None => {
3287                    TokensOrDefault(&self.semi_token).to_tokens(tokens);
3288                }
3289            }
3290        }
3291    }
3292
3293    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3294    impl ToTokens for TraitItemType {
3295        fn to_tokens(&self, tokens: &mut TokenStream) {
3296            tokens.append_all(self.attrs.outer());
3297            self.type_token.to_tokens(tokens);
3298            self.ident.to_tokens(tokens);
3299            self.generics.to_tokens(tokens);
3300            if !self.bounds.is_empty() {
3301                TokensOrDefault(&self.colon_token).to_tokens(tokens);
3302                self.bounds.to_tokens(tokens);
3303            }
3304            if let Some((eq_token, default)) = &self.default {
3305                eq_token.to_tokens(tokens);
3306                default.to_tokens(tokens);
3307            }
3308            self.generics.where_clause.to_tokens(tokens);
3309            self.semi_token.to_tokens(tokens);
3310        }
3311    }
3312
3313    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3314    impl ToTokens for TraitItemMacro {
3315        fn to_tokens(&self, tokens: &mut TokenStream) {
3316            tokens.append_all(self.attrs.outer());
3317            self.mac.to_tokens(tokens);
3318            self.semi_token.to_tokens(tokens);
3319        }
3320    }
3321
3322    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3323    impl ToTokens for ImplItemConst {
3324        fn to_tokens(&self, tokens: &mut TokenStream) {
3325            tokens.append_all(self.attrs.outer());
3326            self.vis.to_tokens(tokens);
3327            self.defaultness.to_tokens(tokens);
3328            self.const_token.to_tokens(tokens);
3329            self.ident.to_tokens(tokens);
3330            self.colon_token.to_tokens(tokens);
3331            self.ty.to_tokens(tokens);
3332            self.eq_token.to_tokens(tokens);
3333            self.expr.to_tokens(tokens);
3334            self.semi_token.to_tokens(tokens);
3335        }
3336    }
3337
3338    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3339    impl ToTokens for ImplItemFn {
3340        fn to_tokens(&self, tokens: &mut TokenStream) {
3341            tokens.append_all(self.attrs.outer());
3342            self.vis.to_tokens(tokens);
3343            self.defaultness.to_tokens(tokens);
3344            self.sig.to_tokens(tokens);
3345            self.block.brace_token.surround(tokens, |tokens| {
3346                tokens.append_all(self.attrs.inner());
3347                tokens.append_all(&self.block.stmts);
3348            });
3349        }
3350    }
3351
3352    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3353    impl ToTokens for ImplItemType {
3354        fn to_tokens(&self, tokens: &mut TokenStream) {
3355            tokens.append_all(self.attrs.outer());
3356            self.vis.to_tokens(tokens);
3357            self.defaultness.to_tokens(tokens);
3358            self.type_token.to_tokens(tokens);
3359            self.ident.to_tokens(tokens);
3360            self.generics.to_tokens(tokens);
3361            self.eq_token.to_tokens(tokens);
3362            self.ty.to_tokens(tokens);
3363            self.generics.where_clause.to_tokens(tokens);
3364            self.semi_token.to_tokens(tokens);
3365        }
3366    }
3367
3368    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3369    impl ToTokens for ImplItemMacro {
3370        fn to_tokens(&self, tokens: &mut TokenStream) {
3371            tokens.append_all(self.attrs.outer());
3372            self.mac.to_tokens(tokens);
3373            self.semi_token.to_tokens(tokens);
3374        }
3375    }
3376
3377    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3378    impl ToTokens for ForeignItemFn {
3379        fn to_tokens(&self, tokens: &mut TokenStream) {
3380            tokens.append_all(self.attrs.outer());
3381            self.vis.to_tokens(tokens);
3382            self.sig.to_tokens(tokens);
3383            self.semi_token.to_tokens(tokens);
3384        }
3385    }
3386
3387    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3388    impl ToTokens for ForeignItemStatic {
3389        fn to_tokens(&self, tokens: &mut TokenStream) {
3390            tokens.append_all(self.attrs.outer());
3391            self.vis.to_tokens(tokens);
3392            self.static_token.to_tokens(tokens);
3393            self.mutability.to_tokens(tokens);
3394            self.ident.to_tokens(tokens);
3395            self.colon_token.to_tokens(tokens);
3396            self.ty.to_tokens(tokens);
3397            self.semi_token.to_tokens(tokens);
3398        }
3399    }
3400
3401    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3402    impl ToTokens for ForeignItemType {
3403        fn to_tokens(&self, tokens: &mut TokenStream) {
3404            tokens.append_all(self.attrs.outer());
3405            self.vis.to_tokens(tokens);
3406            self.type_token.to_tokens(tokens);
3407            self.ident.to_tokens(tokens);
3408            self.generics.to_tokens(tokens);
3409            self.generics.where_clause.to_tokens(tokens);
3410            self.semi_token.to_tokens(tokens);
3411        }
3412    }
3413
3414    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3415    impl ToTokens for ForeignItemMacro {
3416        fn to_tokens(&self, tokens: &mut TokenStream) {
3417            tokens.append_all(self.attrs.outer());
3418            self.mac.to_tokens(tokens);
3419            self.semi_token.to_tokens(tokens);
3420        }
3421    }
3422
3423    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3424    impl ToTokens for Signature {
3425        fn to_tokens(&self, tokens: &mut TokenStream) {
3426            self.constness.to_tokens(tokens);
3427            self.asyncness.to_tokens(tokens);
3428            self.unsafety.to_tokens(tokens);
3429            self.abi.to_tokens(tokens);
3430            self.fn_token.to_tokens(tokens);
3431            self.ident.to_tokens(tokens);
3432            self.generics.to_tokens(tokens);
3433            self.paren_token.surround(tokens, |tokens| {
3434                self.inputs.to_tokens(tokens);
3435                if let Some(variadic) = &self.variadic {
3436                    if !self.inputs.empty_or_trailing() {
3437                        <Token![,]>::default().to_tokens(tokens);
3438                    }
3439                    variadic.to_tokens(tokens);
3440                }
3441            });
3442            self.output.to_tokens(tokens);
3443            self.generics.where_clause.to_tokens(tokens);
3444        }
3445    }
3446
3447    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3448    impl ToTokens for Receiver {
3449        fn to_tokens(&self, tokens: &mut TokenStream) {
3450            tokens.append_all(self.attrs.outer());
3451            if let Some((ampersand, lifetime)) = &self.reference {
3452                ampersand.to_tokens(tokens);
3453                lifetime.to_tokens(tokens);
3454            }
3455            self.mutability.to_tokens(tokens);
3456            self.self_token.to_tokens(tokens);
3457            if let Some(colon_token) = &self.colon_token {
3458                colon_token.to_tokens(tokens);
3459                self.ty.to_tokens(tokens);
3460            } else {
3461                let consistent = match (&self.reference, &self.mutability, &*self.ty) {
3462                    (Some(_), mutability, Type::Reference(ty)) => {
3463                        mutability.is_some() == ty.mutability.is_some()
3464                            && match &*ty.elem {
3465                                Type::Path(ty) => ty.qself.is_none() && ty.path.is_ident("Self"),
3466                                _ => false,
3467                            }
3468                    }
3469                    (None, _, Type::Path(ty)) => ty.qself.is_none() && ty.path.is_ident("Self"),
3470                    _ => false,
3471                };
3472                if !consistent {
3473                    <Token![:]>::default().to_tokens(tokens);
3474                    self.ty.to_tokens(tokens);
3475                }
3476            }
3477        }
3478    }
3479
3480    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3481    impl ToTokens for Variadic {
3482        fn to_tokens(&self, tokens: &mut TokenStream) {
3483            tokens.append_all(self.attrs.outer());
3484            if let Some((pat, colon)) = &self.pat {
3485                pat.to_tokens(tokens);
3486                colon.to_tokens(tokens);
3487            }
3488            self.dots.to_tokens(tokens);
3489            self.comma.to_tokens(tokens);
3490        }
3491    }
3492
3493    #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3494    impl ToTokens for StaticMutability {
3495        fn to_tokens(&self, tokens: &mut TokenStream) {
3496            match self {
3497                StaticMutability::None => {}
3498                StaticMutability::Mut(mut_token) => mut_token.to_tokens(tokens),
3499            }
3500        }
3501    }
3502}