try_v2 0.4.1

Provides a derive macro for `Try` ([try_trait_v2](https://rust-lang.github.io/rfcs/3058-try-trait-v2.html))
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
#![cfg_attr(not(stable_if_let_guard), feature(if_let_guard))]
#![cfg_attr(not(stable_let_chains), feature(let_chains))]
#![feature(never_type)]

//! Provides a derive macro for [Try] & optionally [Try_ConvertResult] for interconversion with
//! `std::result::Result` and [Try_Iterator] for iterating over `IntoIterator` and collecting from
//! `FromIterator` analog to how `Result` & `Option` do this.
//! See ([try_trait_v2](https://rust-lang.github.io/rfcs/3058-try-trait-v2.html)) for more details
//! of the underlying trait.
//!
//! ## Requires
//!
//!   - nightly
//!   - `#![feature(never_type)]`
//!   - `#![feature(try_trait_v2)]`
//!   - `#![feature(try_trait_v2_residual)]`
//!   - optionally: `#![feature(iterator_try_collect)]` (if using Try_Iterator)
//!
//! ## Limitations on the annotated type
//!
//!   - must be an `enum`
//!   - must have _at least one_ generic type
//!   - the _first_ generic type must be the `Output` type (produced when not short circuiting)
//!   - the output variant (does not short-circuit) must be the _first_ variant and store the output
//!     type as the _only unnamed_ field
//!
//! See the individual documentation for [Try], [Try_ConvertResult] and [Try_Iterator] for specifics
//! on the generated code.
//!
//! ## Example Usage
//!
//! ```rust
//! #![feature(never_type)]
//! #![feature(try_trait_v2)]
//! #![feature(try_trait_v2_residual)]
//! use try_v2::{Try, Try_ConvertResult};
//!
//! #[derive(Try, Try_ConvertResult)]
//! enum TestResult<T> {
//!     Ok(T),
//!     TestsFailed,
//!     OtherError(String)
//! }
//!
//! // Basic short circuiting thanks to `#[derive(Try)]`
//! fn run_tests() -> TestResult<()> {
//!     TestResult::OtherError("oops!".to_string())?; // <- Function short-circuits here ...
//!     TestResult::TestsFailed?;
//!     TestResult::Ok(())
//! }
//!
//! assert!(matches!(run_tests(), TestResult::OtherError(msg) if msg == "oops!"));
//!
//!
//! // Conversion from std::result::Result thanks to `#[derive(Try_ConvertResult)]`
//! struct TestFailure {}
//!
//! impl<T> From<TestFailure> for TestResult<T> {
//!     fn from(err: TestFailure) -> Self {
//!         TestResult::TestsFailed
//!     }
//! }
//!
//! fn run_more_tests() -> TestResult<()> {
//!     std::result::Result::Err(TestFailure{})?; // <- Function short-circuits here & converts to a TestResult...
//!     TestResult::Ok(())
//! }
//!
//! assert!(matches!(run_more_tests(), TestResult::TestsFailed));
//! ```
//!
//! ## Stability & MSRV
//!
//! Given that this crate exposes an experimental API from std it makes use of experimental
//! features which require a nightly toolchain.
//!
//! In order to use this crate you must enable the features which it exposes:
//!
//! > 🔬 **Required Experimental Features**
//! >
//! >  - [`#![feature(never_type)]`](https://github.com/rust-lang/rust/issues/35121)
//! >  - [`#![feature(try_trait_v2)]`](https://github.com/rust-lang/rust/issues/84277)
//! >  - [`#![feature(try_trait_v2_residual)]`](https://github.com/rust-lang/rust/issues/91285)
//! >  - optionally: [`#![feature(iterator_try_collect)]`](https://github.com/rust-lang/rust/issues/94047) (if using [Try_Iterator])
//!
//! This crate makes use of the following experimental features in addition to those which it
//! directly supports:
//!
//! > 🔬 **Additional Experimental Features**
//! >
//! > - [`#![feature(if_let_guard)]`](https://github.com/rust-lang/rust/issues/51114) (stable since 1.95.0)
//! > - [`#![feature(let_chains)]`](https://github.com/rust-lang/rust/issues/139951) (stable since 1.88.0)
//! >
//! > This list includes any unstable features used by direct & transitive dependencies (currently, none).
//! >
//! > You do not need to enable these in your own code, the list is for information only.
//!
//! ### Stability guarantees
//!
//! We run automated tests **every month** to ensure no fundamental changes affect this crate and
//! test every PR against the current nightly, as well as the current equivalent beta & stable.
//! If you find an issue before we do, please
//! [raise an issue on github](https://github.com/MusicalNinjaDad/try_v2/issues).
//!
//! ### MSRV
//!
//! For those of you working with a pinned nightly (etc.) this crate supports every version of
//! edition 2024 (rust 1.85.1 onwards, released as stable on 2025-03-18). We use
//! [autocfg](https://crates.io/crates/autocfg/) to seamlessly handle features which have been
//! stabilised since then.
//!
//! ## Currently untested (may work, may not ...):
//!
//!   - `where` clauses
//!   - storing `Fn`s in variants

use proc_macro::TokenStream as TokenStream1;
use proc_macro2::TokenStream as TokenStream2;
use proc_macro2_diagnostic::prelude::*;
use quote::{format_ident, quote};
use syn::{DeriveInput, GenericParam, parse_quote, spanned::Spanned};

mod parse;
use parse::TryEnum;

#[proc_macro_derive(Try)]
/// Derives [try_trait_v2](https://rust-lang.github.io/rfcs/3058-try-trait-v2.html)
///
/// See the [crate level documentation](crate) for restrictions and detailed examples
///
/// ## Derived code
/// ```
/// # #![feature(never_type)]
/// # #![feature(try_trait_v2)]
/// # #![feature(try_trait_v2_residual)]
/// # use try_v2::Try;
/// #[derive(Try)]
/// enum TestResult<T, E> {
///     Ok(T),
///     TestsFailed,
///     OtherError(E)
/// }
/// ```
/// will result in code of the shape:
/// ```ignore
/// impl<T,E> Try for TestResult<T, E> {
///     type Output = T;
///     type Residual = TestResult<!,E>;
///
///     fn from_output(output: T) -> Self {
///         Self::Ok(output)
///     }
///
///     fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
///         Self::Ok(t) => Continue(t),
///         ... each failing variant => Break(failing variant) ...   
///     }
/// }
///
/// impl<T, E> FromResidual<TestResult<!,E>> for TestResult<T, E> {
///     fn from_residual(residual: TestResult<!,E>) -> Self {
///         match residual {
///             ... each failing variant => itself ...              
///         }
///     }
/// }
///
/// impl<T, E> Residual<T> for TestResult<!, E> {
///     type TryType = TestResult<T, E>;
/// }
/// ```
///
/// ## Things to note
///
/// This macro aims to reduce boilerpate for the most common implementations.
///
/// ### Residual
/// The `Residual` is generated by replacing the _first generic type_ with `!`. This means
///     - we rely on the unstable `#![feature(never_type)]` (on the assumption that it will be
///         stabilised on a similar timeframe to `#![feature(try_trait_v2)]`
///     - any short-circuiting variants which also store this type will have a "hole"
///     - the **invariant** _first generic type is stored by first variant_ is **strictly** enforced.
///         This is [by design](https://en.wikipedia.org/wiki/Poka-yoke) to guard against
///         accidental usage errors.
///
/// ### Output / Short-Circuiting
/// The _first variant_ is considered to represent the output case. This means
///     - there is only one continue (non-short-circuiting) case, all other variants will
///         short-circuit on `?`
///     - the first variant **must** store a generic type
///     - the **invariant** _first generic type is stored by first variant_ is **strictly** enforced.
///         This is [by design](https://en.wikipedia.org/wiki/Poka-yoke) to guard against
///         accidental usage errors.
///
/// ### Borrowed data
/// It is possible to derive Try for enums which store references to data, if your use case makes
/// this valuable.
///
/// ```
/// # #![feature(never_type)]
/// # #![feature(try_trait_v2)]
/// # #![feature(try_trait_v2_residual)]
/// # use try_v2::Try;
/// #[derive(Try)]
/// enum TestResult<'t, 'e, T, E> {
///     Ok(&'t T),
///     TestsFailed,
///     OtherError(&'e E)
/// }
/// ```
/// will have
/// ```ignore
///     type Output = &'t T;
///     type Residual = TestResult<'t, 'e, !, E>
/// ```
/// which _still includes all lifetimes_ in the Residual.
///
/// This is important to note if you are writing your own implementations of `FromResidual`.
///
/// Hint for matching on the Residual: `&!` itself will not be recognised as uninhabited by the
/// compiler but `&!` will dereference to `!` which will then coerce into any type or satisfy
/// `match ! {}`. Therefore, you should include a match arm `Ok(never) => *never` (doesn't guarantee
/// it's actually `&!`) or `Ok(&never) => match never {}` (more verbose but guarantees infallibility)
pub fn try_trait_v2_derive(input: TokenStream1) -> TokenStream1 {
    impl_derive(input.into()).into()
}

/// Parses & validates the input then quote!s the impl.  
fn impl_derive(input: TokenStream2) -> DiagnosticStream {
    let ast: DeriveInput = syn::parse2(input).expect("derive macro");

    let tryenum = TryEnum::parse(&ast)?;
    let (
        name,
        output_variant_name,
        output_type,
        _,
        residual_type,
        impl_generics,
        ty_generics,
        where_clause,
    ) = tryenum.split_for_impl();

    if !ast
        .attrs
        .iter()
        .any(|attr| attr.meta.path().is_ident("must_use"))
    {
        warn_spanned(
            (),
            ast.span(),
            "it is recommended to annotate try-types as `#[must_use]`",
        )?
    };

    let (branch_arms, residual_arms) = tryenum.generate_arms();

    let impl_try = quote! {
        impl #impl_generics std::ops::Try for #name #ty_generics #where_clause {
            type Output = #output_type;

            type Residual = #residual_type;

            #[inline]
            fn from_output(output: Self::Output) -> Self {
                Self::#output_variant_name(output)
            }

            #[inline]
            fn branch(self) -> std::ops::ControlFlow<Self::Residual, Self::Output> {
                match self {
                    #(#branch_arms)*
                }
            }
        }

        impl #impl_generics std::ops::FromResidual<#residual_type> for #name #ty_generics #where_clause {
            #[inline]
            #[track_caller]
            fn from_residual(residual: #residual_type) -> Self {
                match residual {
                    #(#residual_arms)*
                }
            }
        }

        impl #impl_generics std::ops::Residual<#output_type> for #residual_type #where_clause {
            type TryType = #name #ty_generics;
        }
    };
    Ok(impl_try)
}

