generics.rs 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  1. // SPDX-License-Identifier: Apache-2.0 OR MIT
  2. use crate::attr::Attribute;
  3. use crate::expr::Expr;
  4. use crate::ident::Ident;
  5. use crate::lifetime::Lifetime;
  6. use crate::path::Path;
  7. use crate::punctuated::{Iter, IterMut, Punctuated};
  8. use crate::token;
  9. use crate::ty::Type;
  10. use proc_macro2::TokenStream;
  11. #[cfg(all(feature = "printing", feature = "extra-traits"))]
  12. use std::fmt::{self, Debug};
  13. #[cfg(all(feature = "printing", feature = "extra-traits"))]
  14. use std::hash::{Hash, Hasher};
  15. ast_struct! {
  16. /// Lifetimes and type parameters attached to a declaration of a function,
  17. /// enum, trait, etc.
  18. ///
  19. /// This struct represents two distinct optional syntactic elements,
  20. /// [generic parameters] and [where clause]. In some locations of the
  21. /// grammar, there may be other tokens in between these two things.
  22. ///
  23. /// [generic parameters]: https://doc.rust-lang.org/stable/reference/items/generics.html#generic-parameters
  24. /// [where clause]: https://doc.rust-lang.org/stable/reference/items/generics.html#where-clauses
  25. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  26. pub struct Generics {
  27. pub lt_token: Option<Token![<]>,
  28. pub params: Punctuated<GenericParam, Token![,]>,
  29. pub gt_token: Option<Token![>]>,
  30. pub where_clause: Option<WhereClause>,
  31. }
  32. }
  33. ast_enum_of_structs! {
  34. /// A generic type parameter, lifetime, or const generic: `T: Into<String>`,
  35. /// `'a: 'b`, `const LEN: usize`.
  36. ///
  37. /// # Syntax tree enum
  38. ///
  39. /// This type is a [syntax tree enum].
  40. ///
  41. /// [syntax tree enum]: crate::expr::Expr#syntax-tree-enums
  42. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  43. pub enum GenericParam {
  44. /// A lifetime parameter: `'a: 'b + 'c + 'd`.
  45. Lifetime(LifetimeParam),
  46. /// A generic type parameter: `T: Into<String>`.
  47. Type(TypeParam),
  48. /// A const generic parameter: `const LENGTH: usize`.
  49. Const(ConstParam),
  50. }
  51. }
  52. ast_struct! {
  53. /// A lifetime definition: `'a: 'b + 'c + 'd`.
  54. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  55. pub struct LifetimeParam {
  56. pub attrs: Vec<Attribute>,
  57. pub lifetime: Lifetime,
  58. pub colon_token: Option<Token![:]>,
  59. pub bounds: Punctuated<Lifetime, Token![+]>,
  60. }
  61. }
  62. ast_struct! {
  63. /// A generic type parameter: `T: Into<String>`.
  64. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  65. pub struct TypeParam {
  66. pub attrs: Vec<Attribute>,
  67. pub ident: Ident,
  68. pub colon_token: Option<Token![:]>,
  69. pub bounds: Punctuated<TypeParamBound, Token![+]>,
  70. pub eq_token: Option<Token![=]>,
  71. pub default: Option<Type>,
  72. }
  73. }
  74. ast_struct! {
  75. /// A const generic parameter: `const LENGTH: usize`.
  76. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  77. pub struct ConstParam {
  78. pub attrs: Vec<Attribute>,
  79. pub const_token: Token![const],
  80. pub ident: Ident,
  81. pub colon_token: Token![:],
  82. pub ty: Type,
  83. pub eq_token: Option<Token![=]>,
  84. pub default: Option<Expr>,
  85. }
  86. }
  87. impl Default for Generics {
  88. fn default() -> Self {
  89. Generics {
  90. lt_token: None,
  91. params: Punctuated::new(),
  92. gt_token: None,
  93. where_clause: None,
  94. }
  95. }
  96. }
  97. impl Generics {
  98. return_impl_trait! {
  99. /// Iterator over the lifetime parameters in `self.params`.
  100. pub fn lifetimes(&self) -> impl Iterator<Item = &LifetimeParam> [Lifetimes] {
  101. Lifetimes(self.params.iter())
  102. }
  103. }
  104. return_impl_trait! {
  105. /// Iterator over the lifetime parameters in `self.params`.
  106. pub fn lifetimes_mut(&mut self) -> impl Iterator<Item = &mut LifetimeParam> [LifetimesMut] {
  107. LifetimesMut(self.params.iter_mut())
  108. }
  109. }
  110. return_impl_trait! {
  111. /// Iterator over the type parameters in `self.params`.
  112. pub fn type_params(&self) -> impl Iterator<Item = &TypeParam> [TypeParams] {
  113. TypeParams(self.params.iter())
  114. }
  115. }
  116. return_impl_trait! {
  117. /// Iterator over the type parameters in `self.params`.
  118. pub fn type_params_mut(&mut self) -> impl Iterator<Item = &mut TypeParam> [TypeParamsMut] {
  119. TypeParamsMut(self.params.iter_mut())
  120. }
  121. }
  122. return_impl_trait! {
  123. /// Iterator over the constant parameters in `self.params`.
  124. pub fn const_params(&self) -> impl Iterator<Item = &ConstParam> [ConstParams] {
  125. ConstParams(self.params.iter())
  126. }
  127. }
  128. return_impl_trait! {
  129. /// Iterator over the constant parameters in `self.params`.
  130. pub fn const_params_mut(&mut self) -> impl Iterator<Item = &mut ConstParam> [ConstParamsMut] {
  131. ConstParamsMut(self.params.iter_mut())
  132. }
  133. }
  134. /// Initializes an empty `where`-clause if there is not one present already.
  135. pub fn make_where_clause(&mut self) -> &mut WhereClause {
  136. self.where_clause.get_or_insert_with(|| WhereClause {
  137. where_token: <Token![where]>::default(),
  138. predicates: Punctuated::new(),
  139. })
  140. }
  141. /// Split a type's generics into the pieces required for impl'ing a trait
  142. /// for that type.
  143. ///
  144. /// ```
  145. /// # use proc_macro2::{Span, Ident};
  146. /// # use quote::quote;
  147. /// #
  148. /// # let generics: syn::Generics = Default::default();
  149. /// # let name = Ident::new("MyType", Span::call_site());
  150. /// #
  151. /// let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
  152. /// quote! {
  153. /// impl #impl_generics MyTrait for #name #ty_generics #where_clause {
  154. /// // ...
  155. /// }
  156. /// }
  157. /// # ;
  158. /// ```
  159. #[cfg(feature = "printing")]
  160. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  161. pub fn split_for_impl(&self) -> (ImplGenerics, TypeGenerics, Option<&WhereClause>) {
  162. (
  163. ImplGenerics(self),
  164. TypeGenerics(self),
  165. self.where_clause.as_ref(),
  166. )
  167. }
  168. }
  169. pub struct Lifetimes<'a>(Iter<'a, GenericParam>);
  170. impl<'a> Iterator for Lifetimes<'a> {
  171. type Item = &'a LifetimeParam;
  172. fn next(&mut self) -> Option<Self::Item> {
  173. if let GenericParam::Lifetime(lifetime) = self.0.next()? {
  174. Some(lifetime)
  175. } else {
  176. self.next()
  177. }
  178. }
  179. }
  180. pub struct LifetimesMut<'a>(IterMut<'a, GenericParam>);
  181. impl<'a> Iterator for LifetimesMut<'a> {
  182. type Item = &'a mut LifetimeParam;
  183. fn next(&mut self) -> Option<Self::Item> {
  184. if let GenericParam::Lifetime(lifetime) = self.0.next()? {
  185. Some(lifetime)
  186. } else {
  187. self.next()
  188. }
  189. }
  190. }
  191. pub struct TypeParams<'a>(Iter<'a, GenericParam>);
  192. impl<'a> Iterator for TypeParams<'a> {
  193. type Item = &'a TypeParam;
  194. fn next(&mut self) -> Option<Self::Item> {
  195. if let GenericParam::Type(type_param) = self.0.next()? {
  196. Some(type_param)
  197. } else {
  198. self.next()
  199. }
  200. }
  201. }
  202. pub struct TypeParamsMut<'a>(IterMut<'a, GenericParam>);
  203. impl<'a> Iterator for TypeParamsMut<'a> {
  204. type Item = &'a mut TypeParam;
  205. fn next(&mut self) -> Option<Self::Item> {
  206. if let GenericParam::Type(type_param) = self.0.next()? {
  207. Some(type_param)
  208. } else {
  209. self.next()
  210. }
  211. }
  212. }
  213. pub struct ConstParams<'a>(Iter<'a, GenericParam>);
  214. impl<'a> Iterator for ConstParams<'a> {
  215. type Item = &'a ConstParam;
  216. fn next(&mut self) -> Option<Self::Item> {
  217. if let GenericParam::Const(const_param) = self.0.next()? {
  218. Some(const_param)
  219. } else {
  220. self.next()
  221. }
  222. }
  223. }
  224. pub struct ConstParamsMut<'a>(IterMut<'a, GenericParam>);
  225. impl<'a> Iterator for ConstParamsMut<'a> {
  226. type Item = &'a mut ConstParam;
  227. fn next(&mut self) -> Option<Self::Item> {
  228. if let GenericParam::Const(const_param) = self.0.next()? {
  229. Some(const_param)
  230. } else {
  231. self.next()
  232. }
  233. }
  234. }
  235. /// Returned by `Generics::split_for_impl`.
  236. #[cfg(feature = "printing")]
  237. #[cfg_attr(
  238. docsrs,
  239. doc(cfg(all(any(feature = "full", feature = "derive"), feature = "printing")))
  240. )]
  241. pub struct ImplGenerics<'a>(&'a Generics);
  242. /// Returned by `Generics::split_for_impl`.
  243. #[cfg(feature = "printing")]
  244. #[cfg_attr(
  245. docsrs,
  246. doc(cfg(all(any(feature = "full", feature = "derive"), feature = "printing")))
  247. )]
  248. pub struct TypeGenerics<'a>(&'a Generics);
  249. /// Returned by `TypeGenerics::as_turbofish`.
  250. #[cfg(feature = "printing")]
  251. #[cfg_attr(
  252. docsrs,
  253. doc(cfg(all(any(feature = "full", feature = "derive"), feature = "printing")))
  254. )]
  255. pub struct Turbofish<'a>(&'a Generics);
  256. #[cfg(feature = "printing")]
  257. macro_rules! generics_wrapper_impls {
  258. ($ty:ident) => {
  259. #[cfg(feature = "clone-impls")]
  260. #[cfg_attr(docsrs, doc(cfg(feature = "clone-impls")))]
  261. impl<'a> Clone for $ty<'a> {
  262. fn clone(&self) -> Self {
  263. $ty(self.0)
  264. }
  265. }
  266. #[cfg(feature = "extra-traits")]
  267. #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))]
  268. impl<'a> Debug for $ty<'a> {
  269. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  270. formatter
  271. .debug_tuple(stringify!($ty))
  272. .field(self.0)
  273. .finish()
  274. }
  275. }
  276. #[cfg(feature = "extra-traits")]
  277. #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))]
  278. impl<'a> Eq for $ty<'a> {}
  279. #[cfg(feature = "extra-traits")]
  280. #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))]
  281. impl<'a> PartialEq for $ty<'a> {
  282. fn eq(&self, other: &Self) -> bool {
  283. self.0 == other.0
  284. }
  285. }
  286. #[cfg(feature = "extra-traits")]
  287. #[cfg_attr(docsrs, doc(cfg(feature = "extra-traits")))]
  288. impl<'a> Hash for $ty<'a> {
  289. fn hash<H: Hasher>(&self, state: &mut H) {
  290. self.0.hash(state);
  291. }
  292. }
  293. };
  294. }
  295. #[cfg(feature = "printing")]
  296. generics_wrapper_impls!(ImplGenerics);
  297. #[cfg(feature = "printing")]
  298. generics_wrapper_impls!(TypeGenerics);
  299. #[cfg(feature = "printing")]
  300. generics_wrapper_impls!(Turbofish);
  301. #[cfg(feature = "printing")]
  302. impl<'a> TypeGenerics<'a> {
  303. /// Turn a type's generics like `<X, Y>` into a turbofish like `::<X, Y>`.
  304. pub fn as_turbofish(&self) -> Turbofish<'a> {
  305. Turbofish(self.0)
  306. }
  307. }
  308. ast_struct! {
  309. /// A set of bound lifetimes: `for<'a, 'b, 'c>`.
  310. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  311. pub struct BoundLifetimes {
  312. pub for_token: Token![for],
  313. pub lt_token: Token![<],
  314. pub lifetimes: Punctuated<GenericParam, Token![,]>,
  315. pub gt_token: Token![>],
  316. }
  317. }
  318. impl Default for BoundLifetimes {
  319. fn default() -> Self {
  320. BoundLifetimes {
  321. for_token: Default::default(),
  322. lt_token: Default::default(),
  323. lifetimes: Punctuated::new(),
  324. gt_token: Default::default(),
  325. }
  326. }
  327. }
  328. impl LifetimeParam {
  329. pub fn new(lifetime: Lifetime) -> Self {
  330. LifetimeParam {
  331. attrs: Vec::new(),
  332. lifetime,
  333. colon_token: None,
  334. bounds: Punctuated::new(),
  335. }
  336. }
  337. }
  338. impl From<Ident> for TypeParam {
  339. fn from(ident: Ident) -> Self {
  340. TypeParam {
  341. attrs: vec![],
  342. ident,
  343. colon_token: None,
  344. bounds: Punctuated::new(),
  345. eq_token: None,
  346. default: None,
  347. }
  348. }
  349. }
  350. ast_enum_of_structs! {
  351. /// A trait or lifetime used as a bound on a type parameter.
  352. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  353. #[non_exhaustive]
  354. pub enum TypeParamBound {
  355. Trait(TraitBound),
  356. Lifetime(Lifetime),
  357. PreciseCapture(PreciseCapture),
  358. Verbatim(TokenStream),
  359. }
  360. }
  361. ast_struct! {
  362. /// A trait used as a bound on a type parameter.
  363. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  364. pub struct TraitBound {
  365. pub paren_token: Option<token::Paren>,
  366. pub modifier: TraitBoundModifier,
  367. /// The `for<'a>` in `for<'a> Foo<&'a T>`
  368. pub lifetimes: Option<BoundLifetimes>,
  369. /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`
  370. pub path: Path,
  371. }
  372. }
  373. ast_enum! {
  374. /// A modifier on a trait bound, currently only used for the `?` in
  375. /// `?Sized`.
  376. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  377. pub enum TraitBoundModifier {
  378. None,
  379. Maybe(Token![?]),
  380. }
  381. }
  382. ast_struct! {
  383. /// Precise capturing bound: the 'use&lt;&hellip;&gt;' in `impl Trait +
  384. /// use<'a, T>`.
  385. #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
  386. pub struct PreciseCapture #full {
  387. pub use_token: Token![use],
  388. pub lt_token: Token![<],
  389. pub params: Punctuated<CapturedParam, Token![,]>,
  390. pub gt_token: Token![>],
  391. }
  392. }
  393. #[cfg(feature = "full")]
  394. ast_enum! {
  395. /// Single parameter in a precise capturing bound.
  396. #[cfg_attr(docsrs, doc(cfg(feature = "full")))]
  397. #[non_exhaustive]
  398. pub enum CapturedParam {
  399. /// A lifetime parameter in precise capturing bound: `fn f<'a>() -> impl
  400. /// Trait + use<'a>`.
  401. Lifetime(Lifetime),
  402. /// A type parameter or const generic parameter in precise capturing
  403. /// bound: `fn f<T>() -> impl Trait + use<T>` or `fn f<const K: T>() ->
  404. /// impl Trait + use<K>`.
  405. Ident(Ident),
  406. }
  407. }
  408. ast_struct! {
  409. /// A `where` clause in a definition: `where T: Deserialize<'de>, D:
  410. /// 'static`.
  411. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  412. pub struct WhereClause {
  413. pub where_token: Token![where],
  414. pub predicates: Punctuated<WherePredicate, Token![,]>,
  415. }
  416. }
  417. ast_enum_of_structs! {
  418. /// A single predicate in a `where` clause: `T: Deserialize<'de>`.
  419. ///
  420. /// # Syntax tree enum
  421. ///
  422. /// This type is a [syntax tree enum].
  423. ///
  424. /// [syntax tree enum]: crate::expr::Expr#syntax-tree-enums
  425. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  426. #[non_exhaustive]
  427. pub enum WherePredicate {
  428. /// A lifetime predicate in a `where` clause: `'a: 'b + 'c`.
  429. Lifetime(PredicateLifetime),
  430. /// A type predicate in a `where` clause: `for<'c> Foo<'c>: Trait<'c>`.
  431. Type(PredicateType),
  432. }
  433. }
  434. ast_struct! {
  435. /// A lifetime predicate in a `where` clause: `'a: 'b + 'c`.
  436. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  437. pub struct PredicateLifetime {
  438. pub lifetime: Lifetime,
  439. pub colon_token: Token![:],
  440. pub bounds: Punctuated<Lifetime, Token![+]>,
  441. }
  442. }
  443. ast_struct! {
  444. /// A type predicate in a `where` clause: `for<'c> Foo<'c>: Trait<'c>`.
  445. #[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
  446. pub struct PredicateType {
  447. /// Any lifetimes from a `for` binding
  448. pub lifetimes: Option<BoundLifetimes>,
  449. /// The type being bounded
  450. pub bounded_ty: Type,
  451. pub colon_token: Token![:],
  452. /// Trait and lifetime bounds (`Clone+Send+'static`)
  453. pub bounds: Punctuated<TypeParamBound, Token![+]>,
  454. }
  455. }
  456. #[cfg(feature = "parsing")]
  457. pub(crate) mod parsing {
  458. use crate::attr::Attribute;
  459. #[cfg(feature = "full")]
  460. use crate::error;
  461. use crate::error::{Error, Result};
  462. use crate::ext::IdentExt as _;
  463. use crate::generics::{
  464. BoundLifetimes, ConstParam, GenericParam, Generics, LifetimeParam, PredicateLifetime,
  465. PredicateType, TraitBound, TraitBoundModifier, TypeParam, TypeParamBound, WhereClause,
  466. WherePredicate,
  467. };
  468. #[cfg(feature = "full")]
  469. use crate::generics::{CapturedParam, PreciseCapture};
  470. use crate::ident::Ident;
  471. use crate::lifetime::Lifetime;
  472. use crate::parse::{Parse, ParseStream};
  473. use crate::path::{self, ParenthesizedGenericArguments, Path, PathArguments};
  474. use crate::punctuated::Punctuated;
  475. use crate::token;
  476. use crate::ty::Type;
  477. use crate::verbatim;
  478. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  479. impl Parse for Generics {
  480. fn parse(input: ParseStream) -> Result<Self> {
  481. if !input.peek(Token![<]) {
  482. return Ok(Generics::default());
  483. }
  484. let lt_token: Token![<] = input.parse()?;
  485. let mut params = Punctuated::new();
  486. loop {
  487. if input.peek(Token![>]) {
  488. break;
  489. }
  490. let attrs = input.call(Attribute::parse_outer)?;
  491. let lookahead = input.lookahead1();
  492. if lookahead.peek(Lifetime) {
  493. params.push_value(GenericParam::Lifetime(LifetimeParam {
  494. attrs,
  495. ..input.parse()?
  496. }));
  497. } else if lookahead.peek(Ident) {
  498. params.push_value(GenericParam::Type(TypeParam {
  499. attrs,
  500. ..input.parse()?
  501. }));
  502. } else if lookahead.peek(Token![const]) {
  503. params.push_value(GenericParam::Const(ConstParam {
  504. attrs,
  505. ..input.parse()?
  506. }));
  507. } else if input.peek(Token![_]) {
  508. params.push_value(GenericParam::Type(TypeParam {
  509. attrs,
  510. ident: input.call(Ident::parse_any)?,
  511. colon_token: None,
  512. bounds: Punctuated::new(),
  513. eq_token: None,
  514. default: None,
  515. }));
  516. } else {
  517. return Err(lookahead.error());
  518. }
  519. if input.peek(Token![>]) {
  520. break;
  521. }
  522. let punct = input.parse()?;
  523. params.push_punct(punct);
  524. }
  525. let gt_token: Token![>] = input.parse()?;
  526. Ok(Generics {
  527. lt_token: Some(lt_token),
  528. params,
  529. gt_token: Some(gt_token),
  530. where_clause: None,
  531. })
  532. }
  533. }
  534. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  535. impl Parse for GenericParam {
  536. fn parse(input: ParseStream) -> Result<Self> {
  537. let attrs = input.call(Attribute::parse_outer)?;
  538. let lookahead = input.lookahead1();
  539. if lookahead.peek(Ident) {
  540. Ok(GenericParam::Type(TypeParam {
  541. attrs,
  542. ..input.parse()?
  543. }))
  544. } else if lookahead.peek(Lifetime) {
  545. Ok(GenericParam::Lifetime(LifetimeParam {
  546. attrs,
  547. ..input.parse()?
  548. }))
  549. } else if lookahead.peek(Token![const]) {
  550. Ok(GenericParam::Const(ConstParam {
  551. attrs,
  552. ..input.parse()?
  553. }))
  554. } else {
  555. Err(lookahead.error())
  556. }
  557. }
  558. }
  559. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  560. impl Parse for LifetimeParam {
  561. fn parse(input: ParseStream) -> Result<Self> {
  562. let has_colon;
  563. Ok(LifetimeParam {
  564. attrs: input.call(Attribute::parse_outer)?,
  565. lifetime: input.parse()?,
  566. colon_token: {
  567. if input.peek(Token![:]) {
  568. has_colon = true;
  569. Some(input.parse()?)
  570. } else {
  571. has_colon = false;
  572. None
  573. }
  574. },
  575. bounds: {
  576. let mut bounds = Punctuated::new();
  577. if has_colon {
  578. loop {
  579. if input.peek(Token![,]) || input.peek(Token![>]) {
  580. break;
  581. }
  582. let value = input.parse()?;
  583. bounds.push_value(value);
  584. if !input.peek(Token![+]) {
  585. break;
  586. }
  587. let punct = input.parse()?;
  588. bounds.push_punct(punct);
  589. }
  590. }
  591. bounds
  592. },
  593. })
  594. }
  595. }
  596. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  597. impl Parse for BoundLifetimes {
  598. fn parse(input: ParseStream) -> Result<Self> {
  599. Ok(BoundLifetimes {
  600. for_token: input.parse()?,
  601. lt_token: input.parse()?,
  602. lifetimes: {
  603. let mut lifetimes = Punctuated::new();
  604. while !input.peek(Token![>]) {
  605. lifetimes.push_value(input.parse()?);
  606. if input.peek(Token![>]) {
  607. break;
  608. }
  609. lifetimes.push_punct(input.parse()?);
  610. }
  611. lifetimes
  612. },
  613. gt_token: input.parse()?,
  614. })
  615. }
  616. }
  617. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  618. impl Parse for Option<BoundLifetimes> {
  619. fn parse(input: ParseStream) -> Result<Self> {
  620. if input.peek(Token![for]) {
  621. input.parse().map(Some)
  622. } else {
  623. Ok(None)
  624. }
  625. }
  626. }
  627. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  628. impl Parse for TypeParam {
  629. fn parse(input: ParseStream) -> Result<Self> {
  630. let attrs = input.call(Attribute::parse_outer)?;
  631. let ident: Ident = input.parse()?;
  632. let colon_token: Option<Token![:]> = input.parse()?;
  633. let mut bounds = Punctuated::new();
  634. if colon_token.is_some() {
  635. loop {
  636. if input.peek(Token![,]) || input.peek(Token![>]) || input.peek(Token![=]) {
  637. break;
  638. }
  639. bounds.push_value({
  640. let allow_precise_capture = false;
  641. let allow_const = true;
  642. TypeParamBound::parse_single(input, allow_precise_capture, allow_const)?
  643. });
  644. if !input.peek(Token![+]) {
  645. break;
  646. }
  647. let punct: Token![+] = input.parse()?;
  648. bounds.push_punct(punct);
  649. }
  650. }
  651. let eq_token: Option<Token![=]> = input.parse()?;
  652. let default = if eq_token.is_some() {
  653. Some(input.parse::<Type>()?)
  654. } else {
  655. None
  656. };
  657. Ok(TypeParam {
  658. attrs,
  659. ident,
  660. colon_token,
  661. bounds,
  662. eq_token,
  663. default,
  664. })
  665. }
  666. }
  667. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  668. impl Parse for TypeParamBound {
  669. fn parse(input: ParseStream) -> Result<Self> {
  670. let allow_precise_capture = true;
  671. let allow_const = true;
  672. Self::parse_single(input, allow_precise_capture, allow_const)
  673. }
  674. }
  675. impl TypeParamBound {
  676. pub(crate) fn parse_single(
  677. input: ParseStream,
  678. #[cfg_attr(not(feature = "full"), allow(unused_variables))] allow_precise_capture: bool,
  679. allow_const: bool,
  680. ) -> Result<Self> {
  681. if input.peek(Lifetime) {
  682. return input.parse().map(TypeParamBound::Lifetime);
  683. }
  684. #[cfg(feature = "full")]
  685. {
  686. if input.peek(Token![use]) {
  687. let precise_capture: PreciseCapture = input.parse()?;
  688. return if allow_precise_capture {
  689. Ok(TypeParamBound::PreciseCapture(precise_capture))
  690. } else {
  691. let msg = "`use<...>` precise capturing syntax is not allowed here";
  692. Err(error::new2(
  693. precise_capture.use_token.span,
  694. precise_capture.gt_token.span,
  695. msg,
  696. ))
  697. };
  698. }
  699. }
  700. let begin = input.fork();
  701. let content;
  702. let (paren_token, content) = if input.peek(token::Paren) {
  703. (Some(parenthesized!(content in input)), &content)
  704. } else {
  705. (None, input)
  706. };
  707. if let Some(mut bound) = TraitBound::do_parse(content, allow_const)? {
  708. bound.paren_token = paren_token;
  709. Ok(TypeParamBound::Trait(bound))
  710. } else {
  711. Ok(TypeParamBound::Verbatim(verbatim::between(&begin, input)))
  712. }
  713. }
  714. pub(crate) fn parse_multiple(
  715. input: ParseStream,
  716. allow_plus: bool,
  717. allow_precise_capture: bool,
  718. allow_const: bool,
  719. ) -> Result<Punctuated<Self, Token![+]>> {
  720. let mut bounds = Punctuated::new();
  721. loop {
  722. let bound = Self::parse_single(input, allow_precise_capture, allow_const)?;
  723. bounds.push_value(bound);
  724. if !(allow_plus && input.peek(Token![+])) {
  725. break;
  726. }
  727. bounds.push_punct(input.parse()?);
  728. if !(input.peek(Ident::peek_any)
  729. || input.peek(Token![::])
  730. || input.peek(Token![?])
  731. || input.peek(Lifetime)
  732. || input.peek(token::Paren)
  733. || (allow_const && (input.peek(token::Bracket) || input.peek(Token![const]))))
  734. {
  735. break;
  736. }
  737. }
  738. Ok(bounds)
  739. }
  740. }
  741. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  742. impl Parse for TraitBound {
  743. fn parse(input: ParseStream) -> Result<Self> {
  744. let allow_const = false;
  745. Self::do_parse(input, allow_const).map(Option::unwrap)
  746. }
  747. }
  748. impl TraitBound {
  749. fn do_parse(input: ParseStream, allow_const: bool) -> Result<Option<Self>> {
  750. let mut lifetimes: Option<BoundLifetimes> = input.parse()?;
  751. let is_conditionally_const = cfg!(feature = "full") && input.peek(token::Bracket);
  752. let is_unconditionally_const = cfg!(feature = "full") && input.peek(Token![const]);
  753. if is_conditionally_const {
  754. let conditionally_const;
  755. let bracket_token = bracketed!(conditionally_const in input);
  756. conditionally_const.parse::<Token![const]>()?;
  757. if !allow_const {
  758. let msg = "`[const]` is not allowed here";
  759. return Err(Error::new(bracket_token.span.join(), msg));
  760. }
  761. } else if is_unconditionally_const {
  762. let const_token: Token![const] = input.parse()?;
  763. if !allow_const {
  764. let msg = "`const` is not allowed here";
  765. return Err(Error::new(const_token.span, msg));
  766. }
  767. }
  768. let modifier: TraitBoundModifier = input.parse()?;
  769. if lifetimes.is_none() && matches!(modifier, TraitBoundModifier::Maybe(_)) {
  770. lifetimes = input.parse()?;
  771. }
  772. let mut path: Path = input.parse()?;
  773. if path.segments.last().unwrap().arguments.is_empty()
  774. && (input.peek(token::Paren) || input.peek(Token![::]) && input.peek3(token::Paren))
  775. {
  776. input.parse::<Option<Token![::]>>()?;
  777. let args: ParenthesizedGenericArguments = input.parse()?;
  778. let parenthesized = PathArguments::Parenthesized(args);
  779. path.segments.last_mut().unwrap().arguments = parenthesized;
  780. }
  781. if lifetimes.is_some() {
  782. match modifier {
  783. TraitBoundModifier::None => {}
  784. TraitBoundModifier::Maybe(maybe) => {
  785. let msg = "`for<...>` binder not allowed with `?` trait polarity modifier";
  786. return Err(Error::new(maybe.span, msg));
  787. }
  788. }
  789. }
  790. if is_conditionally_const || is_unconditionally_const {
  791. Ok(None)
  792. } else {
  793. Ok(Some(TraitBound {
  794. paren_token: None,
  795. modifier,
  796. lifetimes,
  797. path,
  798. }))
  799. }
  800. }
  801. }
  802. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  803. impl Parse for TraitBoundModifier {
  804. fn parse(input: ParseStream) -> Result<Self> {
  805. if input.peek(Token![?]) {
  806. input.parse().map(TraitBoundModifier::Maybe)
  807. } else {
  808. Ok(TraitBoundModifier::None)
  809. }
  810. }
  811. }
  812. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  813. impl Parse for ConstParam {
  814. fn parse(input: ParseStream) -> Result<Self> {
  815. let mut default = None;
  816. Ok(ConstParam {
  817. attrs: input.call(Attribute::parse_outer)?,
  818. const_token: input.parse()?,
  819. ident: input.parse()?,
  820. colon_token: input.parse()?,
  821. ty: input.parse()?,
  822. eq_token: {
  823. if input.peek(Token![=]) {
  824. let eq_token = input.parse()?;
  825. default = Some(path::parsing::const_argument(input)?);
  826. Some(eq_token)
  827. } else {
  828. None
  829. }
  830. },
  831. default,
  832. })
  833. }
  834. }
  835. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  836. impl Parse for WhereClause {
  837. fn parse(input: ParseStream) -> Result<Self> {
  838. let where_token: Token![where] = input.parse()?;
  839. if choose_generics_over_qpath(input) {
  840. return Err(input
  841. .error("generic parameters on `where` clauses are reserved for future use"));
  842. }
  843. Ok(WhereClause {
  844. where_token,
  845. predicates: {
  846. let mut predicates = Punctuated::new();
  847. loop {
  848. if input.is_empty()
  849. || input.peek(token::Brace)
  850. || input.peek(Token![,])
  851. || input.peek(Token![;])
  852. || input.peek(Token![:]) && !input.peek(Token![::])
  853. || input.peek(Token![=])
  854. {
  855. break;
  856. }
  857. let value = input.parse()?;
  858. predicates.push_value(value);
  859. if !input.peek(Token![,]) {
  860. break;
  861. }
  862. let punct = input.parse()?;
  863. predicates.push_punct(punct);
  864. }
  865. predicates
  866. },
  867. })
  868. }
  869. }
  870. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  871. impl Parse for Option<WhereClause> {
  872. fn parse(input: ParseStream) -> Result<Self> {
  873. if input.peek(Token![where]) {
  874. input.parse().map(Some)
  875. } else {
  876. Ok(None)
  877. }
  878. }
  879. }
  880. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  881. impl Parse for WherePredicate {
  882. fn parse(input: ParseStream) -> Result<Self> {
  883. if input.peek(Lifetime) && input.peek2(Token![:]) {
  884. Ok(WherePredicate::Lifetime(PredicateLifetime {
  885. lifetime: input.parse()?,
  886. colon_token: input.parse()?,
  887. bounds: {
  888. let mut bounds = Punctuated::new();
  889. loop {
  890. if input.is_empty()
  891. || input.peek(token::Brace)
  892. || input.peek(Token![,])
  893. || input.peek(Token![;])
  894. || input.peek(Token![:])
  895. || input.peek(Token![=])
  896. {
  897. break;
  898. }
  899. let value = input.parse()?;
  900. bounds.push_value(value);
  901. if !input.peek(Token![+]) {
  902. break;
  903. }
  904. let punct = input.parse()?;
  905. bounds.push_punct(punct);
  906. }
  907. bounds
  908. },
  909. }))
  910. } else {
  911. Ok(WherePredicate::Type(PredicateType {
  912. lifetimes: input.parse()?,
  913. bounded_ty: input.parse()?,
  914. colon_token: input.parse()?,
  915. bounds: {
  916. let mut bounds = Punctuated::new();
  917. loop {
  918. if input.is_empty()
  919. || input.peek(token::Brace)
  920. || input.peek(Token![,])
  921. || input.peek(Token![;])
  922. || input.peek(Token![:]) && !input.peek(Token![::])
  923. || input.peek(Token![=])
  924. {
  925. break;
  926. }
  927. bounds.push_value({
  928. let allow_precise_capture = false;
  929. let allow_const = true;
  930. TypeParamBound::parse_single(
  931. input,
  932. allow_precise_capture,
  933. allow_const,
  934. )?
  935. });
  936. if !input.peek(Token![+]) {
  937. break;
  938. }
  939. let punct = input.parse()?;
  940. bounds.push_punct(punct);
  941. }
  942. bounds
  943. },
  944. }))
  945. }
  946. }
  947. }
  948. #[cfg(feature = "full")]
  949. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  950. impl Parse for PreciseCapture {
  951. fn parse(input: ParseStream) -> Result<Self> {
  952. let use_token: Token![use] = input.parse()?;
  953. let lt_token: Token![<] = input.parse()?;
  954. let mut params = Punctuated::new();
  955. loop {
  956. let lookahead = input.lookahead1();
  957. params.push_value(
  958. if lookahead.peek(Lifetime) || lookahead.peek(Ident) || input.peek(Token![Self])
  959. {
  960. input.parse::<CapturedParam>()?
  961. } else if lookahead.peek(Token![>]) {
  962. break;
  963. } else {
  964. return Err(lookahead.error());
  965. },
  966. );
  967. let lookahead = input.lookahead1();
  968. params.push_punct(if lookahead.peek(Token![,]) {
  969. input.parse::<Token![,]>()?
  970. } else if lookahead.peek(Token![>]) {
  971. break;
  972. } else {
  973. return Err(lookahead.error());
  974. });
  975. }
  976. let gt_token: Token![>] = input.parse()?;
  977. Ok(PreciseCapture {
  978. use_token,
  979. lt_token,
  980. params,
  981. gt_token,
  982. })
  983. }
  984. }
  985. #[cfg(feature = "full")]
  986. #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
  987. impl Parse for CapturedParam {
  988. fn parse(input: ParseStream) -> Result<Self> {
  989. let lookahead = input.lookahead1();
  990. if lookahead.peek(Lifetime) {
  991. input.parse().map(CapturedParam::Lifetime)
  992. } else if lookahead.peek(Ident) || input.peek(Token![Self]) {
  993. input.call(Ident::parse_any).map(CapturedParam::Ident)
  994. } else {
  995. Err(lookahead.error())
  996. }
  997. }
  998. }
  999. pub(crate) fn choose_generics_over_qpath(input: ParseStream) -> bool {
  1000. // Rust syntax has an ambiguity between generic parameters and qualified
  1001. // paths. In `impl <T> :: Thing<T, U> {}` this may either be a generic
  1002. // inherent impl `impl<T> ::Thing<T, U>` or a non-generic inherent impl
  1003. // for an associated type `impl <T>::Thing<T, U>`.
  1004. //
  1005. // After `<` the following continuations can only begin generics, not a
  1006. // qualified path:
  1007. //
  1008. // `<` `>` - empty generic parameters
  1009. // `<` `#` - generic parameters with attribute
  1010. // `<` LIFETIME `>` - single lifetime parameter
  1011. // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
  1012. // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
  1013. // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
  1014. // `<` const - generic const parameter
  1015. //
  1016. // The only truly ambiguous case is:
  1017. //
  1018. // `<` IDENT `>` `::` IDENT ...
  1019. //
  1020. // which we disambiguate in favor of generics because this is almost
  1021. // always the expected one in the context of real-world code.
  1022. input.peek(Token![<])
  1023. && (input.peek2(Token![>])
  1024. || input.peek2(Token![#])
  1025. || (input.peek2(Lifetime) || input.peek2(Ident))
  1026. && (input.peek3(Token![>])
  1027. || input.peek3(Token![,])
  1028. || input.peek3(Token![:]) && !input.peek3(Token![::])
  1029. || input.peek3(Token![=]))
  1030. || input.peek2(Token![const]))
  1031. }
  1032. #[cfg(feature = "full")]
  1033. pub(crate) fn choose_generics_over_qpath_after_keyword(input: ParseStream) -> bool {
  1034. let input = input.fork();
  1035. input.call(Ident::parse_any).unwrap(); // `impl` or `for` or `where`
  1036. choose_generics_over_qpath(&input)
  1037. }
  1038. }
  1039. #[cfg(feature = "printing")]
  1040. pub(crate) mod printing {
  1041. use crate::attr::FilterAttrs;
  1042. #[cfg(feature = "full")]
  1043. use crate::expr;
  1044. use crate::expr::Expr;
  1045. #[cfg(feature = "full")]
  1046. use crate::fixup::FixupContext;
  1047. use crate::generics::{
  1048. BoundLifetimes, ConstParam, GenericParam, Generics, ImplGenerics, LifetimeParam,
  1049. PredicateLifetime, PredicateType, TraitBound, TraitBoundModifier, Turbofish, TypeGenerics,
  1050. TypeParam, WhereClause,
  1051. };
  1052. #[cfg(feature = "full")]
  1053. use crate::generics::{CapturedParam, PreciseCapture};
  1054. use crate::print::TokensOrDefault;
  1055. use crate::token;
  1056. use proc_macro2::TokenStream;
  1057. use quote::{ToTokens, TokenStreamExt};
  1058. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  1059. impl ToTokens for Generics {
  1060. fn to_tokens(&self, tokens: &mut TokenStream) {
  1061. if self.params.is_empty() {
  1062. return;
  1063. }
  1064. TokensOrDefault(&self.lt_token).to_tokens(tokens);
  1065. // Print lifetimes before types and consts, regardless of their
  1066. // order in self.params.
  1067. let mut trailing_or_empty = true;
  1068. for param in self.params.pairs() {
  1069. if let GenericParam::Lifetime(_) = **param.value() {
  1070. param.to_tokens(tokens);
  1071. trailing_or_empty = param.punct().is_some();
  1072. }
  1073. }
  1074. for param in self.params.pairs() {
  1075. match param.value() {
  1076. GenericParam::Type(_) | GenericParam::Const(_) => {
  1077. if !trailing_or_empty {
  1078. <Token![,]>::default().to_tokens(tokens);
  1079. trailing_or_empty = true;
  1080. }
  1081. param.to_tokens(tokens);
  1082. }
  1083. GenericParam::Lifetime(_) => {}
  1084. }
  1085. }
  1086. TokensOrDefault(&self.gt_token).to_tokens(tokens);
  1087. }
  1088. }
  1089. impl<'a> ToTokens for ImplGenerics<'a> {
  1090. fn to_tokens(&self, tokens: &mut TokenStream) {
  1091. if self.0.params.is_empty() {
  1092. return;
  1093. }
  1094. TokensOrDefault(&self.0.lt_token).to_tokens(tokens);
  1095. // Print lifetimes before types and consts, regardless of their
  1096. // order in self.params.
  1097. let mut trailing_or_empty = true;
  1098. for param in self.0.params.pairs() {
  1099. if let GenericParam::Lifetime(_) = **param.value() {
  1100. param.to_tokens(tokens);
  1101. trailing_or_empty = param.punct().is_some();
  1102. }
  1103. }
  1104. for param in self.0.params.pairs() {
  1105. if let GenericParam::Lifetime(_) = **param.value() {
  1106. continue;
  1107. }
  1108. if !trailing_or_empty {
  1109. <Token![,]>::default().to_tokens(tokens);
  1110. trailing_or_empty = true;
  1111. }
  1112. match param.value() {
  1113. GenericParam::Lifetime(_) => unreachable!(),
  1114. GenericParam::Type(param) => {
  1115. // Leave off the type parameter defaults
  1116. tokens.append_all(param.attrs.outer());
  1117. param.ident.to_tokens(tokens);
  1118. if !param.bounds.is_empty() {
  1119. TokensOrDefault(&param.colon_token).to_tokens(tokens);
  1120. param.bounds.to_tokens(tokens);
  1121. }
  1122. }
  1123. GenericParam::Const(param) => {
  1124. // Leave off the const parameter defaults
  1125. tokens.append_all(param.attrs.outer());
  1126. param.const_token.to_tokens(tokens);
  1127. param.ident.to_tokens(tokens);
  1128. param.colon_token.to_tokens(tokens);
  1129. param.ty.to_tokens(tokens);
  1130. }
  1131. }
  1132. param.punct().to_tokens(tokens);
  1133. }
  1134. TokensOrDefault(&self.0.gt_token).to_tokens(tokens);
  1135. }
  1136. }
  1137. impl<'a> ToTokens for TypeGenerics<'a> {
  1138. fn to_tokens(&self, tokens: &mut TokenStream) {
  1139. if self.0.params.is_empty() {
  1140. return;
  1141. }
  1142. TokensOrDefault(&self.0.lt_token).to_tokens(tokens);
  1143. // Print lifetimes before types and consts, regardless of their
  1144. // order in self.params.
  1145. let mut trailing_or_empty = true;
  1146. for param in self.0.params.pairs() {
  1147. if let GenericParam::Lifetime(def) = *param.value() {
  1148. // Leave off the lifetime bounds and attributes
  1149. def.lifetime.to_tokens(tokens);
  1150. param.punct().to_tokens(tokens);
  1151. trailing_or_empty = param.punct().is_some();
  1152. }
  1153. }
  1154. for param in self.0.params.pairs() {
  1155. if let GenericParam::Lifetime(_) = **param.value() {
  1156. continue;
  1157. }
  1158. if !trailing_or_empty {
  1159. <Token![,]>::default().to_tokens(tokens);
  1160. trailing_or_empty = true;
  1161. }
  1162. match param.value() {
  1163. GenericParam::Lifetime(_) => unreachable!(),
  1164. GenericParam::Type(param) => {
  1165. // Leave off the type parameter defaults
  1166. param.ident.to_tokens(tokens);
  1167. }
  1168. GenericParam::Const(param) => {
  1169. // Leave off the const parameter defaults
  1170. param.ident.to_tokens(tokens);
  1171. }
  1172. }
  1173. param.punct().to_tokens(tokens);
  1174. }
  1175. TokensOrDefault(&self.0.gt_token).to_tokens(tokens);
  1176. }
  1177. }
  1178. impl<'a> ToTokens for Turbofish<'a> {
  1179. fn to_tokens(&self, tokens: &mut TokenStream) {
  1180. if !self.0.params.is_empty() {
  1181. <Token![::]>::default().to_tokens(tokens);
  1182. TypeGenerics(self.0).to_tokens(tokens);
  1183. }
  1184. }
  1185. }
  1186. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  1187. impl ToTokens for BoundLifetimes {
  1188. fn to_tokens(&self, tokens: &mut TokenStream) {
  1189. self.for_token.to_tokens(tokens);
  1190. self.lt_token.to_tokens(tokens);
  1191. self.lifetimes.to_tokens(tokens);
  1192. self.gt_token.to_tokens(tokens);
  1193. }
  1194. }
  1195. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  1196. impl ToTokens for LifetimeParam {
  1197. fn to_tokens(&self, tokens: &mut TokenStream) {
  1198. tokens.append_all(self.attrs.outer());
  1199. self.lifetime.to_tokens(tokens);
  1200. if !self.bounds.is_empty() {
  1201. TokensOrDefault(&self.colon_token).to_tokens(tokens);
  1202. self.bounds.to_tokens(tokens);
  1203. }
  1204. }
  1205. }
  1206. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  1207. impl ToTokens for TypeParam {
  1208. fn to_tokens(&self, tokens: &mut TokenStream) {
  1209. tokens.append_all(self.attrs.outer());
  1210. self.ident.to_tokens(tokens);
  1211. if !self.bounds.is_empty() {
  1212. TokensOrDefault(&self.colon_token).to_tokens(tokens);
  1213. self.bounds.to_tokens(tokens);
  1214. }
  1215. if let Some(default) = &self.default {
  1216. TokensOrDefault(&self.eq_token).to_tokens(tokens);
  1217. default.to_tokens(tokens);
  1218. }
  1219. }
  1220. }
  1221. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  1222. impl ToTokens for TraitBound {
  1223. fn to_tokens(&self, tokens: &mut TokenStream) {
  1224. let to_tokens = |tokens: &mut TokenStream| {
  1225. self.modifier.to_tokens(tokens);
  1226. self.lifetimes.to_tokens(tokens);
  1227. self.path.to_tokens(tokens);
  1228. };
  1229. match &self.paren_token {
  1230. Some(paren) => paren.surround(tokens, to_tokens),
  1231. None => to_tokens(tokens),
  1232. }
  1233. }
  1234. }
  1235. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  1236. impl ToTokens for TraitBoundModifier {
  1237. fn to_tokens(&self, tokens: &mut TokenStream) {
  1238. match self {
  1239. TraitBoundModifier::None => {}
  1240. TraitBoundModifier::Maybe(t) => t.to_tokens(tokens),
  1241. }
  1242. }
  1243. }
  1244. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  1245. impl ToTokens for ConstParam {
  1246. fn to_tokens(&self, tokens: &mut TokenStream) {
  1247. tokens.append_all(self.attrs.outer());
  1248. self.const_token.to_tokens(tokens);
  1249. self.ident.to_tokens(tokens);
  1250. self.colon_token.to_tokens(tokens);
  1251. self.ty.to_tokens(tokens);
  1252. if let Some(default) = &self.default {
  1253. TokensOrDefault(&self.eq_token).to_tokens(tokens);
  1254. print_const_argument(default, tokens);
  1255. }
  1256. }
  1257. }
  1258. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  1259. impl ToTokens for WhereClause {
  1260. fn to_tokens(&self, tokens: &mut TokenStream) {
  1261. if !self.predicates.is_empty() {
  1262. self.where_token.to_tokens(tokens);
  1263. self.predicates.to_tokens(tokens);
  1264. }
  1265. }
  1266. }
  1267. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  1268. impl ToTokens for PredicateLifetime {
  1269. fn to_tokens(&self, tokens: &mut TokenStream) {
  1270. self.lifetime.to_tokens(tokens);
  1271. self.colon_token.to_tokens(tokens);
  1272. self.bounds.to_tokens(tokens);
  1273. }
  1274. }
  1275. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  1276. impl ToTokens for PredicateType {
  1277. fn to_tokens(&self, tokens: &mut TokenStream) {
  1278. self.lifetimes.to_tokens(tokens);
  1279. self.bounded_ty.to_tokens(tokens);
  1280. self.colon_token.to_tokens(tokens);
  1281. self.bounds.to_tokens(tokens);
  1282. }
  1283. }
  1284. #[cfg(feature = "full")]
  1285. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  1286. impl ToTokens for PreciseCapture {
  1287. fn to_tokens(&self, tokens: &mut TokenStream) {
  1288. self.use_token.to_tokens(tokens);
  1289. self.lt_token.to_tokens(tokens);
  1290. // Print lifetimes before types and consts, regardless of their
  1291. // order in self.params.
  1292. let mut trailing_or_empty = true;
  1293. for param in self.params.pairs() {
  1294. if let CapturedParam::Lifetime(_) = **param.value() {
  1295. param.to_tokens(tokens);
  1296. trailing_or_empty = param.punct().is_some();
  1297. }
  1298. }
  1299. for param in self.params.pairs() {
  1300. if let CapturedParam::Ident(_) = **param.value() {
  1301. if !trailing_or_empty {
  1302. <Token![,]>::default().to_tokens(tokens);
  1303. trailing_or_empty = true;
  1304. }
  1305. param.to_tokens(tokens);
  1306. }
  1307. }
  1308. self.gt_token.to_tokens(tokens);
  1309. }
  1310. }
  1311. #[cfg(feature = "full")]
  1312. #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
  1313. impl ToTokens for CapturedParam {
  1314. fn to_tokens(&self, tokens: &mut TokenStream) {
  1315. match self {
  1316. CapturedParam::Lifetime(lifetime) => lifetime.to_tokens(tokens),
  1317. CapturedParam::Ident(ident) => ident.to_tokens(tokens),
  1318. }
  1319. }
  1320. }
  1321. pub(crate) fn print_const_argument(expr: &Expr, tokens: &mut TokenStream) {
  1322. match expr {
  1323. Expr::Lit(expr) => expr.to_tokens(tokens),
  1324. Expr::Path(expr)
  1325. if expr.attrs.is_empty()
  1326. && expr.qself.is_none()
  1327. && expr.path.get_ident().is_some() =>
  1328. {
  1329. expr.to_tokens(tokens);
  1330. }
  1331. #[cfg(feature = "full")]
  1332. Expr::Block(expr) => expr.to_tokens(tokens),
  1333. #[cfg(not(feature = "full"))]
  1334. Expr::Verbatim(expr) => expr.to_tokens(tokens),
  1335. // ERROR CORRECTION: Add braces to make sure that the
  1336. // generated code is valid.
  1337. _ => token::Brace::default().surround(tokens, |tokens| {
  1338. #[cfg(feature = "full")]
  1339. expr::printing::print_expr(expr, tokens, FixupContext::new_stmt());
  1340. #[cfg(not(feature = "full"))]
  1341. expr.to_tokens(tokens);
  1342. }),
  1343. }
  1344. }
  1345. }