delegation-codegen 0.4.0

Code generation for `delegation` crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
//! Utils for `#[delegate]` macro expansion on traits.

#[cfg(doc)]
use std::marker::PhantomData;
use std::{
    collections::{HashMap, HashSet},
    iter, mem,
};

use quote::quote;
use syn::{
    parse_quote, punctuated,
    visit::{self, Visit},
    visit_mut::{self, VisitMut},
};
#[cfg(doc)]
use syn::{Generics, Receiver, ReturnType, Signature, Type};

/// Helper extension of [`syn::Generics`].
pub(super) trait GenericsExt {
    /// Returns [`PhantomData`] type for holding these [`Generics`].
    fn phantom_data(&self) -> syn::Type;

    /// Appends the provided [`Generics`] to these.
    fn append(&mut self, other: &syn::Generics);

    /// Generates bounds guaranteeing that the provided [`Type`] is live as long
    /// as all the lifetimes specified in it.
    fn bound_type_to_lifetimes(&mut self, ty: &syn::Type);

    /// Replaces `Self` [`Type`] with the provided one.
    fn replace_self_ty(&mut self, ty: &syn::Type);

    /// Removes `Self:` bounds from these [`Generics`].
    fn remove_self_ty_bounds(&mut self);
}

impl GenericsExt for syn::Generics {
    fn phantom_data(&self) -> syn::Type {
        let ty = self.params.iter().filter_map(|p| match p {
            syn::GenericParam::Type(ty) => {
                let ident = &ty.ident;
                Some(quote! { *const #ident })
            }
            syn::GenericParam::Lifetime(def) => {
                let lt = &def.lifetime;
                Some(quote! { &#lt () })
            }
            syn::GenericParam::Const(_) => None,
        });

        parse_quote! { ::core::marker::PhantomData<( #(#ty),* )> }
    }

    fn append(&mut self, other: &syn::Generics) {
        self.params.extend(other.params.iter().cloned());
        self.make_where_clause().predicates.extend(
            other
                .where_clause
                .iter()
                .flat_map(|wc| wc.predicates.iter().cloned()),
        );
    }

    fn bound_type_to_lifetimes(&mut self, ty: &syn::Type) {
        /// Visitor for collecting types containing [`syn::Lifetime`]s.
        pub(super) struct CollectTypesWithLifetimesVisitor {
            /// [`syn::Lifetime`]s to search for.
            lifetimes: HashSet<syn::Ident>,

            /// Collected [`syn::Type`]s.
            types: HashMap<syn::Type, Vec<syn::Lifetime>>,
        }

        impl CollectTypesWithLifetimesVisitor {
            /// Creates a new [`CollectTypesWithLifetimesVisitor`].
            #[expect( // not supported inside `impl Trait` yet
                single_use_lifetimes,
                reason = "not supported inside `impl Trait` yet"
            )]
            fn new<'a>(
                lifetimes: impl IntoIterator<Item = &'a syn::Lifetime>,
            ) -> Self {
                Self {
                    lifetimes: lifetimes
                        .into_iter()
                        .map(|lt| lt.ident.clone())
                        .collect(),
                    types: HashMap::new(),
                }
            }
        }

        impl<'ast> Visit<'ast> for CollectTypesWithLifetimesVisitor {
            fn visit_lifetime(&mut self, i: &'ast syn::Lifetime) {
                if self.lifetimes.contains(&i.ident) {
                    #[expect( // order doesn't matter here
                        clippy::iter_over_hash_type,
                        reason = "order doesn't matter here"
                    )]
                    for lifetimes in self.types.values_mut() {
                        lifetimes.push(i.clone());
                    }
                }

                visit::visit_lifetime(self, i);
            }

            fn visit_type(&mut self, i: &'ast syn::Type) {
                drop(self.types.insert(i.clone(), Vec::new()));

                visit::visit_type(self, i);
            }
        }

        let mut visitor = CollectTypesWithLifetimesVisitor::new(
            self.lifetimes().map(|d| &d.lifetime),
        );
        visitor.visit_type(ty);

        #[expect( // order doesn't matter here
            clippy::iter_over_hash_type,
            reason = "order doesn't matter here"
        )]
        for (t, lt) in &visitor.types {
            if lt.is_empty() {
                continue;
            }

            self.make_where_clause()
                .predicates
                .push(parse_quote! { #t: #( #lt )+* });
        }
    }

    fn replace_self_ty(&mut self, ty: &syn::Type) {
        /// Visitor for replacing `Self` with provided [`Type`].
        struct ReplaceSelfTy<'a> {
            /// [`Type`] to replace `Self` with.
            ty: &'a syn::Type,
        }

        impl VisitMut for ReplaceSelfTy<'_> {
            fn visit_type_mut(&mut self, i: &mut syn::Type) {
                if let syn::Type::Path(path) = i {
                    if path.path.is_ident("Self") {
                        *i = self.ty.clone();
                    }
                }

                visit_mut::visit_type_mut(self, i);
            }
        }

