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