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