        let mut visitor = ReplaceSelfTy { ty };
        visitor.visit_generics_mut(self);
    }

    fn remove_self_ty_bounds(&mut self) {
        let Some(where_clause) = &mut self.where_clause else {
            return;
        };

        for pred in mem::take(&mut where_clause.predicates) {
            if let syn::WherePredicate::Type(ty) = &pred {
                if let syn::Type::Path(path) = &ty.bounded_ty {
                    if path.path.is_ident("Self") {
                        continue;
                    }
                }
            }

            where_clause.predicates.push(pred);
        }
    }
}

/// Helper extension of a [`syn::Signature`].
pub(super) trait SignatureExt {
    /// Helper for implementing method on an `Either`.
    ///
    /// Returns method's [`Signature`] itself, [`Ident`] and an [`Iterator`]
    /// over inputs, excluding the [`Receiver`].
    ///
    /// [`Ident`]: struct@syn::Ident
    fn split_for_impl(
        &self,
    ) -> (&syn::Signature, &syn::Ident, InputsWithoutReceiverIter<'_>);

    /// Lifts [`Lifetime`] from a [`Receiver`] leaving `self` in its place and
    /// replaces/inserts all the needed occurrences with the provided
    /// `replace_with` [`Lifetime`].
    ///
    /// This method is useful, when it's needed to lift [`Receiver`]'s
    /// [`Lifetime`] to trait/struct generic level.
    ///
    /// [`Lifetime`]: struct@syn::Lifetime
    fn lift_receiver_lifetime(&mut self, replace_with: syn::Lifetime);

    /// Expands all elided [`Lifetime`]s in this [`Signature`].
    ///
    /// [`Lifetime`]: struct@syn::Lifetime
    fn expand_lifetimes<F>(&mut self, receiver_lt: syn::Lifetime, expand_fn: F)
    where
        F: FnMut() -> syn::Lifetime;

    /// Returns the [`ReturnType`] of this [`Signature`] including the default
    /// return type.
    fn return_type(&self) -> syn::Type;

    /// Returns [`Lifetime`]s presented in this [`Signature`] that are limited
    /// to be early bounded.
    ///
    /// See [`rust-lang/rust#87803`] for more details.
    ///
    /// [`Lifetime`]: struct@syn::Lifetime
    /// [`rust-lang/rust#87803`]: https://github.com/rust-lang/rust/issues/87803
    fn to_be_early_bounded_lifetimes(&self) -> HashSet<syn::Lifetime>;
}

impl SignatureExt for syn::Signature {
    fn split_for_impl(
        &self,
    ) -> (&syn::Signature, &syn::Ident, InputsWithoutReceiverIter<'_>) {
        (
            self,
            &self.ident,
            self.inputs.iter().filter_map(|i| match i {
                syn::FnArg::Typed(t) => Some(&t.pat),
                syn::FnArg::Receiver(_) => None,
            }),
        )
    }

