Skip to main content

syn/
item.rs

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