#[proc_macro_derive(Try_ConvertResult)]
/// Derives ?-conversion from Result<T, E> and back where suitable implementations of From/Into exist.
///
/// ## Conversion from Result
/// For ?-conversion _from_ a `Result<T, SomeError>` `impl<T> From<SomeError> for MyTryEnum<T>`.
///
/// This will allow `?` on a call which returns `Result<T, SomeError>` in any function which returns
/// `MyTryEnum<T>`.
///
/// Type-hinting, type aliasing Result may be needed unless you have a
/// blanket From<E: Error> implementation.
///
/// ## Conversion to Result
/// For ?-conversion _to_ a `Result<_, SomeError>` `impl From<MyTryEnumResidual> for SomeError`.
///
/// Note that conversion must be defined between your _Residual_ and SomeError - this both avoids
/// triggering the orphan rule when your enum stores third-party / std types and requires
/// consideration and correct handling of each failure variant.
///
/// See the notes on [Try] for full details on identifying the correct Residual to use.
///
/// ## Derived Code
/// ```
/// # #![feature(never_type)]
/// # #![feature(try_trait_v2)]
/// # #![feature(try_trait_v2_residual)]
/// # use try_v2::{Try, Try_ConvertResult};
/// #[derive(Try, Try_ConvertResult)]
/// #[must_use]
/// enum TestResult<T, E> {
///     Ok(T),
///     TestsFailed,
///     OtherError(E)
/// }
/// ```
/// will generate:
/// ```ignore code-snippet
/// impl<T, E, RE> FromResidual<Result<Infallible, RE>> for TestResult<T, E>
/// where
///     RE: Into<TestResult<!,E>>
///
/// ... which calls Result::Err(e) => e.into(), ...
/// ```
/// and
/// ```ignore code-snippet
/// impl<E, RT, RE> FromResidual<TestResult<!,E>> for Result<RT, RE>
/// where
///     RE: From<TestResult<!,E>>
///
/// ... which calls Result::Err(residual.into()) ...
/// ```
///
/// ## Implementing [TryFrom]
///
/// TryFrom requires a [Result] to be returned. To handle this: use your residual
/// (e.g. `TestResult<!,E>` in the above example, or Eightball<!> in the one below) as the
/// `Error` type. Here's the example from the integration tests:
///
/// ```
/// #![feature(never_type)]
/// #![feature(try_trait_v2)]
/// #![feature(try_trait_v2_residual)]
///
/// use try_v2::{Try, Try_ConvertResult};
///
/// #[derive(Try, Try_ConvertResult)]
/// #[must_use]
/// enum Eightball<Y> {
///     Yes(Y),
///     No,
/// }
///
/// struct Even(i32);
///
/// impl TryFrom<i32> for Even {
///     type Error = Eightball<!>;
///
///     fn try_from(num: i32) -> Result<Even, Eightball<!>> {
///         if num % 2 == 0 {
///             Result::Ok(Even(num))
///         } else {
///             Result::Err(Eightball::No)
///         }
///     }
/// }
///
/// fn even_string(num: i32) -> Eightball<String> {
///     let n = Even::try_from(num)?;
///     let s = format!("{}", n.0);
///     Eightball::Yes(s)
/// }
///
/// assert!(matches!(even_string(2), Eightball::Yes(s) if s == "2"));
/// assert!(matches!(even_string(1), Eightball::No));
/// ```
///
pub fn try_trait_v2_convert_result(input: TokenStream1) -> TokenStream1 {
    impl_convert_result(input.into()).into()
}

