syn/
item.rs

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