Debian Codegraph @

.cargo/vendor/syn/src/generics.rs

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