    fn lift_receiver_lifetime(&mut self, replace_with: syn::Lifetime) {
        // 1. Remove lifetime from the receiver or return, if there is no
        //    reference.
        let self_lifetime = match self.inputs.first_mut() {
            Some(syn::FnArg::Receiver(rec)) => {
                if rec.reference.is_none() {
                    return;
                }

                if let syn::Type::Reference(r) = rec.ty.as_ref() {
                    rec.ty = r.elem.clone();
                }

                rec.mutability = None;
                rec.reference.take().and_then(|(_, l)| l)
            }
            Some(syn::FnArg::Typed(_)) | None => return,
        };

        // 2. Replace receiver's lifetime and `'_` with `replace_with` in
        //    signature's output.
        let mut replacer = ReplaceLifetimes {
            replaced: [self_lifetime, Some(parse_quote! { '_ })]
                .into_iter()
                .flatten()
                .collect(),
            replace_with: &replace_with,
            matched: 0,
        };
        replacer.visit_return_type_mut(&mut self.output);

        // 3. Replace receiver's lifetime with `replace_with` in entire
        //    signature.
        _ = replacer.replaced.remove(&parse_quote! { '_ });
        if !replacer.replaced.is_empty() {
            replacer.visit_signature_mut(self);
        }

        // 4. Remove `replace_with` lifetime from generic parameters.
        let generic_params_len_before = self.generics.params.len();
        self.generics.params = mem::take(&mut self.generics.params)
            .into_iter()
            .filter(|par| match par {
                syn::GenericParam::Lifetime(syn::LifetimeParam {
                    lifetime,
                    ..
                }) => lifetime != replacer.replace_with,
                syn::GenericParam::Type(_) | syn::GenericParam::Const(_) => {
                    true
                }
            })
            .collect();

        // 5. In case `self_lifetime` came from trait generics, we add bound
        //    `#replace_with: #self_lifetime` and
        //    `#self_lifetime: #replace_with` to indicate, that they are
        //    identical.
        if let Some(self_lt) = replacer.replaced.iter().next() {
            if self.generics.params.len() == generic_params_len_before {
                let replace_lt = &replacer.replace_with;
                let predicates: [syn::WherePredicate; 2] = [
                    parse_quote! { #self_lt: #replace_lt },
                    parse_quote! { #replace_lt: #self_lt },
                ];
                self.generics.make_where_clause().predicates.extend(predicates);
            }
        }

        // 6. Insert `replace_with` after every reference without a lifetime in
        //    signature's output.
        InsertLifetime { inserted: replacer.replace_with }
            .visit_return_type_mut(&mut self.output);
    }

    #[expect(clippy::renamed_function_params, reason = "more readable")]
    fn expand_lifetimes<F>(&mut self, return_lt: syn::Lifetime, expand_fn: F)
    where
        F: FnMut() -> syn::Lifetime,
    {
        // 1. Get or expand receiver lifetime.
        let receiver_lt = match self.inputs.first_mut() {
            Some(syn::FnArg::Receiver(rec)) => {
                if let Some((_, lt)) = &mut rec.reference {
                    Some(&*lt.get_or_insert_with(|| {
                        self.generics.params.push(parse_quote! { #return_lt });
                        return_lt.clone()
                    }))
                } else {
                    None
                }
            }
            Some(syn::FnArg::Typed(_)) | None => return,
        };

        // 2. Replace `'_` with `receiver_lt` or `return_lt` in signature's
        //    output.
        let mut replacer = ReplaceLifetimes {
            replaced: iter::once(parse_quote! { '_ }).collect(),
            replace_with: receiver_lt.unwrap_or(&return_lt),
            matched: 0,
        };
        replacer.visit_return_type_mut(&mut self.output);

        // 3. If no receiver's lifetime, create return type's lifetime.
        if replacer.matched > 0 && receiver_lt.is_none() {
            self.generics.params.push(parse_quote! { #return_lt });
        }

        // 4. Insert `replace_with` after every reference without a lifetime in
        //    signature's output.
        InsertLifetime { inserted: replacer.replace_with }
            .visit_return_type_mut(&mut self.output);

        // 5. Expand every elided lifetime in whole signature.
        let mut expander = ExpandLifetime { expand_fn, expanded: vec![] };

        if return_lt.ident != "_" {
            expander.visit_return_type_mut(&mut self.output);
        }

        for arg in self.inputs.iter_mut().skip(1) {
            expander.visit_fn_arg_mut(arg);
        }

        // 6. Add expanded lifetimes to generic parameters.
        self.generics.params.extend(expander.expanded.iter().map(
            |lt| -> syn::GenericParam {
                parse_quote! { #lt }
            },
        ));
    }

    fn return_type(&self) -> syn::Type {
        match &self.output {
            syn::ReturnType::Default => parse_quote! { () },
            syn::ReturnType::Type(_, ty) => (**ty).clone(),
        }
    }

    fn to_be_early_bounded_lifetimes(&self) -> HashSet<syn::Lifetime> {
        /// Collector of the [`Lifetime`]s.
        ///
        /// [`Lifetime`]: struct@syn::Lifetime
        struct CollectLifetimes {
            /// Collected [`Lifetime`]s.
            ///
            /// [`Lifetime`]: struct@syn::Lifetime
            lifetimes: HashSet<syn::Lifetime>,
        }

        impl<'ast> Visit<'ast> for CollectLifetimes {
            fn visit_lifetime(&mut self, i: &'ast syn::Lifetime) {
                if i.ident != "_" {
                    _ = self.lifetimes.insert(i.clone());
                }
            }
        }

        /// Remover of the [`Lifetime`]s that are early bounded. I.e. `'a: 'a`.
        ///
        /// [`Lifetime`]: struct@syn::Lifetime
        struct RemoveEarlyBoundedLifetimes<'a>(&'a mut HashSet<syn::Lifetime>);

        impl<'ast> Visit<'ast> for RemoveEarlyBoundedLifetimes<'_> {
            fn visit_lifetime_param(&mut self, i: &'ast syn::LifetimeParam) {
                if i.bounds.iter().any(|b| *b == i.lifetime) {
                    _ = self.0.remove(&i.lifetime);
                }
            }

            fn visit_predicate_lifetime(
                &mut self,
                i: &'ast syn::PredicateLifetime,
            ) {
                if i.bounds.iter().any(|b| *b == i.lifetime) {
                    _ = self.0.remove(&i.lifetime);
                }
            }
        }

        /// Remover of the [`Lifetime`]s from the provided set.
        ///
        /// [`Lifetime`]: struct@syn::Lifetime
        struct RemoveLifetimes<'a>(&'a mut HashSet<syn::Lifetime>);

        impl<'ast> Visit<'ast> for RemoveLifetimes<'_> {
            fn visit_lifetime(&mut self, i: &'ast syn::Lifetime) {
                _ = self.0.remove(i);
            }
        }

        let mut collector = CollectLifetimes { lifetimes: HashSet::new() };

        // 1. Collect all lifetimes occurring in the arguments.
        for arg in &self.inputs {
            match arg {
                syn::FnArg::Receiver(_) => {}
                syn::FnArg::Typed(syn::PatType { ty, .. }) => {
                    collector.visit_type(ty);
                }
            }
        }

        // 2. Remove receiver's lifetime from the collected set.
        if let Some(syn::FnArg::Receiver(syn::Receiver {
            reference: Some((_, Some(lt))),
            ..
        })) = self.inputs.first()
        {
            if lt.ident != "_" {
                _ = collector.lifetimes.remove(lt);
            }
        };

        // 3. Remove lifetimes defined in trait's generics.
        let method_lifetimes =
            self.generics
                .params
                .iter()
                .filter_map(|p| match p {
                    syn::GenericParam::Lifetime(lt) => Some(&lt.lifetime),
                    syn::GenericParam::Const(_)
                    | syn::GenericParam::Type(_) => None,
                })
                .cloned()
                .collect::<HashSet<_>>();
        collector.lifetimes.retain(|lt| method_lifetimes.contains(lt));

        // 4. Remove lifetimes that are early bounded.
        RemoveEarlyBoundedLifetimes(&mut collector.lifetimes)
            .visit_generics(&self.generics);

        // 5. Remove lifetimes occurring in the return type.
        RemoveLifetimes(&mut collector.lifetimes)
            .visit_return_type(&self.output);

        collector.lifetimes
    }
}

/// [`Iterator`] over [`Signature`]'s inputs, excluding its [`Receiver`].
pub(super) type InputsWithoutReceiverIter<'a> = iter::FilterMap<
    punctuated::Iter<'a, syn::FnArg>,
    fn(&'a syn::FnArg) -> Option<&'a Box<syn::Pat>>,
>;

/// Replacer of the `replaced` [`Lifetime`] with the `replace_with` one.
///
/// [`Lifetime`]: struct@syn::Lifetime
struct ReplaceLifetimes<'r> {
    /// [`Lifetime`] to be replaced.
    ///
    /// [`Lifetime`]: struct@syn::Lifetime
    replaced: HashSet<syn::Lifetime>,

    /// [`Lifetime`] to replace with.
    ///
    /// [`Lifetime`]: struct@syn::Lifetime
    replace_with: &'r syn::Lifetime,

    /// Count of the replaced [`Lifetime`]s.
    ///
    /// [`Lifetime`]: struct@syn::Lifetime
    matched: usize,
}

impl VisitMut for ReplaceLifetimes<'_> {
    fn visit_lifetime_mut(&mut self, i: &mut syn::Lifetime) {
        if self.replaced.contains(i) {
            *i = self.replace_with.clone();
            self.matched += 1;
        }

        visit_mut::visit_lifetime_mut(self, i);
    }
}

/// Inserter of a [`Lifetime`] after every empty reference.
///
/// [`Lifetime`]: struct@syn::Lifetime
struct InsertLifetime<'i> {
    /// [`Lifetime`] to be inserted.
    ///
    /// [`Lifetime`]: struct@syn::Lifetime
    inserted: &'i syn::Lifetime,
}

impl VisitMut for InsertLifetime<'_> {
    fn visit_type_reference_mut(&mut self, i: &mut syn::TypeReference) {
        if i.lifetime.is_none() {
            i.lifetime = Some(self.inserted.clone());
        }

        visit_mut::visit_type_reference_mut(self, i);
    }
}

/// Expander of elided [`Lifetime`]s.
///
/// [`Lifetime`]: struct@syn::Lifetime
struct ExpandLifetime<F>
where
    F: FnMut() -> syn::Lifetime,
{
    /// Function to expand elided [`Lifetime`]s.
    ///
    /// [`Lifetime`]: struct@syn::Lifetime
    expand_fn: F,

    /// Collection of [`Lifetime`]s being expanded.
    ///
    /// [`Lifetime`]: struct@syn::Lifetime
    expanded: Vec<syn::Lifetime>,
}

impl<F> VisitMut for ExpandLifetime<F>
where
    F: FnMut() -> syn::Lifetime,
{
    fn visit_lifetime_mut(&mut self, i: &mut syn::Lifetime) {
        if i.ident == "_" {
            *i = (self.expand_fn)();
            self.expanded.push(i.clone());
        }

        visit_mut::visit_lifetime_mut(self, i);
    }

    fn visit_type_reference_mut(&mut self, i: &mut syn::TypeReference) {
        if i.lifetime.is_none() {
            let lt = (self.expand_fn)();
            i.lifetime = Some(lt.clone());
            self.expanded.push(lt);
        }

        visit_mut::visit_type_reference_mut(self, i);
    }
}

#[cfg(test)]
mod lift_self_lifetime_spec {
    use quote::{quote, ToTokens as _};
    use syn::parse_quote;

    use super::SignatureExt as _;

    fn with() -> syn::Lifetime {
        parse_quote! { '__delegated }
    }

    #[test]
    fn without_receiver() {
        for (input, expected) in [(
            parse_quote! {
                fn test<'a, 'b>(arg1: &'a i32, arg2: &'b i32) -> &'a i32
            },
            quote! {
                fn test<'a, 'b>(arg1: &'a i32, arg2: &'b i32) -> &'a i32
            },
        )] {
            let mut input: syn::Signature = input;
            input.lift_receiver_lifetime(with());

            assert_eq!(
                input.to_token_stream().to_string(),
                expected.to_string(),
            );
        }
    }

    #[test]
    fn receiver_without_reference() {
        for (input, expected) in [(
            parse_quote! {
                fn test<'a>(self, arg2: &'a i32) -> &'a i32
            },
            quote! {
                fn test<'a>(self, arg2: &'a i32) -> &'a i32
            },
        )] {
            let mut input: syn::Signature = input;
            input.lift_receiver_lifetime(with());

            assert_eq!(
                input.to_token_stream().to_string(),
                expected.to_string(),
            );
        }
    }

    #[test]
    fn receiver_without_lifetime() {
        for (input, expected) in [
            (
                parse_quote! {
                    fn test<'a>(&self, arg2: &'a i32) -> &i32
                },
                quote! {
                    fn test<'a>(self, arg2: &'a i32) -> &'__delegated i32
                },
            ),
            (
                parse_quote! {
                    fn test<'a>(&self, arg2: &'a i32) -> &'_ i32
                },
                quote! {
                    fn test<'a>(self, arg2: &'a i32) -> &'__delegated i32
                },
            ),
            (
                parse_quote! {
                    fn test<'a>(&self, arg2: &'a i32) -> &'a i32
                },
                quote! {
                    fn test<'a>(self, arg2: &'a i32) -> &'a i32
                },
            ),
        ] {
            let mut input: syn::Signature = input;
            input.lift_receiver_lifetime(with());

            assert_eq!(
                input.to_token_stream().to_string(),
                expected.to_string(),
            );
        }
    }

