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