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