1use crate::attr::Attribute;
2use crate::data::{Fields, FieldsNamed, Variant};
3use crate::derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput};
4use crate::expr::Expr;
5use crate::generics::{Generics, TypeParamBound};
6use crate::ident::Ident;
7use crate::lifetime::Lifetime;
8use crate::mac::Macro;
9use crate::pat::{Pat, PatType};
10use crate::path::Path;
11use crate::punctuated::Punctuated;
12use crate::restriction::Visibility;
13use crate::stmt::Block;
14use crate::token;
15use crate::ty::{Abi, ReturnType, Type};
16use alloc::boxed::Box;
17use alloc::vec::Vec;
18#[cfg(feature = "parsing")]
19use core::mem;
20use proc_macro2::TokenStream;
21
22ast_enum_of_structs! {
23 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
31 #[non_exhaustive]
32 pub enum Item {
33 Const(ItemConst),
35
36 Enum(ItemEnum),
38
39 ExternCrate(ItemExternCrate),
41
42 Fn(ItemFn),
45
46 ForeignMod(ItemForeignMod),
48
49 Impl(ItemImpl),
52
53 Macro(ItemMacro),
55
56 Mod(ItemMod),
58
59 Static(ItemStatic),
61
62 Struct(ItemStruct),
64
65 Trait(ItemTrait),
67
68 TraitAlias(ItemTraitAlias),
70
71 Type(ItemType),
73
74 Union(ItemUnion),
76
77 Use(ItemUse),
79
80 Verbatim(TokenStream),
82
83 }
101}
102
103ast_struct! {
104 #[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
120ast_struct! {
121 #[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
134ast_struct! {
135 #[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
148ast_struct! {
149 #[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
159ast_struct! {
160 #[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
171ast_struct! {
172 #[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 pub trait_: Option<(Option<Token![!]>, Path, Token![for])>,
183 pub self_ty: Box<Type>,
185 pub brace_token: token::Brace,
186 pub items: Vec<ImplItem>,
187 }
188}
189
190ast_struct! {
191 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
193 pub struct ItemMacro {
194 pub attrs: Vec<Attribute>,
195 pub ident: Option<Ident>,
197 pub mac: Macro,
198 pub semi_token: Option<Token![;]>,
199 }
200}
201
202ast_struct! {
203 #[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
216ast_struct! {
217 #[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
233ast_struct! {
234 #[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
247ast_struct! {
248 #[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
266ast_struct! {
267 #[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
281ast_struct! {
282 #[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
296ast_struct! {
297 #[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
309ast_struct! {
310 #[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
322impl Item {
323 #[cfg(feature = "parsing")]
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
346impl From<DeriveInput> for Item {
347 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
379impl From<ItemStruct> for DeriveInput {
380 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
395impl From<ItemEnum> for DeriveInput {
396 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
411impl From<ItemUnion> for DeriveInput {
412 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
426ast_enum_of_structs! {
427 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
435 pub enum UseTree {
436 Path(UsePath),
438
439 Name(UseName),
441
442 Rename(UseRename),
444
445 Glob(UseGlob),
447
448 Group(UseGroup),
450 }
451}
452
453ast_struct! {
454 #[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
463ast_struct! {
464 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
466 pub struct UseName {
467 pub ident: Ident,
468 }
469}
470
471ast_struct! {
472 #[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
481ast_struct! {
482 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
484 pub struct UseGlob {
485 pub star_token: Token![*],
486 }
487}
488
489ast_struct! {
490 #[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
498ast_enum_of_structs! {
499 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
507 #[non_exhaustive]
508 pub enum ForeignItem {
509 Fn(ForeignItemFn),
511
512 Static(ForeignItemStatic),
514
515 Type(ForeignItemType),
517
518 Macro(ForeignItemMacro),
520
521 Verbatim(TokenStream),
523
524 }
542}
543
544ast_struct! {
545 #[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
555ast_struct! {
556 #[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
570ast_struct! {
571 #[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
583ast_struct! {
584 #[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
593ast_enum_of_structs! {
594 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
602 #[non_exhaustive]
603 pub enum TraitItem {
604 Const(TraitItemConst),
606
607 Fn(TraitItemFn),
609
610 Type(TraitItemType),
612
613 Macro(TraitItemMacro),
615
616 Verbatim(TokenStream),
618
619 }
637}
638
639ast_struct! {
640 #[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
654ast_struct! {
655 #[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
665ast_struct! {
666 #[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
680ast_struct! {
681 #[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
690ast_enum_of_structs! {
691 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
699 #[non_exhaustive]
700 pub enum ImplItem {
701 Const(ImplItemConst),
703
704 Fn(ImplItemFn),
706
707 Type(ImplItemType),
709
710 Macro(ImplItemMacro),
712
713 Verbatim(TokenStream),
715
716 }
734}
735
736ast_struct! {
737 #[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
754ast_struct! {
755 #[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
766ast_struct! {
767 #[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
782ast_struct! {
783 #[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
792ast_struct! {
793 #[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
811impl Signature {
812 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
822ast_enum_of_structs! {
823 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
825 pub enum FnArg {
826 Receiver(Receiver),
828
829 Typed(PatType),
831 }
832}
833
834ast_struct! {
835 #[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
853impl Receiver {
854 pub fn lifetime(&self) -> Option<&Lifetime> {
855 self.reference.as_ref()?.1.as_ref()
856 }
857}
858
859ast_struct! {
860 #[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
880ast_enum! {
881 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
883 #[non_exhaustive]
884 pub enum StaticMutability {
885 Mut(Token![mut]),
886 None,
887 }
888}
889
890ast_enum! {
891 #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
893 #[non_exhaustive]
894 pub enum ImplRestriction {}
895
896
897 }
906
907#[cfg(feature = "parsing")]
908pub(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 alloc::boxed::Box;
938 use alloc::vec::Vec;
939 use proc_macro2::TokenStream;
940
941 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
942 impl Parse for Item {
943 fn parse(input: ParseStream) -> Result<Self> {
944 let begin = input.fork();
945 let attrs = input.call(Attribute::parse_outer)?;
946 parse_rest_of_item(begin, attrs, input)
947 }
948 }
949
950 pub(crate) fn parse_rest_of_item(
951 begin: ParseBuffer,
952 mut attrs: Vec<Attribute>,
953 input: ParseStream,
954 ) -> Result<Item> {
955 let ahead = input.fork();
956 let vis: Visibility = ahead.parse()?;
957
958 let lookahead = ahead.lookahead1();
959 let allow_safe = false;
960 let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead, allow_safe) {
961 let vis: Visibility = input.parse()?;
962 let sig: Signature = input.parse()?;
963 if input.peek(Token![;]) {
964 input.parse::<Token![;]>()?;
965 Ok(Item::Verbatim(verbatim::between(&begin, input)))
966 } else {
967 parse_rest_of_fn(input, Vec::new(), vis, sig).map(Item::Fn)
968 }
969 } else if lookahead.peek(Token![extern]) {
970 ahead.parse::<Token![extern]>()?;
971 let lookahead = ahead.lookahead1();
972 if lookahead.peek(Token![crate]) {
973 input.parse().map(Item::ExternCrate)
974 } else if lookahead.peek(token::Brace) {
975 input.parse().map(Item::ForeignMod)
976 } else if lookahead.peek(LitStr) {
977 ahead.parse::<LitStr>()?;
978 let lookahead = ahead.lookahead1();
979 if lookahead.peek(token::Brace) {
980 input.parse().map(Item::ForeignMod)
981 } else {
982 Err(lookahead.error())
983 }
984 } else {
985 Err(lookahead.error())
986 }
987 } else if lookahead.peek(Token![use]) {
988 let allow_crate_root_in_path = true;
989 match parse_item_use(input, allow_crate_root_in_path)? {
990 Some(item_use) => Ok(Item::Use(item_use)),
991 None => Ok(Item::Verbatim(verbatim::between(&begin, input))),
992 }
993 } else if lookahead.peek(Token![static]) {
994 let vis = input.parse()?;
995 let static_token = input.parse()?;
996 let mutability = input.parse()?;
997 let ident = input.parse()?;
998 if input.peek(Token![=]) {
999 input.parse::<Token![=]>()?;
1000 input.parse::<Expr>()?;
1001 input.parse::<Token![;]>()?;
1002 Ok(Item::Verbatim(verbatim::between(&begin, input)))
1003 } else {
1004 let colon_token = input.parse()?;
1005 let ty = input.parse()?;
1006 if input.peek(Token![;]) {
1007 input.parse::<Token![;]>()?;
1008 Ok(Item::Verbatim(verbatim::between(&begin, input)))
1009 } else {
1010 Ok(Item::Static(ItemStatic {
1011 attrs: Vec::new(),
1012 vis,
1013 static_token,
1014 mutability,
1015 ident,
1016 colon_token,
1017 ty,
1018 eq_token: input.parse()?,
1019 expr: input.parse()?,
1020 semi_token: input.parse()?,
1021 }))
1022 }
1023 }
1024 } else if lookahead.peek(Token![const]) {
1025 let vis = input.parse()?;
1026 let const_token: Token![const] = input.parse()?;
1027 let lookahead = input.lookahead1();
1028 let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
1029 input.call(Ident::parse_any)?
1030 } else {
1031 return Err(lookahead.error());
1032 };
1033 let mut generics: Generics = input.parse()?;
1034 let colon_token = input.parse()?;
1035 let ty = input.parse()?;
1036 let value = if let Some(eq_token) = input.parse::<Option<Token![=]>>()? {
1037 let expr: Expr = input.parse()?;
1038 Some((eq_token, expr))
1039 } else {
1040 None
1041 };
1042 generics.where_clause = input.parse()?;
1043 let semi_token: Token![;] = input.parse()?;
1044 match value {
1045 Some((eq_token, expr))
1046 if generics.lt_token.is_none() && generics.where_clause.is_none() =>
1047 {
1048 Ok(Item::Const(ItemConst {
1049 attrs: Vec::new(),
1050 vis,
1051 const_token,
1052 ident,
1053 generics,
1054 colon_token,
1055 ty,
1056 eq_token,
1057 expr: Box::new(expr),
1058 semi_token,
1059 }))
1060 }
1061 _ => Ok(Item::Verbatim(verbatim::between(&begin, input))),
1062 }
1063 } else if lookahead.peek(Token![unsafe]) {
1064 ahead.parse::<Token![unsafe]>()?;
1065 let lookahead = ahead.lookahead1();
1066 if lookahead.peek(Token![trait])
1067 || lookahead.peek(Token![auto]) && ahead.peek2(Token![trait])
1068 {
1069 input.parse().map(Item::Trait)
1070 } else if lookahead.peek(Token![impl]) {
1071 let allow_verbatim_impl = true;
1072 if let Some(item) = parse_impl(input, allow_verbatim_impl)? {
1073 Ok(Item::Impl(item))
1074 } else {
1075 Ok(Item::Verbatim(verbatim::between(&begin, input)))
1076 }
1077 } else if lookahead.peek(Token![extern]) {
1078 input.parse().map(Item::ForeignMod)
1079 } else if lookahead.peek(Token![mod]) {
1080 input.parse().map(Item::Mod)
1081 } else {
1082 Err(lookahead.error())
1083 }
1084 } else if lookahead.peek(Token![mod]) {
1085 input.parse().map(Item::Mod)
1086 } else if lookahead.peek(Token![type]) {
1087 parse_item_type(begin, input)
1088 } else if lookahead.peek(Token![struct]) {
1089 input.parse().map(Item::Struct)
1090 } else if lookahead.peek(Token![enum]) {
1091 input.parse().map(Item::Enum)
1092 } else if lookahead.peek(Token![union]) && ahead.peek2(Ident) {
1093 input.parse().map(Item::Union)
1094 } else if lookahead.peek(Token![trait]) {
1095 input.call(parse_trait_or_trait_alias)
1096 } else if lookahead.peek(Token![auto]) && ahead.peek2(Token![trait]) {
1097 input.parse().map(Item::Trait)
1098 } else if lookahead.peek(Token![impl])
1099 || lookahead.peek(Token![default]) && !ahead.peek2(Token![!])
1100 {
1101 let allow_verbatim_impl = true;
1102 if let Some(item) = parse_impl(input, allow_verbatim_impl)? {
1103 Ok(Item::Impl(item))
1104 } else {
1105 Ok(Item::Verbatim(verbatim::between(&begin, input)))
1106 }
1107 } else if lookahead.peek(Token![macro]) {
1108 input.advance_to(&ahead);
1109 parse_macro2(begin, vis, input)
1110 } else if vis.is_inherited()
1111 && (lookahead.peek(Ident)
1112 || lookahead.peek(Token![self])
1113 || lookahead.peek(Token![super])
1114 || lookahead.peek(Token![crate])
1115 || lookahead.peek(Token![::]))
1116 {
1117 input.parse().map(Item::Macro)
1118 } else {
1119 Err(lookahead.error())
1120 }?;
1121
1122 attrs.extend(item.replace_attrs(Vec::new()));
1123 item.replace_attrs(attrs);
1124 Ok(item)
1125 }
1126
1127 struct FlexibleItemType {
1128 vis: Visibility,
1129 defaultness: Option<Token![default]>,
1130 type_token: Token![type],
1131 ident: Ident,
1132 generics: Generics,
1133 colon_token: Option<Token![:]>,
1134 bounds: Punctuated<TypeParamBound, Token![+]>,
1135 ty: Option<(Token![=], Type)>,
1136 semi_token: Token![;],
1137 }
1138
1139 enum TypeDefaultness {
1140 Optional,
1141 Disallowed,
1142 }
1143
1144 enum WhereClauseLocation {
1145 BeforeEq,
1147 AfterEq,
1149 Both,
1151 }
1152
1153 impl FlexibleItemType {
1154 fn parse(
1155 input: ParseStream,
1156 allow_defaultness: TypeDefaultness,
1157 where_clause_location: WhereClauseLocation,
1158 ) -> Result<Self> {
1159 let vis: Visibility = input.parse()?;
1160 let defaultness: Option<Token![default]> = match allow_defaultness {
1161 TypeDefaultness::Optional => input.parse()?,
1162 TypeDefaultness::Disallowed => None,
1163 };
1164 let type_token: Token![type] = input.parse()?;
1165 let ident: Ident = input.parse()?;
1166 let mut generics: Generics = input.parse()?;
1167 let (colon_token, bounds) = Self::parse_optional_bounds(input)?;
1168
1169 match where_clause_location {
1170 WhereClauseLocation::BeforeEq | WhereClauseLocation::Both => {
1171 generics.where_clause = input.parse()?;
1172 }
1173 WhereClauseLocation::AfterEq => {}
1174 }
1175
1176 let ty = Self::parse_optional_definition(input)?;
1177
1178 match where_clause_location {
1179 WhereClauseLocation::AfterEq | WhereClauseLocation::Both
1180 if generics.where_clause.is_none() =>
1181 {
1182 generics.where_clause = input.parse()?;
1183 }
1184 _ => {}
1185 }
1186
1187 let semi_token: Token![;] = input.parse()?;
1188
1189 Ok(FlexibleItemType {
1190 vis,
1191 defaultness,
1192 type_token,
1193 ident,
1194 generics,
1195 colon_token,
1196 bounds,
1197 ty,
1198 semi_token,
1199 })
1200 }
1201
1202 fn parse_optional_bounds(
1203 input: ParseStream,
1204 ) -> Result<(Option<Token![:]>, Punctuated<TypeParamBound, Token![+]>)> {
1205 let colon_token: Option<Token![:]> = input.parse()?;
1206
1207 let mut bounds = Punctuated::new();
1208 if colon_token.is_some() {
1209 loop {
1210 if input.peek(Token![where]) || input.peek(Token![=]) || input.peek(Token![;]) {
1211 break;
1212 }
1213 bounds.push_value({
1214 let allow_precise_capture = false;
1215 let allow_const = true;
1216 TypeParamBound::parse_single(input, allow_precise_capture, allow_const)?
1217 });
1218 if input.peek(Token![where]) || input.peek(Token![=]) || input.peek(Token![;]) {
1219 break;
1220 }
1221 bounds.push_punct(input.parse::<Token![+]>()?);
1222 }
1223 }
1224
1225 Ok((colon_token, bounds))
1226 }
1227
1228 fn parse_optional_definition(input: ParseStream) -> Result<Option<(Token![=], Type)>> {
1229 let eq_token: Option<Token![=]> = input.parse()?;
1230 if let Some(eq_token) = eq_token {
1231 let definition: Type = input.parse()?;
1232 Ok(Some((eq_token, definition)))
1233 } else {
1234 Ok(None)
1235 }
1236 }
1237 }
1238
1239 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1240 impl Parse for ItemMacro {
1241 fn parse(input: ParseStream) -> Result<Self> {
1242 let attrs = input.call(Attribute::parse_outer)?;
1243 let path = input.call(Path::parse_mod_style)?;
1244 let bang_token: Token![!] = input.parse()?;
1245 let ident: Option<Ident> = if input.peek(Token![try]) {
1246 input.call(Ident::parse_any).map(Some)
1247 } else {
1248 input.parse()
1249 }?;
1250 let (delimiter, tokens) = input.call(mac::parse_delimiter)?;
1251 let semi_token: Option<Token![;]> = if !delimiter.is_brace() {
1252 Some(input.parse()?)
1253 } else {
1254 None
1255 };
1256 Ok(ItemMacro {
1257 attrs,
1258 ident,
1259 mac: Macro {
1260 path,
1261 bang_token,
1262 delimiter,
1263 tokens,
1264 },
1265 semi_token,
1266 })
1267 }
1268 }
1269
1270 fn parse_macro2(begin: ParseBuffer, _vis: Visibility, input: ParseStream) -> Result<Item> {
1271 input.parse::<Token![macro]>()?;
1272 input.parse::<Ident>()?;
1273
1274 let mut lookahead = input.lookahead1();
1275 if lookahead.peek(token::Paren) {
1276 let paren_content;
1277 parenthesized!(paren_content in input);
1278 paren_content.parse::<TokenStream>()?;
1279 lookahead = input.lookahead1();
1280 }
1281
1282 if lookahead.peek(token::Brace) {
1283 let brace_content;
1284 braced!(brace_content in input);
1285 brace_content.parse::<TokenStream>()?;
1286 } else {
1287 return Err(lookahead.error());
1288 }
1289
1290 Ok(Item::Verbatim(verbatim::between(&begin, input)))
1291 }
1292
1293 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1294 impl Parse for ItemExternCrate {
1295 fn parse(input: ParseStream) -> Result<Self> {
1296 Ok(ItemExternCrate {
1297 attrs: input.call(Attribute::parse_outer)?,
1298 vis: input.parse()?,
1299 extern_token: input.parse()?,
1300 crate_token: input.parse()?,
1301 ident: {
1302 if input.peek(Token![self]) {
1303 input.call(Ident::parse_any)?
1304 } else {
1305 input.parse()?
1306 }
1307 },
1308 rename: {
1309 if input.peek(Token![as]) {
1310 let as_token: Token![as] = input.parse()?;
1311 let rename: Ident = if input.peek(Token![_]) {
1312 Ident::from(input.parse::<Token![_]>()?)
1313 } else {
1314 input.parse()?
1315 };
1316 Some((as_token, rename))
1317 } else {
1318 None
1319 }
1320 },
1321 semi_token: input.parse()?,
1322 })
1323 }
1324 }
1325
1326 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1327 impl Parse for ItemUse {
1328 fn parse(input: ParseStream) -> Result<Self> {
1329 let allow_crate_root_in_path = false;
1330 parse_item_use(input, allow_crate_root_in_path).map(Option::unwrap)
1331 }
1332 }
1333
1334 fn parse_item_use(
1335 input: ParseStream,
1336 allow_crate_root_in_path: bool,
1337 ) -> Result<Option<ItemUse>> {
1338 let attrs = input.call(Attribute::parse_outer)?;
1339 let vis: Visibility = input.parse()?;
1340 let use_token: Token![use] = input.parse()?;
1341 let leading_colon: Option<Token![::]> = input.parse()?;
1342 let tree = parse_use_tree(input, allow_crate_root_in_path && leading_colon.is_none())?;
1343 let semi_token: Token![;] = input.parse()?;
1344
1345 let tree = match tree {
1346 Some(tree) => tree,
1347 None => return Ok(None),
1348 };
1349
1350 Ok(Some(ItemUse {
1351 attrs,
1352 vis,
1353 use_token,
1354 leading_colon,
1355 tree,
1356 semi_token,
1357 }))
1358 }
1359
1360 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1361 impl Parse for UseTree {
1362 fn parse(input: ParseStream) -> Result<UseTree> {
1363 let allow_crate_root_in_path = false;
1364 parse_use_tree(input, allow_crate_root_in_path).map(Option::unwrap)
1365 }
1366 }
1367
1368 fn parse_use_tree(
1369 input: ParseStream,
1370 allow_crate_root_in_path: bool,
1371 ) -> Result<Option<UseTree>> {
1372 let lookahead = input.lookahead1();
1373 if lookahead.peek(Ident)
1374 || lookahead.peek(Token![self])
1375 || lookahead.peek(Token![super])
1376 || lookahead.peek(Token![crate])
1377 || lookahead.peek(Token![try])
1378 {
1379 let ident = input.call(Ident::parse_any)?;
1380 if input.peek(Token![::]) {
1381 Ok(Some(UseTree::Path(UsePath {
1382 ident,
1383 colon2_token: input.parse()?,
1384 tree: Box::new(input.parse()?),
1385 })))
1386 } else if input.peek(Token![as]) {
1387 Ok(Some(UseTree::Rename(UseRename {
1388 ident,
1389 as_token: input.parse()?,
1390 rename: {
1391 if input.peek(Ident) {
1392 input.parse()?
1393 } else if input.peek(Token![_]) {
1394 Ident::from(input.parse::<Token![_]>()?)
1395 } else {
1396 return Err(input.error("expected identifier or underscore"));
1397 }
1398 },
1399 })))
1400 } else {
1401 Ok(Some(UseTree::Name(UseName { ident })))
1402 }
1403 } else if lookahead.peek(Token![*]) {
1404 Ok(Some(UseTree::Glob(UseGlob {
1405 star_token: input.parse()?,
1406 })))
1407 } else if lookahead.peek(token::Brace) {
1408 let content;
1409 let brace_token = braced!(content in input);
1410 let mut items = Punctuated::new();
1411 let mut has_any_crate_root_in_path = false;
1412 loop {
1413 if content.is_empty() {
1414 break;
1415 }
1416 let this_tree_starts_with_crate_root =
1417 allow_crate_root_in_path && content.parse::<Option<Token![::]>>()?.is_some();
1418 has_any_crate_root_in_path |= this_tree_starts_with_crate_root;
1419 match parse_use_tree(
1420 &content,
1421 allow_crate_root_in_path && !this_tree_starts_with_crate_root,
1422 )? {
1423 Some(tree) if !has_any_crate_root_in_path => items.push_value(tree),
1424 _ => has_any_crate_root_in_path = true,
1425 }
1426 if content.is_empty() {
1427 break;
1428 }
1429 let comma: Token![,] = content.parse()?;
1430 if !has_any_crate_root_in_path {
1431 items.push_punct(comma);
1432 }
1433 }
1434 if has_any_crate_root_in_path {
1435 Ok(None)
1436 } else {
1437 Ok(Some(UseTree::Group(UseGroup { brace_token, items })))
1438 }
1439 } else {
1440 Err(lookahead.error())
1441 }
1442 }
1443
1444 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1445 impl Parse for ItemStatic {
1446 fn parse(input: ParseStream) -> Result<Self> {
1447 Ok(ItemStatic {
1448 attrs: input.call(Attribute::parse_outer)?,
1449 vis: input.parse()?,
1450 static_token: input.parse()?,
1451 mutability: input.parse()?,
1452 ident: input.parse()?,
1453 colon_token: input.parse()?,
1454 ty: input.parse()?,
1455 eq_token: input.parse()?,
1456 expr: input.parse()?,
1457 semi_token: input.parse()?,
1458 })
1459 }
1460 }
1461
1462 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1463 impl Parse for ItemConst {
1464 fn parse(input: ParseStream) -> Result<Self> {
1465 let attrs = input.call(Attribute::parse_outer)?;
1466 let vis: Visibility = input.parse()?;
1467 let const_token: Token![const] = input.parse()?;
1468
1469 let lookahead = input.lookahead1();
1470 let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
1471 input.call(Ident::parse_any)?
1472 } else {
1473 return Err(lookahead.error());
1474 };
1475
1476 let colon_token: Token![:] = input.parse()?;
1477 let ty: Type = input.parse()?;
1478 let eq_token: Token![=] = input.parse()?;
1479 let expr: Expr = input.parse()?;
1480 let semi_token: Token![;] = input.parse()?;
1481
1482 Ok(ItemConst {
1483 attrs,
1484 vis,
1485 const_token,
1486 ident,
1487 generics: Generics::default(),
1488 colon_token,
1489 ty: Box::new(ty),
1490 eq_token,
1491 expr: Box::new(expr),
1492 semi_token,
1493 })
1494 }
1495 }
1496
1497 fn peek_signature(input: ParseStream, allow_safe: bool) -> bool {
1498 let fork = input.fork();
1499 fork.parse::<Option<Token![const]>>().is_ok()
1500 && fork.parse::<Option<Token![async]>>().is_ok()
1501 && ((allow_safe
1502 && token::parsing::peek_keyword(fork.cursor(), "safe")
1503 && token::parsing::keyword(&fork, "safe").is_ok())
1504 || fork.parse::<Option<Token![unsafe]>>().is_ok())
1505 && fork.parse::<Option<Abi>>().is_ok()
1506 && fork.peek(Token![fn])
1507 }
1508
1509 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1510 impl Parse for Signature {
1511 fn parse(input: ParseStream) -> Result<Self> {
1512 let allow_safe = false;
1513 parse_signature(input, allow_safe).map(Option::unwrap)
1514 }
1515 }
1516
1517 fn parse_signature(input: ParseStream, allow_safe: bool) -> Result<Option<Signature>> {
1518 let constness: Option<Token![const]> = input.parse()?;
1519 let asyncness: Option<Token![async]> = input.parse()?;
1520 let unsafety: Option<Token![unsafe]> = input.parse()?;
1521 let safe = allow_safe
1522 && unsafety.is_none()
1523 && token::parsing::peek_keyword(input.cursor(), "safe");
1524 if safe {
1525 token::parsing::keyword(input, "safe")?;
1526 }
1527 let abi: Option<Abi> = input.parse()?;
1528 let fn_token: Token![fn] = input.parse()?;
1529 let ident: Ident = input.parse()?;
1530 let mut generics: Generics = input.parse()?;
1531
1532 let content;
1533 let paren_token = parenthesized!(content in input);
1534 let (inputs, variadic) = parse_fn_args(&content)?;
1535
1536 let output: ReturnType = input.parse()?;
1537 generics.where_clause = input.parse()?;
1538
1539 Ok(if safe {
1540 None
1541 } else {
1542 Some(Signature {
1543 constness,
1544 asyncness,
1545 unsafety,
1546 abi,
1547 fn_token,
1548 ident,
1549 generics,
1550 paren_token,
1551 inputs,
1552 variadic,
1553 output,
1554 })
1555 })
1556 }
1557
1558 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1559 impl Parse for ItemFn {
1560 fn parse(input: ParseStream) -> Result<Self> {
1561 let outer_attrs = input.call(Attribute::parse_outer)?;
1562 let vis: Visibility = input.parse()?;
1563 let sig: Signature = input.parse()?;
1564 parse_rest_of_fn(input, outer_attrs, vis, sig)
1565 }
1566 }
1567
1568 fn parse_rest_of_fn(
1569 input: ParseStream,
1570 mut attrs: Vec<Attribute>,
1571 vis: Visibility,
1572 sig: Signature,
1573 ) -> Result<ItemFn> {
1574 let content;
1575 let brace_token = braced!(content in input);
1576 attr::parsing::parse_inner(&content, &mut attrs)?;
1577 let stmts = content.call(Block::parse_within)?;
1578
1579 Ok(ItemFn {
1580 attrs,
1581 vis,
1582 sig,
1583 block: Box::new(Block { brace_token, stmts }),
1584 })
1585 }
1586
1587 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1588 impl Parse for FnArg {
1589 fn parse(input: ParseStream) -> Result<Self> {
1590 let allow_variadic = false;
1591 let attrs = input.call(Attribute::parse_outer)?;
1592 match parse_fn_arg_or_variadic(input, attrs, allow_variadic)? {
1593 FnArgOrVariadic::FnArg(arg) => Ok(arg),
1594 FnArgOrVariadic::Variadic(_) => unreachable!(),
1595 }
1596 }
1597 }
1598
1599 enum FnArgOrVariadic {
1600 FnArg(FnArg),
1601 Variadic(Variadic),
1602 }
1603
1604 fn parse_fn_arg_or_variadic(
1605 input: ParseStream,
1606 attrs: Vec<Attribute>,
1607 allow_variadic: bool,
1608 ) -> Result<FnArgOrVariadic> {
1609 let ahead = input.fork();
1610 if let Ok((reference, mutability, self_token)) = parse_receiver_begin(&ahead) {
1611 input.advance_to(&ahead);
1612 let mut receiver = parse_rest_of_receiver(reference, mutability, self_token, input)?;
1613 receiver.attrs = attrs;
1614 return Ok(FnArgOrVariadic::FnArg(FnArg::Receiver(receiver)));
1615 }
1616
1617 if input.peek(Ident) && input.peek2(Token![<]) {
1621 let span = input.span();
1622 return Ok(FnArgOrVariadic::FnArg(FnArg::Typed(PatType {
1623 attrs,
1624 pat: Box::new(Pat::Wild(PatWild {
1625 attrs: Vec::new(),
1626 underscore_token: Token,
1627 })),
1628 colon_token: Token,
1629 ty: input.parse()?,
1630 })));
1631 }
1632
1633 let pat = Box::new(Pat::parse_single(input)?);
1634 let colon_token: Token![:] = input.parse()?;
1635
1636 if allow_variadic {
1637 if let Some(dots) = input.parse::<Option<Token![...]>>()? {
1638 return Ok(FnArgOrVariadic::Variadic(Variadic {
1639 attrs,
1640 pat: Some((pat, colon_token)),
1641 dots,
1642 comma: None,
1643 }));
1644 }
1645 }
1646
1647 Ok(FnArgOrVariadic::FnArg(FnArg::Typed(PatType {
1648 attrs,
1649 pat,
1650 colon_token,
1651 ty: input.parse()?,
1652 })))
1653 }
1654
1655 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1656 impl Parse for Receiver {
1657 fn parse(input: ParseStream) -> Result<Self> {
1658 let (reference, mutability, self_token) = parse_receiver_begin(input)?;
1659 parse_rest_of_receiver(reference, mutability, self_token, input)
1660 }
1661 }
1662
1663 fn parse_receiver_begin(
1664 input: ParseStream,
1665 ) -> Result<(
1666 Option<(Token![&], Option<Lifetime>)>,
1667 Option<Token![mut]>,
1668 Token![self],
1669 )> {
1670 let reference = if input.peek(Token![&]) {
1671 let ampersand: Token![&] = input.parse()?;
1672 let lifetime: Option<Lifetime> = input.parse()?;
1673 Some((ampersand, lifetime))
1674 } else {
1675 None
1676 };
1677 let mutability: Option<Token![mut]> = input.parse()?;
1678 let self_token: Token![self] = input.parse()?;
1679 Ok((reference, mutability, self_token))
1680 }
1681
1682 fn parse_rest_of_receiver(
1683 reference: Option<(Token![&], Option<Lifetime>)>,
1684 mutability: Option<Token![mut]>,
1685 self_token: Token![self],
1686 input: ParseStream,
1687 ) -> Result<Receiver> {
1688 let colon_token: Option<Token![:]> = if reference.is_some() {
1689 None
1690 } else {
1691 input.parse()?
1692 };
1693 let ty: Type = if colon_token.is_some() {
1694 input.parse()?
1695 } else {
1696 let mut ty = Type::Path(TypePath {
1697 qself: None,
1698 path: Path::from(Ident::new("Self", self_token.span)),
1699 });
1700 if let Some((ampersand, lifetime)) = reference.as_ref() {
1701 ty = Type::Reference(TypeReference {
1702 and_token: Token,
1703 lifetime: lifetime.clone(),
1704 mutability: mutability.as_ref().map(|m| Token),
1705 elem: Box::new(ty),
1706 });
1707 }
1708 ty
1709 };
1710 Ok(Receiver {
1711 attrs: Vec::new(),
1712 reference,
1713 mutability,
1714 self_token,
1715 colon_token,
1716 ty: Box::new(ty),
1717 })
1718 }
1719
1720 fn parse_fn_args(
1721 input: ParseStream,
1722 ) -> Result<(Punctuated<FnArg, Token![,]>, Option<Variadic>)> {
1723 let mut args = Punctuated::new();
1724 let mut variadic = None;
1725 let mut has_receiver = false;
1726
1727 while !input.is_empty() {
1728 let attrs = input.call(Attribute::parse_outer)?;
1729
1730 if let Some(dots) = input.parse::<Option<Token![...]>>()? {
1731 variadic = Some(Variadic {
1732 attrs,
1733 pat: None,
1734 dots,
1735 comma: if input.is_empty() {
1736 None
1737 } else {
1738 Some(input.parse()?)
1739 },
1740 });
1741 break;
1742 }
1743
1744 let allow_variadic = true;
1745 let arg = match parse_fn_arg_or_variadic(input, attrs, allow_variadic)? {
1746 FnArgOrVariadic::FnArg(arg) => arg,
1747 FnArgOrVariadic::Variadic(arg) => {
1748 variadic = Some(Variadic {
1749 comma: if input.is_empty() {
1750 None
1751 } else {
1752 Some(input.parse()?)
1753 },
1754 ..arg
1755 });
1756 break;
1757 }
1758 };
1759
1760 match &arg {
1761 FnArg::Receiver(receiver) if has_receiver => {
1762 return Err(Error::new(
1763 receiver.self_token.span,
1764 "unexpected second method receiver",
1765 ));
1766 }
1767 FnArg::Receiver(receiver) if !args.is_empty() => {
1768 return Err(Error::new(
1769 receiver.self_token.span,
1770 "unexpected method receiver",
1771 ));
1772 }
1773 FnArg::Receiver(_) => has_receiver = true,
1774 FnArg::Typed(_) => {}
1775 }
1776 args.push_value(arg);
1777
1778 if input.is_empty() {
1779 break;
1780 }
1781
1782 let comma: Token![,] = input.parse()?;
1783 args.push_punct(comma);
1784 }
1785
1786 Ok((args, variadic))
1787 }
1788
1789 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1790 impl Parse for ItemMod {
1791 fn parse(input: ParseStream) -> Result<Self> {
1792 let mut attrs = input.call(Attribute::parse_outer)?;
1793 let vis: Visibility = input.parse()?;
1794 let unsafety: Option<Token![unsafe]> = input.parse()?;
1795 let mod_token: Token![mod] = input.parse()?;
1796 let ident: Ident = if input.peek(Token![try]) {
1797 input.call(Ident::parse_any)
1798 } else {
1799 input.parse()
1800 }?;
1801
1802 let lookahead = input.lookahead1();
1803 if lookahead.peek(Token![;]) {
1804 Ok(ItemMod {
1805 attrs,
1806 vis,
1807 unsafety,
1808 mod_token,
1809 ident,
1810 content: None,
1811 semi: Some(input.parse()?),
1812 })
1813 } else if lookahead.peek(token::Brace) {
1814 let content;
1815 let brace_token = braced!(content in input);
1816 attr::parsing::parse_inner(&content, &mut attrs)?;
1817
1818 let mut items = Vec::new();
1819 while !content.is_empty() {
1820 items.push(content.parse()?);
1821 }
1822
1823 Ok(ItemMod {
1824 attrs,
1825 vis,
1826 unsafety,
1827 mod_token,
1828 ident,
1829 content: Some((brace_token, items)),
1830 semi: None,
1831 })
1832 } else {
1833 Err(lookahead.error())
1834 }
1835 }
1836 }
1837
1838 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1839 impl Parse for ItemForeignMod {
1840 fn parse(input: ParseStream) -> Result<Self> {
1841 let mut attrs = input.call(Attribute::parse_outer)?;
1842 let unsafety: Option<Token![unsafe]> = input.parse()?;
1843 let abi: Abi = input.parse()?;
1844
1845 let content;
1846 let brace_token = braced!(content in input);
1847 attr::parsing::parse_inner(&content, &mut attrs)?;
1848 let mut items = Vec::new();
1849 while !content.is_empty() {
1850 items.push(content.parse()?);
1851 }
1852
1853 Ok(ItemForeignMod {
1854 attrs,
1855 unsafety,
1856 abi,
1857 brace_token,
1858 items,
1859 })
1860 }
1861 }
1862
1863 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1864 impl Parse for ForeignItem {
1865 fn parse(input: ParseStream) -> Result<Self> {
1866 let begin = input.fork();
1867 let mut attrs = input.call(Attribute::parse_outer)?;
1868 let ahead = input.fork();
1869 let vis: Visibility = ahead.parse()?;
1870
1871 let lookahead = ahead.lookahead1();
1872 let allow_safe = true;
1873 let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead, allow_safe) {
1874 let vis: Visibility = input.parse()?;
1875 let sig = parse_signature(input, allow_safe)?;
1876 let has_safe = sig.is_none();
1877 let has_body = input.peek(token::Brace);
1878 let semi_token: Option<Token![;]> = if has_body {
1879 let content;
1880 braced!(content in input);
1881 content.call(Attribute::parse_inner)?;
1882 content.call(Block::parse_within)?;
1883 None
1884 } else {
1885 Some(input.parse()?)
1886 };
1887 if has_safe || has_body {
1888 Ok(ForeignItem::Verbatim(verbatim::between(&begin, input)))
1889 } else {
1890 Ok(ForeignItem::Fn(ForeignItemFn {
1891 attrs: Vec::new(),
1892 vis,
1893 sig: sig.unwrap(),
1894 semi_token: semi_token.unwrap(),
1895 }))
1896 }
1897 } else if lookahead.peek(Token![static])
1898 || ((ahead.peek(Token![unsafe])
1899 || token::parsing::peek_keyword(ahead.cursor(), "safe"))
1900 && ahead.peek2(Token![static]))
1901 {
1902 let vis = input.parse()?;
1903 let unsafety: Option<Token![unsafe]> = input.parse()?;
1904 let safe =
1905 unsafety.is_none() && token::parsing::peek_keyword(input.cursor(), "safe");
1906 if safe {
1907 token::parsing::keyword(input, "safe")?;
1908 }
1909 let static_token = input.parse()?;
1910 let mutability = input.parse()?;
1911 let ident = input.parse()?;
1912 let colon_token = input.parse()?;
1913 let ty = input.parse()?;
1914 let has_value = input.peek(Token![=]);
1915 if has_value {
1916 input.parse::<Token![=]>()?;
1917 input.parse::<Expr>()?;
1918 }
1919 let semi_token: Token![;] = input.parse()?;
1920 if unsafety.is_some() || safe || has_value {
1921 Ok(ForeignItem::Verbatim(verbatim::between(&begin, input)))
1922 } else {
1923 Ok(ForeignItem::Static(ForeignItemStatic {
1924 attrs: Vec::new(),
1925 vis,
1926 static_token,
1927 mutability,
1928 ident,
1929 colon_token,
1930 ty,
1931 semi_token,
1932 }))
1933 }
1934 } else if lookahead.peek(Token![type]) {
1935 parse_foreign_item_type(begin, input)
1936 } else if vis.is_inherited()
1937 && (lookahead.peek(Ident)
1938 || lookahead.peek(Token![self])
1939 || lookahead.peek(Token![super])
1940 || lookahead.peek(Token![crate])
1941 || lookahead.peek(Token![::]))
1942 {
1943 input.parse().map(ForeignItem::Macro)
1944 } else {
1945 Err(lookahead.error())
1946 }?;
1947
1948 let item_attrs = match &mut item {
1949 ForeignItem::Fn(item) => &mut item.attrs,
1950 ForeignItem::Static(item) => &mut item.attrs,
1951 ForeignItem::Type(item) => &mut item.attrs,
1952 ForeignItem::Macro(item) => &mut item.attrs,
1953 ForeignItem::Verbatim(_) => return Ok(item),
1954 };
1955 attrs.append(item_attrs);
1956 *item_attrs = attrs;
1957
1958 Ok(item)
1959 }
1960 }
1961
1962 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1963 impl Parse for ForeignItemFn {
1964 fn parse(input: ParseStream) -> Result<Self> {
1965 let attrs = input.call(Attribute::parse_outer)?;
1966 let vis: Visibility = input.parse()?;
1967 let sig: Signature = input.parse()?;
1968 let semi_token: Token![;] = input.parse()?;
1969 Ok(ForeignItemFn {
1970 attrs,
1971 vis,
1972 sig,
1973 semi_token,
1974 })
1975 }
1976 }
1977
1978 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1979 impl Parse for ForeignItemStatic {
1980 fn parse(input: ParseStream) -> Result<Self> {
1981 Ok(ForeignItemStatic {
1982 attrs: input.call(Attribute::parse_outer)?,
1983 vis: input.parse()?,
1984 static_token: input.parse()?,
1985 mutability: input.parse()?,
1986 ident: input.parse()?,
1987 colon_token: input.parse()?,
1988 ty: input.parse()?,
1989 semi_token: input.parse()?,
1990 })
1991 }
1992 }
1993
1994 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
1995 impl Parse for ForeignItemType {
1996 fn parse(input: ParseStream) -> Result<Self> {
1997 Ok(ForeignItemType {
1998 attrs: input.call(Attribute::parse_outer)?,
1999 vis: input.parse()?,
2000 type_token: input.parse()?,
2001 ident: input.parse()?,
2002 generics: {
2003 let mut generics: Generics = input.parse()?;
2004 generics.where_clause = input.parse()?;
2005 generics
2006 },
2007 semi_token: input.parse()?,
2008 })
2009 }
2010 }
2011
2012 fn parse_foreign_item_type(begin: ParseBuffer, input: ParseStream) -> Result<ForeignItem> {
2013 let FlexibleItemType {
2014 vis,
2015 defaultness: _,
2016 type_token,
2017 ident,
2018 generics,
2019 colon_token,
2020 bounds: _,
2021 ty,
2022 semi_token,
2023 } = FlexibleItemType::parse(
2024 input,
2025 TypeDefaultness::Disallowed,
2026 WhereClauseLocation::Both,
2027 )?;
2028
2029 if colon_token.is_some() || ty.is_some() {
2030 Ok(ForeignItem::Verbatim(verbatim::between(&begin, input)))
2031 } else {
2032 Ok(ForeignItem::Type(ForeignItemType {
2033 attrs: Vec::new(),
2034 vis,
2035 type_token,
2036 ident,
2037 generics,
2038 semi_token,
2039 }))
2040 }
2041 }
2042
2043 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2044 impl Parse for ForeignItemMacro {
2045 fn parse(input: ParseStream) -> Result<Self> {
2046 let attrs = input.call(Attribute::parse_outer)?;
2047 let mac: Macro = input.parse()?;
2048 let semi_token: Option<Token![;]> = if mac.delimiter.is_brace() {
2049 None
2050 } else {
2051 Some(input.parse()?)
2052 };
2053 Ok(ForeignItemMacro {
2054 attrs,
2055 mac,
2056 semi_token,
2057 })
2058 }
2059 }
2060
2061 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2062 impl Parse for ItemType {
2063 fn parse(input: ParseStream) -> Result<Self> {
2064 Ok(ItemType {
2065 attrs: input.call(Attribute::parse_outer)?,
2066 vis: input.parse()?,
2067 type_token: input.parse()?,
2068 ident: input.parse()?,
2069 generics: {
2070 let mut generics: Generics = input.parse()?;
2071 generics.where_clause = input.parse()?;
2072 generics
2073 },
2074 eq_token: input.parse()?,
2075 ty: input.parse()?,
2076 semi_token: input.parse()?,
2077 })
2078 }
2079 }
2080
2081 fn parse_item_type(begin: ParseBuffer, input: ParseStream) -> Result<Item> {
2082 let FlexibleItemType {
2083 vis,
2084 defaultness: _,
2085 type_token,
2086 ident,
2087 generics,
2088 colon_token,
2089 bounds: _,
2090 ty,
2091 semi_token,
2092 } = FlexibleItemType::parse(
2093 input,
2094 TypeDefaultness::Disallowed,
2095 WhereClauseLocation::BeforeEq,
2096 )?;
2097
2098 let (eq_token, ty) = match ty {
2099 Some(ty) if colon_token.is_none() => ty,
2100 _ => return Ok(Item::Verbatim(verbatim::between(&begin, input))),
2101 };
2102
2103 Ok(Item::Type(ItemType {
2104 attrs: Vec::new(),
2105 vis,
2106 type_token,
2107 ident,
2108 generics,
2109 eq_token,
2110 ty: Box::new(ty),
2111 semi_token,
2112 }))
2113 }
2114
2115 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2116 impl Parse for ItemStruct {
2117 fn parse(input: ParseStream) -> Result<Self> {
2118 let attrs = input.call(Attribute::parse_outer)?;
2119 let vis = input.parse::<Visibility>()?;
2120 let struct_token = input.parse::<Token![struct]>()?;
2121 let ident = input.parse::<Ident>()?;
2122 let generics = input.parse::<Generics>()?;
2123 let (where_clause, fields, semi_token) = derive::parsing::data_struct(input)?;
2124 Ok(ItemStruct {
2125 attrs,
2126 vis,
2127 struct_token,
2128 ident,
2129 generics: Generics {
2130 where_clause,
2131 ..generics
2132 },
2133 fields,
2134 semi_token,
2135 })
2136 }
2137 }
2138
2139 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2140 impl Parse for ItemEnum {
2141 fn parse(input: ParseStream) -> Result<Self> {
2142 let attrs = input.call(Attribute::parse_outer)?;
2143 let vis = input.parse::<Visibility>()?;
2144 let enum_token = input.parse::<Token![enum]>()?;
2145 let ident = input.parse::<Ident>()?;
2146 let generics = input.parse::<Generics>()?;
2147 let (where_clause, brace_token, variants) = derive::parsing::data_enum(input)?;
2148 Ok(ItemEnum {
2149 attrs,
2150 vis,
2151 enum_token,
2152 ident,
2153 generics: Generics {
2154 where_clause,
2155 ..generics
2156 },
2157 brace_token,
2158 variants,
2159 })
2160 }
2161 }
2162
2163 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2164 impl Parse for ItemUnion {
2165 fn parse(input: ParseStream) -> Result<Self> {
2166 let attrs = input.call(Attribute::parse_outer)?;
2167 let vis = input.parse::<Visibility>()?;
2168 let union_token = input.parse::<Token![union]>()?;
2169 let ident = input.parse::<Ident>()?;
2170 let generics = input.parse::<Generics>()?;
2171 let (where_clause, fields) = derive::parsing::data_union(input)?;
2172 Ok(ItemUnion {
2173 attrs,
2174 vis,
2175 union_token,
2176 ident,
2177 generics: Generics {
2178 where_clause,
2179 ..generics
2180 },
2181 fields,
2182 })
2183 }
2184 }
2185
2186 fn parse_trait_or_trait_alias(input: ParseStream) -> Result<Item> {
2187 let (attrs, vis, trait_token, ident, generics) = parse_start_of_trait_alias(input)?;
2188 let lookahead = input.lookahead1();
2189 if lookahead.peek(token::Brace)
2190 || lookahead.peek(Token![:])
2191 || lookahead.peek(Token![where])
2192 {
2193 let unsafety = None;
2194 let auto_token = None;
2195 parse_rest_of_trait(
2196 input,
2197 attrs,
2198 vis,
2199 unsafety,
2200 auto_token,
2201 trait_token,
2202 ident,
2203 generics,
2204 )
2205 .map(Item::Trait)
2206 } else if lookahead.peek(Token![=]) {
2207 parse_rest_of_trait_alias(input, attrs, vis, trait_token, ident, generics)
2208 .map(Item::TraitAlias)
2209 } else {
2210 Err(lookahead.error())
2211 }
2212 }
2213
2214 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2215 impl Parse for ItemTrait {
2216 fn parse(input: ParseStream) -> Result<Self> {
2217 let outer_attrs = input.call(Attribute::parse_outer)?;
2218 let vis: Visibility = input.parse()?;
2219 let unsafety: Option<Token![unsafe]> = input.parse()?;
2220 let auto_token: Option<Token![auto]> = input.parse()?;
2221 let trait_token: Token![trait] = input.parse()?;
2222 let ident: Ident = input.parse()?;
2223 let generics: Generics = input.parse()?;
2224 parse_rest_of_trait(
2225 input,
2226 outer_attrs,
2227 vis,
2228 unsafety,
2229 auto_token,
2230 trait_token,
2231 ident,
2232 generics,
2233 )
2234 }
2235 }
2236
2237 fn parse_rest_of_trait(
2238 input: ParseStream,
2239 mut attrs: Vec<Attribute>,
2240 vis: Visibility,
2241 unsafety: Option<Token![unsafe]>,
2242 auto_token: Option<Token![auto]>,
2243 trait_token: Token![trait],
2244 ident: Ident,
2245 mut generics: Generics,
2246 ) -> Result<ItemTrait> {
2247 let colon_token: Option<Token![:]> = input.parse()?;
2248
2249 let mut supertraits = Punctuated::new();
2250 if colon_token.is_some() {
2251 loop {
2252 if input.peek(Token![where]) || input.peek(token::Brace) {
2253 break;
2254 }
2255 supertraits.push_value({
2256 let allow_precise_capture = false;
2257 let allow_const = true;
2258 TypeParamBound::parse_single(input, allow_precise_capture, allow_const)?
2259 });
2260 if input.peek(Token![where]) || input.peek(token::Brace) {
2261 break;
2262 }
2263 supertraits.push_punct(input.parse()?);
2264 }
2265 }
2266
2267 generics.where_clause = input.parse()?;
2268
2269 let content;
2270 let brace_token = braced!(content in input);
2271 attr::parsing::parse_inner(&content, &mut attrs)?;
2272 let mut items = Vec::new();
2273 while !content.is_empty() {
2274 items.push(content.parse()?);
2275 }
2276
2277 Ok(ItemTrait {
2278 attrs,
2279 vis,
2280 unsafety,
2281 auto_token,
2282 restriction: None,
2283 trait_token,
2284 ident,
2285 generics,
2286 colon_token,
2287 supertraits,
2288 brace_token,
2289 items,
2290 })
2291 }
2292
2293 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2294 impl Parse for ItemTraitAlias {
2295 fn parse(input: ParseStream) -> Result<Self> {
2296 let (attrs, vis, trait_token, ident, generics) = parse_start_of_trait_alias(input)?;
2297 parse_rest_of_trait_alias(input, attrs, vis, trait_token, ident, generics)
2298 }
2299 }
2300
2301 fn parse_start_of_trait_alias(
2302 input: ParseStream,
2303 ) -> Result<(Vec<Attribute>, Visibility, Token![trait], Ident, Generics)> {
2304 let attrs = input.call(Attribute::parse_outer)?;
2305 let vis: Visibility = input.parse()?;
2306 let trait_token: Token![trait] = input.parse()?;
2307 let ident: Ident = input.parse()?;
2308 let generics: Generics = input.parse()?;
2309 Ok((attrs, vis, trait_token, ident, generics))
2310 }
2311
2312 fn parse_rest_of_trait_alias(
2313 input: ParseStream,
2314 attrs: Vec<Attribute>,
2315 vis: Visibility,
2316 trait_token: Token![trait],
2317 ident: Ident,
2318 mut generics: Generics,
2319 ) -> Result<ItemTraitAlias> {
2320 let eq_token: Token![=] = input.parse()?;
2321
2322 let mut bounds = Punctuated::new();
2323 loop {
2324 if input.peek(Token![where]) || input.peek(Token![;]) {
2325 break;
2326 }
2327 bounds.push_value({
2328 let allow_precise_capture = false;
2329 let allow_const = false;
2330 TypeParamBound::parse_single(input, allow_precise_capture, allow_const)?
2331 });
2332 if input.peek(Token![where]) || input.peek(Token![;]) {
2333 break;
2334 }
2335 bounds.push_punct(input.parse()?);
2336 }
2337
2338 generics.where_clause = input.parse()?;
2339 let semi_token: Token![;] = input.parse()?;
2340
2341 Ok(ItemTraitAlias {
2342 attrs,
2343 vis,
2344 trait_token,
2345 ident,
2346 generics,
2347 eq_token,
2348 bounds,
2349 semi_token,
2350 })
2351 }
2352
2353 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2354 impl Parse for TraitItem {
2355 fn parse(input: ParseStream) -> Result<Self> {
2356 let begin = input.fork();
2357 let mut attrs = input.call(Attribute::parse_outer)?;
2358 let vis: Visibility = input.parse()?;
2359 let defaultness: Option<Token![default]> = input.parse()?;
2360 let ahead = input.fork();
2361
2362 let lookahead = ahead.lookahead1();
2363 let allow_safe = false;
2364 let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead, allow_safe) {
2365 input.parse().map(TraitItem::Fn)
2366 } else if lookahead.peek(Token![const]) {
2367 let const_token: Token![const] = ahead.parse()?;
2368 let lookahead = ahead.lookahead1();
2369 if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
2370 input.advance_to(&ahead);
2371 let ident = input.call(Ident::parse_any)?;
2372 let mut generics: Generics = input.parse()?;
2373 let colon_token: Token![:] = input.parse()?;
2374 let ty: Type = input.parse()?;
2375 let default = if let Some(eq_token) = input.parse::<Option<Token![=]>>()? {
2376 let expr: Expr = input.parse()?;
2377 Some((eq_token, expr))
2378 } else {
2379 None
2380 };
2381 generics.where_clause = input.parse()?;
2382 let semi_token: Token![;] = input.parse()?;
2383 if generics.lt_token.is_none() && generics.where_clause.is_none() {
2384 Ok(TraitItem::Const(TraitItemConst {
2385 attrs: Vec::new(),
2386 const_token,
2387 ident,
2388 generics,
2389 colon_token,
2390 ty,
2391 default,
2392 semi_token,
2393 }))
2394 } else {
2395 return Ok(TraitItem::Verbatim(verbatim::between(&begin, input)));
2396 }
2397 } else if lookahead.peek(Token![async])
2398 || lookahead.peek(Token![unsafe])
2399 || lookahead.peek(Token![extern])
2400 || lookahead.peek(Token![fn])
2401 {
2402 input.parse().map(TraitItem::Fn)
2403 } else {
2404 Err(lookahead.error())
2405 }
2406 } else if lookahead.peek(Token![type]) {
2407 parse_trait_item_type(begin.fork(), input)
2408 } else if vis.is_inherited()
2409 && defaultness.is_none()
2410 && (lookahead.peek(Ident)
2411 || lookahead.peek(Token![self])
2412 || lookahead.peek(Token![super])
2413 || lookahead.peek(Token![crate])
2414 || lookahead.peek(Token![::]))
2415 {
2416 input.parse().map(TraitItem::Macro)
2417 } else {
2418 Err(lookahead.error())
2419 }?;
2420
2421 match (vis, defaultness) {
2422 (Visibility::Inherited, None) => {}
2423 _ => return Ok(TraitItem::Verbatim(verbatim::between(&begin, input))),
2424 }
2425
2426 let item_attrs = match &mut item {
2427 TraitItem::Const(item) => &mut item.attrs,
2428 TraitItem::Fn(item) => &mut item.attrs,
2429 TraitItem::Type(item) => &mut item.attrs,
2430 TraitItem::Macro(item) => &mut item.attrs,
2431 TraitItem::Verbatim(_) => unreachable!(),
2432 };
2433 attrs.append(item_attrs);
2434 *item_attrs = attrs;
2435 Ok(item)
2436 }
2437 }
2438
2439 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2440 impl Parse for TraitItemConst {
2441 fn parse(input: ParseStream) -> Result<Self> {
2442 let attrs = input.call(Attribute::parse_outer)?;
2443 let const_token: Token![const] = input.parse()?;
2444
2445 let lookahead = input.lookahead1();
2446 let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
2447 input.call(Ident::parse_any)?
2448 } else {
2449 return Err(lookahead.error());
2450 };
2451
2452 let colon_token: Token![:] = input.parse()?;
2453 let ty: Type = input.parse()?;
2454 let default = if input.peek(Token![=]) {
2455 let eq_token: Token![=] = input.parse()?;
2456 let default: Expr = input.parse()?;
2457 Some((eq_token, default))
2458 } else {
2459 None
2460 };
2461 let semi_token: Token![;] = input.parse()?;
2462
2463 Ok(TraitItemConst {
2464 attrs,
2465 const_token,
2466 ident,
2467 generics: Generics::default(),
2468 colon_token,
2469 ty,
2470 default,
2471 semi_token,
2472 })
2473 }
2474 }
2475
2476 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2477 impl Parse for TraitItemFn {
2478 fn parse(input: ParseStream) -> Result<Self> {
2479 let mut attrs = input.call(Attribute::parse_outer)?;
2480 let sig: Signature = input.parse()?;
2481
2482 let lookahead = input.lookahead1();
2483 let (brace_token, stmts, semi_token) = if lookahead.peek(token::Brace) {
2484 let content;
2485 let brace_token = braced!(content in input);
2486 attr::parsing::parse_inner(&content, &mut attrs)?;
2487 let stmts = content.call(Block::parse_within)?;
2488 (Some(brace_token), stmts, None)
2489 } else if lookahead.peek(Token![;]) {
2490 let semi_token: Token![;] = input.parse()?;
2491 (None, Vec::new(), Some(semi_token))
2492 } else {
2493 return Err(lookahead.error());
2494 };
2495
2496 Ok(TraitItemFn {
2497 attrs,
2498 sig,
2499 default: brace_token.map(|brace_token| Block { brace_token, stmts }),
2500 semi_token,
2501 })
2502 }
2503 }
2504
2505 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2506 impl Parse for TraitItemType {
2507 fn parse(input: ParseStream) -> Result<Self> {
2508 let attrs = input.call(Attribute::parse_outer)?;
2509 let type_token: Token![type] = input.parse()?;
2510 let ident: Ident = input.parse()?;
2511 let mut generics: Generics = input.parse()?;
2512 let (colon_token, bounds) = FlexibleItemType::parse_optional_bounds(input)?;
2513 let default = FlexibleItemType::parse_optional_definition(input)?;
2514 generics.where_clause = input.parse()?;
2515 let semi_token: Token![;] = input.parse()?;
2516 Ok(TraitItemType {
2517 attrs,
2518 type_token,
2519 ident,
2520 generics,
2521 colon_token,
2522 bounds,
2523 default,
2524 semi_token,
2525 })
2526 }
2527 }
2528
2529 fn parse_trait_item_type(begin: ParseBuffer, input: ParseStream) -> Result<TraitItem> {
2530 let FlexibleItemType {
2531 vis,
2532 defaultness: _,
2533 type_token,
2534 ident,
2535 generics,
2536 colon_token,
2537 bounds,
2538 ty,
2539 semi_token,
2540 } = FlexibleItemType::parse(
2541 input,
2542 TypeDefaultness::Disallowed,
2543 WhereClauseLocation::AfterEq,
2544 )?;
2545
2546 if vis.is_some() {
2547 Ok(TraitItem::Verbatim(verbatim::between(&begin, input)))
2548 } else {
2549 Ok(TraitItem::Type(TraitItemType {
2550 attrs: Vec::new(),
2551 type_token,
2552 ident,
2553 generics,
2554 colon_token,
2555 bounds,
2556 default: ty,
2557 semi_token,
2558 }))
2559 }
2560 }
2561
2562 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2563 impl Parse for TraitItemMacro {
2564 fn parse(input: ParseStream) -> Result<Self> {
2565 let attrs = input.call(Attribute::parse_outer)?;
2566 let mac: Macro = input.parse()?;
2567 let semi_token: Option<Token![;]> = if mac.delimiter.is_brace() {
2568 None
2569 } else {
2570 Some(input.parse()?)
2571 };
2572 Ok(TraitItemMacro {
2573 attrs,
2574 mac,
2575 semi_token,
2576 })
2577 }
2578 }
2579
2580 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2581 impl Parse for ItemImpl {
2582 fn parse(input: ParseStream) -> Result<Self> {
2583 let allow_verbatim_impl = false;
2584 parse_impl(input, allow_verbatim_impl).map(Option::unwrap)
2585 }
2586 }
2587
2588 fn parse_impl(input: ParseStream, allow_verbatim_impl: bool) -> Result<Option<ItemImpl>> {
2589 let mut attrs = input.call(Attribute::parse_outer)?;
2590 let has_visibility = allow_verbatim_impl && input.parse::<Visibility>()?.is_some();
2591 let defaultness: Option<Token![default]> = input.parse()?;
2592 let unsafety: Option<Token![unsafe]> = input.parse()?;
2593 let impl_token: Token![impl] = input.parse()?;
2594
2595 let has_generics = generics::parsing::choose_generics_over_qpath(input);
2596 let mut generics: Generics = if has_generics {
2597 input.parse()?
2598 } else {
2599 Generics::default()
2600 };
2601
2602 let is_const_impl = allow_verbatim_impl
2603 && (input.peek(Token![const]) || input.peek(Token![?]) && input.peek2(Token![const]));
2604 if is_const_impl {
2605 input.parse::<Option<Token![?]>>()?;
2606 input.parse::<Token![const]>()?;
2607 }
2608
2609 let polarity = if input.peek(Token![!]) && !input.peek2(token::Brace) {
2610 Some(input.parse::<Token![!]>()?)
2611 } else {
2612 None
2613 };
2614
2615 #[cfg(not(feature = "printing"))]
2616 let first_ty_span = input.span();
2617 let mut first_ty: Type = input.parse()?;
2618 let self_ty: Type;
2619 let trait_;
2620
2621 let is_impl_for = input.peek(Token![for]);
2622 if is_impl_for {
2623 let for_token: Token![for] = input.parse()?;
2624 let mut first_ty_ref = &first_ty;
2625 while let Type::Group(ty) = first_ty_ref {
2626 first_ty_ref = &ty.elem;
2627 }
2628 if let Type::Path(TypePath { qself: None, .. }) = first_ty_ref {
2629 while let Type::Group(ty) = first_ty {
2630 first_ty = *ty.elem;
2631 }
2632 if let Type::Path(TypePath { qself: None, path }) = first_ty {
2633 trait_ = Some((polarity, path, for_token));
2634 } else {
2635 unreachable!();
2636 }
2637 } else if !allow_verbatim_impl {
2638 #[cfg(feature = "printing")]
2639 return Err(Error::new_spanned(first_ty_ref, "expected trait path"));
2640 #[cfg(not(feature = "printing"))]
2641 return Err(Error::new(first_ty_span, "expected trait path"));
2642 } else {
2643 trait_ = None;
2644 }
2645 self_ty = input.parse()?;
2646 } else if let Some(polarity) = polarity {
2647 return Err(Error::new(
2648 polarity.span,
2649 "inherent impls cannot be negative",
2650 ));
2651 } else {
2652 trait_ = None;
2653 self_ty = first_ty;
2654 }
2655
2656 generics.where_clause = input.parse()?;
2657
2658 let content;
2659 let brace_token = braced!(content in input);
2660 attr::parsing::parse_inner(&content, &mut attrs)?;
2661
2662 let mut items = Vec::new();
2663 while !content.is_empty() {
2664 items.push(content.parse()?);
2665 }
2666
2667 if has_visibility || is_const_impl || is_impl_for && trait_.is_none() {
2668 Ok(None)
2669 } else {
2670 Ok(Some(ItemImpl {
2671 attrs,
2672 defaultness,
2673 unsafety,
2674 impl_token,
2675 generics,
2676 trait_,
2677 self_ty: Box::new(self_ty),
2678 brace_token,
2679 items,
2680 }))
2681 }
2682 }
2683
2684 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2685 impl Parse for ImplItem {
2686 fn parse(input: ParseStream) -> Result<Self> {
2687 let begin = input.fork();
2688 let mut attrs = input.call(Attribute::parse_outer)?;
2689 let ahead = input.fork();
2690 let vis: Visibility = ahead.parse()?;
2691
2692 let mut lookahead = ahead.lookahead1();
2693 let defaultness = if lookahead.peek(Token![default]) && !ahead.peek2(Token![!]) {
2694 let defaultness: Token![default] = ahead.parse()?;
2695 lookahead = ahead.lookahead1();
2696 Some(defaultness)
2697 } else {
2698 None
2699 };
2700
2701 let allow_safe = false;
2702 let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead, allow_safe) {
2703 let allow_omitted_body = true;
2704 if let Some(item) = parse_impl_item_fn(input, allow_omitted_body)? {
2705 Ok(ImplItem::Fn(item))
2706 } else {
2707 Ok(ImplItem::Verbatim(verbatim::between(&begin, input)))
2708 }
2709 } else if lookahead.peek(Token![const]) {
2710 input.advance_to(&ahead);
2711 let const_token: Token![const] = input.parse()?;
2712 let lookahead = input.lookahead1();
2713 let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
2714 input.call(Ident::parse_any)?
2715 } else {
2716 return Err(lookahead.error());
2717 };
2718 let mut generics: Generics = input.parse()?;
2719 let colon_token: Token![:] = input.parse()?;
2720 let ty: Type = input.parse()?;
2721 let value = if let Some(eq_token) = input.parse::<Option<Token![=]>>()? {
2722 let expr: Expr = input.parse()?;
2723 Some((eq_token, expr))
2724 } else {
2725 None
2726 };
2727 generics.where_clause = input.parse()?;
2728 let semi_token: Token![;] = input.parse()?;
2729 return match value {
2730 Some((eq_token, expr))
2731 if generics.lt_token.is_none() && generics.where_clause.is_none() =>
2732 {
2733 Ok(ImplItem::Const(ImplItemConst {
2734 attrs,
2735 vis,
2736 defaultness,
2737 const_token,
2738 ident,
2739 generics,
2740 colon_token,
2741 ty,
2742 eq_token,
2743 expr,
2744 semi_token,
2745 }))
2746 }
2747 _ => Ok(ImplItem::Verbatim(verbatim::between(&begin, input))),
2748 };
2749 } else if lookahead.peek(Token![type]) {
2750 parse_impl_item_type(begin, input)
2751 } else if vis.is_inherited()
2752 && defaultness.is_none()
2753 && (lookahead.peek(Ident)
2754 || lookahead.peek(Token![self])
2755 || lookahead.peek(Token![super])
2756 || lookahead.peek(Token![crate])
2757 || lookahead.peek(Token![::]))
2758 {
2759 input.parse().map(ImplItem::Macro)
2760 } else {
2761 Err(lookahead.error())
2762 }?;
2763
2764 {
2765 let item_attrs = match &mut item {
2766 ImplItem::Const(item) => &mut item.attrs,
2767 ImplItem::Fn(item) => &mut item.attrs,
2768 ImplItem::Type(item) => &mut item.attrs,
2769 ImplItem::Macro(item) => &mut item.attrs,
2770 ImplItem::Verbatim(_) => return Ok(item),
2771 };
2772 attrs.append(item_attrs);
2773 *item_attrs = attrs;
2774 }
2775
2776 Ok(item)
2777 }
2778 }
2779
2780 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2781 impl Parse for ImplItemConst {
2782 fn parse(input: ParseStream) -> Result<Self> {
2783 let attrs = input.call(Attribute::parse_outer)?;
2784 let vis: Visibility = input.parse()?;
2785 let defaultness: Option<Token![default]> = input.parse()?;
2786 let const_token: Token![const] = input.parse()?;
2787
2788 let lookahead = input.lookahead1();
2789 let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) {
2790 input.call(Ident::parse_any)?
2791 } else {
2792 return Err(lookahead.error());
2793 };
2794
2795 let colon_token: Token![:] = input.parse()?;
2796 let ty: Type = input.parse()?;
2797 let eq_token: Token![=] = input.parse()?;
2798 let expr: Expr = input.parse()?;
2799 let semi_token: Token![;] = input.parse()?;
2800
2801 Ok(ImplItemConst {
2802 attrs,
2803 vis,
2804 defaultness,
2805 const_token,
2806 ident,
2807 generics: Generics::default(),
2808 colon_token,
2809 ty,
2810 eq_token,
2811 expr,
2812 semi_token,
2813 })
2814 }
2815 }
2816
2817 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2818 impl Parse for ImplItemFn {
2819 fn parse(input: ParseStream) -> Result<Self> {
2820 let allow_omitted_body = false;
2821 parse_impl_item_fn(input, allow_omitted_body).map(Option::unwrap)
2822 }
2823 }
2824
2825 fn parse_impl_item_fn(
2826 input: ParseStream,
2827 allow_omitted_body: bool,
2828 ) -> Result<Option<ImplItemFn>> {
2829 let mut attrs = input.call(Attribute::parse_outer)?;
2830 let vis: Visibility = input.parse()?;
2831 let defaultness: Option<Token![default]> = input.parse()?;
2832 let sig: Signature = input.parse()?;
2833
2834 if allow_omitted_body && input.parse::<Option<Token![;]>>()?.is_some() {
2838 return Ok(None);
2839 }
2840
2841 let content;
2842 let brace_token = braced!(content in input);
2843 attrs.extend(content.call(Attribute::parse_inner)?);
2844 let block = Block {
2845 brace_token,
2846 stmts: content.call(Block::parse_within)?,
2847 };
2848
2849 Ok(Some(ImplItemFn {
2850 attrs,
2851 vis,
2852 defaultness,
2853 sig,
2854 block,
2855 }))
2856 }
2857
2858 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2859 impl Parse for ImplItemType {
2860 fn parse(input: ParseStream) -> Result<Self> {
2861 let attrs = input.call(Attribute::parse_outer)?;
2862 let vis: Visibility = input.parse()?;
2863 let defaultness: Option<Token![default]> = input.parse()?;
2864 let type_token: Token![type] = input.parse()?;
2865 let ident: Ident = input.parse()?;
2866 let mut generics: Generics = input.parse()?;
2867 let eq_token: Token![=] = input.parse()?;
2868 let ty: Type = input.parse()?;
2869 generics.where_clause = input.parse()?;
2870 let semi_token: Token![;] = input.parse()?;
2871 Ok(ImplItemType {
2872 attrs,
2873 vis,
2874 defaultness,
2875 type_token,
2876 ident,
2877 generics,
2878 eq_token,
2879 ty,
2880 semi_token,
2881 })
2882 }
2883 }
2884
2885 fn parse_impl_item_type(begin: ParseBuffer, input: ParseStream) -> Result<ImplItem> {
2886 let FlexibleItemType {
2887 vis,
2888 defaultness,
2889 type_token,
2890 ident,
2891 generics,
2892 colon_token,
2893 bounds: _,
2894 ty,
2895 semi_token,
2896 } = FlexibleItemType::parse(
2897 input,
2898 TypeDefaultness::Optional,
2899 WhereClauseLocation::AfterEq,
2900 )?;
2901
2902 let (eq_token, ty) = match ty {
2903 Some(ty) if colon_token.is_none() => ty,
2904 _ => return Ok(ImplItem::Verbatim(verbatim::between(&begin, input))),
2905 };
2906
2907 Ok(ImplItem::Type(ImplItemType {
2908 attrs: Vec::new(),
2909 vis,
2910 defaultness,
2911 type_token,
2912 ident,
2913 generics,
2914 eq_token,
2915 ty,
2916 semi_token,
2917 }))
2918 }
2919
2920 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2921 impl Parse for ImplItemMacro {
2922 fn parse(input: ParseStream) -> Result<Self> {
2923 let attrs = input.call(Attribute::parse_outer)?;
2924 let mac: Macro = input.parse()?;
2925 let semi_token: Option<Token![;]> = if mac.delimiter.is_brace() {
2926 None
2927 } else {
2928 Some(input.parse()?)
2929 };
2930 Ok(ImplItemMacro {
2931 attrs,
2932 mac,
2933 semi_token,
2934 })
2935 }
2936 }
2937
2938 impl Visibility {
2939 fn is_inherited(&self) -> bool {
2940 match self {
2941 Visibility::Inherited => true,
2942 _ => false,
2943 }
2944 }
2945 }
2946
2947 #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
2948 impl Parse for StaticMutability {
2949 fn parse(input: ParseStream) -> Result<Self> {
2950 let mut_token: Option<Token![mut]> = input.parse()?;
2951 Ok(mut_token.map_or(StaticMutability::None, StaticMutability::Mut))
2952 }
2953 }
2954}
2955
2956#[cfg(feature = "printing")]
2957mod printing {
2958 use crate::attr::FilterAttrs;
2959 use crate::data::Fields;
2960 use crate::item::{
2961 ForeignItemFn, ForeignItemMacro, ForeignItemStatic, ForeignItemType, ImplItemConst,
2962 ImplItemFn, ImplItemMacro, ImplItemType, ItemConst, ItemEnum, ItemExternCrate, ItemFn,
2963 ItemForeignMod, ItemImpl, ItemMacro, ItemMod, ItemStatic, ItemStruct, ItemTrait,
2964 ItemTraitAlias, ItemType, ItemUnion, ItemUse, Receiver, Signature, StaticMutability,
2965 TraitItemConst, TraitItemFn, TraitItemMacro, TraitItemType, UseGlob, UseGroup, UseName,
2966 UsePath, UseRename, Variadic,
2967 };
2968 use crate::mac::MacroDelimiter;
2969 use crate::path;
2970 use crate::path::printing::PathStyle;
2971 use crate::print::TokensOrDefault;
2972 use crate::ty::Type;
2973 use proc_macro2::TokenStream;
2974 use quote::{ToTokens, TokenStreamExt as _};
2975
2976 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
2977 impl ToTokens for ItemExternCrate {
2978 fn to_tokens(&self, tokens: &mut TokenStream) {
2979 tokens.append_all(self.attrs.outer());
2980 self.vis.to_tokens(tokens);
2981 self.extern_token.to_tokens(tokens);
2982 self.crate_token.to_tokens(tokens);
2983 self.ident.to_tokens(tokens);
2984 if let Some((as_token, rename)) = &self.rename {
2985 as_token.to_tokens(tokens);
2986 rename.to_tokens(tokens);
2987 }
2988 self.semi_token.to_tokens(tokens);
2989 }
2990 }
2991
2992 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
2993 impl ToTokens for ItemUse {
2994 fn to_tokens(&self, tokens: &mut TokenStream) {
2995 tokens.append_all(self.attrs.outer());
2996 self.vis.to_tokens(tokens);
2997 self.use_token.to_tokens(tokens);
2998 self.leading_colon.to_tokens(tokens);
2999 self.tree.to_tokens(tokens);
3000 self.semi_token.to_tokens(tokens);
3001 }
3002 }
3003
3004 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3005 impl ToTokens for ItemStatic {
3006 fn to_tokens(&self, tokens: &mut TokenStream) {
3007 tokens.append_all(self.attrs.outer());
3008 self.vis.to_tokens(tokens);
3009 self.static_token.to_tokens(tokens);
3010 self.mutability.to_tokens(tokens);
3011 self.ident.to_tokens(tokens);
3012 self.colon_token.to_tokens(tokens);
3013 self.ty.to_tokens(tokens);
3014 self.eq_token.to_tokens(tokens);
3015 self.expr.to_tokens(tokens);
3016 self.semi_token.to_tokens(tokens);
3017 }
3018 }
3019
3020 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3021 impl ToTokens for ItemConst {
3022 fn to_tokens(&self, tokens: &mut TokenStream) {
3023 tokens.append_all(self.attrs.outer());
3024 self.vis.to_tokens(tokens);
3025 self.const_token.to_tokens(tokens);
3026 self.ident.to_tokens(tokens);
3027 self.colon_token.to_tokens(tokens);
3028 self.ty.to_tokens(tokens);
3029 self.eq_token.to_tokens(tokens);
3030 self.expr.to_tokens(tokens);
3031 self.semi_token.to_tokens(tokens);
3032 }
3033 }
3034
3035 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3036 impl ToTokens for ItemFn {
3037 fn to_tokens(&self, tokens: &mut TokenStream) {
3038 tokens.append_all(self.attrs.outer());
3039 self.vis.to_tokens(tokens);
3040 self.sig.to_tokens(tokens);
3041 self.block.brace_token.surround(tokens, |tokens| {
3042 tokens.append_all(self.attrs.inner());
3043 tokens.append_all(&self.block.stmts);
3044 });
3045 }
3046 }
3047
3048 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3049 impl ToTokens for ItemMod {
3050 fn to_tokens(&self, tokens: &mut TokenStream) {
3051 tokens.append_all(self.attrs.outer());
3052 self.vis.to_tokens(tokens);
3053 self.unsafety.to_tokens(tokens);
3054 self.mod_token.to_tokens(tokens);
3055 self.ident.to_tokens(tokens);
3056 if let Some((brace, items)) = &self.content {
3057 brace.surround(tokens, |tokens| {
3058 tokens.append_all(self.attrs.inner());
3059 tokens.append_all(items);
3060 });
3061 } else {
3062 TokensOrDefault(&self.semi).to_tokens(tokens);
3063 }
3064 }
3065 }
3066
3067 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3068 impl ToTokens for ItemForeignMod {
3069 fn to_tokens(&self, tokens: &mut TokenStream) {
3070 tokens.append_all(self.attrs.outer());
3071 self.unsafety.to_tokens(tokens);
3072 self.abi.to_tokens(tokens);
3073 self.brace_token.surround(tokens, |tokens| {
3074 tokens.append_all(self.attrs.inner());
3075 tokens.append_all(&self.items);
3076 });
3077 }
3078 }
3079
3080 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3081 impl ToTokens for ItemType {
3082 fn to_tokens(&self, tokens: &mut TokenStream) {
3083 tokens.append_all(self.attrs.outer());
3084 self.vis.to_tokens(tokens);
3085 self.type_token.to_tokens(tokens);
3086 self.ident.to_tokens(tokens);
3087 self.generics.to_tokens(tokens);
3088 self.generics.where_clause.to_tokens(tokens);
3089 self.eq_token.to_tokens(tokens);
3090 self.ty.to_tokens(tokens);
3091 self.semi_token.to_tokens(tokens);
3092 }
3093 }
3094
3095 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3096 impl ToTokens for ItemEnum {
3097 fn to_tokens(&self, tokens: &mut TokenStream) {
3098 tokens.append_all(self.attrs.outer());
3099 self.vis.to_tokens(tokens);
3100 self.enum_token.to_tokens(tokens);
3101 self.ident.to_tokens(tokens);
3102 self.generics.to_tokens(tokens);
3103 self.generics.where_clause.to_tokens(tokens);
3104 self.brace_token.surround(tokens, |tokens| {
3105 self.variants.to_tokens(tokens);
3106 });
3107 }
3108 }
3109
3110 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3111 impl ToTokens for ItemStruct {
3112 fn to_tokens(&self, tokens: &mut TokenStream) {
3113 tokens.append_all(self.attrs.outer());
3114 self.vis.to_tokens(tokens);
3115 self.struct_token.to_tokens(tokens);
3116 self.ident.to_tokens(tokens);
3117 self.generics.to_tokens(tokens);
3118 match &self.fields {
3119 Fields::Named(fields) => {
3120 self.generics.where_clause.to_tokens(tokens);
3121 fields.to_tokens(tokens);
3122 }
3123 Fields::Unnamed(fields) => {
3124 fields.to_tokens(tokens);
3125 self.generics.where_clause.to_tokens(tokens);
3126 TokensOrDefault(&self.semi_token).to_tokens(tokens);
3127 }
3128 Fields::Unit => {
3129 self.generics.where_clause.to_tokens(tokens);
3130 TokensOrDefault(&self.semi_token).to_tokens(tokens);
3131 }
3132 }
3133 }
3134 }
3135
3136 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3137 impl ToTokens for ItemUnion {
3138 fn to_tokens(&self, tokens: &mut TokenStream) {
3139 tokens.append_all(self.attrs.outer());
3140 self.vis.to_tokens(tokens);
3141 self.union_token.to_tokens(tokens);
3142 self.ident.to_tokens(tokens);
3143 self.generics.to_tokens(tokens);
3144 self.generics.where_clause.to_tokens(tokens);
3145 self.fields.to_tokens(tokens);
3146 }
3147 }
3148
3149 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3150 impl ToTokens for ItemTrait {
3151 fn to_tokens(&self, tokens: &mut TokenStream) {
3152 tokens.append_all(self.attrs.outer());
3153 self.vis.to_tokens(tokens);
3154 self.unsafety.to_tokens(tokens);
3155 self.auto_token.to_tokens(tokens);
3156 self.trait_token.to_tokens(tokens);
3157 self.ident.to_tokens(tokens);
3158 self.generics.to_tokens(tokens);
3159 if !self.supertraits.is_empty() {
3160 TokensOrDefault(&self.colon_token).to_tokens(tokens);
3161 self.supertraits.to_tokens(tokens);
3162 }
3163 self.generics.where_clause.to_tokens(tokens);
3164 self.brace_token.surround(tokens, |tokens| {
3165 tokens.append_all(self.attrs.inner());
3166 tokens.append_all(&self.items);
3167 });
3168 }
3169 }
3170
3171 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3172 impl ToTokens for ItemTraitAlias {
3173 fn to_tokens(&self, tokens: &mut TokenStream) {
3174 tokens.append_all(self.attrs.outer());
3175 self.vis.to_tokens(tokens);
3176 self.trait_token.to_tokens(tokens);
3177 self.ident.to_tokens(tokens);
3178 self.generics.to_tokens(tokens);
3179 self.eq_token.to_tokens(tokens);
3180 self.bounds.to_tokens(tokens);
3181 self.generics.where_clause.to_tokens(tokens);
3182 self.semi_token.to_tokens(tokens);
3183 }
3184 }
3185
3186 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3187 impl ToTokens for ItemImpl {
3188 fn to_tokens(&self, tokens: &mut TokenStream) {
3189 tokens.append_all(self.attrs.outer());
3190 self.defaultness.to_tokens(tokens);
3191 self.unsafety.to_tokens(tokens);
3192 self.impl_token.to_tokens(tokens);
3193 self.generics.to_tokens(tokens);
3194 if let Some((polarity, path, for_token)) = &self.trait_ {
3195 polarity.to_tokens(tokens);
3196 path.to_tokens(tokens);
3197 for_token.to_tokens(tokens);
3198 }
3199 self.self_ty.to_tokens(tokens);
3200 self.generics.where_clause.to_tokens(tokens);
3201 self.brace_token.surround(tokens, |tokens| {
3202 tokens.append_all(self.attrs.inner());
3203 tokens.append_all(&self.items);
3204 });
3205 }
3206 }
3207
3208 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3209 impl ToTokens for ItemMacro {
3210 fn to_tokens(&self, tokens: &mut TokenStream) {
3211 tokens.append_all(self.attrs.outer());
3212 path::printing::print_path(tokens, &self.mac.path, PathStyle::Mod);
3213 self.mac.bang_token.to_tokens(tokens);
3214 self.ident.to_tokens(tokens);
3215 match &self.mac.delimiter {
3216 MacroDelimiter::Paren(paren) => {
3217 paren.surround(tokens, |tokens| self.mac.tokens.to_tokens(tokens));
3218 }
3219 MacroDelimiter::Brace(brace) => {
3220 brace.surround(tokens, |tokens| self.mac.tokens.to_tokens(tokens));
3221 }
3222 MacroDelimiter::Bracket(bracket) => {
3223 bracket.surround(tokens, |tokens| self.mac.tokens.to_tokens(tokens));
3224 }
3225 }
3226 self.semi_token.to_tokens(tokens);
3227 }
3228 }
3229
3230 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3231 impl ToTokens for UsePath {
3232 fn to_tokens(&self, tokens: &mut TokenStream) {
3233 self.ident.to_tokens(tokens);
3234 self.colon2_token.to_tokens(tokens);
3235 self.tree.to_tokens(tokens);
3236 }
3237 }
3238
3239 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3240 impl ToTokens for UseName {
3241 fn to_tokens(&self, tokens: &mut TokenStream) {
3242 self.ident.to_tokens(tokens);
3243 }
3244 }
3245
3246 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3247 impl ToTokens for UseRename {
3248 fn to_tokens(&self, tokens: &mut TokenStream) {
3249 self.ident.to_tokens(tokens);
3250 self.as_token.to_tokens(tokens);
3251 self.rename.to_tokens(tokens);
3252 }
3253 }
3254
3255 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3256 impl ToTokens for UseGlob {
3257 fn to_tokens(&self, tokens: &mut TokenStream) {
3258 self.star_token.to_tokens(tokens);
3259 }
3260 }
3261
3262 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3263 impl ToTokens for UseGroup {
3264 fn to_tokens(&self, tokens: &mut TokenStream) {
3265 self.brace_token.surround(tokens, |tokens| {
3266 self.items.to_tokens(tokens);
3267 });
3268 }
3269 }
3270
3271 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3272 impl ToTokens for TraitItemConst {
3273 fn to_tokens(&self, tokens: &mut TokenStream) {
3274 tokens.append_all(self.attrs.outer());
3275 self.const_token.to_tokens(tokens);
3276 self.ident.to_tokens(tokens);
3277 self.colon_token.to_tokens(tokens);
3278 self.ty.to_tokens(tokens);
3279 if let Some((eq_token, default)) = &self.default {
3280 eq_token.to_tokens(tokens);
3281 default.to_tokens(tokens);
3282 }
3283 self.semi_token.to_tokens(tokens);
3284 }
3285 }
3286
3287 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3288 impl ToTokens for TraitItemFn {
3289 fn to_tokens(&self, tokens: &mut TokenStream) {
3290 tokens.append_all(self.attrs.outer());
3291 self.sig.to_tokens(tokens);
3292 match &self.default {
3293 Some(block) => {
3294 block.brace_token.surround(tokens, |tokens| {
3295 tokens.append_all(self.attrs.inner());
3296 tokens.append_all(&block.stmts);
3297 });
3298 }
3299 None => {
3300 TokensOrDefault(&self.semi_token).to_tokens(tokens);
3301 }
3302 }
3303 }
3304 }
3305
3306 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3307 impl ToTokens for TraitItemType {
3308 fn to_tokens(&self, tokens: &mut TokenStream) {
3309 tokens.append_all(self.attrs.outer());
3310 self.type_token.to_tokens(tokens);
3311 self.ident.to_tokens(tokens);
3312 self.generics.to_tokens(tokens);
3313 if !self.bounds.is_empty() {
3314 TokensOrDefault(&self.colon_token).to_tokens(tokens);
3315 self.bounds.to_tokens(tokens);
3316 }
3317 if let Some((eq_token, default)) = &self.default {
3318 eq_token.to_tokens(tokens);
3319 default.to_tokens(tokens);
3320 }
3321 self.generics.where_clause.to_tokens(tokens);
3322 self.semi_token.to_tokens(tokens);
3323 }
3324 }
3325
3326 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3327 impl ToTokens for TraitItemMacro {
3328 fn to_tokens(&self, tokens: &mut TokenStream) {
3329 tokens.append_all(self.attrs.outer());
3330 self.mac.to_tokens(tokens);
3331 self.semi_token.to_tokens(tokens);
3332 }
3333 }
3334
3335 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3336 impl ToTokens for ImplItemConst {
3337 fn to_tokens(&self, tokens: &mut TokenStream) {
3338 tokens.append_all(self.attrs.outer());
3339 self.vis.to_tokens(tokens);
3340 self.defaultness.to_tokens(tokens);
3341 self.const_token.to_tokens(tokens);
3342 self.ident.to_tokens(tokens);
3343 self.colon_token.to_tokens(tokens);
3344 self.ty.to_tokens(tokens);
3345 self.eq_token.to_tokens(tokens);
3346 self.expr.to_tokens(tokens);
3347 self.semi_token.to_tokens(tokens);
3348 }
3349 }
3350
3351 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3352 impl ToTokens for ImplItemFn {
3353 fn to_tokens(&self, tokens: &mut TokenStream) {
3354 tokens.append_all(self.attrs.outer());
3355 self.vis.to_tokens(tokens);
3356 self.defaultness.to_tokens(tokens);
3357 self.sig.to_tokens(tokens);
3358 self.block.brace_token.surround(tokens, |tokens| {
3359 tokens.append_all(self.attrs.inner());
3360 tokens.append_all(&self.block.stmts);
3361 });
3362 }
3363 }
3364
3365 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3366 impl ToTokens for ImplItemType {
3367 fn to_tokens(&self, tokens: &mut TokenStream) {
3368 tokens.append_all(self.attrs.outer());
3369 self.vis.to_tokens(tokens);
3370 self.defaultness.to_tokens(tokens);
3371 self.type_token.to_tokens(tokens);
3372 self.ident.to_tokens(tokens);
3373 self.generics.to_tokens(tokens);
3374 self.eq_token.to_tokens(tokens);
3375 self.ty.to_tokens(tokens);
3376 self.generics.where_clause.to_tokens(tokens);
3377 self.semi_token.to_tokens(tokens);
3378 }
3379 }
3380
3381 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3382 impl ToTokens for ImplItemMacro {
3383 fn to_tokens(&self, tokens: &mut TokenStream) {
3384 tokens.append_all(self.attrs.outer());
3385 self.mac.to_tokens(tokens);
3386 self.semi_token.to_tokens(tokens);
3387 }
3388 }
3389
3390 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3391 impl ToTokens for ForeignItemFn {
3392 fn to_tokens(&self, tokens: &mut TokenStream) {
3393 tokens.append_all(self.attrs.outer());
3394 self.vis.to_tokens(tokens);
3395 self.sig.to_tokens(tokens);
3396 self.semi_token.to_tokens(tokens);
3397 }
3398 }
3399
3400 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3401 impl ToTokens for ForeignItemStatic {
3402 fn to_tokens(&self, tokens: &mut TokenStream) {
3403 tokens.append_all(self.attrs.outer());
3404 self.vis.to_tokens(tokens);
3405 self.static_token.to_tokens(tokens);
3406 self.mutability.to_tokens(tokens);
3407 self.ident.to_tokens(tokens);
3408 self.colon_token.to_tokens(tokens);
3409 self.ty.to_tokens(tokens);
3410 self.semi_token.to_tokens(tokens);
3411 }
3412 }
3413
3414 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3415 impl ToTokens for ForeignItemType {
3416 fn to_tokens(&self, tokens: &mut TokenStream) {
3417 tokens.append_all(self.attrs.outer());
3418 self.vis.to_tokens(tokens);
3419 self.type_token.to_tokens(tokens);
3420 self.ident.to_tokens(tokens);
3421 self.generics.to_tokens(tokens);
3422 self.generics.where_clause.to_tokens(tokens);
3423 self.semi_token.to_tokens(tokens);
3424 }
3425 }
3426
3427 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3428 impl ToTokens for ForeignItemMacro {
3429 fn to_tokens(&self, tokens: &mut TokenStream) {
3430 tokens.append_all(self.attrs.outer());
3431 self.mac.to_tokens(tokens);
3432 self.semi_token.to_tokens(tokens);
3433 }
3434 }
3435
3436 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3437 impl ToTokens for Signature {
3438 fn to_tokens(&self, tokens: &mut TokenStream) {
3439 self.constness.to_tokens(tokens);
3440 self.asyncness.to_tokens(tokens);
3441 self.unsafety.to_tokens(tokens);
3442 self.abi.to_tokens(tokens);
3443 self.fn_token.to_tokens(tokens);
3444 self.ident.to_tokens(tokens);
3445 self.generics.to_tokens(tokens);
3446 self.paren_token.surround(tokens, |tokens| {
3447 self.inputs.to_tokens(tokens);
3448 if let Some(variadic) = &self.variadic {
3449 if !self.inputs.empty_or_trailing() {
3450 <Token![,]>::default().to_tokens(tokens);
3451 }
3452 variadic.to_tokens(tokens);
3453 }
3454 });
3455 self.output.to_tokens(tokens);
3456 self.generics.where_clause.to_tokens(tokens);
3457 }
3458 }
3459
3460 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3461 impl ToTokens for Receiver {
3462 fn to_tokens(&self, tokens: &mut TokenStream) {
3463 tokens.append_all(self.attrs.outer());
3464 if let Some((ampersand, lifetime)) = &self.reference {
3465 ampersand.to_tokens(tokens);
3466 lifetime.to_tokens(tokens);
3467 }
3468 self.mutability.to_tokens(tokens);
3469 self.self_token.to_tokens(tokens);
3470 if let Some(colon_token) = &self.colon_token {
3471 colon_token.to_tokens(tokens);
3472 self.ty.to_tokens(tokens);
3473 } else {
3474 let consistent = match (&self.reference, &self.mutability, &*self.ty) {
3475 (Some(_), mutability, Type::Reference(ty)) => {
3476 mutability.is_some() == ty.mutability.is_some()
3477 && match &*ty.elem {
3478 Type::Path(ty) => ty.qself.is_none() && ty.path.is_ident("Self"),
3479 _ => false,
3480 }
3481 }
3482 (None, _, Type::Path(ty)) => ty.qself.is_none() && ty.path.is_ident("Self"),
3483 _ => false,
3484 };
3485 if !consistent {
3486 <Token![:]>::default().to_tokens(tokens);
3487 self.ty.to_tokens(tokens);
3488 }
3489 }
3490 }
3491 }
3492
3493 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3494 impl ToTokens for Variadic {
3495 fn to_tokens(&self, tokens: &mut TokenStream) {
3496 tokens.append_all(self.attrs.outer());
3497 if let Some((pat, colon)) = &self.pat {
3498 pat.to_tokens(tokens);
3499 colon.to_tokens(tokens);
3500 }
3501 self.dots.to_tokens(tokens);
3502 self.comma.to_tokens(tokens);
3503 }
3504 }
3505
3506 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
3507 impl ToTokens for StaticMutability {
3508 fn to_tokens(&self, tokens: &mut TokenStream) {
3509 match self {
3510 StaticMutability::None => {}
3511 StaticMutability::Mut(mut_token) => mut_token.to_tokens(tokens),
3512 }
3513 }
3514 }
3515}