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