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