fn impl_convert_result(input: TokenStream2) -> DiagnosticStream {
    let ast: DeriveInput = syn::parse2(input).expect("derive macro");

    let tryenum = TryEnum::parse(&ast)?;
    let (name, _, _, output_type_name, residual_type, _, ty_generics, where_clause) =
        tryenum.split_for_impl();

    let result_e = format_ident!("Derive_TryConvert_ResultE");
    let result_t = format_ident!("Derive_TryConvert_ResultT");

    let from_result_generics = tryenum.generics(|g| {
        g.params
            .push(parse_quote! {#result_e: Into<#residual_type>})
    });
    let (from_result_impl_generics, _, _) = from_result_generics.split_for_impl();

    let mut impl_convert = quote! {
        impl #from_result_impl_generics std::ops::FromResidual<std::result::Result<std::convert::Infallible, #result_e>> for #name #ty_generics #where_clause
        {
            #[inline]
            #[track_caller]
            fn from_residual(residual: std::result::Result<std::convert::Infallible, #result_e>) -> Self {
                match residual {
                    std::result::Result::Err(e) => {
                        let bang: #residual_type = e.into();
                        Self::from_residual(bang)
                    }
                }
            }
        }
    };

    let to_result_generics = tryenum.generics_with_params(|p| {
        p
            //remove output type
            .filter(|p| !matches!(p, GenericParam::Type(t) if t.ident == *output_type_name))
            // add result types
            .chain([
                parse_quote! {#result_t},
                parse_quote! {#result_e: From<#residual_type>},
            ])
    });

    let (to_result_impl_generics, _, _) = to_result_generics.split_for_impl();

    impl_convert.extend(quote! {
        impl #to_result_impl_generics std::ops::FromResidual<#residual_type> for std::result::Result<#result_t, #result_e>
        {
            #[inline]
            #[track_caller]
            fn from_residual(residual: #residual_type) -> Self {
                std::result::Result::Err(residual.into())
            }
        }
    });
    Ok(impl_convert)
}

#[proc_macro_derive(Try_Iterator)]
/// Derives `IntoIterator` and `FromIterator` analog to `Result` & `Option`.
///
/// - Vec<TryEnum>::collect() -> TryEnum<Vec>.
/// - TryEnum.into_iter() -> yields _one_ value if Ok, else empty.
///
/// ## Example
/// ```
/// # #![feature(never_type)]
/// # #![feature(try_trait_v2)]
/// # #![feature(try_trait_v2_residual)]
/// # #![feature(iterator_try_collect)]
/// # use try_v2::{Try, Try_Iterator};
/// # use TestResult::{Ok, TestsFailed, OtherError};
/// #[derive(Try, Try_Iterator)]
/// #[must_use]
/// enum TestResult<T, E> {
///     Ok(T),
///     TestsFailed,
///     OtherError(E),
/// }
///
/// # fn main() {
/// let tests: Vec<TestResult<i32, &'static str>> = vec![Ok(1), TestsFailed, Ok(2), OtherError("something wierd"), Ok(3), Ok(4)];
///
/// let first_results: TestResult<Vec<i32>, &'static str> = tests.into_iter().collect();
/// assert!(matches!(first_results, TestsFailed));
///
/// let mut test: TestResult<i32, &'static str> = Ok(4);
/// let borrowed_result: &i32 = test.iter().next().unwrap();
/// assert_eq!(borrowed_result, &4);
/// match test.iter_mut().next() {
///     Some(v) => *v = 5,
///     None => {},
/// }
/// assert!(matches!(test, TestResult::Ok(v) if v == 5));
/// let result = test.into_iter().next();
/// assert_eq!(result, Some(5));
/// # }
/// ```
pub fn iterator_traits(input: TokenStream1) -> TokenStream1 {
    impl_iterator_traits(input.into()).into()
}

fn impl_iterator_traits(input: TokenStream2) -> DiagnosticStream {
    let ast: DeriveInput = syn::parse2(input).expect("derive macro");

    let tryenum = TryEnum::parse(&ast)?;
    let (
        name,
        output_variant_name,
        output_type,
        output_type_name,
        _,
        impl_generics,
        ty_generics,
        where_clause,
    ) = tryenum.split_for_impl();

    // Standing on the shoulders of giants & blatanty (ab)using `std::option`'s work
    let mut impl_traits = quote! {
        impl #impl_generics std::iter::IntoIterator for #name #ty_generics #where_clause {
            type Item = #output_type;
            type IntoIter = std::option::IntoIter<#output_type>;


            fn into_iter(self) -> Self::IntoIter {
                let opt = match self {
                    Self::#output_variant_name(v) => Some(v),
                    _ => None,
                };
                opt.into_iter()
            }
        }

        impl #impl_generics #name #ty_generics {
            pub fn iter(&self) -> std::option::IntoIter<&#output_type> {
                let opt = match self {
                    Self::#output_variant_name(v) => Some(v),
                    _ => None,
                };
                opt.into_iter()
            }

            pub fn iter_mut(&mut self) -> std::option::IntoIter<&mut #output_type> {
                let opt = match self {
                    Self::#output_variant_name(v) => Some(v),
                    _ => None,
                };
                opt.into_iter()
            }
        }
    };

    let defined_type = quote! {#name #ty_generics};
    let vec_ish = format_ident!("Derive_TryIterator_V");

    let full_generics = tryenum.generics(|g| {
        g.params
            .push(parse_quote! {#vec_ish: FromIterator<#output_type>})
    });

    let (full_impl_generics, _, full_where_clause) = full_generics.split_for_impl();

    let returned_generics = tryenum.generics(|g| {
        for param in g.type_params_mut() {
            if param.ident == *output_type_name {
                *param = parse_quote! {#vec_ish};
                break;
            }
        }
    });
    let (_, ret_ty_generics, _) = returned_generics.split_for_impl();

    impl_traits.extend(quote! {
        impl #full_impl_generics std::iter::FromIterator<#defined_type> for #name #ret_ty_generics #full_where_clause
        {
            fn from_iter<I: IntoIterator<Item=#defined_type>>(iter: I) -> Self {
                iter.into_iter().try_collect()
            }
        }
    });

    Ok(impl_traits)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn derive() {
        let original: TokenStream2 = quote! {
            #[derive(Try)]
            #[must_use]
            enum Exit<T: Termination> {
                Ok(T),
                TestsFailed,
                OtherError(String),
                NamedError{err: String, text: String},
            }
        };

        let derived_impl: TokenStream2 = quote! {
            impl<T: Termination> std::ops::Try for Exit<T> {
                type Output = T;

                type Residual = Exit<!>;

                #[inline]
                fn from_output(output: Self::Output) -> Self {
                    Self::Ok(output)
                }

                #[inline]
                fn branch(self) -> std::ops::ControlFlow<Self::Residual, Self::Output> {
                    match self {
                        Self::Ok(v0) => std::ops::ControlFlow::Continue(v0),
                        Self::TestsFailed => std::ops::ControlFlow::Break(Exit::TestsFailed),
                        Self::OtherError(v0) => std::ops::ControlFlow::Break(Exit::OtherError(v0)),
                        Self::NamedError{err, text} => std::ops::ControlFlow::Break(Exit::NamedError{err, text}),
                    }
                }
            }

            impl<T: Termination> std::ops::FromResidual<Exit<!> > for Exit<T> {
                #[inline]
                #[track_caller]
                fn from_residual(residual: Exit<!>) -> Self {
                    match residual {
                        Exit::TestsFailed => Exit::TestsFailed,
                        Exit::OtherError(v0) => Exit::OtherError(v0),
                        Exit::NamedError{err, text} => Exit::NamedError{err, text},
                    }
                }
            }

            impl<T: Termination> std::ops::Residual<T> for Exit<!> {
                type TryType = Exit<T>;
            }
        };
        assert_eq!(
            derived_impl.to_string(),
            impl_derive(original).unwrap().to_string()
        )
    }
    #[test]
    fn convert_result() {
        let original: TokenStream2 = quote! {
            #[derive(Try_ConvertResult)]
            enum Exit<T: Termination, E> {
                Ok(T),
                TestsFailed,
                OtherError(E),
            }
        };

        let expected_impl: TokenStream2 = quote! {
            impl<T: Termination, E, Derive_TryConvert_ResultE: Into< Exit<!, E> > > std::ops::FromResidual<std::result::Result<std::convert::Infallible, Derive_TryConvert_ResultE>> for Exit<T, E>
            {
                #[inline]
                #[track_caller]
                fn from_residual(residual: std::result::Result<std::convert::Infallible, Derive_TryConvert_ResultE>) -> Self {
                    match residual {
                        std::result::Result::Err(e) => {
                            let bang: Exit<!, E> = e.into();
                            Self::from_residual(bang)
                        }
                    }
                }
            }

            impl<E, Derive_TryConvert_ResultT, Derive_TryConvert_ResultE: From<Exit<!, E> > > std::ops::FromResidual<Exit<!, E> > for std::result::Result<Derive_TryConvert_ResultT, Derive_TryConvert_ResultE>
            {
                #[inline]
                #[track_caller]
                fn from_residual(residual: Exit<!, E>) -> Self {
                    std::result::Result::Err(residual.into())
                }
            }
        };

        assert_eq!(
            expected_impl.to_string(),
            impl_convert_result(original).unwrap().to_string()
        )
    }
}