    #[test]
    fn receiver_with_anonymous_lifetime() {
        for (input, expected) in [
            (
                parse_quote! {
                    fn test<'a>(&'_ self, arg2: &'a i32) -> &i32
                },
                quote! {
                    fn test<'a>(self, arg2: &'a i32) -> &'__delegated i32
                },
            ),
            (
                parse_quote! {
                    fn test<'a>(&'_ self, arg2: &'a i32) -> &'_ i32
                },
                quote! {
                    fn test<'a>(self, arg2: &'a i32) -> &'__delegated i32
                },
            ),
            (
                parse_quote! {
                    fn test<'a>(&'_ self, arg2: &'a i32) -> &'a i32
                },
                quote! {
                    fn test<'a>(self, arg2: &'a i32) -> &'a i32
                },
            ),
            (
                parse_quote! {
                    fn test(&'_ self, arg2: &'_ i32) -> &i32
                },
                quote! {
                    fn test(self, arg2: &'_ i32) -> &'__delegated i32
                },
            ),
            (
                parse_quote! {
                    fn test(&'_ self, arg2: &'_ i32) -> &'_ i32
                },
                quote! {
                    fn test(self, arg2: &'_ i32) -> &'__delegated i32
                },
            ),
        ] {
            let mut input: syn::Signature = input;
            input.lift_receiver_lifetime(with());

            assert_eq!(
                input.to_token_stream().to_string(),
                expected.to_string(),
            );
        }
    }

