Skip to main content

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