xref: /linux/rust/syn/item.rs (revision 808c999fc9e7c366fd47da564e69d579c1dc8279)
1 use crate::attr::Attribute;
2 use crate::data::{Fields, FieldsNamed, Variant};
3 use crate::derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput};
4 use crate::expr::Expr;
5 use crate::generics::{Generics, TypeParamBound};
6 use crate::ident::Ident;
7 use crate::lifetime::Lifetime;
8 use crate::mac::Macro;
9 use crate::pat::{Pat, PatType};
10 use crate::path::Path;
11 use crate::punctuated::Punctuated;
12 use crate::restriction::Visibility;
13 use crate::stmt::Block;
14 use crate::token;
15 use crate::ty::{Abi, ReturnType, Type};
16 use proc_macro2::TokenStream;
17 #[cfg(feature = "parsing")]
18 use std::mem;
19 
20 ast_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 
101 ast_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 
118 ast_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 
132 ast_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 
146 ast_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 
157 ast_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 
169 ast_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 
188 ast_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 
200 ast_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 
214 ast_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 
231 ast_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 
245 ast_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 
264 ast_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 
279 ast_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 
294 ast_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 
307 ast_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 
320 impl 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 
344 impl 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 
377 impl 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 
393 impl 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 
409 impl 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 
424 ast_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 
451 ast_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 
461 ast_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 
469 ast_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 
479 ast_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 
487 ast_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 
496 ast_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 
542 ast_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 
553 ast_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 
568 ast_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 
581 ast_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 
591 ast_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 
637 ast_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 
652 ast_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 
663 ast_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 
678 ast_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 
688 ast_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 
734 ast_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 
752 ast_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 
764 ast_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 
780 ast_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 
790 ast_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 
809 impl 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 
820 ast_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 
832 ast_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 
851 impl Receiver {
852     pub fn lifetime(&self) -> Option<&Lifetime> {
853         self.reference.as_ref()?.1.as_ref()
854     }
855 }
856 
857 ast_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 
878 ast_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 
888 ast_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")]
906 pub(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::{self, 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_const = true;
1212                         TypeParamBound::parse_single(input, allow_precise_capture, allow_const)?
1213                     });
1214                     if input.peek(Token![where]) || input.peek(Token![=]) || input.peek(Token![;]) {
1215                         break;
1216                     }
1217                     bounds.push_punct(input.parse::<Token![+]>()?);
1218                 }
1219             }
1220 
1221             Ok((colon_token, bounds))
1222         }
1223 
1224         fn parse_optional_definition(input: ParseStream) -> Result<Option<(Token![=], Type)>> {
1225             let eq_token: Option<Token![=]> = input.parse()?;
1226             if let Some(eq_token) = eq_token {
1227                 let definition: Type = input.parse()?;
1228                 Ok(Some((eq_token, definition)))
1229             } else {
1230                 Ok(None)
1231             }
1232         }
1233     }
1234 
1235     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1236     impl Parse for ItemMacro {
1237         fn parse(input: ParseStream) -> Result<Self> {
1238             let attrs = input.call(Attribute::parse_outer)?;
1239             let path = input.call(Path::parse_mod_style)?;
1240             let bang_token: Token![!] = input.parse()?;
1241             let ident: Option<Ident> = if input.peek(Token![try]) {
1242                 input.call(Ident::parse_any).map(Some)
1243             } else {
1244                 input.parse()
1245             }?;
1246             let (delimiter, tokens) = input.call(mac::parse_delimiter)?;
1247             let semi_token: Option<Token![;]> = if !delimiter.is_brace() {
1248                 Some(input.parse()?)
1249             } else {
1250                 None
1251             };
1252             Ok(ItemMacro {
1253                 attrs,
1254                 ident,
1255                 mac: Macro {
1256                     path,
1257                     bang_token,
1258                     delimiter,
1259                     tokens,
1260                 },
1261                 semi_token,
1262             })
1263         }
1264     }
1265 
1266     fn parse_macro2(begin: ParseBuffer, _vis: Visibility, input: ParseStream) -> Result<Item> {
1267         input.parse::<Token![macro]>()?;
1268         input.parse::<Ident>()?;
1269 
1270         let mut lookahead = input.lookahead1();
1271         if lookahead.peek(token::Paren) {
1272             let paren_content;
1273             parenthesized!(paren_content in input);
1274             paren_content.parse::<TokenStream>()?;
1275             lookahead = input.lookahead1();
1276         }
1277 
1278         if lookahead.peek(token::Brace) {
1279             let brace_content;
1280             braced!(brace_content in input);
1281             brace_content.parse::<TokenStream>()?;
1282         } else {
1283             return Err(lookahead.error());
1284         }
1285 
1286         Ok(Item::Verbatim(verbatim::between(&begin, input)))
1287     }
1288 
1289     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1290     impl Parse for ItemExternCrate {
1291         fn parse(input: ParseStream) -> Result<Self> {
1292             Ok(ItemExternCrate {
1293                 attrs: input.call(Attribute::parse_outer)?,
1294                 vis: input.parse()?,
1295                 extern_token: input.parse()?,
1296                 crate_token: input.parse()?,
1297                 ident: {
1298                     if input.peek(Token![self]) {
1299                         input.call(Ident::parse_any)?
1300                     } else {
1301                         input.parse()?
1302                     }
1303                 },
1304                 rename: {
1305                     if input.peek(Token![as]) {
1306                         let as_token: Token![as] = input.parse()?;
1307                         let rename: Ident = if input.peek(Token![_]) {
1308                             Ident::from(input.parse::<Token![_]>()?)
1309                         } else {
1310                             input.parse()?
1311                         };
1312                         Some((as_token, rename))
1313                     } else {
1314                         None
1315                     }
1316                 },
1317                 semi_token: input.parse()?,
1318             })
1319         }
1320     }
1321 
1322     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1323     impl Parse for ItemUse {
1324         fn parse(input: ParseStream) -> Result<Self> {
1325             let allow_crate_root_in_path = false;
1326             parse_item_use(input, allow_crate_root_in_path).map(Option::unwrap)
1327         }
1328     }
1329 
1330     fn parse_item_use(
1331         input: ParseStream,
1332         allow_crate_root_in_path: bool,
1333     ) -> Result<Option<ItemUse>> {
1334         let attrs = input.call(Attribute::parse_outer)?;
1335         let vis: Visibility = input.parse()?;
1336         let use_token: Token![use] = input.parse()?;
1337         let leading_colon: Option<Token![::]> = input.parse()?;
1338         let tree = parse_use_tree(input, allow_crate_root_in_path && leading_colon.is_none())?;
1339         let semi_token: Token![;] = input.parse()?;
1340 
1341         let tree = match tree {
1342             Some(tree) => tree,
1343             None => return Ok(None),
1344         };
1345 
1346         Ok(Some(ItemUse {
1347             attrs,
1348             vis,
1349             use_token,
1350             leading_colon,
1351             tree,
1352             semi_token,
1353         }))
1354     }
1355 
1356     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1357     impl Parse for UseTree {
1358         fn parse(input: ParseStream) -> Result<UseTree> {
1359             let allow_crate_root_in_path = false;
1360             parse_use_tree(input, allow_crate_root_in_path).map(Option::unwrap)
1361         }
1362     }
1363 
1364     fn parse_use_tree(
1365         input: ParseStream,
1366         allow_crate_root_in_path: bool,
1367     ) -> Result<Option<UseTree>> {
1368         let lookahead = input.lookahead1();
1369         if lookahead.peek(Ident)
1370             || lookahead.peek(Token![self])
1371             || lookahead.peek(Token![super])
1372             || lookahead.peek(Token![crate])
1373             || lookahead.peek(Token![try])
1374         {
1375             let ident = input.call(Ident::parse_any)?;
1376             if input.peek(Token![::]) {
1377                 Ok(Some(UseTree::Path(UsePath {
1378                     ident,
1379                     colon2_token: input.parse()?,
1380                     tree: Box::new(input.parse()?),
1381                 })))
1382             } else if input.peek(Token![as]) {
1383                 Ok(Some(UseTree::Rename(UseRename {
1384                     ident,
1385                     as_token: input.parse()?,
1386                     rename: {
1387                         if input.peek(Ident) {
1388                             input.parse()?
1389                         } else if input.peek(Token![_]) {
1390                             Ident::from(input.parse::<Token![_]>()?)
1391                         } else {
1392                             return Err(input.error("expected identifier or underscore"));
1393                         }
1394                     },
1395                 })))
1396             } else {
1397                 Ok(Some(UseTree::Name(UseName { ident })))
1398             }
1399         } else if lookahead.peek(Token![*]) {
1400             Ok(Some(UseTree::Glob(UseGlob {
1401                 star_token: input.parse()?,
1402             })))
1403         } else if lookahead.peek(token::Brace) {
1404             let content;
1405             let brace_token = braced!(content in input);
1406             let mut items = Punctuated::new();
1407             let mut has_any_crate_root_in_path = false;
1408             loop {
1409                 if content.is_empty() {
1410                     break;
1411                 }
1412                 let this_tree_starts_with_crate_root =
1413                     allow_crate_root_in_path && content.parse::<Option<Token![::]>>()?.is_some();
1414                 has_any_crate_root_in_path |= this_tree_starts_with_crate_root;
1415                 match parse_use_tree(
1416                     &content,
1417                     allow_crate_root_in_path && !this_tree_starts_with_crate_root,
1418                 )? {
1419                     Some(tree) if !has_any_crate_root_in_path => items.push_value(tree),
1420                     _ => has_any_crate_root_in_path = true,
1421                 }
1422                 if content.is_empty() {
1423                     break;
1424                 }
1425                 let comma: Token![,] = content.parse()?;
1426                 if !has_any_crate_root_in_path {
1427                     items.push_punct(comma);
1428                 }
1429             }
1430             if has_any_crate_root_in_path {
1431                 Ok(None)
1432             } else {
1433                 Ok(Some(UseTree::Group(UseGroup { brace_token, items })))
1434             }
1435         } else {
1436             Err(lookahead.error())
1437         }
1438     }
1439 
1440     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1441     impl Parse for ItemStatic {
1442         fn parse(input: ParseStream) -> Result<Self> {
1443             Ok(ItemStatic {
1444                 attrs: input.call(Attribute::parse_outer)?,
1445                 vis: input.parse()?,
1446                 static_token: input.parse()?,
1447                 mutability: input.parse()?,
1448                 ident: input.parse()?,
1449                 colon_token: input.parse()?,
1450                 ty: input.parse()?,
1451                 eq_token: input.parse()?,
1452                 expr: input.parse()?,
1453                 semi_token: input.parse()?,
1454             })
1455         }
1456     }
1457 
1458     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1459     impl Parse for ItemConst {
1460         fn parse(input: ParseStream) -> Result<Self> {
1461             let attrs = input.call(Attribute::parse_outer)?;
1462             let vis: Visibility = input.parse()?;
1463             let const_token: Token![const] = input.parse()?;
1464 
1465             let lookahead = input.lookahead1();
1466             let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
1467                 input.call(Ident::parse_any)?
1468             } else {
1469                 return Err(lookahead.error());
1470             };
1471 
1472             let colon_token: Token![:] = input.parse()?;
1473             let ty: Type = input.parse()?;
1474             let eq_token: Token![=] = input.parse()?;
1475             let expr: Expr = input.parse()?;
1476             let semi_token: Token![;] = input.parse()?;
1477 
1478             Ok(ItemConst {
1479                 attrs,
1480                 vis,
1481                 const_token,
1482                 ident,
1483                 generics: Generics::default(),
1484                 colon_token,
1485                 ty: Box::new(ty),
1486                 eq_token,
1487                 expr: Box::new(expr),
1488                 semi_token,
1489             })
1490         }
1491     }
1492 
1493     fn peek_signature(input: ParseStream, allow_safe: bool) -> bool {
1494         let fork = input.fork();
1495         fork.parse::<Option<Token![const]>>().is_ok()
1496             && fork.parse::<Option<Token![async]>>().is_ok()
1497             && ((allow_safe
1498                 && token::parsing::peek_keyword(fork.cursor(), "safe")
1499                 && token::parsing::keyword(&fork, "safe").is_ok())
1500                 || fork.parse::<Option<Token![unsafe]>>().is_ok())
1501             && fork.parse::<Option<Abi>>().is_ok()
1502             && fork.peek(Token![fn])
1503     }
1504 
1505     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1506     impl Parse for Signature {
1507         fn parse(input: ParseStream) -> Result<Self> {
1508             let allow_safe = false;
1509             parse_signature(input, allow_safe).map(Option::unwrap)
1510         }
1511     }
1512 
1513     fn parse_signature(input: ParseStream, allow_safe: bool) -> Result<Option<Signature>> {
1514         let constness: Option<Token![const]> = input.parse()?;
1515         let asyncness: Option<Token![async]> = input.parse()?;
1516         let unsafety: Option<Token![unsafe]> = input.parse()?;
1517         let safe = allow_safe
1518             && unsafety.is_none()
1519             && token::parsing::peek_keyword(input.cursor(), "safe");
1520         if safe {
1521             token::parsing::keyword(input, "safe")?;
1522         }
1523         let abi: Option<Abi> = input.parse()?;
1524         let fn_token: Token![fn] = input.parse()?;
1525         let ident: Ident = input.parse()?;
1526         let mut generics: Generics = input.parse()?;
1527 
1528         let content;
1529         let paren_token = parenthesized!(content in input);
1530         let (inputs, variadic) = parse_fn_args(&content)?;
1531 
1532         let output: ReturnType = input.parse()?;
1533         generics.where_clause = input.parse()?;
1534 
1535         Ok(if safe {
1536             None
1537         } else {
1538             Some(Signature {
1539                 constness,
1540                 asyncness,
1541                 unsafety,
1542                 abi,
1543                 fn_token,
1544                 ident,
1545                 generics,
1546                 paren_token,
1547                 inputs,
1548                 variadic,
1549                 output,
1550             })
1551         })
1552     }
1553 
1554     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1555     impl Parse for ItemFn {
1556         fn parse(input: ParseStream) -> Result<Self> {
1557             let outer_attrs = input.call(Attribute::parse_outer)?;
1558             let vis: Visibility = input.parse()?;
1559             let sig: Signature = input.parse()?;
1560             parse_rest_of_fn(input, outer_attrs, vis, sig)
1561         }
1562     }
1563 
1564     fn parse_rest_of_fn(
1565         input: ParseStream,
1566         mut attrs: Vec<Attribute>,
1567         vis: Visibility,
1568         sig: Signature,
1569     ) -> Result<ItemFn> {
1570         let content;
1571         let brace_token = braced!(content in input);
1572         attr::parsing::parse_inner(&content, &mut attrs)?;
1573         let stmts = content.call(Block::parse_within)?;
1574 
1575         Ok(ItemFn {
1576             attrs,
1577             vis,
1578             sig,
1579             block: Box::new(Block { brace_token, stmts }),
1580         })
1581     }
1582 
1583     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1584     impl Parse for FnArg {
1585         fn parse(input: ParseStream) -> Result<Self> {
1586             let allow_variadic = false;
1587             let attrs = input.call(Attribute::parse_outer)?;
1588             match parse_fn_arg_or_variadic(input, attrs, allow_variadic)? {
1589                 FnArgOrVariadic::FnArg(arg) => Ok(arg),
1590                 FnArgOrVariadic::Variadic(_) => unreachable!(),
1591             }
1592         }
1593     }
1594 
1595     enum FnArgOrVariadic {
1596         FnArg(FnArg),
1597         Variadic(Variadic),
1598     }
1599 
1600     fn parse_fn_arg_or_variadic(
1601         input: ParseStream,
1602         attrs: Vec<Attribute>,
1603         allow_variadic: bool,
1604     ) -> Result<FnArgOrVariadic> {
1605         let ahead = input.fork();
1606         if let Ok(mut receiver) = ahead.parse::<Receiver>() {
1607             input.advance_to(&ahead);
1608             receiver.attrs = attrs;
1609             return Ok(FnArgOrVariadic::FnArg(FnArg::Receiver(receiver)));
1610         }
1611 
1612         // Hack to parse pre-2018 syntax in
1613         // test/ui/rfc-2565-param-attrs/param-attrs-pretty.rs
1614         // because the rest of the test case is valuable.
1615         if input.peek(Ident) && input.peek2(Token![<]) {
1616             let span = input.span();
1617             return Ok(FnArgOrVariadic::FnArg(FnArg::Typed(PatType {
1618                 attrs,
1619                 pat: Box::new(Pat::Wild(PatWild {
1620                     attrs: Vec::new(),
1621                     underscore_token: Token![_](span),
1622                 })),
1623                 colon_token: Token![:](span),
1624                 ty: input.parse()?,
1625             })));
1626         }
1627 
1628         let pat = Box::new(Pat::parse_single(input)?);
1629         let colon_token: Token![:] = input.parse()?;
1630 
1631         if allow_variadic {
1632             if let Some(dots) = input.parse::<Option<Token![...]>>()? {
1633                 return Ok(FnArgOrVariadic::Variadic(Variadic {
1634                     attrs,
1635                     pat: Some((pat, colon_token)),
1636                     dots,
1637                     comma: None,
1638                 }));
1639             }
1640         }
1641 
1642         Ok(FnArgOrVariadic::FnArg(FnArg::Typed(PatType {
1643             attrs,
1644             pat,
1645             colon_token,
1646             ty: input.parse()?,
1647         })))
1648     }
1649 
1650     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1651     impl Parse for Receiver {
1652         fn parse(input: ParseStream) -> Result<Self> {
1653             let reference = if input.peek(Token![&]) {
1654                 let ampersand: Token![&] = input.parse()?;
1655                 let lifetime: Option<Lifetime> = input.parse()?;
1656                 Some((ampersand, lifetime))
1657             } else {
1658                 None
1659             };
1660             let mutability: Option<Token![mut]> = input.parse()?;
1661             let self_token: Token![self] = input.parse()?;
1662             let colon_token: Option<Token![:]> = if reference.is_some() {
1663                 None
1664             } else {
1665                 input.parse()?
1666             };
1667             let ty: Type = if colon_token.is_some() {
1668                 input.parse()?
1669             } else {
1670                 let mut ty = Type::Path(TypePath {
1671                     qself: None,
1672                     path: Path::from(Ident::new("Self", self_token.span)),
1673                 });
1674                 if let Some((ampersand, lifetime)) = reference.as_ref() {
1675                     ty = Type::Reference(TypeReference {
1676                         and_token: Token![&](ampersand.span),
1677                         lifetime: lifetime.clone(),
1678                         mutability: mutability.as_ref().map(|m| Token![mut](m.span)),
1679                         elem: Box::new(ty),
1680                     });
1681                 }
1682                 ty
1683             };
1684             Ok(Receiver {
1685                 attrs: Vec::new(),
1686                 reference,
1687                 mutability,
1688                 self_token,
1689                 colon_token,
1690                 ty: Box::new(ty),
1691             })
1692         }
1693     }
1694 
1695     fn parse_fn_args(
1696         input: ParseStream,
1697     ) -> Result<(Punctuated<FnArg, Token![,]>, Option<Variadic>)> {
1698         let mut args = Punctuated::new();
1699         let mut variadic = None;
1700         let mut has_receiver = false;
1701 
1702         while !input.is_empty() {
1703             let attrs = input.call(Attribute::parse_outer)?;
1704 
1705             if let Some(dots) = input.parse::<Option<Token![...]>>()? {
1706                 variadic = Some(Variadic {
1707                     attrs,
1708                     pat: None,
1709                     dots,
1710                     comma: if input.is_empty() {
1711                         None
1712                     } else {
1713                         Some(input.parse()?)
1714                     },
1715                 });
1716                 break;
1717             }
1718 
1719             let allow_variadic = true;
1720             let arg = match parse_fn_arg_or_variadic(input, attrs, allow_variadic)? {
1721                 FnArgOrVariadic::FnArg(arg) => arg,
1722                 FnArgOrVariadic::Variadic(arg) => {
1723                     variadic = Some(Variadic {
1724                         comma: if input.is_empty() {
1725                             None
1726                         } else {
1727                             Some(input.parse()?)
1728                         },
1729                         ..arg
1730                     });
1731                     break;
1732                 }
1733             };
1734 
1735             match &arg {
1736                 FnArg::Receiver(receiver) if has_receiver => {
1737                     return Err(Error::new(
1738                         receiver.self_token.span,
1739                         "unexpected second method receiver",
1740                     ));
1741                 }
1742                 FnArg::Receiver(receiver) if !args.is_empty() => {
1743                     return Err(Error::new(
1744                         receiver.self_token.span,
1745                         "unexpected method receiver",
1746                     ));
1747                 }
1748                 FnArg::Receiver(_) => has_receiver = true,
1749                 FnArg::Typed(_) => {}
1750             }
1751             args.push_value(arg);
1752 
1753             if input.is_empty() {
1754                 break;
1755             }
1756 
1757             let comma: Token![,] = input.parse()?;
1758             args.push_punct(comma);
1759         }
1760 
1761         Ok((args, variadic))
1762     }
1763 
1764     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1765     impl Parse for ItemMod {
1766         fn parse(input: ParseStream) -> Result<Self> {
1767             let mut attrs = input.call(Attribute::parse_outer)?;
1768             let vis: Visibility = input.parse()?;
1769             let unsafety: Option<Token![unsafe]> = input.parse()?;
1770             let mod_token: Token![mod] = input.parse()?;
1771             let ident: Ident = if input.peek(Token![try]) {
1772                 input.call(Ident::parse_any)
1773             } else {
1774                 input.parse()
1775             }?;
1776 
1777             let lookahead = input.lookahead1();
1778             if lookahead.peek(Token![;]) {
1779                 Ok(ItemMod {
1780                     attrs,
1781                     vis,
1782                     unsafety,
1783                     mod_token,
1784                     ident,
1785                     content: None,
1786                     semi: Some(input.parse()?),
1787                 })
1788             } else if lookahead.peek(token::Brace) {
1789                 let content;
1790                 let brace_token = braced!(content in input);
1791                 attr::parsing::parse_inner(&content, &mut attrs)?;
1792 
1793                 let mut items = Vec::new();
1794                 while !content.is_empty() {
1795                     items.push(content.parse()?);
1796                 }
1797 
1798                 Ok(ItemMod {
1799                     attrs,
1800                     vis,
1801                     unsafety,
1802                     mod_token,
1803                     ident,
1804                     content: Some((brace_token, items)),
1805                     semi: None,
1806                 })
1807             } else {
1808                 Err(lookahead.error())
1809             }
1810         }
1811     }
1812 
1813     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1814     impl Parse for ItemForeignMod {
1815         fn parse(input: ParseStream) -> Result<Self> {
1816             let mut attrs = input.call(Attribute::parse_outer)?;
1817             let unsafety: Option<Token![unsafe]> = input.parse()?;
1818             let abi: Abi = input.parse()?;
1819 
1820             let content;
1821             let brace_token = braced!(content in input);
1822             attr::parsing::parse_inner(&content, &mut attrs)?;
1823             let mut items = Vec::new();
1824             while !content.is_empty() {
1825                 items.push(content.parse()?);
1826             }
1827 
1828             Ok(ItemForeignMod {
1829                 attrs,
1830                 unsafety,
1831                 abi,
1832                 brace_token,
1833                 items,
1834             })
1835         }
1836     }
1837 
1838     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1839     impl Parse for ForeignItem {
1840         fn parse(input: ParseStream) -> Result<Self> {
1841             let begin = input.fork();
1842             let mut attrs = input.call(Attribute::parse_outer)?;
1843             let ahead = input.fork();
1844             let vis: Visibility = ahead.parse()?;
1845 
1846             let lookahead = ahead.lookahead1();
1847             let allow_safe = true;
1848             let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead, allow_safe) {
1849                 let vis: Visibility = input.parse()?;
1850                 let sig = parse_signature(input, allow_safe)?;
1851                 let has_safe = sig.is_none();
1852                 let has_body = input.peek(token::Brace);
1853                 let semi_token: Option<Token![;]> = if has_body {
1854                     let content;
1855                     braced!(content in input);
1856                     content.call(Attribute::parse_inner)?;
1857                     content.call(Block::parse_within)?;
1858                     None
1859                 } else {
1860                     Some(input.parse()?)
1861                 };
1862                 if has_safe || has_body {
1863                     Ok(ForeignItem::Verbatim(verbatim::between(&begin, input)))
1864                 } else {
1865                     Ok(ForeignItem::Fn(ForeignItemFn {
1866                         attrs: Vec::new(),
1867                         vis,
1868                         sig: sig.unwrap(),
1869                         semi_token: semi_token.unwrap(),
1870                     }))
1871                 }
1872             } else if lookahead.peek(Token![static])
1873                 || ((ahead.peek(Token![unsafe])
1874                     || token::parsing::peek_keyword(ahead.cursor(), "safe"))
1875                     && ahead.peek2(Token![static]))
1876             {
1877                 let vis = input.parse()?;
1878                 let unsafety: Option<Token![unsafe]> = input.parse()?;
1879                 let safe =
1880                     unsafety.is_none() && token::parsing::peek_keyword(input.cursor(), "safe");
1881                 if safe {
1882                     token::parsing::keyword(input, "safe")?;
1883                 }
1884                 let static_token = input.parse()?;
1885                 let mutability = input.parse()?;
1886                 let ident = input.parse()?;
1887                 let colon_token = input.parse()?;
1888                 let ty = input.parse()?;
1889                 let has_value = input.peek(Token![=]);
1890                 if has_value {
1891                     input.parse::<Token![=]>()?;
1892                     input.parse::<Expr>()?;
1893                 }
1894                 let semi_token: Token![;] = input.parse()?;
1895                 if unsafety.is_some() || safe || has_value {
1896                     Ok(ForeignItem::Verbatim(verbatim::between(&begin, input)))
1897                 } else {
1898                     Ok(ForeignItem::Static(ForeignItemStatic {
1899                         attrs: Vec::new(),
1900                         vis,
1901                         static_token,
1902                         mutability,
1903                         ident,
1904                         colon_token,
1905                         ty,
1906                         semi_token,
1907                     }))
1908                 }
1909             } else if lookahead.peek(Token![type]) {
1910                 parse_foreign_item_type(begin, input)
1911             } else if vis.is_inherited()
1912                 && (lookahead.peek(Ident)
1913                     || lookahead.peek(Token![self])
1914                     || lookahead.peek(Token![super])
1915                     || lookahead.peek(Token![crate])
1916                     || lookahead.peek(Token![::]))
1917             {
1918                 input.parse().map(ForeignItem::Macro)
1919             } else {
1920                 Err(lookahead.error())
1921             }?;
1922 
1923             let item_attrs = match &mut item {
1924                 ForeignItem::Fn(item) => &mut item.attrs,
1925                 ForeignItem::Static(item) => &mut item.attrs,
1926                 ForeignItem::Type(item) => &mut item.attrs,
1927                 ForeignItem::Macro(item) => &mut item.attrs,
1928                 ForeignItem::Verbatim(_) => return Ok(item),
1929             };
1930             attrs.append(item_attrs);
1931             *item_attrs = attrs;
1932 
1933             Ok(item)
1934         }
1935     }
1936 
1937     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1938     impl Parse for ForeignItemFn {
1939         fn parse(input: ParseStream) -> Result<Self> {
1940             let attrs = input.call(Attribute::parse_outer)?;
1941             let vis: Visibility = input.parse()?;
1942             let sig: Signature = input.parse()?;
1943             let semi_token: Token![;] = input.parse()?;
1944             Ok(ForeignItemFn {
1945                 attrs,
1946                 vis,
1947                 sig,
1948                 semi_token,
1949             })
1950         }
1951     }
1952 
1953     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1954     impl Parse for ForeignItemStatic {
1955         fn parse(input: ParseStream) -> Result<Self> {
1956             Ok(ForeignItemStatic {
1957                 attrs: input.call(Attribute::parse_outer)?,
1958                 vis: input.parse()?,
1959                 static_token: input.parse()?,
1960                 mutability: input.parse()?,
1961                 ident: input.parse()?,
1962                 colon_token: input.parse()?,
1963                 ty: input.parse()?,
1964                 semi_token: input.parse()?,
1965             })
1966         }
1967     }
1968 
1969     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1970     impl Parse for ForeignItemType {
1971         fn parse(input: ParseStream) -> Result<Self> {
1972             Ok(ForeignItemType {
1973                 attrs: input.call(Attribute::parse_outer)?,
1974                 vis: input.parse()?,
1975                 type_token: input.parse()?,
1976                 ident: input.parse()?,
1977                 generics: {
1978                     let mut generics: Generics = input.parse()?;
1979                     generics.where_clause = input.parse()?;
1980                     generics
1981                 },
1982                 semi_token: input.parse()?,
1983             })
1984         }
1985     }
1986 
1987     fn parse_foreign_item_type(begin: ParseBuffer, input: ParseStream) -> Result<ForeignItem> {
1988         let FlexibleItemType {
1989             vis,
1990             defaultness: _,
1991             type_token,
1992             ident,
1993             generics,
1994             colon_token,
1995             bounds: _,
1996             ty,
1997             semi_token,
1998         } = FlexibleItemType::parse(
1999             input,
2000             TypeDefaultness::Disallowed,
2001             WhereClauseLocation::Both,
2002         )?;
2003 
2004         if colon_token.is_some() || ty.is_some() {
2005             Ok(ForeignItem::Verbatim(verbatim::between(&begin, input)))
2006         } else {
2007             Ok(ForeignItem::Type(ForeignItemType {
2008                 attrs: Vec::new(),
2009                 vis,
2010                 type_token,
2011                 ident,
2012                 generics,
2013                 semi_token,
2014             }))
2015         }
2016     }
2017 
2018     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2019     impl Parse for ForeignItemMacro {
2020         fn parse(input: ParseStream) -> Result<Self> {
2021             let attrs = input.call(Attribute::parse_outer)?;
2022             let mac: Macro = input.parse()?;
2023             let semi_token: Option<Token![;]> = if mac.delimiter.is_brace() {
2024                 None
2025             } else {
2026                 Some(input.parse()?)
2027             };
2028             Ok(ForeignItemMacro {
2029                 attrs,
2030                 mac,
2031                 semi_token,
2032             })
2033         }
2034     }
2035 
2036     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2037     impl Parse for ItemType {
2038         fn parse(input: ParseStream) -> Result<Self> {
2039             Ok(ItemType {
2040                 attrs: input.call(Attribute::parse_outer)?,
2041                 vis: input.parse()?,
2042                 type_token: input.parse()?,
2043                 ident: input.parse()?,
2044                 generics: {
2045                     let mut generics: Generics = input.parse()?;
2046                     generics.where_clause = input.parse()?;
2047                     generics
2048                 },
2049                 eq_token: input.parse()?,
2050                 ty: input.parse()?,
2051                 semi_token: input.parse()?,
2052             })
2053         }
2054     }
2055 
2056     fn parse_item_type(begin: ParseBuffer, input: ParseStream) -> Result<Item> {
2057         let FlexibleItemType {
2058             vis,
2059             defaultness: _,
2060             type_token,
2061             ident,
2062             generics,
2063             colon_token,
2064             bounds: _,
2065             ty,
2066             semi_token,
2067         } = FlexibleItemType::parse(
2068             input,
2069             TypeDefaultness::Disallowed,
2070             WhereClauseLocation::BeforeEq,
2071         )?;
2072 
2073         let (eq_token, ty) = match ty {
2074             Some(ty) if colon_token.is_none() => ty,
2075             _ => return Ok(Item::Verbatim(verbatim::between(&begin, input))),
2076         };
2077 
2078         Ok(Item::Type(ItemType {
2079             attrs: Vec::new(),
2080             vis,
2081             type_token,
2082             ident,
2083             generics,
2084             eq_token,
2085             ty: Box::new(ty),
2086             semi_token,
2087         }))
2088     }
2089 
2090     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2091     impl Parse for ItemStruct {
2092         fn parse(input: ParseStream) -> Result<Self> {
2093             let attrs = input.call(Attribute::parse_outer)?;
2094             let vis = input.parse::<Visibility>()?;
2095             let struct_token = input.parse::<Token![struct]>()?;
2096             let ident = input.parse::<Ident>()?;
2097             let generics = input.parse::<Generics>()?;
2098             let (where_clause, fields, semi_token) = derive::parsing::data_struct(input)?;
2099             Ok(ItemStruct {
2100                 attrs,
2101                 vis,
2102                 struct_token,
2103                 ident,
2104                 generics: Generics {
2105                     where_clause,
2106                     ..generics
2107                 },
2108                 fields,
2109                 semi_token,
2110             })
2111         }
2112     }
2113 
2114     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2115     impl Parse for ItemEnum {
2116         fn parse(input: ParseStream) -> Result<Self> {
2117             let attrs = input.call(Attribute::parse_outer)?;
2118             let vis = input.parse::<Visibility>()?;
2119             let enum_token = input.parse::<Token![enum]>()?;
2120             let ident = input.parse::<Ident>()?;
2121             let generics = input.parse::<Generics>()?;
2122             let (where_clause, brace_token, variants) = derive::parsing::data_enum(input)?;
2123             Ok(ItemEnum {
2124                 attrs,
2125                 vis,
2126                 enum_token,
2127                 ident,
2128                 generics: Generics {
2129                     where_clause,
2130                     ..generics
2131                 },
2132                 brace_token,
2133                 variants,
2134             })
2135         }
2136     }
2137 
2138     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2139     impl Parse for ItemUnion {
2140         fn parse(input: ParseStream) -> Result<Self> {
2141             let attrs = input.call(Attribute::parse_outer)?;
2142             let vis = input.parse::<Visibility>()?;
2143             let union_token = input.parse::<Token![union]>()?;
2144             let ident = input.parse::<Ident>()?;
2145             let generics = input.parse::<Generics>()?;
2146             let (where_clause, fields) = derive::parsing::data_union(input)?;
2147             Ok(ItemUnion {
2148                 attrs,
2149                 vis,
2150                 union_token,
2151                 ident,
2152                 generics: Generics {
2153                     where_clause,
2154                     ..generics
2155                 },
2156                 fields,
2157             })
2158         }
2159     }
2160 
2161     fn parse_trait_or_trait_alias(input: ParseStream) -> Result<Item> {
2162         let (attrs, vis, trait_token, ident, generics) = parse_start_of_trait_alias(input)?;
2163         let lookahead = input.lookahead1();
2164         if lookahead.peek(token::Brace)
2165             || lookahead.peek(Token![:])
2166             || lookahead.peek(Token![where])
2167         {
2168             let unsafety = None;
2169             let auto_token = None;
2170             parse_rest_of_trait(
2171                 input,
2172                 attrs,
2173                 vis,
2174                 unsafety,
2175                 auto_token,
2176                 trait_token,
2177                 ident,
2178                 generics,
2179             )
2180             .map(Item::Trait)
2181         } else if lookahead.peek(Token![=]) {
2182             parse_rest_of_trait_alias(input, attrs, vis, trait_token, ident, generics)
2183                 .map(Item::TraitAlias)
2184         } else {
2185             Err(lookahead.error())
2186         }
2187     }
2188 
2189     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2190     impl Parse for ItemTrait {
2191         fn parse(input: ParseStream) -> Result<Self> {
2192             let outer_attrs = input.call(Attribute::parse_outer)?;
2193             let vis: Visibility = input.parse()?;
2194             let unsafety: Option<Token![unsafe]> = input.parse()?;
2195             let auto_token: Option<Token![auto]> = input.parse()?;
2196             let trait_token: Token![trait] = input.parse()?;
2197             let ident: Ident = input.parse()?;
2198             let generics: Generics = input.parse()?;
2199             parse_rest_of_trait(
2200                 input,
2201                 outer_attrs,
2202                 vis,
2203                 unsafety,
2204                 auto_token,
2205                 trait_token,
2206                 ident,
2207                 generics,
2208             )
2209         }
2210     }
2211 
2212     fn parse_rest_of_trait(
2213         input: ParseStream,
2214         mut attrs: Vec<Attribute>,
2215         vis: Visibility,
2216         unsafety: Option<Token![unsafe]>,
2217         auto_token: Option<Token![auto]>,
2218         trait_token: Token![trait],
2219         ident: Ident,
2220         mut generics: Generics,
2221     ) -> Result<ItemTrait> {
2222         let colon_token: Option<Token![:]> = input.parse()?;
2223 
2224         let mut supertraits = Punctuated::new();
2225         if colon_token.is_some() {
2226             loop {
2227                 if input.peek(Token![where]) || input.peek(token::Brace) {
2228                     break;
2229                 }
2230                 supertraits.push_value({
2231                     let allow_precise_capture = false;
2232                     let allow_const = true;
2233                     TypeParamBound::parse_single(input, allow_precise_capture, allow_const)?
2234                 });
2235                 if input.peek(Token![where]) || input.peek(token::Brace) {
2236                     break;
2237                 }
2238                 supertraits.push_punct(input.parse()?);
2239             }
2240         }
2241 
2242         generics.where_clause = input.parse()?;
2243 
2244         let content;
2245         let brace_token = braced!(content in input);
2246         attr::parsing::parse_inner(&content, &mut attrs)?;
2247         let mut items = Vec::new();
2248         while !content.is_empty() {
2249             items.push(content.parse()?);
2250         }
2251 
2252         Ok(ItemTrait {
2253             attrs,
2254             vis,
2255             unsafety,
2256             auto_token,
2257             restriction: None,
2258             trait_token,
2259             ident,
2260             generics,
2261             colon_token,
2262             supertraits,
2263             brace_token,
2264             items,
2265         })
2266     }
2267 
2268     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2269     impl Parse for ItemTraitAlias {
2270         fn parse(input: ParseStream) -> Result<Self> {
2271             let (attrs, vis, trait_token, ident, generics) = parse_start_of_trait_alias(input)?;
2272             parse_rest_of_trait_alias(input, attrs, vis, trait_token, ident, generics)
2273         }
2274     }
2275 
2276     fn parse_start_of_trait_alias(
2277         input: ParseStream,
2278     ) -> Result<(Vec<Attribute>, Visibility, Token![trait], Ident, Generics)> {
2279         let attrs = input.call(Attribute::parse_outer)?;
2280         let vis: Visibility = input.parse()?;
2281         let trait_token: Token![trait] = input.parse()?;
2282         let ident: Ident = input.parse()?;
2283         let generics: Generics = input.parse()?;
2284         Ok((attrs, vis, trait_token, ident, generics))
2285     }
2286 
2287     fn parse_rest_of_trait_alias(
2288         input: ParseStream,
2289         attrs: Vec<Attribute>,
2290         vis: Visibility,
2291         trait_token: Token![trait],
2292         ident: Ident,
2293         mut generics: Generics,
2294     ) -> Result<ItemTraitAlias> {
2295         let eq_token: Token![=] = input.parse()?;
2296 
2297         let mut bounds = Punctuated::new();
2298         loop {
2299             if input.peek(Token![where]) || input.peek(Token![;]) {
2300                 break;
2301             }
2302             bounds.push_value({
2303                 let allow_precise_capture = false;
2304                 let allow_const = false;
2305                 TypeParamBound::parse_single(input, allow_precise_capture, allow_const)?
2306             });
2307             if input.peek(Token![where]) || input.peek(Token![;]) {
2308                 break;
2309             }
2310             bounds.push_punct(input.parse()?);
2311         }
2312 
2313         generics.where_clause = input.parse()?;
2314         let semi_token: Token![;] = input.parse()?;
2315 
2316         Ok(ItemTraitAlias {
2317             attrs,
2318             vis,
2319             trait_token,
2320             ident,
2321             generics,
2322             eq_token,
2323             bounds,
2324             semi_token,
2325         })
2326     }
2327 
2328     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2329     impl Parse for TraitItem {
2330         fn parse(input: ParseStream) -> Result<Self> {
2331             let begin = input.fork();
2332             let mut attrs = input.call(Attribute::parse_outer)?;
2333             let vis: Visibility = input.parse()?;
2334             let defaultness: Option<Token![default]> = input.parse()?;
2335             let ahead = input.fork();
2336 
2337             let lookahead = ahead.lookahead1();
2338             let allow_safe = false;
2339             let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead, allow_safe) {
2340                 input.parse().map(TraitItem::Fn)
2341             } else if lookahead.peek(Token![const]) {
2342                 let const_token: Token![const] = ahead.parse()?;
2343                 let lookahead = ahead.lookahead1();
2344                 if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
2345                     input.advance_to(&ahead);
2346                     let ident = input.call(Ident::parse_any)?;
2347                     let mut generics: Generics = input.parse()?;
2348                     let colon_token: Token![:] = input.parse()?;
2349                     let ty: Type = input.parse()?;
2350                     let default = if let Some(eq_token) = input.parse::<Option<Token![=]>>()? {
2351                         let expr: Expr = input.parse()?;
2352                         Some((eq_token, expr))
2353                     } else {
2354                         None
2355                     };
2356                     generics.where_clause = input.parse()?;
2357                     let semi_token: Token![;] = input.parse()?;
2358                     if generics.lt_token.is_none() && generics.where_clause.is_none() {
2359                         Ok(TraitItem::Const(TraitItemConst {
2360                             attrs: Vec::new(),
2361                             const_token,
2362                             ident,
2363                             generics,
2364                             colon_token,
2365                             ty,
2366                             default,
2367                             semi_token,
2368                         }))
2369                     } else {
2370                         return Ok(TraitItem::Verbatim(verbatim::between(&begin, input)));
2371                     }
2372                 } else if lookahead.peek(Token![async])
2373                     || lookahead.peek(Token![unsafe])
2374                     || lookahead.peek(Token![extern])
2375                     || lookahead.peek(Token![fn])
2376                 {
2377                     input.parse().map(TraitItem::Fn)
2378                 } else {
2379                     Err(lookahead.error())
2380                 }
2381             } else if lookahead.peek(Token![type]) {
2382                 parse_trait_item_type(begin.fork(), input)
2383             } else if vis.is_inherited()
2384                 && defaultness.is_none()
2385                 && (lookahead.peek(Ident)
2386                     || lookahead.peek(Token![self])
2387                     || lookahead.peek(Token![super])
2388                     || lookahead.peek(Token![crate])
2389                     || lookahead.peek(Token![::]))
2390             {
2391                 input.parse().map(TraitItem::Macro)
2392             } else {
2393                 Err(lookahead.error())
2394             }?;
2395 
2396             match (vis, defaultness) {
2397                 (Visibility::Inherited, None) => {}
2398                 _ => return Ok(TraitItem::Verbatim(verbatim::between(&begin, input))),
2399             }
2400 
2401             let item_attrs = match &mut item {
2402                 TraitItem::Const(item) => &mut item.attrs,
2403                 TraitItem::Fn(item) => &mut item.attrs,
2404                 TraitItem::Type(item) => &mut item.attrs,
2405                 TraitItem::Macro(item) => &mut item.attrs,
2406                 TraitItem::Verbatim(_) => unreachable!(),
2407             };
2408             attrs.append(item_attrs);
2409             *item_attrs = attrs;
2410             Ok(item)
2411         }
2412     }
2413 
2414     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2415     impl Parse for TraitItemConst {
2416         fn parse(input: ParseStream) -> Result<Self> {
2417             let attrs = input.call(Attribute::parse_outer)?;
2418             let const_token: Token![const] = input.parse()?;
2419 
2420             let lookahead = input.lookahead1();
2421             let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
2422                 input.call(Ident::parse_any)?
2423             } else {
2424                 return Err(lookahead.error());
2425             };
2426 
2427             let colon_token: Token![:] = input.parse()?;
2428             let ty: Type = input.parse()?;
2429             let default = if input.peek(Token![=]) {
2430                 let eq_token: Token![=] = input.parse()?;
2431                 let default: Expr = input.parse()?;
2432                 Some((eq_token, default))
2433             } else {
2434                 None
2435             };
2436             let semi_token: Token![;] = input.parse()?;
2437 
2438             Ok(TraitItemConst {
2439                 attrs,
2440                 const_token,
2441                 ident,
2442                 generics: Generics::default(),
2443                 colon_token,
2444                 ty,
2445                 default,
2446                 semi_token,
2447             })
2448         }
2449     }
2450 
2451     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2452     impl Parse for TraitItemFn {
2453         fn parse(input: ParseStream) -> Result<Self> {
2454             let mut attrs = input.call(Attribute::parse_outer)?;
2455             let sig: Signature = input.parse()?;
2456 
2457             let lookahead = input.lookahead1();
2458             let (brace_token, stmts, semi_token) = if lookahead.peek(token::Brace) {
2459                 let content;
2460                 let brace_token = braced!(content in input);
2461                 attr::parsing::parse_inner(&content, &mut attrs)?;
2462                 let stmts = content.call(Block::parse_within)?;
2463                 (Some(brace_token), stmts, None)
2464             } else if lookahead.peek(Token![;]) {
2465                 let semi_token: Token![;] = input.parse()?;
2466                 (None, Vec::new(), Some(semi_token))
2467             } else {
2468                 return Err(lookahead.error());
2469             };
2470 
2471             Ok(TraitItemFn {
2472                 attrs,
2473                 sig,
2474                 default: brace_token.map(|brace_token| Block { brace_token, stmts }),
2475                 semi_token,
2476             })
2477         }
2478     }
2479 
2480     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2481     impl Parse for TraitItemType {
2482         fn parse(input: ParseStream) -> Result<Self> {
2483             let attrs = input.call(Attribute::parse_outer)?;
2484             let type_token: Token![type] = input.parse()?;
2485             let ident: Ident = input.parse()?;
2486             let mut generics: Generics = input.parse()?;
2487             let (colon_token, bounds) = FlexibleItemType::parse_optional_bounds(input)?;
2488             let default = FlexibleItemType::parse_optional_definition(input)?;
2489             generics.where_clause = input.parse()?;
2490             let semi_token: Token![;] = input.parse()?;
2491             Ok(TraitItemType {
2492                 attrs,
2493                 type_token,
2494                 ident,
2495                 generics,
2496                 colon_token,
2497                 bounds,
2498                 default,
2499                 semi_token,
2500             })
2501         }
2502     }
2503 
2504     fn parse_trait_item_type(begin: ParseBuffer, input: ParseStream) -> Result<TraitItem> {
2505         let FlexibleItemType {
2506             vis,
2507             defaultness: _,
2508             type_token,
2509             ident,
2510             generics,
2511             colon_token,
2512             bounds,
2513             ty,
2514             semi_token,
2515         } = FlexibleItemType::parse(
2516             input,
2517             TypeDefaultness::Disallowed,
2518             WhereClauseLocation::AfterEq,
2519         )?;
2520 
2521         if vis.is_some() {
2522             Ok(TraitItem::Verbatim(verbatim::between(&begin, input)))
2523         } else {
2524             Ok(TraitItem::Type(TraitItemType {
2525                 attrs: Vec::new(),
2526                 type_token,
2527                 ident,
2528                 generics,
2529                 colon_token,
2530                 bounds,
2531                 default: ty,
2532                 semi_token,
2533             }))
2534         }
2535     }
2536 
2537     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2538     impl Parse for TraitItemMacro {
2539         fn parse(input: ParseStream) -> Result<Self> {
2540             let attrs = input.call(Attribute::parse_outer)?;
2541             let mac: Macro = input.parse()?;
2542             let semi_token: Option<Token![;]> = if mac.delimiter.is_brace() {
2543                 None
2544             } else {
2545                 Some(input.parse()?)
2546             };
2547             Ok(TraitItemMacro {
2548                 attrs,
2549                 mac,
2550                 semi_token,
2551             })
2552         }
2553     }
2554 
2555     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2556     impl Parse for ItemImpl {
2557         fn parse(input: ParseStream) -> Result<Self> {
2558             let allow_verbatim_impl = false;
2559             parse_impl(input, allow_verbatim_impl).map(Option::unwrap)
2560         }
2561     }
2562 
2563     fn parse_impl(input: ParseStream, allow_verbatim_impl: bool) -> Result<Option<ItemImpl>> {
2564         let mut attrs = input.call(Attribute::parse_outer)?;
2565         let has_visibility = allow_verbatim_impl && input.parse::<Visibility>()?.is_some();
2566         let defaultness: Option<Token![default]> = input.parse()?;
2567         let unsafety: Option<Token![unsafe]> = input.parse()?;
2568         let impl_token: Token![impl] = input.parse()?;
2569 
2570         let has_generics = generics::parsing::choose_generics_over_qpath(input);
2571         let mut generics: Generics = if has_generics {
2572             input.parse()?
2573         } else {
2574             Generics::default()
2575         };
2576 
2577         let is_const_impl = allow_verbatim_impl
2578             && (input.peek(Token![const]) || input.peek(Token![?]) && input.peek2(Token![const]));
2579         if is_const_impl {
2580             input.parse::<Option<Token![?]>>()?;
2581             input.parse::<Token![const]>()?;
2582         }
2583 
2584         let polarity = if input.peek(Token![!]) && !input.peek2(token::Brace) {
2585             Some(input.parse::<Token![!]>()?)
2586         } else {
2587             None
2588         };
2589 
2590         #[cfg(not(feature = "printing"))]
2591         let first_ty_span = input.span();
2592         let mut first_ty: Type = input.parse()?;
2593         let self_ty: Type;
2594         let trait_;
2595 
2596         let is_impl_for = input.peek(Token![for]);
2597         if is_impl_for {
2598             let for_token: Token![for] = input.parse()?;
2599             let mut first_ty_ref = &first_ty;
2600             while let Type::Group(ty) = first_ty_ref {
2601                 first_ty_ref = &ty.elem;
2602             }
2603             if let Type::Path(TypePath { qself: None, .. }) = first_ty_ref {
2604                 while let Type::Group(ty) = first_ty {
2605                     first_ty = *ty.elem;
2606                 }
2607                 if let Type::Path(TypePath { qself: None, path }) = first_ty {
2608                     trait_ = Some((polarity, path, for_token));
2609                 } else {
2610                     unreachable!();
2611                 }
2612             } else if !allow_verbatim_impl {
2613                 #[cfg(feature = "printing")]
2614                 return Err(Error::new_spanned(first_ty_ref, "expected trait path"));
2615                 #[cfg(not(feature = "printing"))]
2616                 return Err(Error::new(first_ty_span, "expected trait path"));
2617             } else {
2618                 trait_ = None;
2619             }
2620             self_ty = input.parse()?;
2621         } else if let Some(polarity) = polarity {
2622             return Err(Error::new(
2623                 polarity.span,
2624                 "inherent impls cannot be negative",
2625             ));
2626         } else {
2627             trait_ = None;
2628             self_ty = first_ty;
2629         }
2630 
2631         generics.where_clause = input.parse()?;
2632 
2633         let content;
2634         let brace_token = braced!(content in input);
2635         attr::parsing::parse_inner(&content, &mut attrs)?;
2636 
2637         let mut items = Vec::new();
2638         while !content.is_empty() {
2639             items.push(content.parse()?);
2640         }
2641 
2642         if has_visibility || is_const_impl || is_impl_for && trait_.is_none() {
2643             Ok(None)
2644         } else {
2645             Ok(Some(ItemImpl {
2646                 attrs,
2647                 defaultness,
2648                 unsafety,
2649                 impl_token,
2650                 generics,
2651                 trait_,
2652                 self_ty: Box::new(self_ty),
2653                 brace_token,
2654                 items,
2655             }))
2656         }
2657     }
2658 
2659     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2660     impl Parse for ImplItem {
2661         fn parse(input: ParseStream) -> Result<Self> {
2662             let begin = input.fork();
2663             let mut attrs = input.call(Attribute::parse_outer)?;
2664             let ahead = input.fork();
2665             let vis: Visibility = ahead.parse()?;
2666 
2667             let mut lookahead = ahead.lookahead1();
2668             let defaultness = if lookahead.peek(Token![default]) && !ahead.peek2(Token![!]) {
2669                 let defaultness: Token![default] = ahead.parse()?;
2670                 lookahead = ahead.lookahead1();
2671                 Some(defaultness)
2672             } else {
2673                 None
2674             };
2675 
2676             let allow_safe = false;
2677             let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead, allow_safe) {
2678                 let allow_omitted_body = true;
2679                 if let Some(item) = parse_impl_item_fn(input, allow_omitted_body)? {
2680                     Ok(ImplItem::Fn(item))
2681                 } else {
2682                     Ok(ImplItem::Verbatim(verbatim::between(&begin, input)))
2683                 }
2684             } else if lookahead.peek(Token![const]) {
2685                 input.advance_to(&ahead);
2686                 let const_token: Token![const] = input.parse()?;
2687                 let lookahead = input.lookahead1();
2688                 let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
2689                     input.call(Ident::parse_any)?
2690                 } else {
2691                     return Err(lookahead.error());
2692                 };
2693                 let mut generics: Generics = input.parse()?;
2694                 let colon_token: Token![:] = input.parse()?;
2695                 let ty: Type = input.parse()?;
2696                 let value = if let Some(eq_token) = input.parse::<Option<Token![=]>>()? {
2697                     let expr: Expr = input.parse()?;
2698                     Some((eq_token, expr))
2699                 } else {
2700                     None
2701                 };
2702                 generics.where_clause = input.parse()?;
2703                 let semi_token: Token![;] = input.parse()?;
2704                 return match value {
2705                     Some((eq_token, expr))
2706                         if generics.lt_token.is_none() && generics.where_clause.is_none() =>
2707                     {
2708                         Ok(ImplItem::Const(ImplItemConst {
2709                             attrs,
2710                             vis,
2711                             defaultness,
2712                             const_token,
2713                             ident,
2714                             generics,
2715                             colon_token,
2716                             ty,
2717                             eq_token,
2718                             expr,
2719                             semi_token,
2720                         }))
2721                     }
2722                     _ => Ok(ImplItem::Verbatim(verbatim::between(&begin, input))),
2723                 };
2724             } else if lookahead.peek(Token![type]) {
2725                 parse_impl_item_type(begin, input)
2726             } else if vis.is_inherited()
2727                 && defaultness.is_none()
2728                 && (lookahead.peek(Ident)
2729                     || lookahead.peek(Token![self])
2730                     || lookahead.peek(Token![super])
2731                     || lookahead.peek(Token![crate])
2732                     || lookahead.peek(Token![::]))
2733             {
2734                 input.parse().map(ImplItem::Macro)
2735             } else {
2736                 Err(lookahead.error())
2737             }?;
2738 
2739             {
2740                 let item_attrs = match &mut item {
2741                     ImplItem::Const(item) => &mut item.attrs,
2742                     ImplItem::Fn(item) => &mut item.attrs,
2743                     ImplItem::Type(item) => &mut item.attrs,
2744                     ImplItem::Macro(item) => &mut item.attrs,
2745                     ImplItem::Verbatim(_) => return Ok(item),
2746                 };
2747                 attrs.append(item_attrs);
2748                 *item_attrs = attrs;
2749             }
2750 
2751             Ok(item)
2752         }
2753     }
2754 
2755     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2756     impl Parse for ImplItemConst {
2757         fn parse(input: ParseStream) -> Result<Self> {
2758             let attrs = input.call(Attribute::parse_outer)?;
2759             let vis: Visibility = input.parse()?;
2760             let defaultness: Option<Token![default]> = input.parse()?;
2761             let const_token: Token![const] = input.parse()?;
2762 
2763             let lookahead = input.lookahead1();
2764             let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
2765                 input.call(Ident::parse_any)?
2766             } else {
2767                 return Err(lookahead.error());
2768             };
2769 
2770             let colon_token: Token![:] = input.parse()?;
2771             let ty: Type = input.parse()?;
2772             let eq_token: Token![=] = input.parse()?;
2773             let expr: Expr = input.parse()?;
2774             let semi_token: Token![;] = input.parse()?;
2775 
2776             Ok(ImplItemConst {
2777                 attrs,
2778                 vis,
2779                 defaultness,
2780                 const_token,
2781                 ident,
2782                 generics: Generics::default(),
2783                 colon_token,
2784                 ty,
2785                 eq_token,
2786                 expr,
2787                 semi_token,
2788             })
2789         }
2790     }
2791 
2792     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2793     impl Parse for ImplItemFn {
2794         fn parse(input: ParseStream) -> Result<Self> {
2795             let allow_omitted_body = false;
2796             parse_impl_item_fn(input, allow_omitted_body).map(Option::unwrap)
2797         }
2798     }
2799 
2800     fn parse_impl_item_fn(
2801         input: ParseStream,
2802         allow_omitted_body: bool,
2803     ) -> Result<Option<ImplItemFn>> {
2804         let mut attrs = input.call(Attribute::parse_outer)?;
2805         let vis: Visibility = input.parse()?;
2806         let defaultness: Option<Token![default]> = input.parse()?;
2807         let sig: Signature = input.parse()?;
2808 
2809         // Accept functions without a body in an impl block because rustc's
2810         // *parser* does not reject them (the compilation error is emitted later
2811         // than parsing) and it can be useful for macro DSLs.
2812         if allow_omitted_body && input.parse::<Option<Token![;]>>()?.is_some() {
2813             return Ok(None);
2814         }
2815 
2816         let content;
2817         let brace_token = braced!(content in input);
2818         attrs.extend(content.call(Attribute::parse_inner)?);
2819         let block = Block {
2820             brace_token,
2821             stmts: content.call(Block::parse_within)?,
2822         };
2823 
2824         Ok(Some(ImplItemFn {
2825             attrs,
2826             vis,
2827             defaultness,
2828             sig,
2829             block,
2830         }))
2831     }
2832 
2833     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2834     impl Parse for ImplItemType {
2835         fn parse(input: ParseStream) -> Result<Self> {
2836             let attrs = input.call(Attribute::parse_outer)?;
2837             let vis: Visibility = input.parse()?;
2838             let defaultness: Option<Token![default]> = input.parse()?;
2839             let type_token: Token![type] = input.parse()?;
2840             let ident: Ident = input.parse()?;
2841             let mut generics: Generics = input.parse()?;
2842             let eq_token: Token![=] = input.parse()?;
2843             let ty: Type = input.parse()?;
2844             generics.where_clause = input.parse()?;
2845             let semi_token: Token![;] = input.parse()?;
2846             Ok(ImplItemType {
2847                 attrs,
2848                 vis,
2849                 defaultness,
2850                 type_token,
2851                 ident,
2852                 generics,
2853                 eq_token,
2854                 ty,
2855                 semi_token,
2856             })
2857         }
2858     }
2859 
2860     fn parse_impl_item_type(begin: ParseBuffer, input: ParseStream) -> Result<ImplItem> {
2861         let FlexibleItemType {
2862             vis,
2863             defaultness,
2864             type_token,
2865             ident,
2866             generics,
2867             colon_token,
2868             bounds: _,
2869             ty,
2870             semi_token,
2871         } = FlexibleItemType::parse(
2872             input,
2873             TypeDefaultness::Optional,
2874             WhereClauseLocation::AfterEq,
2875         )?;
2876 
2877         let (eq_token, ty) = match ty {
2878             Some(ty) if colon_token.is_none() => ty,
2879             _ => return Ok(ImplItem::Verbatim(verbatim::between(&begin, input))),
2880         };
2881 
2882         Ok(ImplItem::Type(ImplItemType {
2883             attrs: Vec::new(),
2884             vis,
2885             defaultness,
2886             type_token,
2887             ident,
2888             generics,
2889             eq_token,
2890             ty,
2891             semi_token,
2892         }))
2893     }
2894 
2895     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2896     impl Parse for ImplItemMacro {
2897         fn parse(input: ParseStream) -> Result<Self> {
2898             let attrs = input.call(Attribute::parse_outer)?;
2899             let mac: Macro = input.parse()?;
2900             let semi_token: Option<Token![;]> = if mac.delimiter.is_brace() {
2901                 None
2902             } else {
2903                 Some(input.parse()?)
2904             };
2905             Ok(ImplItemMacro {
2906                 attrs,
2907                 mac,
2908                 semi_token,
2909             })
2910         }
2911     }
2912 
2913     impl Visibility {
2914         fn is_inherited(&self) -> bool {
2915             match self {
2916                 Visibility::Inherited => true,
2917                 _ => false,
2918             }
2919         }
2920     }
2921 
2922     #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2923     impl Parse for StaticMutability {
2924         fn parse(input: ParseStream) -> Result<Self> {
2925             let mut_token: Option<Token![mut]> = input.parse()?;
2926             Ok(mut_token.map_or(StaticMutability::None, StaticMutability::Mut))
2927         }
2928     }
2929 }
2930 
2931 #[cfg(feature = "printing")]
2932 mod printing {
2933     use crate::attr::FilterAttrs;
2934     use crate::data::Fields;
2935     use crate::item::{
2936         ForeignItemFn, ForeignItemMacro, ForeignItemStatic, ForeignItemType, ImplItemConst,
2937         ImplItemFn, ImplItemMacro, ImplItemType, ItemConst, ItemEnum, ItemExternCrate, ItemFn,
2938         ItemForeignMod, ItemImpl, ItemMacro, ItemMod, ItemStatic, ItemStruct, ItemTrait,
2939         ItemTraitAlias, ItemType, ItemUnion, ItemUse, Receiver, Signature, StaticMutability,
2940         TraitItemConst, TraitItemFn, TraitItemMacro, TraitItemType, UseGlob, UseGroup, UseName,
2941         UsePath, UseRename, Variadic,
2942     };
2943     use crate::mac::MacroDelimiter;
2944     use crate::path;
2945     use crate::path::printing::PathStyle;
2946     use crate::print::TokensOrDefault;
2947     use crate::ty::Type;
2948     use proc_macro2::TokenStream;
2949     use quote::{ToTokens, TokenStreamExt};
2950 
2951     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
2952     impl ToTokens for ItemExternCrate {
2953         fn to_tokens(&self, tokens: &mut TokenStream) {
2954             tokens.append_all(self.attrs.outer());
2955             self.vis.to_tokens(tokens);
2956             self.extern_token.to_tokens(tokens);
2957             self.crate_token.to_tokens(tokens);
2958             self.ident.to_tokens(tokens);
2959             if let Some((as_token, rename)) = &self.rename {
2960                 as_token.to_tokens(tokens);
2961                 rename.to_tokens(tokens);
2962             }
2963             self.semi_token.to_tokens(tokens);
2964         }
2965     }
2966 
2967     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
2968     impl ToTokens for ItemUse {
2969         fn to_tokens(&self, tokens: &mut TokenStream) {
2970             tokens.append_all(self.attrs.outer());
2971             self.vis.to_tokens(tokens);
2972             self.use_token.to_tokens(tokens);
2973             self.leading_colon.to_tokens(tokens);
2974             self.tree.to_tokens(tokens);
2975             self.semi_token.to_tokens(tokens);
2976         }
2977     }
2978 
2979     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
2980     impl ToTokens for ItemStatic {
2981         fn to_tokens(&self, tokens: &mut TokenStream) {
2982             tokens.append_all(self.attrs.outer());
2983             self.vis.to_tokens(tokens);
2984             self.static_token.to_tokens(tokens);
2985             self.mutability.to_tokens(tokens);
2986             self.ident.to_tokens(tokens);
2987             self.colon_token.to_tokens(tokens);
2988             self.ty.to_tokens(tokens);
2989             self.eq_token.to_tokens(tokens);
2990             self.expr.to_tokens(tokens);
2991             self.semi_token.to_tokens(tokens);
2992         }
2993     }
2994 
2995     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
2996     impl ToTokens for ItemConst {
2997         fn to_tokens(&self, tokens: &mut TokenStream) {
2998             tokens.append_all(self.attrs.outer());
2999             self.vis.to_tokens(tokens);
3000             self.const_token.to_tokens(tokens);
3001             self.ident.to_tokens(tokens);
3002             self.colon_token.to_tokens(tokens);
3003             self.ty.to_tokens(tokens);
3004             self.eq_token.to_tokens(tokens);
3005             self.expr.to_tokens(tokens);
3006             self.semi_token.to_tokens(tokens);
3007         }
3008     }
3009 
3010     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3011     impl ToTokens for ItemFn {
3012         fn to_tokens(&self, tokens: &mut TokenStream) {
3013             tokens.append_all(self.attrs.outer());
3014             self.vis.to_tokens(tokens);
3015             self.sig.to_tokens(tokens);
3016             self.block.brace_token.surround(tokens, |tokens| {
3017                 tokens.append_all(self.attrs.inner());
3018                 tokens.append_all(&self.block.stmts);
3019             });
3020         }
3021     }
3022 
3023     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3024     impl ToTokens for ItemMod {
3025         fn to_tokens(&self, tokens: &mut TokenStream) {
3026             tokens.append_all(self.attrs.outer());
3027             self.vis.to_tokens(tokens);
3028             self.unsafety.to_tokens(tokens);
3029             self.mod_token.to_tokens(tokens);
3030             self.ident.to_tokens(tokens);
3031             if let Some((brace, items)) = &self.content {
3032                 brace.surround(tokens, |tokens| {
3033                     tokens.append_all(self.attrs.inner());
3034                     tokens.append_all(items);
3035                 });
3036             } else {
3037                 TokensOrDefault(&self.semi).to_tokens(tokens);
3038             }
3039         }
3040     }
3041 
3042     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3043     impl ToTokens for ItemForeignMod {
3044         fn to_tokens(&self, tokens: &mut TokenStream) {
3045             tokens.append_all(self.attrs.outer());
3046             self.unsafety.to_tokens(tokens);
3047             self.abi.to_tokens(tokens);
3048             self.brace_token.surround(tokens, |tokens| {
3049                 tokens.append_all(self.attrs.inner());
3050                 tokens.append_all(&self.items);
3051             });
3052         }
3053     }
3054 
3055     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3056     impl ToTokens for ItemType {
3057         fn to_tokens(&self, tokens: &mut TokenStream) {
3058             tokens.append_all(self.attrs.outer());
3059             self.vis.to_tokens(tokens);
3060             self.type_token.to_tokens(tokens);
3061             self.ident.to_tokens(tokens);
3062             self.generics.to_tokens(tokens);
3063             self.generics.where_clause.to_tokens(tokens);
3064             self.eq_token.to_tokens(tokens);
3065             self.ty.to_tokens(tokens);
3066             self.semi_token.to_tokens(tokens);
3067         }
3068     }
3069 
3070     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3071     impl ToTokens for ItemEnum {
3072         fn to_tokens(&self, tokens: &mut TokenStream) {
3073             tokens.append_all(self.attrs.outer());
3074             self.vis.to_tokens(tokens);
3075             self.enum_token.to_tokens(tokens);
3076             self.ident.to_tokens(tokens);
3077             self.generics.to_tokens(tokens);
3078             self.generics.where_clause.to_tokens(tokens);
3079             self.brace_token.surround(tokens, |tokens| {
3080                 self.variants.to_tokens(tokens);
3081             });
3082         }
3083     }
3084 
3085     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3086     impl ToTokens for ItemStruct {
3087         fn to_tokens(&self, tokens: &mut TokenStream) {
3088             tokens.append_all(self.attrs.outer());
3089             self.vis.to_tokens(tokens);
3090             self.struct_token.to_tokens(tokens);
3091             self.ident.to_tokens(tokens);
3092             self.generics.to_tokens(tokens);
3093             match &self.fields {
3094                 Fields::Named(fields) => {
3095                     self.generics.where_clause.to_tokens(tokens);
3096                     fields.to_tokens(tokens);
3097                 }
3098                 Fields::Unnamed(fields) => {
3099                     fields.to_tokens(tokens);
3100                     self.generics.where_clause.to_tokens(tokens);
3101                     TokensOrDefault(&self.semi_token).to_tokens(tokens);
3102                 }
3103                 Fields::Unit => {
3104                     self.generics.where_clause.to_tokens(tokens);
3105                     TokensOrDefault(&self.semi_token).to_tokens(tokens);
3106                 }
3107             }
3108         }
3109     }
3110 
3111     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3112     impl ToTokens for ItemUnion {
3113         fn to_tokens(&self, tokens: &mut TokenStream) {
3114             tokens.append_all(self.attrs.outer());
3115             self.vis.to_tokens(tokens);
3116             self.union_token.to_tokens(tokens);
3117             self.ident.to_tokens(tokens);
3118             self.generics.to_tokens(tokens);
3119             self.generics.where_clause.to_tokens(tokens);
3120             self.fields.to_tokens(tokens);
3121         }
3122     }
3123 
3124     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3125     impl ToTokens for ItemTrait {
3126         fn to_tokens(&self, tokens: &mut TokenStream) {
3127             tokens.append_all(self.attrs.outer());
3128             self.vis.to_tokens(tokens);
3129             self.unsafety.to_tokens(tokens);
3130             self.auto_token.to_tokens(tokens);
3131             self.trait_token.to_tokens(tokens);
3132             self.ident.to_tokens(tokens);
3133             self.generics.to_tokens(tokens);
3134             if !self.supertraits.is_empty() {
3135                 TokensOrDefault(&self.colon_token).to_tokens(tokens);
3136                 self.supertraits.to_tokens(tokens);
3137             }
3138             self.generics.where_clause.to_tokens(tokens);
3139             self.brace_token.surround(tokens, |tokens| {
3140                 tokens.append_all(self.attrs.inner());
3141                 tokens.append_all(&self.items);
3142             });
3143         }
3144     }
3145 
3146     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3147     impl ToTokens for ItemTraitAlias {
3148         fn to_tokens(&self, tokens: &mut TokenStream) {
3149             tokens.append_all(self.attrs.outer());
3150             self.vis.to_tokens(tokens);
3151             self.trait_token.to_tokens(tokens);
3152             self.ident.to_tokens(tokens);
3153             self.generics.to_tokens(tokens);
3154             self.eq_token.to_tokens(tokens);
3155             self.bounds.to_tokens(tokens);
3156             self.generics.where_clause.to_tokens(tokens);
3157             self.semi_token.to_tokens(tokens);
3158         }
3159     }
3160 
3161     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3162     impl ToTokens for ItemImpl {
3163         fn to_tokens(&self, tokens: &mut TokenStream) {
3164             tokens.append_all(self.attrs.outer());
3165             self.defaultness.to_tokens(tokens);
3166             self.unsafety.to_tokens(tokens);
3167             self.impl_token.to_tokens(tokens);
3168             self.generics.to_tokens(tokens);
3169             if let Some((polarity, path, for_token)) = &self.trait_ {
3170                 polarity.to_tokens(tokens);
3171                 path.to_tokens(tokens);
3172                 for_token.to_tokens(tokens);
3173             }
3174             self.self_ty.to_tokens(tokens);
3175             self.generics.where_clause.to_tokens(tokens);
3176             self.brace_token.surround(tokens, |tokens| {
3177                 tokens.append_all(self.attrs.inner());
3178                 tokens.append_all(&self.items);
3179             });
3180         }
3181     }
3182 
3183     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3184     impl ToTokens for ItemMacro {
3185         fn to_tokens(&self, tokens: &mut TokenStream) {
3186             tokens.append_all(self.attrs.outer());
3187             path::printing::print_path(tokens, &self.mac.path, PathStyle::Mod);
3188             self.mac.bang_token.to_tokens(tokens);
3189             self.ident.to_tokens(tokens);
3190             match &self.mac.delimiter {
3191                 MacroDelimiter::Paren(paren) => {
3192                     paren.surround(tokens, |tokens| self.mac.tokens.to_tokens(tokens));
3193                 }
3194                 MacroDelimiter::Brace(brace) => {
3195                     brace.surround(tokens, |tokens| self.mac.tokens.to_tokens(tokens));
3196                 }
3197                 MacroDelimiter::Bracket(bracket) => {
3198                     bracket.surround(tokens, |tokens| self.mac.tokens.to_tokens(tokens));
3199                 }
3200             }
3201             self.semi_token.to_tokens(tokens);
3202         }
3203     }
3204 
3205     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3206     impl ToTokens for UsePath {
3207         fn to_tokens(&self, tokens: &mut TokenStream) {
3208             self.ident.to_tokens(tokens);
3209             self.colon2_token.to_tokens(tokens);
3210             self.tree.to_tokens(tokens);
3211         }
3212     }
3213 
3214     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3215     impl ToTokens for UseName {
3216         fn to_tokens(&self, tokens: &mut TokenStream) {
3217             self.ident.to_tokens(tokens);
3218         }
3219     }
3220 
3221     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3222     impl ToTokens for UseRename {
3223         fn to_tokens(&self, tokens: &mut TokenStream) {
3224             self.ident.to_tokens(tokens);
3225             self.as_token.to_tokens(tokens);
3226             self.rename.to_tokens(tokens);
3227         }
3228     }
3229 
3230     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3231     impl ToTokens for UseGlob {
3232         fn to_tokens(&self, tokens: &mut TokenStream) {
3233             self.star_token.to_tokens(tokens);
3234         }
3235     }
3236 
3237     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3238     impl ToTokens for UseGroup {
3239         fn to_tokens(&self, tokens: &mut TokenStream) {
3240             self.brace_token.surround(tokens, |tokens| {
3241                 self.items.to_tokens(tokens);
3242             });
3243         }
3244     }
3245 
3246     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3247     impl ToTokens for TraitItemConst {
3248         fn to_tokens(&self, tokens: &mut TokenStream) {
3249             tokens.append_all(self.attrs.outer());
3250             self.const_token.to_tokens(tokens);
3251             self.ident.to_tokens(tokens);
3252             self.colon_token.to_tokens(tokens);
3253             self.ty.to_tokens(tokens);
3254             if let Some((eq_token, default)) = &self.default {
3255                 eq_token.to_tokens(tokens);
3256                 default.to_tokens(tokens);
3257             }
3258             self.semi_token.to_tokens(tokens);
3259         }
3260     }
3261 
3262     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3263     impl ToTokens for TraitItemFn {
3264         fn to_tokens(&self, tokens: &mut TokenStream) {
3265             tokens.append_all(self.attrs.outer());
3266             self.sig.to_tokens(tokens);
3267             match &self.default {
3268                 Some(block) => {
3269                     block.brace_token.surround(tokens, |tokens| {
3270                         tokens.append_all(self.attrs.inner());
3271                         tokens.append_all(&block.stmts);
3272                     });
3273                 }
3274                 None => {
3275                     TokensOrDefault(&self.semi_token).to_tokens(tokens);
3276                 }
3277             }
3278         }
3279     }
3280 
3281     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3282     impl ToTokens for TraitItemType {
3283         fn to_tokens(&self, tokens: &mut TokenStream) {
3284             tokens.append_all(self.attrs.outer());
3285             self.type_token.to_tokens(tokens);
3286             self.ident.to_tokens(tokens);
3287             self.generics.to_tokens(tokens);
3288             if !self.bounds.is_empty() {
3289                 TokensOrDefault(&self.colon_token).to_tokens(tokens);
3290                 self.bounds.to_tokens(tokens);
3291             }
3292             if let Some((eq_token, default)) = &self.default {
3293                 eq_token.to_tokens(tokens);
3294                 default.to_tokens(tokens);
3295             }
3296             self.generics.where_clause.to_tokens(tokens);
3297             self.semi_token.to_tokens(tokens);
3298         }
3299     }
3300 
3301     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3302     impl ToTokens for TraitItemMacro {
3303         fn to_tokens(&self, tokens: &mut TokenStream) {
3304             tokens.append_all(self.attrs.outer());
3305             self.mac.to_tokens(tokens);
3306             self.semi_token.to_tokens(tokens);
3307         }
3308     }
3309 
3310     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3311     impl ToTokens for ImplItemConst {
3312         fn to_tokens(&self, tokens: &mut TokenStream) {
3313             tokens.append_all(self.attrs.outer());
3314             self.vis.to_tokens(tokens);
3315             self.defaultness.to_tokens(tokens);
3316             self.const_token.to_tokens(tokens);
3317             self.ident.to_tokens(tokens);
3318             self.colon_token.to_tokens(tokens);
3319             self.ty.to_tokens(tokens);
3320             self.eq_token.to_tokens(tokens);
3321             self.expr.to_tokens(tokens);
3322             self.semi_token.to_tokens(tokens);
3323         }
3324     }
3325 
3326     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3327     impl ToTokens for ImplItemFn {
3328         fn to_tokens(&self, tokens: &mut TokenStream) {
3329             tokens.append_all(self.attrs.outer());
3330             self.vis.to_tokens(tokens);
3331             self.defaultness.to_tokens(tokens);
3332             self.sig.to_tokens(tokens);
3333             self.block.brace_token.surround(tokens, |tokens| {
3334                 tokens.append_all(self.attrs.inner());
3335                 tokens.append_all(&self.block.stmts);
3336             });
3337         }
3338     }
3339 
3340     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3341     impl ToTokens for ImplItemType {
3342         fn to_tokens(&self, tokens: &mut TokenStream) {
3343             tokens.append_all(self.attrs.outer());
3344             self.vis.to_tokens(tokens);
3345             self.defaultness.to_tokens(tokens);
3346             self.type_token.to_tokens(tokens);
3347             self.ident.to_tokens(tokens);
3348             self.generics.to_tokens(tokens);
3349             self.eq_token.to_tokens(tokens);
3350             self.ty.to_tokens(tokens);
3351             self.generics.where_clause.to_tokens(tokens);
3352             self.semi_token.to_tokens(tokens);
3353         }
3354     }
3355 
3356     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3357     impl ToTokens for ImplItemMacro {
3358         fn to_tokens(&self, tokens: &mut TokenStream) {
3359             tokens.append_all(self.attrs.outer());
3360             self.mac.to_tokens(tokens);
3361             self.semi_token.to_tokens(tokens);
3362         }
3363     }
3364 
3365     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3366     impl ToTokens for ForeignItemFn {
3367         fn to_tokens(&self, tokens: &mut TokenStream) {
3368             tokens.append_all(self.attrs.outer());
3369             self.vis.to_tokens(tokens);
3370             self.sig.to_tokens(tokens);
3371             self.semi_token.to_tokens(tokens);
3372         }
3373     }
3374 
3375     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3376     impl ToTokens for ForeignItemStatic {
3377         fn to_tokens(&self, tokens: &mut TokenStream) {
3378             tokens.append_all(self.attrs.outer());
3379             self.vis.to_tokens(tokens);
3380             self.static_token.to_tokens(tokens);
3381             self.mutability.to_tokens(tokens);
3382             self.ident.to_tokens(tokens);
3383             self.colon_token.to_tokens(tokens);
3384             self.ty.to_tokens(tokens);
3385             self.semi_token.to_tokens(tokens);
3386         }
3387     }
3388 
3389     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3390     impl ToTokens for ForeignItemType {
3391         fn to_tokens(&self, tokens: &mut TokenStream) {
3392             tokens.append_all(self.attrs.outer());
3393             self.vis.to_tokens(tokens);
3394             self.type_token.to_tokens(tokens);
3395             self.ident.to_tokens(tokens);
3396             self.generics.to_tokens(tokens);
3397             self.generics.where_clause.to_tokens(tokens);
3398             self.semi_token.to_tokens(tokens);
3399         }
3400     }
3401 
3402     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3403     impl ToTokens for ForeignItemMacro {
3404         fn to_tokens(&self, tokens: &mut TokenStream) {
3405             tokens.append_all(self.attrs.outer());
3406             self.mac.to_tokens(tokens);
3407             self.semi_token.to_tokens(tokens);
3408         }
3409     }
3410 
3411     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3412     impl ToTokens for Signature {
3413         fn to_tokens(&self, tokens: &mut TokenStream) {
3414             self.constness.to_tokens(tokens);
3415             self.asyncness.to_tokens(tokens);
3416             self.unsafety.to_tokens(tokens);
3417             self.abi.to_tokens(tokens);
3418             self.fn_token.to_tokens(tokens);
3419             self.ident.to_tokens(tokens);
3420             self.generics.to_tokens(tokens);
3421             self.paren_token.surround(tokens, |tokens| {
3422                 self.inputs.to_tokens(tokens);
3423                 if let Some(variadic) = &self.variadic {
3424                     if !self.inputs.empty_or_trailing() {
3425                         <Token![,]>::default().to_tokens(tokens);
3426                     }
3427                     variadic.to_tokens(tokens);
3428                 }
3429             });
3430             self.output.to_tokens(tokens);
3431             self.generics.where_clause.to_tokens(tokens);
3432         }
3433     }
3434 
3435     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3436     impl ToTokens for Receiver {
3437         fn to_tokens(&self, tokens: &mut TokenStream) {
3438             tokens.append_all(self.attrs.outer());
3439             if let Some((ampersand, lifetime)) = &self.reference {
3440                 ampersand.to_tokens(tokens);
3441                 lifetime.to_tokens(tokens);
3442             }
3443             self.mutability.to_tokens(tokens);
3444             self.self_token.to_tokens(tokens);
3445             if let Some(colon_token) = &self.colon_token {
3446                 colon_token.to_tokens(tokens);
3447                 self.ty.to_tokens(tokens);
3448             } else {
3449                 let consistent = match (&self.reference, &self.mutability, &*self.ty) {
3450                     (Some(_), mutability, Type::Reference(ty)) => {
3451                         mutability.is_some() == ty.mutability.is_some()
3452                             && match &*ty.elem {
3453                                 Type::Path(ty) => ty.qself.is_none() && ty.path.is_ident("Self"),
3454                                 _ => false,
3455                             }
3456                     }
3457                     (None, _, Type::Path(ty)) => ty.qself.is_none() && ty.path.is_ident("Self"),
3458                     _ => false,
3459                 };
3460                 if !consistent {
3461                     <Token![:]>::default().to_tokens(tokens);
3462                     self.ty.to_tokens(tokens);
3463                 }
3464             }
3465         }
3466     }
3467 
3468     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3469     impl ToTokens for Variadic {
3470         fn to_tokens(&self, tokens: &mut TokenStream) {
3471             tokens.append_all(self.attrs.outer());
3472             if let Some((pat, colon)) = &self.pat {
3473                 pat.to_tokens(tokens);
3474                 colon.to_tokens(tokens);
3475             }
3476             self.dots.to_tokens(tokens);
3477             self.comma.to_tokens(tokens);
3478         }
3479     }
3480 
3481     #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3482     impl ToTokens for StaticMutability {
3483         fn to_tokens(&self, tokens: &mut TokenStream) {
3484             match self {
3485                 StaticMutability::None => {}
3486                 StaticMutability::Mut(mut_token) => mut_token.to_tokens(tokens),
3487             }
3488         }
3489     }
3490 }
3491