    #[test]
    fn receiver_with_lifetime() {
        for (input, expected) in [
            (
                parse_quote! {
                    fn test<'a, 'b>(&'a self, arg2: &'b i32) -> &'a i32
                },
                quote! {
                    fn test<'b>(self, arg2: &'b i32) -> &'__delegated i32
                },
            ),
            (
                parse_quote! {
                    fn test<'a, 'b>(&'a self, arg2: &'b i32) -> &'b i32
                },
                quote! {
                    fn test<'b>(self, arg2: &'b i32) -> &'b i32
                },
            ),
            (
                parse_quote! {
                    fn test<'b>(&'a self, arg2: &'b i32) -> &'a i32
                },
                quote! {
                    fn test<'b>(self, arg2: &'b i32) -> &'__delegated i32
                    where
                        'a: '__delegated,
                        '__delegated: 'a
                },
            ),
            (
                parse_quote! {
                    fn test<'b>(&'a self, arg2: &'b i32) -> &'b i32
                },
                quote! {
                    fn test<'b>(self, arg2: &'b i32) -> &'b i32
                    where
                        'a: '__delegated,
                        '__delegated: 'a
                },
            ),
            (
                parse_quote! {
                    fn test<'a>(&'a self, arg2: &'b i32) -> &'b i32
                },
                quote! {
                    fn test(self, arg2: &'b i32) -> &'b i32
                },
            ),
            (
                parse_quote! {
                    fn test<'a>(&'a self, arg2: &'b i32) -> &'a i32
                },
                quote! {
                    fn test(self, arg2: &'b i32) -> &'__delegated i32
                },
            ),
            (
                parse_quote! {
                    fn test<'a, 'b>(&'a self, arg2: &'b i32) -> &'a i32
                    where
                        'a: 'b
                },
                quote! {
                    fn test<'b>(self, arg2: &'b i32) -> &'__delegated i32
                    where
                        '__delegated: 'b
                },
            ),
            (
                parse_quote! {
                    fn test<'b>(&'a self, arg2: &'b i32) -> &'a i32
                    where
                        'a: 'b
                },
                quote! {
                    fn test<'b>(self, arg2: &'b i32) -> &'__delegated i32
                    where
                        '__delegated: 'b,
                        'a: '__delegated,
                        '__delegated: 'a
                },
            ),
        ] {
            let mut input: syn::Signature = input;
            input.lift_receiver_lifetime(with());

            assert_eq!(
                input.to_token_stream().to_string(),
                expected.to_string(),
            );
        }
    }
}