item.rs 119 KB

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