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