Skip to main content

syn/
generics.rs

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