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